<commit_before>/**
 * Copyright (c) 2015-present, goreutils
 * All rights reserved.
 *
 * This source code is licensed under the MIT-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

"use strict";

var path = require("path"),
    _ = require("lodash"),
    defaults = require(path.join(__dirname, "/defaults")),
    glob = require("glob"),
    Q = require("q"),
    querystring = require("querystring"),
    webpack = require("webpack");

function full(config) {
    return _.assign(config, {
        "debug": false,
        "plugins": [
            new webpack.optimize.CommonsChunkPlugin(config.pckg.name + ".common.min.js"),
            new webpack.optimize.UglifyJsPlugin()
        ]
    });
}

function normalizeAliasPaths(baseDir, pckg) {
    var alias = {};

    alias[pckg.name] = path.resolve(baseDir, pckg.directories.lib);

    return _.merge(alias, pckg.alias);
}

function normalizeEntries(entries) {
    var i,
        ret = {};

    for (i = 0; i < entries.length; i += 1) {
        ret[normalizeEntry(entries[i], defaults.ecmaScriptFileExtensions)] = entries[i];
    }

    return ret;
}

function normalizeEntry(entry, fileExtensions) {
    var i,
        fileExtension;

    for (i = 0; i < fileExtensions.length; i += 1) {
        fileExtension = ".entry" + fileExtensions[i];
        if (_.endsWith(entry, fileExtension)) {
            return path.basename(entry, fileExtension);
        }
    }

    return entry;
}

function quick(config) {
    return _.assign(config, {
        "debug": true,
        "plugins": [
            new webpack.optimize.CommonsChunkPlugin(config.pckg.name + ".common.min.js")
        ]
    });
}

function run(config) {
    return new Q.Promise(function (resolve, reject) {
        webpack(config, function (err) {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
}

function stub(baseDir, pckgPromise) {
    return pckgPromise.then(function (pckg) {
            return Q.nfcall(glob, path.resolve(baseDir, pckg.directories.lib, "**", "*.entry" + defaults.ecmaScriptFileExtensionsGlobPattern))
                .then(function (entries) {
                    return [
                        normalizeEntries(entries),
                        pckg
                    ];
                });
        })
        .spread(function (entries, pckg) {
            return {
                "bail": true,
                "devtool": "source-map",
                "entry": entries,
                "externals": pckg.externals,
                "module": {
                    "loaders": [
                        {
                            // bower components usually expect to run in browser
                            // environment and sometimes assume that global 'this'
                            // is always the Window object which is a mistake
                            "test": /bower_components/,
                            "loader": require.resolve("imports-loader") + "?this=>window"
                        },
                        {
                            "test": /\.jsx$/,
                            "exclude": /(bower_components|node_modules)/,
                            "loader": require.resolve("babel-loader") + "?" + querystring.stringify({
                                "loose": [
                                    "es6.modules",
                                    "es6.properties.computed",
                                    "es6.templateLiterals"
                                ],
                                "optional": [
                                    "es3.runtime",
                                    "runtime",
                                    "utility.deadCodeElimination",
                                    "utility.inlineEnvironmentVariables",
                                    "utility.inlineExpressions",
                                    "validation.react"
                                ]
                            })
                        }
                    ]
                },
                "output": {
                    "filename": pckg.name + ".[name].min.js",
                    "path": path.resolve(baseDir, pckg.directories.dist)
                },
                "pckg": pckg,
                "resolve": {
                    "alias": normalizeAliasPaths(baseDir, pckg),
                    "extensions": defaults.ecmaScriptFileExtensions,
                    "root": baseDir
                }
            };
        });
}

module.exports = {
    "full": function (baseDir, pckgPromise) {
        return function () {
            return stub(baseDir, pckgPromise).then(full).then(run);
        };
    },
    "quick": function (baseDir, pckgPromise) {
        return function () {
            return stub(baseDir, pckgPromise).then(quick).then(run);
        };
    }
};
<commit_msg>close #8 (Improve entry point name resolution)<commit_after>/**
 * Copyright (c) 2015-present, goreutils
 * All rights reserved.
 *
 * This source code is licensed under the MIT-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

"use strict";

var path = require("path"),
    _ = require("lodash"),
    defaults = require(path.join(__dirname, "/defaults")),
    glob = require("glob"),
    Q = require("q"),
    querystring = require("querystring"),
    webpack = require("webpack");

function full(config) {
    return _.assign(config, {
        "debug": false,
        "plugins": [
            new webpack.optimize.CommonsChunkPlugin(config.pckg.name + ".common.min.js"),
            new webpack.optimize.UglifyJsPlugin()
        ]
    });
}

function normalizeAliasPaths(baseDir, pckg) {
    var alias = {};

    alias[pckg.name] = path.resolve(baseDir, pckg.directories.lib);

    return _.merge(alias, pckg.alias);
}

function normalizeEntries(baseDir, pckg, entries) {
    var i,
        ret = {};

    for (i = 0; i < entries.length; i += 1) {
        ret[normalizeEntry(baseDir, pckg, entries[i], defaults.ecmaScriptFileExtensions)] = entries[i];
    }

    return ret;
}

function normalizeEntry(baseDir, pckg, entry, fileExtensions) {
    var i,
        entryPointStem,
        fileExtension;

    for (i = 0; i < fileExtensions.length; i += 1) {
        fileExtension = ".entry" + fileExtensions[i];
        if (_.endsWith(entry, fileExtension)) {
            entryPointStem = path.relative(path.join(baseDir, pckg.directories.lib), entry);
            entryPointStem = entryPointStem.replace(path.sep, "-");

            return path.basename(entryPointStem, fileExtension);
        }
    }

    return entry;
}

function quick(config) {
    return _.assign(config, {
        "debug": true,
        "plugins": [
            new webpack.optimize.CommonsChunkPlugin(config.pckg.name + ".common.min.js")
        ]
    });
}

function run(config) {
    return new Q.Promise(function (resolve, reject) {
        webpack(config, function (err) {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
}

function stub(baseDir, pckgPromise) {
    return pckgPromise.then(function (pckg) {
            return Q.nfcall(glob, path.resolve(baseDir, pckg.directories.lib, "**", "*.entry" + defaults.ecmaScriptFileExtensionsGlobPattern))
                .then(function (entries) {
                    return [
                        normalizeEntries(baseDir, pckg, entries),
                        pckg
                    ];
                });
        })
        .spread(function (entries, pckg) {
            return {
                "bail": true,
                "devtool": "source-map",
                "entry": entries,
                "externals": pckg.externals,
                "module": {
                    "loaders": [
                        {
                            // bower components usually expect to run in browser
                            // environment and sometimes assume that global 'this'
                            // is always the Window object which is a mistake
                            "test": /bower_components/,
                            "loader": require.resolve("imports-loader") + "?this=>window"
                        },
                        {
                            "test": /\.jsx$/,
                            "exclude": /(bower_components|node_modules)/,
                            "loader": require.resolve("babel-loader") + "?" + querystring.stringify({
                                "loose": [
                                    "es6.modules",
                                    "es6.properties.computed",
                                    "es6.templateLiterals"
                                ],
                                "optional": [
                                    "es3.runtime",
                                    "runtime",
                                    "utility.deadCodeElimination",
                                    "utility.inlineEnvironmentVariables",
                                    "utility.inlineExpressions",
                                    "validation.react"
                                ]
                            })
                        }
                    ]
                },
                "output": {
                    "filename": pckg.name + ".[name].min.js",
                    "path": path.resolve(baseDir, pckg.directories.dist)
                },
                "pckg": pckg,
                "resolve": {
                    "alias": normalizeAliasPaths(baseDir, pckg),
                    "extensions": defaults.ecmaScriptFileExtensions,
                    "root": baseDir
                }
            };
        });
}

module.exports = {
    "full": function (baseDir, pckgPromise) {
        return function () {
            return stub(baseDir, pckgPromise).then(full).then(run);
        };
    },
    "quick": function (baseDir, pckgPromise) {
        return function () {
            return stub(baseDir, pckgPromise).then(quick).then(run);
        };
    }
};
<|endoftext|>


<commit_before>var base64 = require('./base64'),
    fs = require('fs');

function makeid(n) {
  var text = "";
  var possible =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < n; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }

  return text;
}

function _randomTempDir() {
  return '/tmp/' + makeid(8);
}

// Decode a "data:" URL and write it to disk.
function _dataUrlToDisk(dataUrl, destinationPath) {
  var pngHeader = 'data:image/png;base64,';
  if (dataUrl.substr(0, pngHeader.length) != pngHeader) {
    throw "data URL lacked PNG header: " + dataUrl.substr(0, 20);
  }
  var data64 = dataUrl.substr(pngHeader.length);
  var rawPngStr = base64.decodeToString(data64);
  fs.write(destinationPath, rawPngStr, 'wb');
}

/**
 * @param {string} actual_data data: URL for actual screenshot
 * @param {string} expected_data data: URL for expected screenshot
 * @param {string} diff_data data: URL for the perceptual diff.
 * @return {string} Path to index.html for viewing the diff.
 */
function writeDiffFamily(actual_data, expected_data, diff_data) {
  var dir = _randomTempDir();
  fs.makeDirectory(dir);
  var base = dir + fs.separator;

  _dataUrlToDisk(actual_data, base + 'actual.png');
  _dataUrlToDisk(expected_data, base + 'expected.png');
  _dataUrlToDisk(diff_data, base + 'diff.png');

  var index = base + 'index.html';
  fs.copy('pdiff-tests/lib/diff-viewer.html', index);
  return index;
}

module.exports = {
  startTest: function(casper, relativePath, cb) {
    casper.start(relativePath, function() {
      // TODO(danvk): find a copy of this in NPM
      phantom.injectJs('pdiff-tests/lib/pdiffy.js');

      casper.page.evaluate(function() {
        document.body.bgColor = 'white';
      });

      cb();
    });
  },

  takeScreenshot: function(casper, opt_pathToPngFile) {
    // To capture a screenshot to a file, use this:
    actual_screenshot = 'data:image/png;base64,' + casper.captureBase64('png');
    if (opt_pathToPngFile) {
      casper.capture(opt_pathToPngFile);
    }

    return actual_screenshot;
  },

  checkAgainstGolden: function(casper, actual_screenshot, goldenPath) {
    var results, expected_screenshot;

    // compare the screenshot against a known baseline
    casper.then(function() {
      var absPath = fs.absolute(goldenPath);
      var xhr = new XMLHttpRequest();
      xhr.open('GET', 'file://' + absPath, false);
      xhr.responseType = 'arraybuffer';
      xhr.onload = function(e) {
        var data64 = base64.base64ArrayBuffer(e.currentTarget.response);
        expected_screenshot = 'data:image/png;base64,' + data64;

        pdiffy(actual_screenshot)
          .compareTo(expected_screenshot)
          .onComplete(function(data) {
            results = data;
          });
      };
      xhr.send();
    });

    // Wait for the async compareTo(...) to return, then do assertion check
    // for test results
    casper.waitFor(function check() {
      return (results !== undefined);
    }, function then() {
      if (results.misMatchPercentage != "0.00") {
        var indexFile = writeDiffFamily(actual_screenshot, expected_screenshot, results.getImageDataUrl());
        console.log('Actual screenshot did not match expected.');
        console.log('See ' + indexFile + ' for diffs');
      }

      casper.test.assertEquals(results.misMatchPercentage, "0.00",
          "Expected and actual screenshots match");
    });
  }
};
<commit_msg>update pdiff file to accept arbitrary screenshot size<commit_after>var base64 = require('./base64'),
    fs = require('fs');

function makeid(n) {
  var text = "";
  var possible =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < n; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }

  return text;
}

function _randomTempDir() {
  return '/tmp/' + makeid(8);
}

// Decode a "data:" URL and write it to disk.
function _dataUrlToDisk(dataUrl, destinationPath) {
  var pngHeader = 'data:image/png;base64,';
  if (dataUrl.substr(0, pngHeader.length) != pngHeader) {
    throw "data URL lacked PNG header: " + dataUrl.substr(0, 20);
  }
  var data64 = dataUrl.substr(pngHeader.length);
  var rawPngStr = base64.decodeToString(data64);
  fs.write(destinationPath, rawPngStr, 'wb');
}

/**
 * @param {string} actual_data data: URL for actual screenshot
 * @param {string} expected_data data: URL for expected screenshot
 * @param {string} diff_data data: URL for the perceptual diff.
 * @return {string} Path to index.html for viewing the diff.
 */
function writeDiffFamily(actual_data, expected_data, diff_data) {
  var dir = _randomTempDir();
  fs.makeDirectory(dir);
  var base = dir + fs.separator;

  _dataUrlToDisk(actual_data, base + 'actual.png');
  _dataUrlToDisk(expected_data, base + 'expected.png');
  _dataUrlToDisk(diff_data, base + 'diff.png');

  var index = base + 'index.html';
  fs.copy('pdiff-tests/lib/diff-viewer.html', index);
  return index;
}

module.exports = {
  startTest: function(casper, relativePath, cb) {
    casper.start(relativePath, function() {
      // TODO(danvk): find a copy of this in NPM
      phantom.injectJs('pdiff-tests/lib/pdiffy.js');

      casper.page.evaluate(function() {
        document.body.bgColor = 'white';
      });

      cb();
    });
  },

  takeScreenshot: function(casper, area) {
    // To capture a screenshot to a file, use this:
    actual_screenshot = 'data:image/png;base64,' + casper.captureBase64('png', area);
    return actual_screenshot;
  },

  checkAgainstGolden: function(casper, actual_screenshot, goldenPath) {
    var results, expected_screenshot;

    // compare the screenshot against a known baseline
    casper.then(function() {
      var absPath = fs.absolute(goldenPath);
      var xhr = new XMLHttpRequest();
      xhr.open('GET', 'file://' + absPath, false);
      xhr.responseType = 'arraybuffer';
      xhr.onload = function(e) {
        var data64 = base64.base64ArrayBuffer(e.currentTarget.response);
        expected_screenshot = 'data:image/png;base64,' + data64;

        pdiffy(actual_screenshot)
          .compareTo(expected_screenshot)
          .onComplete(function(data) {
            results = data;
          });
      };
      xhr.send();
    });

    // Wait for the async compareTo(...) to return, then do assertion check
    // for test results
    casper.waitFor(function check() {
      return (results !== undefined);
    }, function then() {
      if (results.misMatchPercentage != "0.00") {
        var indexFile = writeDiffFamily(actual_screenshot, expected_screenshot, results.getImageDataUrl());
        console.log('Actual screenshot did not match expected.');
        console.log('See ' + indexFile + ' for diffs');
      }

      casper.test.assertEquals(results.misMatchPercentage, "0.00",
          "Expected and actual screenshots match");
    });
  }
};
<|endoftext|>


<commit_before>module.exports = {
  'northern_virginia' : {
    'name': 'US East (N. Virginia)',
    'code': 'us-east-1'
  },
  'ohio' : {
    'name': 'US East (Ohio)',
    'code': 'us-east-2'
  },
  'oregon' : {
    'name': 'US West (Oregon)',
    'code': 'us-west-2'
  },
  'northern_california' : {
    'name': 'US West (N. California)',
    'code': 'us-west-1'
  },
  'montreal' : {
    'name': 'Canada (Central)',
    'code': 'ca-central-1'
  },
  'são_paulo' : {
    'name': 'South America (São Paulo)',
    'code': 'sa-east-1'
  },
  'govcloud_us-east' : {
    'name': 'GovCloud (US-East)',
    'code': 'us-gov-east-1'
  },
  'govcloud_us-west' : {
    'name': 'GovCloud (US-West)',
    'code': 'us-gov-west-1'
  },
  'ireland' : {
    'name': 'EU (Ireland)',
    'code': 'eu-west-1'
  },
  'london' : {
    'name': 'EU (London)',
    'code': 'eu-west-2'
  },
  'paris' : {
    'name': 'EU (Paris)',
    'code': 'eu-west-3'
  },
  'frankfurt' : {
    'name': 'EU (Frankfurt)',
    'code': 'eu-central-1'
  },
  'stockholm': {
    'name': 'EU (Stockholm)',
    'code': 'eu-north-1'
  },
  'singapore' : {
    'name': 'Asia Pacific (Singapore)',
    'code': 'ap-southeast-1'
  },
  'tokyo' : {
    'name': 'Asia Pacific (Tokyo)',
    'code': 'ap-northeast-1'
  },
  'osaka' : {
    'name': 'Asia Pacific (Osaka-Local)',
    'code': 'ap-northeast-3'
  },
  'sydney' : {
    'name': 'Asia Pacific (Sydney)',
    'code': 'ap-southeast-2'
  },
  'seoul' : {
    'name': 'Asia Pacific (Seoul)',
    'code': 'ap-northeast-2'
  },
  'mumbai' : {
    'name': 'Asia Pacific (Mumbai)',
    'code': 'ap-south-1'
  },
  'beijing' : {
    'name': 'China (Beijing)',
    'code': 'cn-north-1'
  },
  'ningxia' : {
    'name': 'China (Ningxia)',
    'code': 'cn-northwest-1'
  }
};
<commit_msg>add Hong Kong region<commit_after>module.exports = {
  'northern_virginia' : {
    'name': 'US East (N. Virginia)',
    'code': 'us-east-1'
  },
  'ohio' : {
    'name': 'US East (Ohio)',
    'code': 'us-east-2'
  },
  'oregon' : {
    'name': 'US West (Oregon)',
    'code': 'us-west-2'
  },
  'northern_california' : {
    'name': 'US West (N. California)',
    'code': 'us-west-1'
  },
  'montreal' : {
    'name': 'Canada (Central)',
    'code': 'ca-central-1'
  },
  'são_paulo' : {
    'name': 'South America (São Paulo)',
    'code': 'sa-east-1'
  },
  'govcloud_us-east' : {
    'name': 'GovCloud (US-East)',
    'code': 'us-gov-east-1'
  },
  'govcloud_us-west' : {
    'name': 'GovCloud (US-West)',
    'code': 'us-gov-west-1'
  },
  'ireland' : {
    'name': 'EU (Ireland)',
    'code': 'eu-west-1'
  },
  'london' : {
    'name': 'EU (London)',
    'code': 'eu-west-2'
  },
  'paris' : {
    'name': 'EU (Paris)',
    'code': 'eu-west-3'
  },
  'frankfurt' : {
    'name': 'EU (Frankfurt)',
    'code': 'eu-central-1'
  },
  'stockholm': {
    'name': 'EU (Stockholm)',
    'code': 'eu-north-1'
  },
  'singapore' : {
    'name': 'Asia Pacific (Singapore)',
    'code': 'ap-southeast-1'
  },
  'tokyo' : {
    'name': 'Asia Pacific (Tokyo)',
    'code': 'ap-northeast-1'
  },
  'osaka' : {
    'name': 'Asia Pacific (Osaka-Local)',
    'code': 'ap-northeast-3'
  },
  'sydney' : {
    'name': 'Asia Pacific (Sydney)',
    'code': 'ap-southeast-2'
  },
  'hong_kong' : {
    'name': 'Asia Pacific (Hong Kong)',
    'code': 'ap-east-1'
  },
  'seoul' : {
    'name': 'Asia Pacific (Seoul)',
    'code': 'ap-northeast-2'
  },
  'mumbai' : {
    'name': 'Asia Pacific (Mumbai)',
    'code': 'ap-south-1'
  },
  'beijing' : {
    'name': 'China (Beijing)',
    'code': 'cn-north-1'
  },
  'ningxia' : {
    'name': 'China (Ningxia)',
    'code': 'cn-northwest-1'
  }
};
<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';
import { boolean, text, select } from '@storybook/addon-knobs';
import { action } from '@storybook/addon-actions';
import { Store, State } from '@sambego/storybook-state';
import { Select, Option } from '.';
import OptionsHelper from '../../../utils/helpers/options-helper';

const singleSelectStore = new Store({
  value: undefined
});

const multiSelectStore = new Store({
  value: []
});

const commonKnobs = (store) => {
  const filterable = boolean('filterable', Select.defaultProps.filterable);
  const typeAhead = filterable && boolean('typeAhead', Select.defaultProps.typeAhead);
  const label = text('label', '');

  const knobs = {
    disabled: boolean('disabled', false),
    errorMessage: text('errorMessage', ''),
    infoMessage: text('infoMessage', ''),
    onChange: (ev) => {
      store.set({ value: ev.target.value });
      action('change')(ev);
    },
    placeholder: text('placeholder', ''),
    readOnly: boolean('readOnly', false),
    size: select('size', OptionsHelper.sizesRestricted, OptionsHelper.sizesRestricted[1]),
    warningMessage: text('warningMessage', ''),
    filterable,
    typeAhead,
    label
  };

  if (label.length) {
    knobs.labelAlign = select('labelAlign', OptionsHelper.alignBinary, OptionsHelper.alignBinary[0]);
    knobs.labelInline = boolean('labelInline', false);
  }

  return knobs;
};

const selectOptionsLabels = [
  'Amber', 'Black', 'Blue', 'Brown', 'Green', 'Orange', 'Pink', 'Purple', 'Red', 'White', 'Yellow'
];

const selectOptions = selectOptionsLabels.map((label, index) => (
  <Option
    key={ label }
    text={ label }
    value={ String(index + 1) }
  />
));

storiesOf('Experimental/Select', module)
  .addParameters({
    info: {
      propTablesExclude: [State]
    }
  })
  .add('default', () => {
    return (
      <State store={ singleSelectStore }>
        <Select { ...commonKnobs(singleSelectStore) }>
          { selectOptions }
        </Select>
      </State>
    );
  })

  .add('multiple', () => {
    return (
      <State store={ multiSelectStore }>
        <Select { ...commonKnobs(multiSelectStore) }>
          { selectOptions }
        </Select>
      </State>
    );
  });
<commit_msg>add escape html<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { boolean, text, select } from '@storybook/addon-knobs';
import { action } from '@storybook/addon-actions';
import { Store, State } from '@sambego/storybook-state';
import { Select, Option } from '.';
import OptionsHelper from '../../../utils/helpers/options-helper';

const singleSelectStore = new Store({
  value: undefined
});

const multiSelectStore = new Store({
  value: []
});

const commonKnobs = (store) => {
  const filterable = boolean('filterable', Select.defaultProps.filterable);
  const typeAhead = filterable && boolean('typeAhead', Select.defaultProps.typeAhead);
  const label = text('label', '');

  const knobs = {
    disabled: boolean('disabled', false),
    errorMessage: text('errorMessage', ''),
    infoMessage: text('infoMessage', ''),
    onChange: (ev) => {
      store.set({ value: ev.target.value });
      action('change')(ev);
    },
    placeholder: text('placeholder', ''),
    readOnly: boolean('readOnly', false),
    size: select('size', OptionsHelper.sizesRestricted, OptionsHelper.sizesRestricted[1]),
    warningMessage: text('warningMessage', ''),
    filterable,
    typeAhead,
    label
  };

  if (label.length) {
    knobs.labelAlign = select('labelAlign', OptionsHelper.alignBinary, OptionsHelper.alignBinary[0]);
    knobs.labelInline = boolean('labelInline', false);
  }

  return knobs;
};

const selectOptionsLabels = [
  'Amber', 'Black', 'Blue', 'Brown', 'Green', 'Orange', 'Pink', 'Purple', 'Red', 'White', 'Yellow'
];

const selectOptions = selectOptionsLabels.map((label, index) => (
  <Option
    key={ label }
    text={ label }
    value={ String(index + 1) }
  />
));

storiesOf('Experimental/Select', module)
  .addParameters({
    info: {
      propTablesExclude: [State]
    },
    knobs: { escapeHTML: false }
  })
  .add('default', () => {
    return (
      <State store={ singleSelectStore }>
        <Select { ...commonKnobs(singleSelectStore) }>
          { selectOptions }
        </Select>
      </State>
    );
  })

  .add('multiple', () => {
    return (
      <State store={ multiSelectStore }>
        <Select { ...commonKnobs(multiSelectStore) }>
          { selectOptions }
        </Select>
      </State>
    );
  });
<|endoftext|>


<commit_before>/*global FormplayerFrontend, Util */

FormplayerFrontend.module("SessionNavigate", function (SessionNavigate, FormplayerFrontend, Backbone, Marionette) {
    SessionNavigate.Router = Marionette.AppRouter.extend({
        appRoutes: {
            "apps": "listApps", // list all apps available to this user
            "single_app/:id": "singleApp", // Show app in phone mode (SingleAppView)
            "home/:id": "landingPageApp", // Show app in landing page mode (LandingPageAppView)
            "sessions": "listSessions", //list all this user's current sessions (incomplete forms)
            "sessions/:id": "getSession",
            "local/:path": "localInstall",
            "restore_as/:page/:query": "listUsers",
            "restore_as/:page/": "listUsers",
            "restore_as": "listUsers",
            "settings": "listSettings",
            ":session": "listMenus",  // Default route
        },
    });

    var API = {
        listApps: function () {
            FormplayerFrontend.regions.breadcrumb.empty();
            FormplayerFrontend.Apps.Controller.listApps();
        },
        singleApp: function (appId) {
            var user = FormplayerFrontend.request('currentUser');
            FormplayerFrontend.regions.breadcrumb.empty();
            user.previewAppId = appId;
            FormplayerFrontend.Apps.Controller.singleApp(appId);
        },
        landingPageApp: function (appId) {
            FormplayerFrontend.Apps.Controller.landingPageApp(appId);
        },
        selectApp: function (appId, isInitial) {
            FormplayerFrontend.Menus.Controller.selectMenu({
                'appId': appId,
                'isInitial': isInitial,
            });
        },
        listMenus: function (sessionObject) {
            var urlObject = Util.CloudcareUrl.fromJson(
                Util.encodedUrlToObject(sessionObject || Backbone.history.getFragment())
            );
            if (!urlObject.appId && !urlObject.installReference) {
                // We can't do any menu navigation without an appId
                FormplayerFrontend.trigger("apps:list");
            } else {
                FormplayerFrontend.Menus.Controller.selectMenu(urlObject);
            }
        },
        listUsers: function (page, query) {
            FormplayerFrontend.trigger("clearForm");
            page = parseInt(page);
            if (_.isNaN(page)) {
                page = 1;
            }
            FormplayerFrontend.Users.Controller.listUsers(page, query);
        },
        listSettings: function () {
            FormplayerFrontend.Apps.Controller.listSettings();
        },
        showDetail: function (caseId, detailTabIndex, isPersistent) {
            FormplayerFrontend.Menus.Controller.selectDetail(caseId, detailTabIndex, isPersistent);
        },
        listSessions: function () {
            SessionNavigate.SessionList.Controller.listSessions();
        },
        getSession: function (sessionId) {
            FormplayerFrontend.request("getSession", sessionId);
        },
        localInstall: function (path) {
            FormplayerFrontend.trigger("localInstall", path);
        },
        /**
         * renderResponse
         *
         * Takes a response from a successfully submitted form and routes
         * the application to the correct screen. In normal circumstances,
         * the response is a menu response since the user is navigating to
         * module list or home screen. When linking forms, the response will
         * be a form response which will route to a new form.
         */
        renderResponse: function (response) {
            var currentFragment,
                urlObject,
                encodedUrl,
                menuCollection;

            currentFragment = Backbone.history.getFragment();
            urlObject = Util.CloudcareUrl.fromJson(Util.encodedUrlToObject(currentFragment));
            response.appId = urlObject.appId;

            // When the response gets parsed, it will automatically trigger form
            // entry if it is a form response.
            menuCollection = new FormplayerFrontend.Menus.Collections.MenuSelect(
                response,
                { parse: true }
            );
            // Need to get URL fragment again since fetch might have updated it
            currentFragment = Backbone.history.getFragment();
            urlObject = Util.CloudcareUrl.fromJson(Util.encodedUrlToObject(currentFragment));
            encodedUrl = Util.objectToEncodedUrl(urlObject.toJson());
            FormplayerFrontend.navigate(encodedUrl);

            FormplayerFrontend.Menus.Controller.showMenu(menuCollection);
        },
    };
    API = SessionNavigate.Middleware.apply(API);

    FormplayerFrontend.on("apps:currentApp", function () {
        var urlObject = Util.currentUrlToObject();
        urlObject.clearExceptApp();
        Util.setUrlToObject(urlObject);
        API.selectApp(urlObject.appId);
    });

    FormplayerFrontend.on("apps:list", function () {
        FormplayerFrontend.navigate("apps");
        API.listApps();
    });

    FormplayerFrontend.on("app:select", function (appId) {
        var urlObject = new Util.CloudcareUrl({'appId': appId});
        Util.setUrlToObject(urlObject);
        API.selectApp(appId, true);
    });

    FormplayerFrontend.on('app:singleApp', function (appId) {
        FormplayerFrontend.navigate("/single_app/" + appId);
        API.singleApp(appId);
    });

    FormplayerFrontend.on('app:landingPageApp', function (appId) {
        FormplayerFrontend.navigate("/home/" + appId);
        API.landingPageApp(appId);
    });

    FormplayerFrontend.on("menu:select", function (index) {
        var urlObject = Util.currentUrlToObject();
        urlObject.addStep(index);
        Util.setUrlToObject(urlObject);
        API.listMenus();
    });

    FormplayerFrontend.on("menu:paginate", function (page) {
        var urlObject = Util.currentUrlToObject();
        urlObject.setPage(page);
        Util.setUrlToObject(urlObject);
        API.listMenus();
    });

    FormplayerFrontend.on("menu:sort", function (newSortIndex) {
        var urlObject = Util.currentUrlToObject();
        var currentSortIndex = urlObject.sortIndex;
        // If the column index is the same as already loaded, reverse the sort
        if (newSortIndex === Math.abs(currentSortIndex)) {
            newSortIndex = -1 * currentSortIndex;
        }
        urlObject.setSort(newSortIndex);
        Util.setUrlToObject(urlObject);
        API.listMenus();
    });

    FormplayerFrontend.on("menu:search", function (search) {
        debugger;
        var urlObject = Util.currentUrlToObject();
        urlObject.setSearch(search);
        Util.setUrlToObject(urlObject);
        API.listMenus();
    });

    FormplayerFrontend.on("menu:query", function (queryDict) {
        var urlObject = Util.currentUrlToObject();
        urlObject.setQuery(queryDict);
        Util.setUrlToObject(urlObject);
        API.listMenus();
    });

    FormplayerFrontend.on('restore_as:list', function () {
        FormplayerFrontend.navigate("/restore_as");
        API.listUsers();
    });

    FormplayerFrontend.on('settings:list', function () {
        FormplayerFrontend.navigate("/settings");
        API.listSettings();
    });

    FormplayerFrontend.on("menu:show:detail", function (caseId, detailTabIndex, isPersistent) {
        API.showDetail(caseId, detailTabIndex, isPersistent);
    });

    FormplayerFrontend.on("sessions", function () {
        FormplayerFrontend.navigate("/sessions");
        API.listSessions();
    });

    FormplayerFrontend.on("getSession", function (sessionId) {
        FormplayerFrontend.navigate("/sessions/" + sessionId);
        API.getSession(sessionId);
    });

    FormplayerFrontend.on("renderResponse", function (menuResponse) {
        API.renderResponse(menuResponse);
    });

    SessionNavigate.start = function () {
        return new SessionNavigate.Router({
            controller: API,
        });
    };

    FormplayerFrontend.on("breadcrumbSelect", function (index) {
        FormplayerFrontend.trigger("clearForm");
        var urlObject = Util.currentUrlToObject();
        urlObject.spliceSteps(index);
        Util.setUrlToObject(urlObject);
        var options = {
            'appId': urlObject.appId,
            'steps': urlObject.steps,
        };
        FormplayerFrontend.Menus.Controller.selectMenu(options);
    });

    FormplayerFrontend.on("localInstall", function (path) {
        var urlObject = new Util.CloudcareUrl({
            'installReference': path,
        });
        Util.setUrlToObject(urlObject);
        FormplayerFrontend.Menus.Controller.selectMenu(urlObject);
    });
});
<commit_msg>fixed the forgotten debugger message<commit_after>/*global FormplayerFrontend, Util */

FormplayerFrontend.module("SessionNavigate", function (SessionNavigate, FormplayerFrontend, Backbone, Marionette) {
    SessionNavigate.Router = Marionette.AppRouter.extend({
        appRoutes: {
            "apps": "listApps", // list all apps available to this user
            "single_app/:id": "singleApp", // Show app in phone mode (SingleAppView)
            "home/:id": "landingPageApp", // Show app in landing page mode (LandingPageAppView)
            "sessions": "listSessions", //list all this user's current sessions (incomplete forms)
            "sessions/:id": "getSession",
            "local/:path": "localInstall",
            "restore_as/:page/:query": "listUsers",
            "restore_as/:page/": "listUsers",
            "restore_as": "listUsers",
            "settings": "listSettings",
            ":session": "listMenus",  // Default route
        },
    });

    var API = {
        listApps: function () {
            FormplayerFrontend.regions.breadcrumb.empty();
            FormplayerFrontend.Apps.Controller.listApps();
        },
        singleApp: function (appId) {
            var user = FormplayerFrontend.request('currentUser');
            FormplayerFrontend.regions.breadcrumb.empty();
            user.previewAppId = appId;
            FormplayerFrontend.Apps.Controller.singleApp(appId);
        },
        landingPageApp: function (appId) {
            FormplayerFrontend.Apps.Controller.landingPageApp(appId);
        },
        selectApp: function (appId, isInitial) {
            FormplayerFrontend.Menus.Controller.selectMenu({
                'appId': appId,
                'isInitial': isInitial,
            });
        },
        listMenus: function (sessionObject) {
            var urlObject = Util.CloudcareUrl.fromJson(
                Util.encodedUrlToObject(sessionObject || Backbone.history.getFragment())
            );
            if (!urlObject.appId && !urlObject.installReference) {
                // We can't do any menu navigation without an appId
                FormplayerFrontend.trigger("apps:list");
            } else {
                FormplayerFrontend.Menus.Controller.selectMenu(urlObject);
            }
        },
        listUsers: function (page, query) {
            FormplayerFrontend.trigger("clearForm");
            page = parseInt(page);
            if (_.isNaN(page)) {
                page = 1;
            }
            FormplayerFrontend.Users.Controller.listUsers(page, query);
        },
        listSettings: function () {
            FormplayerFrontend.Apps.Controller.listSettings();
        },
        showDetail: function (caseId, detailTabIndex, isPersistent) {
            FormplayerFrontend.Menus.Controller.selectDetail(caseId, detailTabIndex, isPersistent);
        },
        listSessions: function () {
            SessionNavigate.SessionList.Controller.listSessions();
        },
        getSession: function (sessionId) {
            FormplayerFrontend.request("getSession", sessionId);
        },
        localInstall: function (path) {
            FormplayerFrontend.trigger("localInstall", path);
        },
        /**
         * renderResponse
         *
         * Takes a response from a successfully submitted form and routes
         * the application to the correct screen. In normal circumstances,
         * the response is a menu response since the user is navigating to
         * module list or home screen. When linking forms, the response will
         * be a form response which will route to a new form.
         */
        renderResponse: function (response) {
            var currentFragment,
                urlObject,
                encodedUrl,
                menuCollection;

            currentFragment = Backbone.history.getFragment();
            urlObject = Util.CloudcareUrl.fromJson(Util.encodedUrlToObject(currentFragment));
            response.appId = urlObject.appId;

            // When the response gets parsed, it will automatically trigger form
            // entry if it is a form response.
            menuCollection = new FormplayerFrontend.Menus.Collections.MenuSelect(
                response,
                { parse: true }
            );
            // Need to get URL fragment again since fetch might have updated it
            currentFragment = Backbone.history.getFragment();
            urlObject = Util.CloudcareUrl.fromJson(Util.encodedUrlToObject(currentFragment));
            encodedUrl = Util.objectToEncodedUrl(urlObject.toJson());
            FormplayerFrontend.navigate(encodedUrl);

            FormplayerFrontend.Menus.Controller.showMenu(menuCollection);
        },
    };
    API = SessionNavigate.Middleware.apply(API);

    FormplayerFrontend.on("apps:currentApp", function () {
        var urlObject = Util.currentUrlToObject();
        urlObject.clearExceptApp();
        Util.setUrlToObject(urlObject);
        API.selectApp(urlObject.appId);
    });

    FormplayerFrontend.on("apps:list", function () {
        FormplayerFrontend.navigate("apps");
        API.listApps();
    });

    FormplayerFrontend.on("app:select", function (appId) {
        var urlObject = new Util.CloudcareUrl({'appId': appId});
        Util.setUrlToObject(urlObject);
        API.selectApp(appId, true);
    });

    FormplayerFrontend.on('app:singleApp', function (appId) {
        FormplayerFrontend.navigate("/single_app/" + appId);
        API.singleApp(appId);
    });

    FormplayerFrontend.on('app:landingPageApp', function (appId) {
        FormplayerFrontend.navigate("/home/" + appId);
        API.landingPageApp(appId);
    });

    FormplayerFrontend.on("menu:select", function (index) {
        var urlObject = Util.currentUrlToObject();
        urlObject.addStep(index);
        Util.setUrlToObject(urlObject);
        API.listMenus();
    });

    FormplayerFrontend.on("menu:paginate", function (page) {
        var urlObject = Util.currentUrlToObject();
        urlObject.setPage(page);
        Util.setUrlToObject(urlObject);
        API.listMenus();
    });

    FormplayerFrontend.on("menu:sort", function (newSortIndex) {
        var urlObject = Util.currentUrlToObject();
        var currentSortIndex = urlObject.sortIndex;
        // If the column index is the same as already loaded, reverse the sort
        if (newSortIndex === Math.abs(currentSortIndex)) {
            newSortIndex = -1 * currentSortIndex;
        }
        urlObject.setSort(newSortIndex);
        Util.setUrlToObject(urlObject);
        API.listMenus();
    });

    FormplayerFrontend.on("menu:search", function (search) {
        var urlObject = Util.currentUrlToObject();
        urlObject.setSearch(search);
        Util.setUrlToObject(urlObject);
        API.listMenus();
    });

    FormplayerFrontend.on("menu:query", function (queryDict) {
        var urlObject = Util.currentUrlToObject();
        urlObject.setQuery(queryDict);
        Util.setUrlToObject(urlObject);
        API.listMenus();
    });

    FormplayerFrontend.on('restore_as:list', function () {
        FormplayerFrontend.navigate("/restore_as");
        API.listUsers();
    });

    FormplayerFrontend.on('settings:list', function () {
        FormplayerFrontend.navigate("/settings");
        API.listSettings();
    });

    FormplayerFrontend.on("menu:show:detail", function (caseId, detailTabIndex, isPersistent) {
        API.showDetail(caseId, detailTabIndex, isPersistent);
    });

    FormplayerFrontend.on("sessions", function () {
        FormplayerFrontend.navigate("/sessions");
        API.listSessions();
    });

    FormplayerFrontend.on("getSession", function (sessionId) {
        FormplayerFrontend.navigate("/sessions/" + sessionId);
        API.getSession(sessionId);
    });

    FormplayerFrontend.on("renderResponse", function (menuResponse) {
        API.renderResponse(menuResponse);
    });

    SessionNavigate.start = function () {
        return new SessionNavigate.Router({
            controller: API,
        });
    };

    FormplayerFrontend.on("breadcrumbSelect", function (index) {
        FormplayerFrontend.trigger("clearForm");
        var urlObject = Util.currentUrlToObject();
        urlObject.spliceSteps(index);
        Util.setUrlToObject(urlObject);
        var options = {
            'appId': urlObject.appId,
            'steps': urlObject.steps,
        };
        FormplayerFrontend.Menus.Controller.selectMenu(options);
    });

    FormplayerFrontend.on("localInstall", function (path) {
        var urlObject = new Util.CloudcareUrl({
            'installReference': path,
        });
        Util.setUrlToObject(urlObject);
        FormplayerFrontend.Menus.Controller.selectMenu(urlObject);
    });
});
<|endoftext|>


<commit_before>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
  	this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual("Mmmm soup!");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual("Everything's cool!");
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(2);
    expect(this.swedishChef.hobby).toEqual("cooking");
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual("chillin");
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
//  var g = new Gonzo(...);
//  g instanceOf Muppet //true

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
    this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(FILL_ME_IN);
    expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual(FILL_ME_IN);
  });
});
<commit_msg>Completed AboutInheritance.js: Completed describe "About Crockford's inheritance improvement" Object.prototype.beget = function () {   function F() {}   F.prototype = this;   return new F(); }<commit_after>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
  	this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual("Mmmm soup!");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual("Everything's cool!");
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(2);
    expect(this.swedishChef.hobby).toEqual("cooking");
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual("chillin");
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
//  var g = new Gonzo(...);
//  g instanceOf Muppet //true

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
    this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual("eat a tire");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual("Everything's cool!");
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(3);
    expect(this.gonzo.hobby).toEqual("daredevil performer");
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual("eat a tire");
  });
});
<|endoftext|>


<commit_before>const td              = require('testdouble');
const mockProject     = require('../../fixtures/corber-mock/project');
const path            = require('path');
const contains        = td.matchers.contains;

const initValidator = function() {
  const ValidateWebpack  = require('../../../lib/validators/webpack-plugin');
  return new ValidateWebpack();
};

describe('Validate Webpack Plugin', function() {
  let validator;
  let warnDouble;

  beforeEach(function() {
    let logDouble = td.replace('../../../lib/utils/logger');
    warnDouble = td.replace(logDouble, 'warn');
  });

  afterEach(function() {
    td.reset();
  });

  context('when framework is Vue', function() {
    beforeEach(function() {
      validator = initValidator();
      validator.framework = 'vue';
      validator.configPath = path.join(mockProject.project.root, 'vue.config.js');
    });

    context('when configureWebpack property missing', function () {
      beforeEach(function() {
        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './'
        }));
      });

      it('warns and resolves', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(contains('vue.config.js')));
          done();
        }).catch(done);
      });
    });

    context('when plugins property missing', function () {
      beforeEach(function() {
        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
          configureWebpack: {}
        }));
      });

      it('warns and resolves', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(contains('vue.config.js')));
          done();
        }).catch(done);
      });
    });

    context('when plugins property missing webpack plugin', function () {
      beforeEach(function() {
        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
          configureWebpack: {
            plugins: []
          }
        }));
      });

      it('warns and resolves', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(contains('vue.config.js')));
          done();
        }).catch(done);
      });
    });

    context('when plugins property includes webpack plugin', function () {
      beforeEach(function() {
        function CorberWebpackPlugin() {}

        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
          configureWebpack: {
            plugins: [new CorberWebpackPlugin()]
          }
        }));
      });

      it('resolves silently', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(), { times: 0, ignoreExtraArgs: true });
          done();
        }).catch(done);
      });
    });
  });

  context('when framework is other framework', function() {
    beforeEach(function() {
      validator = initValidator();
      validator.framework = 'react';
      validator.configPath = path.join(
        mockProject.project.root,
        'build',
        'webpack-with-plugin.dev.conf.js'
      );
    });

    context('when plugins property missing', function () {
      beforeEach(function() {
        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
        }));
      });

      it('warns and resolves', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(contains('config/webpack.config.dev.js')));
          done();
        }).catch(done);
      });
    });

    context('when plugins property missing webpack plugin', function () {
      beforeEach(function() {
        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
          plugins: []
        }));
      });

      it('warns and resolves', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(contains('config/webpack.config.dev.js')));
          done();
        }).catch(done);
      });
    });

    context('when plugins property includes webpack plugin', function () {
      beforeEach(function() {
        function CorberWebpackPlugin() {}

        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
          plugins: [new CorberWebpackPlugin()]
        }));
      });

      it('resolves silently', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(), { times: 0, ignoreExtraArgs: true });
          done();
        }).catch(done);
      });
    });
  });
});

<commit_msg>feat(webpack-plugin): Update test to assert Vue CLI 2 support<commit_after>const td              = require('testdouble');
const mockProject     = require('../../fixtures/corber-mock/project');
const path            = require('path');
const contains        = td.matchers.contains;

const initValidator = function() {
  const ValidateWebpack  = require('../../../lib/validators/webpack-plugin');
  return new ValidateWebpack();
};

describe('Validate Webpack Plugin', function() {
  let validator;
  let warnDouble;

  beforeEach(function() {
    let logDouble = td.replace('../../../lib/utils/logger');
    warnDouble = td.replace(logDouble, 'warn');
  });

  afterEach(function() {
    td.reset();
  });

  context('when config path from Vue CLI v3', function() {
    beforeEach(function() {
      validator = initValidator();
      validator.root = mockProject.project.root;
      validator.framework = 'vue';
      validator.configPath = path.join(mockProject.project.root, 'vue.config.js');
    });

    context('when configureWebpack property missing', function () {
      beforeEach(function() {
        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './'
        }));
      });

      it('warns and resolves', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(contains('vue.config.js')));
          done();
        }).catch(done);
      });
    });

    context('when plugins property missing', function () {
      beforeEach(function() {
        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
          configureWebpack: {}
        }));
      });

      it('warns and resolves', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(contains('vue.config.js')));
          done();
        }).catch(done);
      });
    });

    context('when plugins property missing webpack plugin', function () {
      beforeEach(function() {
        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
          configureWebpack: {
            plugins: []
          }
        }));
      });

      it('warns and resolves', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(contains('vue.config.js')));
          done();
        }).catch(done);
      });
    });

    context('when plugins property includes webpack plugin', function () {
      beforeEach(function() {
        function CorberWebpackPlugin() {}

        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
          configureWebpack: {
            plugins: [new CorberWebpackPlugin()]
          }
        }));
      });

      it('resolves silently', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(), { times: 0, ignoreExtraArgs: true });
          done();
        }).catch(done);
      });
    });
  });

  context('when config path from Vue CLI v2', function() {
    beforeEach(function() {
      validator = initValidator();
      validator.root = mockProject.project.root;
      validator.framework = 'vue';
      validator.configPath = path.join(
        mockProject.project.root,
        'build',
        'webpack.dev.conf'
      );
    });

    context('when plugins property missing', function () {
      beforeEach(function() {
        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
        }));
      });

      it('warns and resolves', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(contains('build/webpack.dev.conf')));
          done();
        }).catch(done);
      });
    });

    context('when plugins property missing webpack plugin', function () {
      beforeEach(function() {
        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
          plugins: []
        }));
      });

      it('warns and resolves', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(contains('build/webpack.dev.conf')));
          done();
        }).catch(done);
      });
    });

    context('when plugins property includes webpack plugin', function () {
      beforeEach(function() {
        function CorberWebpackPlugin() {}

        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
          plugins: [new CorberWebpackPlugin()]
        }));
      });

      it('resolves silently', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(), { times: 0, ignoreExtraArgs: true });
          done();
        }).catch(done);
      });
    });
  });

  context('when config path is not from Vue CLI', function() {
    beforeEach(function() {
      validator = initValidator();
      validator.root = mockProject.project.root;
      validator.framework = 'react';
      validator.configPath = path.join(
        mockProject.project.root,
        'config',
        'webpack.config.dev.js'
      );
    });

    context('when plugins property missing', function () {
      beforeEach(function() {
        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
        }));
      });

      it('warns and resolves', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(contains('config/webpack.config.dev.js')));
          done();
        }).catch(done);
      });
    });

    context('when plugins property missing webpack plugin', function () {
      beforeEach(function() {
        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
          plugins: []
        }));
      });

      it('warns and resolves', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(contains('config/webpack.config.dev.js')));
          done();
        }).catch(done);
      });
    });

    context('when plugins property includes webpack plugin', function () {
      beforeEach(function() {
        function CorberWebpackPlugin() {}

        td.replace(validator, 'getConfig', () => new Object({
          baseUrl: './',
          plugins: [new CorberWebpackPlugin()]
        }));
      });

      it('resolves silently', function(done) {
        validator.run().then(function() {
          td.verify(warnDouble(), { times: 0, ignoreExtraArgs: true });
          done();
        }).catch(done);
      });
    });
  });
});

<|endoftext|>


<commit_before>var Operator = new function() {
	var operators = {
		add: '+', subtract: '-', multiply: '*', divide: '/', equals: '==',
		modulo: '%'
	};
	var operatorNames = {
		add: 'Addition', subtract: 'Subtraction', multiply: 'Multiplication',
		divide: 'Division', equals: 'Comparison', modulo: 'Modulo'
	};

	var operatorClasses = {
		Point: true,
		Size: true
	};

	return {
		isOperator: function(symbol) {
			// As a convention, only add non static bean properties to
			// the documentation. static properties are all supposed to
			// be uppercae and constants.
			if (symbol.operator == 'none')
				print(!(symbol.operator && symbol.operator != 'none'));
			return symbol.params.length == 1 && !symbol.isStatic && (
					/^(add|subtract|multiply|divide|modulo)(\^[0-9])*$/.test(symbol.name)
					&& (symbol.operator != 'none')
				) || ( // equals
					symbol.name == 'equals'
					&& symbol.returns.length && symbol.returns[0].type == 'boolean'
				);
		},

		getOperator: function(symbol) {
			return operators[symbol.name.replace(/\^[0-9]$/,'')];
		}
	}
}

var Helpers = {
	getSymbolId: function(symbol) {
		var id = [symbol.name.toLowerCase().replace(/[\^][0-9]/g, '')];
		if (symbol.params) {
			for (var i = 0, l = symbol.params.length; i < l; i++) {
				var param = symbol.params[i];
				if (!param.isOptional)
					id.push(param.name);
			}
		}
		return id.join('-');
	}
};

var templates;
/** Called automatically by JsDoc Toolkit. */
function publish(symbolSet) {
	publish.conf = {  // trailing slash expected for dirs
		ext:		 ".html",
		outDir:	  JSDOC.opt.d || SYS.pwd+"../out/jsdoc/",
		templatesDir: JSDOC.opt.t || SYS.pwd+"../templates/jsdoc/",
		symbolsDir:  "symbols/",
		srcDir:	  "symbols/src/"
	};

	templates = {
		_class: new JSDOC.JsPlate(publish.conf.templatesDir + "class.tmpl"),
		method: new JSDOC.JsPlate(publish.conf.templatesDir + "method.tmpl"),
		property: new JSDOC.JsPlate(publish.conf.templatesDir + "property.tmpl"),
		parameters: new JSDOC.JsPlate(publish.conf.templatesDir + "parameters.tmpl"),
		operators: new JSDOC.JsPlate(publish.conf.templatesDir + "operators.tmpl"),
		examples: new JSDOC.JsPlate(publish.conf.templatesDir + "examples.tmpl")
	};

	// is source output is suppressed, just display the links to the source file
	if (JSDOC.opt.s && defined(Link) && Link.prototype._makeSrcLink) {
		Link.prototype._makeSrcLink = function(srcFilePath) {
			return "<"+srcFilePath+">";
		}
	}

	// Copy over the static files
	copyDirectory(
		new java.io.File(publish.conf.templatesDir + 'resources/'),
		new java.io.File(publish.conf.outDir + 'resources/')
	);

	// used to allow Link to check the details of things being linked to
	Link.symbolSet = symbolSet;

	// create the required templates
	try {
		var classTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"class.tmpl");
		var classesTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allclasses.tmpl");
	}
	catch(e) {
		print("Couldn't create the required templates: "+e);
		quit();
	}

	// some ustility filters
	function hasNoParent($) {return ($.memberOf == "")}
	function isaFile($) {return ($.is("FILE"))}
	function isaClass($) {return ($.is("CONSTRUCTOR") || $.isNamespace)}

	// get an array version of the symbolset, useful for filtering
	var symbols = symbolSet.toArray();

	// create the hilited source code files
	var files = JSDOC.opt.srcFiles;
	 	for (var i = 0, l = files.length; i < l; i++) {
	 		var file = files[i];
	 		var srcDir = publish.conf.outDir + "symbols/src/";
		makeSrcFile(file, srcDir);
	 	}

 	// get a list of all the classes in the symbolset
 	var classes = symbols.filter(isaClass).sort(makeSortby("alias"));

	// create a filemap in which outfiles must be to be named uniquely, ignoring case
	if (JSDOC.opt.u) {
		var filemapCounts = {};
		Link.filemap = {};
		for (var i = 0, l = classes.length; i < l; i++) {
			var lcAlias = classes[i].alias.toLowerCase();

			if (!filemapCounts[lcAlias]) filemapCounts[lcAlias] = 1;
			else filemapCounts[lcAlias]++;

			Link.filemap[classes[i].alias] =
				(filemapCounts[lcAlias] > 1)?
				lcAlias+"_"+filemapCounts[lcAlias] : lcAlias;
		}
	}

	// create a class index, displayed in the left-hand column of every class page
	Link.base = "../";
 	publish.classesIndex = classesTemplate.process(classes); // kept in memory

	// create each of the class pages
	for (var i = 0, l = classes.length; i < l; i++) {
		var symbol = classes[i];

		symbol.events = symbol.getEvents();   // 1 order matters
		symbol.methods = symbol.getMethods(); // 2
		for (var j = 0; j < symbol.methods.length; j++) {
			var method = symbol.methods[j];
			method.isOperator = Operator.isOperator(method);
		}

		Link.currentSymbol= symbol;
		var output = "";
		output = classTemplate.process(symbol);

		IO.saveFile(publish.conf.outDir+"symbols/", ((JSDOC.opt.u)? Link.filemap[symbol.alias] : symbol.alias) + publish.conf.ext, output);
	}

	// regenerate the index with different relative links, used in the index pages
	Link.base = "";
	publish.classesIndex = classesTemplate.process(classes);

	// create the class index page
	try {
		var classesindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"index.tmpl");
	}
	catch(e) { print(e.message); quit(); }

	var classesIndex = classesindexTemplate.process(classes);
	IO.saveFile(publish.conf.outDir, "index"+publish.conf.ext, classesIndex);
	classesindexTemplate = classesIndex = classes = null;

	// create the file index page
	try {
		var fileindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allfiles.tmpl");
	}
	catch(e) { print(e.message); quit(); }

	var documentedFiles = symbols.filter(isaFile); // files that have file-level docs
	var allFiles = []; // not all files have file-level docs, but we need to list every one

	for (var i = 0; i < files.length; i++) {
		allFiles.push(new JSDOC.Symbol(files[i], [], "FILE", new JSDOC.DocComment("/** */")));
	}

	for (var i = 0; i < documentedFiles.length; i++) {
		var offset = files.indexOf(documentedFiles[i].alias);
		allFiles[offset] = documentedFiles[i];
	}

	allFiles = allFiles.sort(makeSortby("name"));

	// output the file index page
	var filesIndex = fileindexTemplate.process(allFiles);
	IO.saveFile(publish.conf.outDir, "files"+publish.conf.ext, filesIndex);
	fileindexTemplate = filesIndex = files = null;
}

/** Just the first sentence (up to a full stop). Should not break on dotted variable names. */
function summarize(desc) {
	if (typeof desc != "undefined")
		return desc.match(/([\w\W]+?\.)[^a-z0-9_$]/i)? RegExp.$1 : desc;
}

/** Make a symbol sorter by some attribute. */
function makeSortby(attribute) {
	return function(a, b) {
		if (a[attribute] != undefined && b[attribute] != undefined) {
			a = a[attribute].toLowerCase();
			b = b[attribute].toLowerCase();
			if (a  b) return 1;
			return 0;
		}
	}
}

/** Pull in the contents of an external file at the given path. */
function include(path) {
	var path = publish.conf.templatesDir+path;
	return IO.readFile(path);
}

/** Turn a raw source file into a code-hilited page in the docs. */
function makeSrcFile(path, srcDir, name) {
	if (JSDOC.opt.s) return;

	if (!name) {
		name = path.replace(/\.\.?[\\\/]/g, "").replace(/[\\\/]/g, "_");
		name = name.replace(/\:/g, "_");
	}

	var src = {path: path, name:name, charset: IO.encoding, hilited: ""};

	if (defined(JSDOC.PluginManager)) {
		JSDOC.PluginManager.run("onPublishSrc", src);
	}

	if (src.hilited) {
		IO.saveFile(srcDir, name+publish.conf.ext, src.hilited);
	}
}

/** Build output for displaying function parameters. */
function makeSignature(params) {
	if (!params) return "()";
	var postString = '';
	var first = true;
	params = params.filter(
		function($) {
			return $.name.indexOf(".") == -1; // don't show config params in signature
		}
	);
	var signature = '';
	var postSignature = '';
	for (var i = 0, l = params.length; i < l; i++) {
		var param = params[i];
		if (param.isOptional) {
			signature += '[';
			postSignature += ']';
		}
		if (i > 0)
			signature += ', ';
		signature += param.name;
	}
	return '(' + signature + postSignature + ')';
}

function processGroupTitle(str, symbol) {
	// if (/grouptitle/.test(str))
	// 	print('yeah');
	// print(str);
	var groupTitle = str.match(/\{@grouptitle ([^}]+)\}/);
	if (groupTitle) {
		symbol.groupTitle = groupTitle[1];
		str = str.replace(/\{@grouptitle ([^}]+)\}/, '');
	}
	return str;
}

function processInlineTags(str, param) {
	if (!param)
		param = {};
	// .. ->
..

	str = str.replace(/<(\/)*(code)>/g, '<$1pre>');

	// {@link ...} -> html links
	str = str.replace(/\{@link ([^} ]+) ?\}/gi,
		function(match, symbolName) {
			return new Link().toSymbol(symbolName.replace(/[\^]/g, '-'));
		}
	);
	// {@code ...} -> code blocks
	str = str.replace(/\{@code[\s]([^}]+)\}/gi,
		function(match, code) {
			return '<tt>' + code + '</tt>';
		}
	);

	var lineBreak = java.lang.System.getProperty('line.separator');

	// Convert any type of lineBreak to the one we're using now:
	str = str.replace(/(\r\n|\n|\r)/g, function(match, lineBreak) {
		return lineBreak;
	});

	// Replace inline  with <tt></tt>
	str = str.replace(/[ \t]*([^\n\r]*?)[ \t]*<\/code>/g, function(match, content) {
		return '<tt>' + content + '</tt>';
	});

	// Put code and pre tags on the same line as the content, as white-space: pre is set:
	str = str.replace(/(<(?:code|pre)>)\s*([\u0000-\uffff]*?)\s*(<\/(?:code|pre)>)/g, function(match, open, content, close) {
		// Filter out the first white space at the beginning of each line, since
		// that stems from the space after the * in the comment and replace
		// with
, to fix a IE problem where lighter.js does not receive
		// linebreaks from code tags weven when white-space: pre is set.
		return '
' + content.replace(/(\r\n|\n|\r) /mg, function(match, lineBreak) {
			return lineBreak;
		}) + '
';
	});
	// Empty lines -> Paragraphs
	if (!param.stripParagraphs) {
		if (param.wrapInParagraphs === undefined || param.wrapInParagraphs)
			str = '
' + str.trim() + '
';
		str = str.trim().replace(/(\r\n|\n|\r)\s*(\r\n|\n|\r)/g, function(match, lineBreak) {
			return '
' + lineBreak + '
';
		});
		// Automatically put

 at the end of sentences with line breaks.
		// Match following
 and
 tags and swallow them. This happens when
		// the original content contains these.
		str = str.trim().replace(/([.:?!;])\s*(\r\n|\n|\r)(\s*)(<\/p>|
|)/g, function(match, before, lineBreak, whiteSpace, after) {
			// Include following whiteSpace as well, since for code blocks they are relevant (e.g. indentation on new line)
			return before + '
' + lineBreak + whiteSpace + '
';
		});
		// Filter out
 tags within and around  and
 blocks again
		str = str.replace(/((?:
\s*|)<(?:code|pre)[^>]*>[\u0000-\uffff]*<\/(?:code|pre)>(?:\s*<\/p>|))/g, function(match, code) {
			return stripTags(code, 'p');
		});
		// Filter out empty paragraphs
		str = str.replace(/
<\/p>/g, '');
	}

	return str;
}

function stripTags(str, tag) {
	var tag = tag || '.*?'; // Default: all tags
	return str.replace(new RegExp('<' + tag + '>|</' + tag + '>', 'g'), '');
}

function copyStatic(dir) {
	var dir = publish.conf.templatesDir + 'resources/';

}

function copyDirectory(sourceLocation, targetLocation) {
	if (sourceLocation.isDirectory()) {
		if (!targetLocation.exists()) {
			targetLocation.mkdir();
		}

		var children = sourceLocation.list();
		for (var i = 0; i < children.length; i++) {
			copyDirectory(new File(sourceLocation, children[i]),
					new File(targetLocation, children[i]));
		}
	} else {
		// Copy the file with FileChannels:
		targetLocation.createNewFile();
		var src = new java.io.FileInputStream(sourceLocation).getChannel();
		var dst = new java.io.FileOutputStream(targetLocation).getChannel();
		var amount = dst.transferFrom(src, 0, src.size());
		src.close();
		dst.close();
	}
}<commit_msg>jsdoc: support @true tag.<commit_after>var Operator = new function() {
	var operators = {
		add: '+', subtract: '-', multiply: '*', divide: '/', equals: '==',
		modulo: '%'
	};
	var operatorNames = {
		add: 'Addition', subtract: 'Subtraction', multiply: 'Multiplication',
		divide: 'Division', equals: 'Comparison', modulo: 'Modulo'
	};

	var operatorClasses = {
		Point: true,
		Size: true
	};

	return {
		isOperator: function(symbol) {
			// As a convention, only add non static bean properties to
			// the documentation. static properties are all supposed to
			// be uppercae and constants.
			if (symbol.operator == 'none')
				print(!(symbol.operator && symbol.operator != 'none'));
			return symbol.params.length == 1 && !symbol.isStatic && (
					/^(add|subtract|multiply|divide|modulo)(\^[0-9])*$/.test(symbol.name)
					&& (symbol.operator != 'none')
				) || ( // equals
					symbol.name == 'equals'
					&& symbol.returns.length && symbol.returns[0].type == 'boolean'
				);
		},

		getOperator: function(symbol) {
			return operators[symbol.name.replace(/\^[0-9]$/,'')];
		}
	}
}

var Helpers = {
	getSymbolId: function(symbol) {
		var id = [symbol.name.toLowerCase().replace(/[\^][0-9]/g, '')];
		if (symbol.params) {
			for (var i = 0, l = symbol.params.length; i < l; i++) {
				var param = symbol.params[i];
				if (!param.isOptional)
					id.push(param.name);
			}
		}
		return id.join('-');
	}
};

var templates;
/** Called automatically by JsDoc Toolkit. */
function publish(symbolSet) {
	publish.conf = {  // trailing slash expected for dirs
		ext:		 ".html",
		outDir:	  JSDOC.opt.d || SYS.pwd+"../out/jsdoc/",
		templatesDir: JSDOC.opt.t || SYS.pwd+"../templates/jsdoc/",
		symbolsDir:  "symbols/",
		srcDir:	  "symbols/src/"
	};

	templates = {
		_class: new JSDOC.JsPlate(publish.conf.templatesDir + "class.tmpl"),
		method: new JSDOC.JsPlate(publish.conf.templatesDir + "method.tmpl"),
		property: new JSDOC.JsPlate(publish.conf.templatesDir + "property.tmpl"),
		parameters: new JSDOC.JsPlate(publish.conf.templatesDir + "parameters.tmpl"),
		operators: new JSDOC.JsPlate(publish.conf.templatesDir + "operators.tmpl"),
		examples: new JSDOC.JsPlate(publish.conf.templatesDir + "examples.tmpl")
	};

	// is source output is suppressed, just display the links to the source file
	if (JSDOC.opt.s && defined(Link) && Link.prototype._makeSrcLink) {
		Link.prototype._makeSrcLink = function(srcFilePath) {
			return "<"+srcFilePath+">";
		}
	}

	// Copy over the static files
	copyDirectory(
		new java.io.File(publish.conf.templatesDir + 'resources/'),
		new java.io.File(publish.conf.outDir + 'resources/')
	);

	// used to allow Link to check the details of things being linked to
	Link.symbolSet = symbolSet;

	// create the required templates
	try {
		var classTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"class.tmpl");
		var classesTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allclasses.tmpl");
	}
	catch(e) {
		print("Couldn't create the required templates: "+e);
		quit();
	}

	// some ustility filters
	function hasNoParent($) {return ($.memberOf == "")}
	function isaFile($) {return ($.is("FILE"))}
	function isaClass($) {return ($.is("CONSTRUCTOR") || $.isNamespace)}

	// get an array version of the symbolset, useful for filtering
	var symbols = symbolSet.toArray();

	// create the hilited source code files
	var files = JSDOC.opt.srcFiles;
	 	for (var i = 0, l = files.length; i < l; i++) {
	 		var file = files[i];
	 		var srcDir = publish.conf.outDir + "symbols/src/";
		makeSrcFile(file, srcDir);
	 	}

 	// get a list of all the classes in the symbolset
 	var classes = symbols.filter(isaClass).sort(makeSortby("alias"));

	// create a filemap in which outfiles must be to be named uniquely, ignoring case
	if (JSDOC.opt.u) {
		var filemapCounts = {};
		Link.filemap = {};
		for (var i = 0, l = classes.length; i < l; i++) {
			var lcAlias = classes[i].alias.toLowerCase();

			if (!filemapCounts[lcAlias]) filemapCounts[lcAlias] = 1;
			else filemapCounts[lcAlias]++;

			Link.filemap[classes[i].alias] =
				(filemapCounts[lcAlias] > 1)?
				lcAlias+"_"+filemapCounts[lcAlias] : lcAlias;
		}
	}

	// create a class index, displayed in the left-hand column of every class page
	Link.base = "../";
 	publish.classesIndex = classesTemplate.process(classes); // kept in memory

	// create each of the class pages
	for (var i = 0, l = classes.length; i < l; i++) {
		var symbol = classes[i];

		symbol.events = symbol.getEvents();   // 1 order matters
		symbol.methods = symbol.getMethods(); // 2
		for (var j = 0; j < symbol.methods.length; j++) {
			var method = symbol.methods[j];
			method.isOperator = Operator.isOperator(method);
		}

		Link.currentSymbol= symbol;
		var output = "";
		output = classTemplate.process(symbol);

		IO.saveFile(publish.conf.outDir+"symbols/", ((JSDOC.opt.u)? Link.filemap[symbol.alias] : symbol.alias) + publish.conf.ext, output);
	}

	// regenerate the index with different relative links, used in the index pages
	Link.base = "";
	publish.classesIndex = classesTemplate.process(classes);

	// create the class index page
	try {
		var classesindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"index.tmpl");
	}
	catch(e) { print(e.message); quit(); }

	var classesIndex = classesindexTemplate.process(classes);
	IO.saveFile(publish.conf.outDir, "index"+publish.conf.ext, classesIndex);
	classesindexTemplate = classesIndex = classes = null;

	// create the file index page
	try {
		var fileindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allfiles.tmpl");
	}
	catch(e) { print(e.message); quit(); }

	var documentedFiles = symbols.filter(isaFile); // files that have file-level docs
	var allFiles = []; // not all files have file-level docs, but we need to list every one

	for (var i = 0; i < files.length; i++) {
		allFiles.push(new JSDOC.Symbol(files[i], [], "FILE", new JSDOC.DocComment("/** */")));
	}

	for (var i = 0; i < documentedFiles.length; i++) {
		var offset = files.indexOf(documentedFiles[i].alias);
		allFiles[offset] = documentedFiles[i];
	}

	allFiles = allFiles.sort(makeSortby("name"));

	// output the file index page
	var filesIndex = fileindexTemplate.process(allFiles);
	IO.saveFile(publish.conf.outDir, "files"+publish.conf.ext, filesIndex);
	fileindexTemplate = filesIndex = files = null;
}

/** Just the first sentence (up to a full stop). Should not break on dotted variable names. */
function summarize(desc) {
	if (typeof desc != "undefined")
		return desc.match(/([\w\W]+?\.)[^a-z0-9_$]/i)? RegExp.$1 : desc;
}

/** Make a symbol sorter by some attribute. */
function makeSortby(attribute) {
	return function(a, b) {
		if (a[attribute] != undefined && b[attribute] != undefined) {
			a = a[attribute].toLowerCase();
			b = b[attribute].toLowerCase();
			if (a  b) return 1;
			return 0;
		}
	}
}

/** Pull in the contents of an external file at the given path. */
function include(path) {
	var path = publish.conf.templatesDir+path;
	return IO.readFile(path);
}

/** Turn a raw source file into a code-hilited page in the docs. */
function makeSrcFile(path, srcDir, name) {
	if (JSDOC.opt.s) return;

	if (!name) {
		name = path.replace(/\.\.?[\\\/]/g, "").replace(/[\\\/]/g, "_");
		name = name.replace(/\:/g, "_");
	}

	var src = {path: path, name:name, charset: IO.encoding, hilited: ""};

	if (defined(JSDOC.PluginManager)) {
		JSDOC.PluginManager.run("onPublishSrc", src);
	}

	if (src.hilited) {
		IO.saveFile(srcDir, name+publish.conf.ext, src.hilited);
	}
}

/** Build output for displaying function parameters. */
function makeSignature(params) {
	if (!params) return "()";
	var postString = '';
	var first = true;
	params = params.filter(
		function($) {
			return $.name.indexOf(".") == -1; // don't show config params in signature
		}
	);
	var signature = '';
	var postSignature = '';
	for (var i = 0, l = params.length; i < l; i++) {
		var param = params[i];
		if (param.isOptional) {
			signature += '[';
			postSignature += ']';
		}
		if (i > 0)
			signature += ', ';
		signature += param.name;
	}
	return '(' + signature + postSignature + ')';
}

function processGroupTitle(str, symbol) {
	// if (/grouptitle/.test(str))
	// 	print('yeah');
	// print(str);
	var groupTitle = str.match(/\{@grouptitle ([^}]+)\}/);
	if (groupTitle) {
		symbol.groupTitle = groupTitle[1];
		str = str.replace(/\{@grouptitle ([^}]+)\}/, '');
	}
	return str;
}

function processInlineTags(str, param) {
	if (!param)
		param = {};
	// .. ->
..

	str = str.replace(/<(\/)*(code)>/g, '<$1pre>');

	// {@link ...} -> html links
	str = str.replace(/\{@link ([^} ]+) ?\}/gi,
		function(match, symbolName) {
			return new Link().toSymbol(symbolName.replace(/[\^]/g, '-'));
		}
	);
	// {@code ...} -> code blocks
	str = str.replace(/\{@code[\s]([^}]+)\}/gi,
		function(match, code) {
			return '<tt>' + code + '</tt>';
		}
	);

	// {@true ...} -> true if.. false otherwise..
	str = str.replace(/\{@true[\s]([^}]+)\}/gi,
		function(match, text) {
			return '<tt>true</tt> ' + text + ', <tt>false</tt> otherwise';
		}
	);

	var lineBreak = java.lang.System.getProperty('line.separator');

	// Convert any type of lineBreak to the one we're using now:
	str = str.replace(/(\r\n|\n|\r)/g, function(match, lineBreak) {
		return lineBreak;
	});

	// Replace inline  with <tt></tt>
	str = str.replace(/[ \t]*([^\n\r]*?)[ \t]*<\/code>/g, function(match, content) {
		return '<tt>' + content + '</tt>';
	});

	// Put code and pre tags on the same line as the content, as white-space: pre is set:
	str = str.replace(/(<(?:code|pre)>)\s*([\u0000-\uffff]*?)\s*(<\/(?:code|pre)>)/g, function(match, open, content, close) {
		// Filter out the first white space at the beginning of each line, since
		// that stems from the space after the * in the comment and replace
		// with
, to fix a IE problem where lighter.js does not receive
		// linebreaks from code tags weven when white-space: pre is set.
		return '
' + content.replace(/(\r\n|\n|\r) /mg, function(match, lineBreak) {
			return lineBreak;
		}) + '
';
	});
	// Empty lines -> Paragraphs
	if (!param.stripParagraphs) {
		if (param.wrapInParagraphs === undefined || param.wrapInParagraphs)
			str = '
' + str.trim() + '
';
		str = str.trim().replace(/(\r\n|\n|\r)\s*(\r\n|\n|\r)/g, function(match, lineBreak) {
			return '
' + lineBreak + '
';
		});
		// Automatically put

 at the end of sentences with line breaks.
		// Match following
 and
 tags and swallow them. This happens when
		// the original content contains these.
		str = str.trim().replace(/([.:?!;])\s*(\r\n|\n|\r)(\s*)(<\/p>|
|)/g, function(match, before, lineBreak, whiteSpace, after) {
			// Include following whiteSpace as well, since for code blocks they are relevant (e.g. indentation on new line)
			return before + '
' + lineBreak + whiteSpace + '
';
		});
		// Filter out
 tags within and around  and
 blocks again
		str = str.replace(/((?:
\s*|)<(?:code|pre)[^>]*>[\u0000-\uffff]*<\/(?:code|pre)>(?:\s*<\/p>|))/g, function(match, code) {
			return stripTags(code, 'p');
		});
		// Filter out empty paragraphs
		str = str.replace(/
<\/p>/g, '');
	}

	return str;
}

function stripTags(str, tag) {
	var tag = tag || '.*?'; // Default: all tags
	return str.replace(new RegExp('<' + tag + '>|</' + tag + '>', 'g'), '');
}

function copyStatic(dir) {
	var dir = publish.conf.templatesDir + 'resources/';

}

function copyDirectory(sourceLocation, targetLocation) {
	if (sourceLocation.isDirectory()) {
		if (!targetLocation.exists()) {
			targetLocation.mkdir();
		}

		var children = sourceLocation.list();
		for (var i = 0; i < children.length; i++) {
			copyDirectory(new File(sourceLocation, children[i]),
					new File(targetLocation, children[i]));
		}
	} else {
		// Copy the file with FileChannels:
		targetLocation.createNewFile();
		var src = new java.io.FileInputStream(sourceLocation).getChannel();
		var dst = new java.io.FileOutputStream(targetLocation).getChannel();
		var amount = dst.transferFrom(src, 0, src.size());
		src.close();
		dst.close();
	}
}<|endoftext|>


<commit_before>var SudokuCell = React.createClass({
  render: function(){
    return(

        {this.props.cellValue}

    );
  }
});

var SudokuRow = React.createClass({
  render: function(){
    var values = this.props.rowData.map(function(value){
      return(
        <SudokuCell cellValue={ value }/>
      );
    });

    return(

        {values}

    );
  }
});

var SudokuBox = React.createClass({
  getInitialState: function() {
    var board = SudokuBoard.create("000000000000000000123456789000000000050000500000000000000000000000000000000000000");
    return { data: board.values() };
  },
  render: function() {
    var rows = [];
    for(i = 0; i < 9; i++){
      rows.push(
        <SudokuRow rowIndex={i} rowData={this.state.data[i]}/>
      );
    }
    return (

          {rows}

    );
  }
});

React.render(
  <SudokuBox />,
  document.getElementById('content')
);
<commit_msg>User can now change the value in a cell<commit_after>var SudokuCell = React.createClass({
  render: function(){
    return(

       <input id={this.props.cellId} value={this.props.cellValue} onChange={this.props.onChange}/>

    );
  }
});

var SudokuRow = React.createClass({
  render: function(){
    var row = this.props.rowIndex;
    var onChange = this.props.onChange;
    var values = this.props.rowData.map(function(value, column){
      return(
        <SudokuCell cellValue={ value } cellId={"cell-" + row + column} onChange={onChange}/>
      );
    });

    return(

        {values}

    );
  }
});

var SudokuBox = React.createClass({
  getInitialState: function() {
    var board = SudokuBoard.create("000000000000000000123456789000000000050000500000000000000000000000000000000000000");
    return { data: board };
  },
  cellChange: function(event){
    var chars = event.target.id.split("");
    var row = parseInt(chars[5]);
    var col = parseInt(chars[6]);
    var board = this.state.data;

    board.changeValue(row, col, parseInt(event.target.value));
    this.setState({ data: board });
  },
  render: function() {
    var rows = [];
    for(i = 0; i < 9; i++){
      rows.push(
        <SudokuRow rowIndex={i} rowData={this.state.data.values()[i]} onChange={this.cellChange}/>
      );
    }
    return (

          {rows}

    );
  }
});

React.render(
  <SudokuBox />,
  document.getElementById('content')
);
<|endoftext|>


<commit_before>const Client       = require('../../../base/client');
const BinarySocket = require('../../../base/socket');
const localize     = require('../../../../_common/localize').localize;
const State        = require('../../../../_common/storage').State;

const Settings = (() => {
    const onLoad = () => {
        BinarySocket.wait('get_account_status').then(() => {
            $('.real').setVisibility(!Client.get('is_virtual'));

            const status = State.getResponse('get_account_status.status') || [];

            if (!/social_signup/.test(status)) {
                $('#change_password').setVisibility(1);
            }

            // Professional Client menu should only be shown to maltainvest accounts.
            if ((Client.get('landing_company_shortcode') === 'maltainvest')) {
                const is_professional_client    = status.indexOf('professional') !== -1;
                const is_requested_professional = /professional_requested/.test(status);
                let localized_text = '';
                if (is_professional_client) {
                    localized_text = localize('You are categorised as a professional client.');
                } else if (is_requested_professional) {
                    localized_text = localize('Your application to be treated as a professional client is being processed.');
                } else { // is retail client
                    localized_text = localize('You are categorised as a retail client. Apply to be treated as a professional trader.');
                }
                $('#professional_client').setVisibility(1).find('p').text(localized_text);
            }

            $('#settings_container').setVisibility(1);
        });
    };

    return {
        onLoad,
    };
})();

module.exports = Settings;
<commit_msg>Added alert for svg accout authentication<commit_after>const Client       = require('../../../base/client');
const BinarySocket = require('../../../base/socket');
const Dialog       = require('../../../common/attach_dom/dialog');
const localize     = require('../../../../_common/localize').localize;
const State        = require('../../../../_common/storage').State;

const Settings = (() => {
    const onLoad = () => {
        BinarySocket.wait('get_account_status').then(() => {
            $('.real').setVisibility(!Client.get('is_virtual'));

            const status = State.getResponse('get_account_status.status') || [];

            if (!/social_signup/.test(status)) {
                $('#change_password').setVisibility(1);
            }

            // Disabling Authentication button for SVG accounts
            if ((Client.get('landing_company_shortcode') === 'svg')) {
                $('#authenticate a')
                    .attr('href', '#')
                    .on('click',  () => {
                        Dialog.alert({
                            id               : 'authorize_svg_error',
                            localized_message: localize('You do not need to authenticate your account at this time.[_1]We will inform you when your account needs to be authenticated.', '<br />'),
                            localized_title  : localize('No authentication required'),
                            ok_text          : localize('Back to trading'),
                        });
                    });
            }

            // Professional Client menu should only be shown to maltainvest accounts.
            if ((Client.get('landing_company_shortcode') === 'maltainvest')) {
                const is_professional_client    = status.indexOf('professional') !== -1;
                const is_requested_professional = /professional_requested/.test(status);
                let localized_text = '';
                if (is_professional_client) {
                    localized_text = localize('You are categorised as a professional client.');
                } else if (is_requested_professional) {
                    localized_text = localize('Your application to be treated as a professional client is being processed.');
                } else { // is retail client
                    localized_text = localize('You are categorised as a retail client. Apply to be treated as a professional trader.');
                }
                $('#professional_client').setVisibility(1).find('p').text(localized_text);
            }

            $('#settings_container').setVisibility(1);
        });
    };

    return {
        onLoad,
    };
})();

module.exports = Settings;
<|endoftext|>