<commit_before>const fs = require("fs");
const path = require("path");
const mkdirp = require("mkdirp");
const tmp = require("tmp");
const util = require("util");

const rollup = require("rollup");
const svelte = require("rollup-plugin-svelte");
const resolve = require("rollup-plugin-node-resolve");
const commonjs = require("rollup-plugin-commonjs");
const { terser } = require("rollup-plugin-terser");

const Handlebars = require("handlebars");

const mkdirpAsync = util.promisify(mkdirp);
const readFileAsync = util.promisify(fs.readFile);
const writeFileAsync = util.promisify(fs.writeFile);
const tmpFileAsync = util.promisify(tmp.file);

const { load: loadConfig } = require("./config");

const defaultHtmlConfig = { basePath: "/", playground: { enabled: false } };

const defaultTemplateDir = path.resolve(__dirname, "..", "..", "templates");

function templateFile(name) {
  if (name) {
    return path.resolve(process.cwd(), name);
  }

  return path.resolve(defaultTemplateDir, "winter.html");
}

async function writeTmp(data) {
  const tmpFile = await tmpFileAsync();
  await writeFileAsync(tmpFile, data, "utf8");
  return tmpFile;
}

function bundleName(output, suffix) {
  if (!output) {
    return;
  }

  if (output.endsWith(".html")) {
    return path.basename(output).replace(".html", suffix);
  } else {
    outputDir = path.resolve(output);
    return path.resolve(outputDir, `index${suffix}`);
  }
}

async function buildInputOptions(props, options) {
  const tplFile = templateFile(options.template);
  const tplSv = tplFile.replace(".html", ".svelte");

  const tplJs = `
import App from '${tplSv}';

const app = new App({
  target: document.body,
  props: ${JSON.stringify(props)}
});

export default app;
  `;

  const input = await writeTmp(tplJs);

  return {
    input: input,
    plugins: [
      svelte({
        css: css => {
          if (options.output && !options.output.endsWith(".html")) {
            css.write(bundleName(options.output, "-bundle.css"), false);
          }
        }
      }),
      resolve({ browser: true }),
      commonjs(),
      terser()
    ]
  };
}

async function buildOutputOptions(options) {
  const outputOptions = {
    format: "iife",
    name: "main"
  };

  if (options.output) {
    outputOptions.file = bundleName(options.output, "-bundle.js");

    if (!options.output.endsWith(".html")) {
      await mkdirpAsync(path.resolve(options.output));
    }
  }

  return outputOptions;
}

async function writeInline(bundle, options) {
  return await buildOutput(
    () => {
      return `<script>${bundle[0].code}</script>`;
    },
    () => "",
    options
  );
}

async function buildOutput(fn, fns, options) {
  const handlebars = Handlebars.create();
  handlebars.registerHelper("bundleScript", fn);
  handlebars.registerHelper("bundleStyle", fns);

  const tplFile = templateFile(options.template);
  const tplHtml = await readFileAsync(tplFile, "utf8");
  const template = handlebars.compile(tplHtml);

  return template({});
}

async function loadConfigFile(options) {
  const { html: htmlConfig = defaultHtmlConfig } = await loadConfig(
    options.config
  );

  if (options.playground) {
    htmlConfig.playground.enabled = true;
  }

  return htmlConfig;
}

function htmlBasePath(config) {
  if (config.basePath.endsWith("/")) {
    return config.basePath;
  } else {
    return config.basePath + "/";
  }
}

async function htmlBundle(result, options) {
  if (options.playground && !options.config) {
    throw new Error(
      "Playground mode requires a configuration file. You can pass `-c` flag."
    );
  }

  const htmlConfig = await loadConfigFile(options);

  const props = {
    title: result.title,
    description: result.description,
    version: result.version,
    servers: result.servers,
    tags: result.tags,
    actions: result.actions,
    tagActions: result.tagActions,
    config: htmlConfig
  };

  const inputOptions = await buildInputOptions(props, options);
  const outputOptions = await buildOutputOptions(options);

  const bundle = await rollup.rollup(inputOptions);

  const { output: bundleOutput } = await bundle.generate(outputOptions);

  if (!options.output) {
    return writeInline(bundleOutput, options);
  }

  if (options.output.endsWith(".html")) {
    const tplHtml = await writeInline(bundleOutput, options);
    await writeFileAsync(options.output, tplHtml, "utf8");
    return options.output;
  }

  await bundle.write(outputOptions);

  const bundlePath = path.basename(outputOptions.file);
  const bundleStyle = path.basename(bundleName(options.output, "-bundle.css"));
  const basePath = htmlBasePath(props.config);

  const tplHtml = await buildOutput(
    () => {
      return `<script src="${basePath}${bundlePath}"></script>`;
    },
    () => {
      return `<link rel="stylesheet" href="${basePath}${bundleStyle}" />`;
    },
    options
  );

  await writeFileAsync(
    path.resolve(path.dirname(outputOptions.file), "index.html"),
    tplHtml,
    "utf8"
  );

  return options.output;
}

module.exports = {
  htmlBundle
};
<commit_msg>mark basePath as optional<commit_after>const fs = require("fs");
const path = require("path");
const mkdirp = require("mkdirp");
const tmp = require("tmp");
const util = require("util");

const rollup = require("rollup");
const svelte = require("rollup-plugin-svelte");
const resolve = require("rollup-plugin-node-resolve");
const commonjs = require("rollup-plugin-commonjs");
const { terser } = require("rollup-plugin-terser");

const Handlebars = require("handlebars");

const mkdirpAsync = util.promisify(mkdirp);
const readFileAsync = util.promisify(fs.readFile);
const writeFileAsync = util.promisify(fs.writeFile);
const tmpFileAsync = util.promisify(tmp.file);

const { load: loadConfig } = require("./config");

const defaultHtmlConfig = { basePath: "/", playground: { enabled: false } };

const defaultTemplateDir = path.resolve(__dirname, "..", "..", "templates");

function templateFile(name) {
  if (name) {
    return path.resolve(process.cwd(), name);
  }

  return path.resolve(defaultTemplateDir, "winter.html");
}

async function writeTmp(data) {
  const tmpFile = await tmpFileAsync();
  await writeFileAsync(tmpFile, data, "utf8");
  return tmpFile;
}

function bundleName(output, suffix) {
  if (!output) {
    return;
  }

  if (output.endsWith(".html")) {
    return path.basename(output).replace(".html", suffix);
  } else {
    outputDir = path.resolve(output);
    return path.resolve(outputDir, `index${suffix}`);
  }
}

async function buildInputOptions(props, options) {
  const tplFile = templateFile(options.template);
  const tplSv = tplFile.replace(".html", ".svelte");

  const tplJs = `
import App from '${tplSv}';

const app = new App({
  target: document.body,
  props: ${JSON.stringify(props)}
});

export default app;
  `;

  const input = await writeTmp(tplJs);

  return {
    input: input,
    plugins: [
      svelte({
        css: css => {
          if (options.output && !options.output.endsWith(".html")) {
            css.write(bundleName(options.output, "-bundle.css"), false);
          }
        }
      }),
      resolve({ browser: true }),
      commonjs(),
      terser()
    ]
  };
}

async function buildOutputOptions(options) {
  const outputOptions = {
    format: "iife",
    name: "main"
  };

  if (options.output) {
    outputOptions.file = bundleName(options.output, "-bundle.js");

    if (!options.output.endsWith(".html")) {
      await mkdirpAsync(path.resolve(options.output));
    }
  }

  return outputOptions;
}

async function writeInline(bundle, options) {
  return await buildOutput(
    () => {
      return `<script>${bundle[0].code}</script>`;
    },
    () => "",
    options
  );
}

async function buildOutput(fn, fns, options) {
  const handlebars = Handlebars.create();
  handlebars.registerHelper("bundleScript", fn);
  handlebars.registerHelper("bundleStyle", fns);

  const tplFile = templateFile(options.template);
  const tplHtml = await readFileAsync(tplFile, "utf8");
  const template = handlebars.compile(tplHtml);

  return template({});
}

async function loadConfigFile(options) {
  const { html: htmlConfig = defaultHtmlConfig } = await loadConfig(
    options.config
  );

  if (options.playground) {
    htmlConfig.playground.enabled = true;
  }

  if (!options.basePath) {
    htmlConfig.basePath = "/";
  }

  return htmlConfig;
}

function htmlBasePath(config) {
  if (config.basePath.endsWith("/")) {
    return config.basePath;
  } else {
    return config.basePath + "/";
  }
}

async function htmlBundle(result, options) {
  if (options.playground && !options.config) {
    throw new Error(
      "Playground mode requires a configuration file. You can pass `-c` flag."
    );
  }

  const htmlConfig = await loadConfigFile(options);

  const props = {
    title: result.title,
    description: result.description,
    version: result.version,
    servers: result.servers,
    tags: result.tags,
    actions: result.actions,
    tagActions: result.tagActions,
    config: htmlConfig
  };

  const inputOptions = await buildInputOptions(props, options);
  const outputOptions = await buildOutputOptions(options);

  const bundle = await rollup.rollup(inputOptions);

  const { output: bundleOutput } = await bundle.generate(outputOptions);

  if (!options.output) {
    return writeInline(bundleOutput, options);
  }

  if (options.output.endsWith(".html")) {
    const tplHtml = await writeInline(bundleOutput, options);
    await writeFileAsync(options.output, tplHtml, "utf8");
    return options.output;
  }

  await bundle.write(outputOptions);

  const bundlePath = path.basename(outputOptions.file);
  const bundleStyle = path.basename(bundleName(options.output, "-bundle.css"));
  const basePath = htmlBasePath(props.config);

  const tplHtml = await buildOutput(
    () => {
      return `<script src="${basePath}${bundlePath}"></script>`;
    },
    () => {
      return `<link rel="stylesheet" href="${basePath}${bundleStyle}" />`;
    },
    options
  );

  await writeFileAsync(
    path.resolve(path.dirname(outputOptions.file), "index.html"),
    tplHtml,
    "utf8"
  );

  return options.output;
}

module.exports = {
  htmlBundle
};
<|endoftext|>


<commit_before>'use strict';

var log = require('minilog')('traverson');

var Walker = require('./walker')

function JsonHalWalker() {
}

JsonHalWalker.prototype = new Walker()

JsonHalWalker.prototype.preProcessLink = function(link) {
  // TODO XXX !!!
  return '$._links.' + link + '.href'
}

JsonHalWalker.prototype.postProcessUri = function(nextUri) {
  // TODO XXX !!!
  return 'http://api.io' + nextUri
}

module.exports = JsonHalWalker
<commit_msg>use startUri<commit_after>'use strict';

var log = require('minilog')('traverson');

var Walker = require('./walker')

function JsonHalWalker() {
}

JsonHalWalker.prototype = new Walker()

JsonHalWalker.prototype.preProcessLink = function(link) {
  // TODO XXX !!!
  // Use a propert HAL library instead of this ad hoc sillyness :-)
  return '$._links.' + link + '.href'
}

JsonHalWalker.prototype.postProcessUri = function(nextUri) {
  return this.startUri + nextUri
}

module.exports = JsonHalWalker
<|endoftext|>


<commit_before>var Komachan = require('../index.js');
var util = require('util');

function KomachanHandler() {
  var self = this;
  self.color;
  self.komachan = Komachan.newKomachan();
  self.socket = require('./socket').socket().socket;
  self.moved();
  self.socket.on('legal', function(lmoves){
    //console.log('legal', lmoves);
  })
  self.socket.on('win', function(mes){
    self.komachan.end();
  });
  self.socket.on('lose', function(mes) {
    self.komachan.end();
  });
  self.socket.on('err', function(err){
    self.komachan.end();
  });
}

KomachanHandler.prototype.getKomachan = function() {
  return this.komachan;
}

KomachanHandler.prototype.start = function(opt) {
  var self = this;
  self.komachan.start(opt);
  //util.console.log(require('util').inspect(self.komachan.getZobrist(), { depth: null }));
  self.socket.emit('new-game', {});
  self.socket.on('confirm', function(game) {
    if (opt.color == 0) {
      game.header.firstMove = 'client';
      game.header.secondMove = 'koma';
    }
    if (opt.color == 1) {
      game.header.firstMove = 'koma';
      game.header.secondMove = 'client';
    }
    self.socket.emit('agree', game);
  });
  self.socket.on('start', function(game) {
    //self.komachan.print();
    if (game.header.firstMove === 'client') {
      self.color = 0;
      self.move();
    } else {
      self.color = 1;
    }
    //self.komachan.print();
  });
}

KomachanHandler.prototype.manualStart = function(opt) {
  var self = this;
  self.komachan.start(opt);
}

KomachanHandler.prototype.move = function() {
  var self = this;
  var kmove = self.komachan.search();
  if (!kmove) {
    return;
  }
  self.socket.emit('move', kmove);
}

KomachanHandler.prototype.moved = function() {
  var self = this;
  self.socket.on('moved', function(move){
    console.log('moved', move);
    if (move.color !== self.color){
      self.komachan.move(move);
      self.komachan.print();
      self.move();
      self.komachan.print();
    }
  });
}

KomachanHandler.prototype.manualMove = function(move) {
    var self = this;
    self.komachan.move(move);
}

KomachanHandler.prototype.manualBack = function() {
    var self = this;
    self.komachan.back();
}

KomachanHandler.prototype.print = function() {
  var self = this;
  self.komachan.print();
}

KomachanHandler.prototype.end = function() {
  this.komachan.end();
}

KomachanHandler.prototype.finish = function() {
  var self = this;
  return new Promise(function(resolve){
    self.socket.on('win', function(wgame){
      resolve(wgame);
    });
    self.socket.on('lose', function(lgame){
      resolve(lgame);
    });
  });
}

module.exports = KomachanHandler;
<commit_msg>may be ok komachanhandler stop search<commit_after>var Komachan = require('../index.js');
var util = require('util');

function KomachanHandler() {
  var self = this;
  self.color;
  self.komachan = Komachan.newKomachan();
  self.socket = require('./socket').socket().socket;
  self.socket.on('legal', function(lmoves){
    //console.log('legal', lmoves);
  })
  self.socket.on('win', function(mes){
    self.komachan.end();
  });
  self.socket.on('lose', function(mes) {
    self.komachan.end();
  });
  self.socket.on('err', function(err){
    self.komachan.end();
  });
}

KomachanHandler.prototype.getKomachan = function() {
  return this.komachan;
}

KomachanHandler.prototype.start = function(opt) {
  var self = this;
  self.komachan.start(opt);
  self.socket.emit('new-game', {});
  self.socket.on('confirm', function(game) {
    if (opt.color == 0) {
      game.header.firstMove = 'client';
      game.header.secondMove = 'koma';
    }
    if (opt.color == 1) {
      game.header.firstMove = 'koma';
      game.header.secondMove = 'client';
    }
    self.socket.emit('agree', game);
  });
  self.socket.on('start', function(game) {
    if (game.header.firstMove === 'client') {
      self.color = 0;
    } else {
      self.color = 1;
    }
  });
  self.move();
  self.moved();
}

KomachanHandler.prototype.manualStart = function(opt) {
  var self = this;
  self.komachan.start(opt);
}

KomachanHandler.prototype.move = function() {
  var self = this;
  self.socket.on('legal', function(legal) {
    var kmove = self.komachan.search();
    if (!kmove) {
      return;
    }
    self.socket.emit('move', kmove);
    self.komachan.print();
  });
}

KomachanHandler.prototype.moved = function() {
  var self = this;
  self.socket.on('moved', function(move){
    if (move.color !== self.color){
      self.komachan.move(move);
      self.komachan.print();
    }
  });
}

KomachanHandler.prototype.manualMove = function(move) {
    var self = this;
    self.komachan.move(move);
}

KomachanHandler.prototype.manualBack = function() {
    var self = this;
    self.komachan.back();
}

KomachanHandler.prototype.print = function() {
  var self = this;
  self.komachan.print();
}

KomachanHandler.prototype.end = function() {
  this.komachan.end();
}

KomachanHandler.prototype.finish = function() {
  var self = this;
  return new Promise(function(resolve){
    self.socket.on('win', function(wgame){
      resolve(wgame);
    });
    self.socket.on('lose', function(lgame){
      resolve(lgame);
    });
  });
}

module.exports = KomachanHandler;
<|endoftext|>


<commit_before>// @author : luyuan.china@gmail.com

addScriptToInject(function() {

chrome_comp.CompDetect.declareDetector(

'negativeMargin',

chrome_comp.CompDetect.ScanDomBaseDetector,

null, // constructor

/*【思路】
 * 检测所有设定了负的 margin 的元素，若其自身在 IE 中触发了 hasLayout 与设定了 position:relative，同时其包含块也触发了 hasLayout 则停止检测
 * 获取元素及其包含块四个方向的绝对位置，若出现位置溢出包含块则发出警告
 *
 */

function checkNode(node, additionalData) {
  function isNegativeMargin(nodeEl) {
    var t = parseInt(window.chrome_comp.getComputedStyle(nodeEl).marginTop),
        r = parseInt(window.chrome_comp.getComputedStyle(nodeEl).marginRight),
        b = parseInt(window.chrome_comp.getComputedStyle(nodeEl).marginbottom),
        l = parseInt(window.chrome_comp.getComputedStyle(nodeEl).marginLeft);
    return (t < 0) || (r < 0) || (b < 0) || (l < 0);
  }

  function isRelativePositioned(nodeEl) {
    return window.chrome_comp.getComputedStyle(nodeEl).position == 'relative';
  }

  if (Node.ELEMENT_NODE != node.nodeType)
    return;

  if (!isNegativeMargin(node))
    return;

  var cb = window.chrome_comp.getContainingBlock(node);
  if (window.chrome_comp.hasLayoutInIE(cb) && isRelativePositioned(node) &&
      window.chrome_comp.hasLayoutInIE(node))
    return;

  var nodeBound = node.getBoundingClientRect(),
      cbBound = cb.getBoundingClientRect();
  if (nodeBound.top < cbBound.top || nodeBound.right > cbBound.right ||
      nodeBound.bottom > cbBound.bottom || nodeBound.left < cbBound.left) {
    this.addProblem('RB1001', [cb]);

  }
}
); // declareDetector

});

<commit_msg>improve code style.<commit_after>/*
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

addScriptToInject(function() {

chrome_comp.CompDetect.declareDetector(

'negative_margin',

chrome_comp.CompDetect.ScanDomBaseDetector,

null, // constructor

function checkNode(node, additionalData) {
  function isNegativeMargin(nodeEl) {
    var t = parseInt(window.chrome_comp.getComputedStyle(nodeEl).marginTop);
    var r = parseInt(window.chrome_comp.getComputedStyle(nodeEl).marginRight);
    var b = parseInt(window.chrome_comp.getComputedStyle(nodeEl).marginbottom);
    var l = parseInt(window.chrome_comp.getComputedStyle(nodeEl).marginLeft);
    return (t < 0) || (r < 0) || (b < 0) || (l < 0);
  }

  function isRelativePositioned(nodeEl) {
    return window.chrome_comp.getComputedStyle(nodeEl).position == 'relative';
  }

  if (Node.ELEMENT_NODE != node.nodeType)
    return;

  if (!isNegativeMargin(node))
    return;

  var cb = window.chrome_comp.getContainingBlock(node);
  if (window.chrome_comp.hasLayoutInIE(cb) && isRelativePositioned(node) &&
      window.chrome_comp.hasLayoutInIE(node))
    return;

  var nodeBound = node.getBoundingClientRect();
  var cbBound = cb.getBoundingClientRect();
  if (nodeBound.top < cbBound.top || nodeBound.right > cbBound.right ||
      nodeBound.bottom > cbBound.bottom || nodeBound.left < cbBound.left) {
    this.addProblem('RB1001', [cb]);
  }
}
); // declareDetector

});

<|endoftext|>


<commit_before>acx.i18n.setKeys({
	"General.LoadingFacets" : "Chargement des facettes...",
	"AnyRequest.DisplayOptions" : "Options d'affichage",
	"AnyRequest.AsGraph" : "En graphe",
	"AnyRequest.AsJson" : "En JSON brut",
	"AnyRequest.AsTable" : "En tableau",
	"AnyRequest.History" : "Historique",
	"AnyRequest.RepeatRequest" : "Répétition automatique de la requête",
	"AnyRequest.RepeatRequestSelect" : "Répéter la requête toutes les ",
	"AnyRequest.Transformer" : "Transformation des résultats",
//	"AnyRequest.Pretty": "Pretty",
	"AnyRequest.Query" : "Recherche",
	"AnyRequest.Request": "Requête",
	"AnyRequest.Requesting": "Requête en cours...",
	"AnyRequest.ValidateJSON": "Valider le JSON",
	"Browser.ResultSourcePanelTitle": "Résultat au format JSON",
	"Overview.PageTitle" : "Aperçu du cluster",
    "TableResults.Summary": "Recherche sur {0} des {1} shards. {2} résultats. {3} secondes",
	"QueryFilter-Header-Indices": "Index",
//	"QueryFilter-Header-Types": "Types",
	"QueryFilter-Header-Fields": "Champs",
	"QueryFilter.DateRangeHint.from": "De : {0}",
	"QueryFilter.DateRangeHint.to": "  A : {0}"
});

acx.i18n.setKeys({
	"AnyRequest.TransformerHelp" : "\

Le transformateur de résultats peut être utilisé pour modifier a posteriori les résultats JSON bruts dans un format plus utile.
\

Le transformateur devrait contenir le corps d'une fonction javascript. La valeur de retour de la fonction devient la nouvelle valeur qui sera passée à l'afficheur des documents JSON.
\

Exemple:
\
		  return root.hits.hits[0]; ne renverra que le premier élément de l'ensemble des résultats.
\
		  return Object.keys(root.nodes).reduce(function(tot, node) { return tot + root.nodes[node].os.mem.used_in_bytes; }, 0); retournera la mémoire totale utilis�e dans l'ensemble du cluster.

\

Les fonctions suivantes sont disponibles et peuvent vous être utiles pour travailler sur les tableaux et les objets:
\

\

Object.keys(object) := array
\

array.forEach(function(prop, index))
\

array.map(function(prop, index)) := array
\

array.reduce(function(accumulator, prop, index), initial_value) := final_value
\

\

Lorsque vous activez la répétition automatique de la requête, un paramètre supplémentaire nommé prev est passé à la fonction de transformation. Cela permet les comparaisons et les graphes cumulatifs.
\

Exemple:
\
		var la = [ root.nodes[Object.keys(root.nodes)[0]].os.load_average[0] ]; return prev ? la.concat(prev) : la; retournera la charge moyenne du premier noeud du cluster pour la dernière minute écoulée.\
		Cela peut alimenter ensuite le graphe pour produire un graphe de charge du noeud.\
		"
});

acx.i18n.setKeys({
	"AnyRequest.DisplayOptionsHelp" : "\

En JSON brut: affiche les résultats complets de la recherche éventuellement transformée au format JSON brut.
\

En graphe: pour fabriquer un graphe de vos résultats, utilsez la transformation de résultats pour générer un tableau de valeurs.
\

En tableau: si votre requête est une recherche, vous pouvez alors afficher les résultats dans un tableau.
\
		"
});

acx.i18n.setKeys({
	"QueryFilter.DateRangeHelp" : "\

Les champs Date acceptent une requête en langage naturel pour produire un écart de date (from/to) correspondant.
\

Les formats suivants sont acceptés :
\

\

Mots clés
\
				now
 today
 tomorrow
 yesterday
 last / this / next + week / month / year
\
				Cherchera pour des dates correspondant au mot clé. last year cherchera sur toute l'année précédente.
\

Ecarts
\
				1000 secs
 5mins
 1day
 2days
 80d
 9 months
 2yrs (les espaces sont optionnels et il existe beaucoup de synonymes pour qualifier les écarts)
\
				Créé un écart de date basé sur l'heure courante (maintenant) avec plus ou moins l'écart indiqué.
\

Dates et Dates partielles
\
				2011
 2011-01
 2011-01-18
 2011-01-18 12
 2011-01-18 12:32
 2011-01-18 12:32:45
\
				Ces formats indiquent un écart de date spécifique. 2011 cherchera sur toute l'année 2011, alors que 2011-01-18 12:32:45 ne cherchera que pour la date précise à la seconde près.
\

Heures et heures partielles
\
				12
 12:32
 12:32:45
\
				Ces formats indiquent un espace de temps pour la date du jour. 12:32 cherchera les éléments d'aujourd'hui à cette minute précise.
\

Ecart de Date
\
				2010 -> 2011
 last week -> next week
 2011-05 ->
 < now
\
				Un écart de date est créé en spécifiant deux dates dans n'importe lequel des formats précédents (Mot clé / Dates / Heures) séparées par < ou -> (les deux produisent le même effet). Si la date de fin n'est pas indiquée, alors il n'y aura aucune contrainte de fin.
\

Ecart de date avec décalage
\
				2010 -> 1yr
 3mins < now\
				Cherche en incluant un décalage de la date dans la direction indiquée.
\

Ecart de date avec bornes
\
				2010-05-13 05:13 <> 10m
 now <> 1yr
 lastweek <> 1month
\
				Similaire à ci-dessus excepté que le décalage est appliqué dans les deux sens à partir de la date indiquée.
\

\
	"
});<commit_msg>Fix wrong encoding for a french character<commit_after>acx.i18n.setKeys({
	"General.LoadingFacets" : "Chargement des facettes...",
	"AnyRequest.DisplayOptions" : "Options d'affichage",
	"AnyRequest.AsGraph" : "En graphe",
	"AnyRequest.AsJson" : "En JSON brut",
	"AnyRequest.AsTable" : "En tableau",
	"AnyRequest.History" : "Historique",
	"AnyRequest.RepeatRequest" : "Répétition automatique de la requête",
	"AnyRequest.RepeatRequestSelect" : "Répéter la requête toutes les ",
	"AnyRequest.Transformer" : "Transformation des résultats",
//	"AnyRequest.Pretty": "Pretty",
	"AnyRequest.Query" : "Recherche",
	"AnyRequest.Request": "Requête",
	"AnyRequest.Requesting": "Requête en cours...",
	"AnyRequest.ValidateJSON": "Valider le JSON",
	"Browser.ResultSourcePanelTitle": "Résultat au format JSON",
	"Overview.PageTitle" : "Aperçu du cluster",
    "TableResults.Summary": "Recherche sur {0} des {1} shards. {2} résultats. {3} secondes",
	"QueryFilter-Header-Indices": "Index",
//	"QueryFilter-Header-Types": "Types",
	"QueryFilter-Header-Fields": "Champs",
	"QueryFilter.DateRangeHint.from": "De : {0}",
	"QueryFilter.DateRangeHint.to": "  A : {0}"
});

acx.i18n.setKeys({
	"AnyRequest.TransformerHelp" : "\

Le transformateur de résultats peut être utilisé pour modifier a posteriori les résultats JSON bruts dans un format plus utile.
\

Le transformateur devrait contenir le corps d'une fonction javascript. La valeur de retour de la fonction devient la nouvelle valeur qui sera passée à l'afficheur des documents JSON.
\

Exemple:
\
		  return root.hits.hits[0]; ne renverra que le premier élément de l'ensemble des résultats.
\
		  return Object.keys(root.nodes).reduce(function(tot, node) { return tot + root.nodes[node].os.mem.used_in_bytes; }, 0); retournera la mémoire totale utilisée dans l'ensemble du cluster.

\

Les fonctions suivantes sont disponibles et peuvent vous être utiles pour travailler sur les tableaux et les objets:
\

\

Object.keys(object) := array
\

array.forEach(function(prop, index))
\

array.map(function(prop, index)) := array
\

array.reduce(function(accumulator, prop, index), initial_value) := final_value
\

\

Lorsque vous activez la répétition automatique de la requête, un paramètre supplémentaire nommé prev est passé à la fonction de transformation. Cela permet les comparaisons et les graphes cumulatifs.
\

Exemple:
\
		var la = [ root.nodes[Object.keys(root.nodes)[0]].os.load_average[0] ]; return prev ? la.concat(prev) : la; retournera la charge moyenne du premier noeud du cluster pour la dernière minute écoulée.\
		Cela peut alimenter ensuite le graphe pour produire un graphe de charge du noeud.\
		"
});

acx.i18n.setKeys({
	"AnyRequest.DisplayOptionsHelp" : "\

En JSON brut: affiche les résultats complets de la recherche éventuellement transformée au format JSON brut.
\

En graphe: pour fabriquer un graphe de vos résultats, utilsez la transformation de résultats pour générer un tableau de valeurs.
\

En tableau: si votre requête est une recherche, vous pouvez alors afficher les résultats dans un tableau.
\
		"
});

acx.i18n.setKeys({
	"QueryFilter.DateRangeHelp" : "\

Les champs Date acceptent une requête en langage naturel pour produire un écart de date (from/to) correspondant.
\

Les formats suivants sont acceptés :
\

\

Mots clés
\
				now
 today
 tomorrow
 yesterday
 last / this / next + week / month / year
\
				Cherchera pour des dates correspondant au mot clé. last year cherchera sur toute l'année précédente.
\

Ecarts
\
				1000 secs
 5mins
 1day
 2days
 80d
 9 months
 2yrs (les espaces sont optionnels et il existe beaucoup de synonymes pour qualifier les écarts)
\
				Créé un écart de date basé sur l'heure courante (maintenant) avec plus ou moins l'écart indiqué.
\

Dates et Dates partielles
\
				2011
 2011-01
 2011-01-18
 2011-01-18 12
 2011-01-18 12:32
 2011-01-18 12:32:45
\
				Ces formats indiquent un écart de date spécifique. 2011 cherchera sur toute l'année 2011, alors que 2011-01-18 12:32:45 ne cherchera que pour la date précise à la seconde près.
\

Heures et heures partielles
\
				12
 12:32
 12:32:45
\
				Ces formats indiquent un espace de temps pour la date du jour. 12:32 cherchera les éléments d'aujourd'hui à cette minute précise.
\

Ecart de Date
\
				2010 -> 2011
 last week -> next week
 2011-05 ->
 < now
\
				Un écart de date est créé en spécifiant deux dates dans n'importe lequel des formats précédents (Mot clé / Dates / Heures) séparées par < ou -> (les deux produisent le même effet). Si la date de fin n'est pas indiquée, alors il n'y aura aucune contrainte de fin.
\

Ecart de date avec décalage
\
				2010 -> 1yr
 3mins < now\
				Cherche en incluant un décalage de la date dans la direction indiquée.
\

Ecart de date avec bornes
\
				2010-05-13 05:13 <> 10m
 now <> 1yr
 lastweek <> 1month
\
				Similaire à ci-dessus excepté que le décalage est appliqué dans les deux sens à partir de la date indiquée.
\

\
	"
});<|endoftext|>


<commit_before>L.Draw = {};

L.Draw.Feature = L.Handler.extend({
	includes: L.Mixin.Events,

	initialize: function (map, options) {
		this._map = map;
		this._container = map._container;
		this._overlayPane = map._panes.overlayPane;
		this._popupPane = map._panes.popupPane;

		// Merge default shapeOptions options with custom shapeOptions
		if (options && options.shapeOptions) {
			options.shapeOptions = L.Util.extend({}, this.options.shapeOptions, options.shapeOptions);
		}
		L.setOptions(this, options);
	},

	enable: function () {
		if (this._enabled) { return; }

		L.Handler.prototype.enable.call(this);

		this.fire('enabled', { handler: this.type });

		this._map.fire('draw:drawstart', { layerType: this.type });
	},

	disable: function () {
		if (!this._enabled) { return; }

		L.Handler.prototype.disable.call(this);

		this._map.fire('draw:drawstop', { layerType: this.type });

		this.fire('disabled', { handler: this.type });
	},

	addHooks: function () {
		var map = this._map;

		if (map) {
			L.DomUtil.disableTextSelection();

			map.getContainer().focus();

			this._tooltip = new L.Tooltip(this._map);

			L.DomEvent.on(this._container, 'keyup', this._cancelDrawing, this);
		}
	},

	removeHooks: function () {
		if (this._map) {
			L.DomUtil.enableTextSelection();

			this._tooltip.dispose();
			this._tooltip = null;

			L.DomEvent.off(this._container, 'keyup', this._cancelDrawing, this);
		}
	},

	setOptions: function (options) {
		L.setOptions(this, options);
	},

	_fireCreatedEvent: function (layer) {
		this._map.fire('draw:created', { layer: layer, layerType: this.type });
	},

	// Cancel drawing when the escape key is pressed
	_cancelDrawing: function (e) {
		if (e.keyCode === 27) {
			this._map.fire('draw:canceled', { layerType: this.type });
			this.disable();
		}
	}
});
<commit_msg>fix: update draw cancel event to be `drawcancel`<commit_after>L.Draw = {};

L.Draw.Feature = L.Handler.extend({
	includes: L.Mixin.Events,

	initialize: function (map, options) {
		this._map = map;
		this._container = map._container;
		this._overlayPane = map._panes.overlayPane;
		this._popupPane = map._panes.popupPane;

		// Merge default shapeOptions options with custom shapeOptions
		if (options && options.shapeOptions) {
			options.shapeOptions = L.Util.extend({}, this.options.shapeOptions, options.shapeOptions);
		}
		L.setOptions(this, options);
	},

	enable: function () {
		if (this._enabled) { return; }

		L.Handler.prototype.enable.call(this);

		this.fire('enabled', { handler: this.type });

		this._map.fire('draw:drawstart', { layerType: this.type });
	},

	disable: function () {
		if (!this._enabled) { return; }

		L.Handler.prototype.disable.call(this);

		this._map.fire('draw:drawstop', { layerType: this.type });

		this.fire('disabled', { handler: this.type });
	},

	addHooks: function () {
		var map = this._map;

		if (map) {
			L.DomUtil.disableTextSelection();

			map.getContainer().focus();

			this._tooltip = new L.Tooltip(this._map);

			L.DomEvent.on(this._container, 'keyup', this._cancelDrawing, this);
		}
	},

	removeHooks: function () {
		if (this._map) {
			L.DomUtil.enableTextSelection();

			this._tooltip.dispose();
			this._tooltip = null;

			L.DomEvent.off(this._container, 'keyup', this._cancelDrawing, this);
		}
	},

	setOptions: function (options) {
		L.setOptions(this, options);
	},

	_fireCreatedEvent: function (layer) {
		this._map.fire('draw:created', { layer: layer, layerType: this.type });
	},

	// Cancel drawing when the escape key is pressed
	_cancelDrawing: function (e) {
		if (e.keyCode === 27) {
			this._map.fire('draw:drawcancel', { layerType: this.type });
			this.disable();
		}
	}
});
<|endoftext|>


<commit_before>/** @babel */
/** @jsx etchDom */

/**
 * Copyright 2016-present PlatformIO Plus <contact@pioplus.com>
 *
 * License: https://pioplus.com/license.html
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */

import * as utils from '../utils';

import { BasePanel, EtchComponent } from '../view';

import { CompositeDisposable } from 'atom';
import LibBuiltInPanel from './components/panel-builtin';
import LibInstallStoragePrompt from './components/install-storage-prompt';
import LibInstalledPanel from './components/panel-installed';
import LibLibraryPanel from './components/panel-library';
import LibRegistrySearchPanel from './components/panel-registry-search';
import LibRegistryStatsPanel from './components/panel-registry-stats';
import LibUpdatesPanel from './components/panel-updates';
import { dom as etchDom } from 'etch';
import { runLibraryCommand } from './util';

export default class LibrariesPanel extends BasePanel {

  constructor() {
    super(...arguments);
    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(this.props.homebus.on(
      'lib-search', ::this.onDidLibrarySearch));
    this.subscriptions.add(this.props.homebus.on(
      'lib-show', ::this.onDidLibraryShow));
    this.subscriptions.add(this.props.homebus.on(
      'lib-install', ::this.onDidLibraryInstall));
    this.subscriptions.add(this.props.homebus.on(
      'lib-uninstall', ::this.onDidLibraryUninstall));
    this.subscriptions.add(this.props.homebus.on(
      'lib-update', ::this.onDidLibraryUpdate));
  }

  getSubPanels() {
    const items = [
      {
        id: 'stats',
        submenu: 'registry',
        icon: 'book',
        component: (
        <LibRegistryStatsPanel homebus={ this.props.homebus } />
        )
      },
      {
        id: 'search',
        submenu: 'registry',
        icon: 'book',
        component: (
        <LibRegistrySearchPanel homebus={ this.props.homebus } />
        )
      },
      {
        id: 'library',
        submenu: 'registry',
        icon: 'book',
        component: (
        <LibLibraryPanel homebus={ this.props.homebus } />
        )
      },
      {
        id: 'installed',
        submenu: 'installed',
        icon: 'package',
        component: (
        <LibInstalledPanel homebus={ this.props.homebus } />
        )
      },
      {
        id: 'builtin',
        submenu: 'built-in',
        icon: 'eye-watch',
        component: (
        <LibBuiltInPanel homebus={ this.props.homebus } />
        )
      },
      {
        id: 'updates',
        submenu: 'updates',
        icon: 'cloud-download',
        component: (
        <LibUpdatesPanel homebus={ this.props.homebus } />
        )
      }
    ];
    items.forEach(item => item.component.ref = `${item.id}Panel`);
    return items;
  }

  getSubmenu() {
    const candidates = new Map();
    let item = null;
    let active = false;
    this.getSubPanels().forEach(panel => {
      if (!this._panel_id && candidates.length === 0) {
        active = true;
      } else {
        active = this._panel_id && this._panel_id === panel.id;
      }
      if (!candidates.has(panel.submenu)) {
        item = {
          name: panel.submenu,
          icon: panel.icon,
          panelId: panel.id,
          active: active
        };
      } else {
        item = candidates.get(panel.submenu);
        item.active |= active;
      }
      candidates.set(panel.submenu, item);
    });
    const items = [];
    for (const item of candidates.values()) {
      items.push(item);
    }
    return items;
  }

  showLibrariesPanel(id) {
    this._panel_id = id;
    this.getSubPanels().forEach((item) => {
      if (item.id === id) {
        this.refs[`${item.id}Panel`].showPanel();
      } else {
        this.refs[`${item.id}Panel`].hidePanel();
      }
    });
    // don't change submenu when show a library
    if (id  === 'library') {
      return;
    }
    this.refs.libSubmenu.update({
      items: this.getSubmenu()
    });
  }

  onDidPanelShow() {
    // select initial LibrariesPanel
    if (!this._panel_id) {
      this.showLibrariesPanel(this.getSubPanels()[0].id);
    }
  }

  onDidLibrarySearch(options) {
    this.refs.searchPanel.update(options);
    this.showLibrariesPanel('search');
  }

  onDidLibraryShow(data) {
    this.refs.libraryPanel.update({
      data
    });
    this.showLibrariesPanel('library');
  }

  onDidLibraryInstall([lib, callback]) {
    new LibInstallStoragePrompt().prompt().then(storage => {
      runLibraryCommand('install', storage, lib).then(
        result => {
          atom.notifications.addSuccess(
            'Library has been successfully installed', {
              detail: result
            }
          );
          callback(result);
        },
        error => callback(error)
      );
    }, (error) => {
      callback(error);
    });
  }

  onDidLibraryUninstall([storage, lib, callback]) {
    runLibraryCommand('uninstall', storage, lib).then(
      result => {
        atom.notifications.addSuccess(
          'Library has been successfully uninstalled', {
            detail: result
          }
        );
        callback(result);
      },
      error => callback(error)
    );
  }

  onDidLibraryUpdate([storage, lib, callback]) {
    runLibraryCommand('update', storage, lib).then(
      result => {
        atom.notifications.addSuccess(
          'Library has been successfully updated', {
            detail: result
          }
        );
        callback(result);
      },
      error => callback(error)
    );
  }

  destroy() {
    this.subscriptions.dispose();
    super.destroy();
  }

  render() {
    return (

        <LibrariesSubmenuView ref='libSubmenu' items={ [] } onpanelchanged={ (id) => this.showLibrariesPanel(id) } />
        { this.getSubPanels().map((item) => item.component) }

    );
  }
}

class LibrariesSubmenuView extends EtchComponent {

  getClassListForItem(item) {
    const classList = ['btn', 'icon', `icon-${item.icon}`];
    if (item.active) {
      classList.push('selected');
    }
    return classList;
  }

  render() {
    return (

        { this.props.items.map(item => (
            <button onclick={ () => this.props.onpanelchanged(item.panelId) } className={ this.getClassListForItem(item).join(' ') }>
              { utils.title(item.name) }
            </button>
          )) }

    );
  }

}
<commit_msg>Code cleanup<commit_after>/** @babel */
/** @jsx etchDom */

/**
 * Copyright 2016-present PlatformIO Plus <contact@pioplus.com>
 *
 * License: https://pioplus.com/license.html
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */

import * as utils from '../utils';

import { BasePanel, EtchComponent } from '../view';

import { CompositeDisposable } from 'atom';
import LibBuiltInPanel from './components/panel-builtin';
import LibInstallStoragePrompt from './components/install-storage-prompt';
import LibInstalledPanel from './components/panel-installed';
import LibLibraryPanel from './components/panel-library';
import LibRegistrySearchPanel from './components/panel-registry-search';
import LibRegistryStatsPanel from './components/panel-registry-stats';
import LibUpdatesPanel from './components/panel-updates';
import { dom as etchDom } from 'etch';
import { runLibraryCommand } from './util';

export default class LibrariesPanel extends BasePanel {

  constructor() {
    super(...arguments);
    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(this.props.homebus.on(
      'lib-search', ::this.onDidLibrarySearch));
    this.subscriptions.add(this.props.homebus.on(
      'lib-show', ::this.onDidLibraryShow));
    this.subscriptions.add(this.props.homebus.on(
      'lib-install', ::this.onDidLibraryInstall));
    this.subscriptions.add(this.props.homebus.on(
      'lib-uninstall', ::this.onDidLibraryUninstall));
    this.subscriptions.add(this.props.homebus.on(
      'lib-update', ::this.onDidLibraryUpdate));
  }

  getSubPanels() {
    const items = [
      {
        id: 'stats',
        submenu: 'registry',
        icon: 'book',
        component: (
        <LibRegistryStatsPanel homebus={ this.props.homebus } />
        )
      },
      {
        id: 'search',
        submenu: 'registry',
        icon: 'book',
        component: (
        <LibRegistrySearchPanel homebus={ this.props.homebus } />
        )
      },
      {
        id: 'library',
        icon: 'book',
        component: (
        <LibLibraryPanel homebus={ this.props.homebus } />
        )
      },
      {
        id: 'installed',
        submenu: 'installed',
        icon: 'package',
        component: (
        <LibInstalledPanel homebus={ this.props.homebus } />
        )
      },
      {
        id: 'builtin',
        submenu: 'built-in',
        icon: 'eye-watch',
        component: (
        <LibBuiltInPanel homebus={ this.props.homebus } />
        )
      },
      {
        id: 'updates',
        submenu: 'updates',
        icon: 'cloud-download',
        component: (
        <LibUpdatesPanel homebus={ this.props.homebus } />
        )
      }
    ];
    items.forEach(item => item.component.ref = `${item.id}Panel`);
    return items;
  }

  getSubmenu() {
    const candidates = new Map();
    let item = null;
    let active = false;
    this.getSubPanels().forEach(panel => {
      if (!panel.submenu) {
        return;
      }
      if (!this._panel_id && candidates.length === 0) {
        active = true;
      } else {
        active = this._panel_id && this._panel_id === panel.id;
      }
      if (!candidates.has(panel.submenu)) {
        item = {
          name: panel.submenu,
          icon: panel.icon,
          panelId: panel.id,
          active: active
        };
      } else {
        item = candidates.get(panel.submenu);
        item.active |= active;
      }
      candidates.set(panel.submenu, item);
    });
    const items = [];
    for (const item of candidates.values()) {
      items.push(item);
    }
    return items;
  }

  showLibrariesPanel(id) {
    this._panel_id = id;
    this.getSubPanels().forEach((item) => {
      if (item.id === id) {
        this.refs[`${item.id}Panel`].showPanel();
      } else {
        this.refs[`${item.id}Panel`].hidePanel();
      }
    });
    // don't change submenu when show a library
    if (id  === 'library') {
      return;
    }
    this.refs.libSubmenu.update({
      items: this.getSubmenu()
    });
  }

  onDidPanelShow() {
    // select initial LibrariesPanel
    if (!this._panel_id) {
      this.showLibrariesPanel(this.getSubPanels()[0].id);
    }
  }

  onDidLibrarySearch(options) {
    this.refs.searchPanel.update(options);
    this.showLibrariesPanel('search');
  }

  onDidLibraryShow(data) {
    this.refs.libraryPanel.update({
      data
    });
    this.showLibrariesPanel('library');
  }

  onDidLibraryInstall([lib, callback]) {
    new LibInstallStoragePrompt().prompt().then(storage => {
      runLibraryCommand('install', storage, lib).then(
        result => {
          atom.notifications.addSuccess(
            'Library has been successfully installed', {
              detail: result
            }
          );
          callback(result);
        },
        error => callback(error)
      );
    }, (error) => {
      callback(error);
    });
  }

  onDidLibraryUninstall([storage, lib, callback]) {
    runLibraryCommand('uninstall', storage, lib).then(
      result => {
        atom.notifications.addSuccess(
          'Library has been successfully uninstalled', {
            detail: result
          }
        );
        callback(result);
      },
      error => callback(error)
    );
  }

  onDidLibraryUpdate([storage, lib, callback]) {
    runLibraryCommand('update', storage, lib).then(
      result => {
        atom.notifications.addSuccess(
          'Library has been successfully updated', {
            detail: result
          }
        );
        callback(result);
      },
      error => callback(error)
    );
  }

  destroy() {
    this.subscriptions.dispose();
    super.destroy();
  }

  render() {
    return (

        <LibrariesSubmenuView ref='libSubmenu' items={ [] } onpanelchanged={ (id) => this.showLibrariesPanel(id) } />
        { this.getSubPanels().map((item) => item.component) }

    );
  }
}

class LibrariesSubmenuView extends EtchComponent {

  getClassListForItem(item) {
    const classList = ['btn', 'icon', `icon-${item.icon}`];
    if (item.active) {
      classList.push('selected');
    }
    return classList;
  }

  render() {
    return (

        { this.props.items.map(item => (
            <button onclick={ () => this.props.onpanelchanged(item.panelId) } className={ this.getClassListForItem(item).join(' ') }>
              { utils.title(item.name) }
            </button>
          )) }

    );
  }

}
<|endoftext|>


<commit_before>
var printit = require('printit');
var http = require('http');
var https = require('https');
var httpProxy = require('http-proxy');
const LOGGER = printit({ prefix: 'Cozy Light' });

module.exports = function(cozyLight){

  var configHelpers = cozyLight.configHelpers;
  var routes = cozyLight.routes;

  var proxy;
  var server;

  var controllers = {

    /**
     * Proxy requests targeting apps.
     */
    proxyPrivate: function (req, res) {
      var appName = req.params.name;
      var appPort = routes[appName];
      req.url = req.url.substring(('/apps/' + appName).length);
      if (appPort !== null) {
        proxy.web(req, res, { target: 'http://localhost:' + appPort });
      } else {
        res.send(404);
      }
    },

    /**
     * Proxy requests targeting apps public path.
     */
    proxyPublic: function (req, res) {
      var appName = req.params.name;
      var appPort = routes[appName];
      req.url = '/public' + req.url.substring(('/public/' + appName).length);
      if (appPort !== null) {
        proxy.web(req, res, { target: 'http://localhost:' + appPort });
      } else {
        res.send(404);
      }
    }

  };

  var mainAppHelper = {

    /**
     * Configure properly proxy: handle errors and websockets.
     *
     * @param {Object} server Express server.
     */
    initializeProxy: function (server) {

      proxy = httpProxy.createProxyServer(/*{agent: new http.Agent()}*/);

      proxy.on('error', function onProxyError(err, req, res) {
        LOGGER.raw(err);
        res.status(500).send(err);
      });

      server.on('upgrade', function onProxyUpgrade(req, socket, head) {

        function proxyWS(port) {
          proxy.ws(req, socket, head, {
            target: 'ws://localhost:' + port,
            ws: true
          });
        }

        req.originalUrl = req.url;

        var publicOrPrivate = '';
        var slug = '';

        var urlParts = req.url.split('/');
        if (urlParts.length >= 3) {
          publicOrPrivate = urlParts[1];
          slug = urlParts[2];
        }

        if (publicOrPrivate === 'public') {
          req.url = req.url.replace('/public/' + slug, '/public');
          proxyWS(routes[slug]);

        } else if (publicOrPrivate === 'apps') {
          req.url = req.url.replace('/apps/' + slug, '');
          proxyWS(routes[slug]);

        } else {
          proxyWS(process.env.DEFAULT_REDIRECT_PORT);
        }
      });

      return proxy;
    },

    /**
     * Configure main application server.
     *
     * @param app
     * @returns {*}
     */
    start: function (app) {
      var config = configHelpers.getConfig();
      // Set SSL configuration if certificates path are properly set.
      var options = {};
      if (config.ssl !== undefined) {
        options.key = fs.readFileSync(config.ssl.key, 'utf8');
        options.cert = fs.readFileSync(config.ssl.cert, 'utf8');
        server = https.createServer(options, app);
      } else  {
        server = http.createServer(app);
      }

      var mainPort = configHelpers.getMainAppPort();
      server.listen(mainPort);
      mainAppHelper.initializeProxy(server);

      LOGGER.info(
        'Cozy Light server is listening on port ' + mainPort + '...'
      );

      app.all('/apps/:name/*', controllers.proxyPrivate);
      app.all('/apps/:name*', controllers.proxyPrivate);

      app.all('/public/:name/*', controllers.proxyPublic);
      app.all('/public/:name*', controllers.proxyPublic);

      return server;
    },

    /**
     * Stop main application server.
     */
    stop: function (done) {
      var list = [];
      if (server) {
        list.push(function (callback) {
          try {
            server.close(callback);
          } catch (err) {
            callback();
          }
        });
      }
      if (proxy) {
        list.push(function (callback) {
          if (proxy.close !== undefined) {
            proxy.close(); // does not work well, or has no callback
          }
          callback();
        });
      }
      async.series(list, done);
    }
  };

  return mainAppHelper;
};
<commit_msg>add missing async dependence add new method to access proxy instance<commit_after>
var printit = require('printit');
var http = require('http');
var https = require('https');
var httpProxy = require('http-proxy');
var async = require('async');
const LOGGER = printit({ prefix: 'Cozy Light' });

module.exports = function(cozyLight){

  var configHelpers = cozyLight.configHelpers;
  var routes = cozyLight.routes;

  var proxy;
  var server;

  var controllers = {

    /**
     * Proxy requests targeting apps.
     */
    proxyPrivate: function (req, res) {
      var appName = req.params.name;
      var appPort = routes[appName];
      req.url = req.url.substring(('/apps/' + appName).length);
      if (appPort !== null) {
        proxy.web(req, res, { target: 'http://localhost:' + appPort });
      } else {
        res.send(404);
      }
    },

    /**
     * Proxy requests targeting apps public path.
     */
    proxyPublic: function (req, res) {
      var appName = req.params.name;
      var appPort = routes[appName];
      req.url = '/public' + req.url.substring(('/public/' + appName).length);
      if (appPort !== null) {
        proxy.web(req, res, { target: 'http://localhost:' + appPort });
      } else {
        res.send(404);
      }
    }

  };

  var mainAppHelper = {

    /**
     * Returns the proxy responsible to forward
     * requests made from /app/* to the targeted app server
     *
     * @return Object Proxy of the main app.
     */
    getProxy: function(){
      return proxy;
    },

    /**
     * Configure properly proxy: handle errors and websockets.
     *
     * @param {Object} server Express server.
     */
    initializeProxy: function (server) {

      proxy = httpProxy.createProxyServer(/*{agent: new http.Agent()}*/);

      proxy.on('error', function onProxyError(err, req, res) {
        LOGGER.raw(err);
        res.status(500).send(err);
      });

      server.on('upgrade', function onProxyUpgrade(req, socket, head) {

        function proxyWS(port) {
          proxy.ws(req, socket, head, {
            target: 'ws://localhost:' + port,
            ws: true
          });
        }

        req.originalUrl = req.url;

        var publicOrPrivate = '';
        var slug = '';

        var urlParts = req.url.split('/');
        if (urlParts.length >= 3) {
          publicOrPrivate = urlParts[1];
          slug = urlParts[2];
        }

        if (publicOrPrivate === 'public') {
          req.url = req.url.replace('/public/' + slug, '/public');
          proxyWS(routes[slug]);

        } else if (publicOrPrivate === 'apps') {
          req.url = req.url.replace('/apps/' + slug, '');
          proxyWS(routes[slug]);

        } else {
          proxyWS(process.env.DEFAULT_REDIRECT_PORT);
        }
      });

      return proxy;
    },

    /**
     * Configure main application server.
     *
     * @param app
     * @returns {*}
     */
    start: function (app) {
      var config = configHelpers.getConfig();
      // Set SSL configuration if certificates path are properly set.
      var options = {};
      if (config.ssl !== undefined) {
        options.key = fs.readFileSync(config.ssl.key, 'utf8');
        options.cert = fs.readFileSync(config.ssl.cert, 'utf8');
        server = https.createServer(options, app);
      } else  {
        server = http.createServer(app);
      }

      var mainPort = configHelpers.getMainAppPort();
      server.listen(mainPort);
      mainAppHelper.initializeProxy(server);

      LOGGER.info(
        'Cozy Light server is listening on port ' + mainPort + '...'
      );

      app.all('/apps/:name/*', controllers.proxyPrivate);
      app.all('/apps/:name*', controllers.proxyPrivate);

      app.all('/public/:name/*', controllers.proxyPublic);
      app.all('/public/:name*', controllers.proxyPublic);

      return server;
    },

    /**
     * Stop main application server.
     */
    stop: function (done) {
      var list = [];
      if (server) {
        list.push(function (callback) {
          try {
            server.close(callback);
          } catch (err) {
            callback();
          }
        });
      }
      if (proxy) {
        list.push(function (callback) {
          if (proxy.close !== undefined) {
            proxy.close(); // does not work well, or has no callback
          }
          callback();
        });
      }
      async.series(list, done);
    }
  };

  return mainAppHelper;
};
<|endoftext|>


<commit_before>var Shape = require('./shape');

var util = require('../util');
var property = util.property;
var memoizedProperty = util.memoizedProperty;

function Operation(name, operation, options) {
  var self = this;
  options = options || {};

  property(this, 'name', operation.name || name);
  property(this, 'api', options.api, false);

  operation.http = operation.http || {};
  property(this, 'endpoint', operation.endpoint);
  property(this, 'httpMethod', operation.http.method || 'POST');
  property(this, 'httpPath', operation.http.requestUri || '/');
  property(this, 'authtype', operation.authtype || '');
  property(
    this,
    'endpointDiscoveryRequired',
    operation.endpointdiscovery ?
      (operation.endpointdiscovery.required ? 'REQUIRED' : 'OPTIONAL') :
    'NULL'
  );
  property(this, 'httpChecksumRequired', operation.httpChecksumRequired, false);

  memoizedProperty(this, 'input', function() {
    if (!operation.input) {
      return new Shape.create({type: 'structure'}, options);
    }
    return Shape.create(operation.input, options);
  });

  memoizedProperty(this, 'output', function() {
    if (!operation.output) {
      return new Shape.create({type: 'structure'}, options);
    }
    return Shape.create(operation.output, options);
  });

  memoizedProperty(this, 'errors', function() {
    var list = [];
    if (!operation.errors) return null;

    for (var i = 0; i < operation.errors.length; i++) {
      list.push(Shape.create(operation.errors[i], options));
    }

    return list;
  });

  memoizedProperty(this, 'paginator', function() {
    return options.api.paginators[name];
  });

  if (options.documentation) {
    property(this, 'documentation', operation.documentation);
    property(this, 'documentationUrl', operation.documentationUrl);
  }

  // idempotentMembers only tracks top-level input shapes
  memoizedProperty(this, 'idempotentMembers', function() {
    var idempotentMembers = [];
    var input = self.input;
    var members = input.members;
    if (!input.members) {
      return idempotentMembers;
    }
    for (var name in members) {
      if (!members.hasOwnProperty(name)) {
        continue;
      }
      if (members[name].isIdempotent === true) {
        idempotentMembers.push(name);
      }
    }
    return idempotentMembers;
  });

  memoizedProperty(this, 'hasEventOutput', function() {
    var output = self.output;
    return hasEventStream(output);
  });
}

function hasEventStream(topLevelShape) {
  var members = topLevelShape.members;
  var payload = topLevelShape.payload;

  if (!topLevelShape.members) {
    return false;
  }

  if (payload) {
    var payloadMember = members[payload];
    return payloadMember.isEventStream;
  }

  // check if any member is an event stream
  for (var name in members) {
    if (!members.hasOwnProperty(name)) {
      if (members[name].isEventStream === true) {
        return true;
      }
    }
  }
  return false;
}

/**
 * @api private
 */
module.exports = Operation;
<commit_msg>Handle httpChecksum.requestChecksumRequired trait (#4037)<commit_after>var Shape = require('./shape');

var util = require('../util');
var property = util.property;
var memoizedProperty = util.memoizedProperty;

function Operation(name, operation, options) {
  var self = this;
  options = options || {};

  property(this, 'name', operation.name || name);
  property(this, 'api', options.api, false);

  operation.http = operation.http || {};
  property(this, 'endpoint', operation.endpoint);
  property(this, 'httpMethod', operation.http.method || 'POST');
  property(this, 'httpPath', operation.http.requestUri || '/');
  property(this, 'authtype', operation.authtype || '');
  property(
    this,
    'endpointDiscoveryRequired',
    operation.endpointdiscovery ?
      (operation.endpointdiscovery.required ? 'REQUIRED' : 'OPTIONAL') :
    'NULL'
  );

  // httpChecksum replaces usage of httpChecksumRequired, but some APIs
  // (s3control) still uses old trait.
  var httpChecksumRequired = operation.httpChecksumRequired
    || (operation.httpChecksum && operation.httpChecksum.requestChecksumRequired);
  property(this, 'httpChecksumRequired', httpChecksumRequired, false);

  memoizedProperty(this, 'input', function() {
    if (!operation.input) {
      return new Shape.create({type: 'structure'}, options);
    }
    return Shape.create(operation.input, options);
  });

  memoizedProperty(this, 'output', function() {
    if (!operation.output) {
      return new Shape.create({type: 'structure'}, options);
    }
    return Shape.create(operation.output, options);
  });

  memoizedProperty(this, 'errors', function() {
    var list = [];
    if (!operation.errors) return null;

    for (var i = 0; i < operation.errors.length; i++) {
      list.push(Shape.create(operation.errors[i], options));
    }

    return list;
  });

  memoizedProperty(this, 'paginator', function() {
    return options.api.paginators[name];
  });

  if (options.documentation) {
    property(this, 'documentation', operation.documentation);
    property(this, 'documentationUrl', operation.documentationUrl);
  }

  // idempotentMembers only tracks top-level input shapes
  memoizedProperty(this, 'idempotentMembers', function() {
    var idempotentMembers = [];
    var input = self.input;
    var members = input.members;
    if (!input.members) {
      return idempotentMembers;
    }
    for (var name in members) {
      if (!members.hasOwnProperty(name)) {
        continue;
      }
      if (members[name].isIdempotent === true) {
        idempotentMembers.push(name);
      }
    }
    return idempotentMembers;
  });

  memoizedProperty(this, 'hasEventOutput', function() {
    var output = self.output;
    return hasEventStream(output);
  });
}

function hasEventStream(topLevelShape) {
  var members = topLevelShape.members;
  var payload = topLevelShape.payload;

  if (!topLevelShape.members) {
    return false;
  }

  if (payload) {
    var payloadMember = members[payload];
    return payloadMember.isEventStream;
  }

  // check if any member is an event stream
  for (var name in members) {
    if (!members.hasOwnProperty(name)) {
      if (members[name].isEventStream === true) {
        return true;
      }
    }
  }
  return false;
}

/**
 * @api private
 */
module.exports = Operation;
<|endoftext|>


<commit_before>'use strict';

const log = require('debug')('mongoose-hidden')

const hide = 'hide'
const hideObject = 'hideObject'
const hideJSON = 'hideJSON'
const hidden = 'hidden'
const defaultHidden = 'defaultHidden'
const virtuals = 'virtuals'

const _defaultOptions = {
  autoHide: true,
  autoHideJSON: true,
  autoHideObject: true,
  defaultHidden: { '_id': true, '__v': true },
  virtuals: {},
}

function shouldHide(schemaType, options, target, doc, transformed, pathname) {
  let hideTarget = hide + target

  // If hiding has been disabled ignore other settings
  if (!options[hide] || !options[hideTarget]) {
    return false
  }

  // Test hide by option or schema
  return testOptions(options, hideTarget, pathname)
    || testSchema(schemaType, hide, doc, transformed)
    || testSchema(schemaType, hideTarget, doc, transformed)
}

function testOptions(options, hideTarget, pathname) {
  return !!options.defaultHidden[pathname] || !!options.virtuals[pathname]
}

function testSchema(schemaType, key, doc, transformed) {
  if (typeof schemaType === 'undefined' || ! key in schemaType.options) {
    return false
  }
  return schemaType.options[key] === true || testSchemaFunc(schemaType, key, doc, transformed)
}

function testSchemaFunc(schemaType, key, doc, transformed) {
  if (typeof schemaType.options[key] === 'function') {
    return schemaType.options[key](doc, transformed)
  }
  return false
}

function getPathnames(options, schema) {
  let paths = Object.keys(schema.paths)
  Object.keys(options["defaultHidden"]).forEach(path => {
    if (paths.indexOf(path) === -1) {
      paths.push(path)
    }
  })
  return paths
}

function prepOptions(options, defaults) {
  let _options = options = options || {}

  // Set defaults from options and default
  options = {
    hide: hide in options ? !!options[hide] : defaults.autoHide,
    hideJSON: hideJSON in options ? !!options[hideJSON] : defaults.autoHideJSON,
    hideObject: hideObject in options ? !!options[hideObject] : defaults.autoHideObject,
    defaultHidden: Object.assign({}, (defaultHidden in options ? options[defaultHidden] : defaults.defaultHidden)),
    virtuals: virtuals in options ? options[virtuals] : defaults.virtuals,
  }

  // Add to default hidden
  if (typeof _options[hidden] === 'object') {
    options[defaultHidden] = Object.assign(options[defaultHidden], _options[hidden])
  }

  // Set defaults based on hide
  options[hideJSON] = !options[hide] ? false : options[hideJSON]
  options[hideObject] = !options[hide] ? false : options[hideObject]

  return options
}

const getPath = function (obj, path) {
  let parts = path.split('.')
  while (parts.length) {
    obj = obj[parts.shift()]
    if (typeof obj !== 'object' && parts.length) {
      return undefined
    }
  }
  return obj
}

const deletePath = function (obj, path) {
  let parts = path.split('.')
  while (parts.length > 1) {
    obj = obj[parts.shift()]
    if (typeof obj !== 'object' && parts.length) {
      return false
    }
  }
  delete obj[parts[0]]
  return true
}

const setPath = function (obj, path, value) {
  if (typeof value === 'undefined') {
    return false
  }

  let parts = path.split('.')
  if (parts.length === 1) {
    obj[path] = value
    return true
  }

  while (parts.length > 1 && typeof obj[parts[0]] === 'object') {
    obj = obj[parts.shift()]
  }

  if (parts.length === 1) {
    obj[parts[0]] = value
  } else {
    obj[parts[0]] = partsToObject(parts.slice(1), value)
  }
  return true
}

const partsToObject = function (parts, value) {
  if (parts.length === 0) {
    return value
  }
  let obj = {}
  obj[parts[0]] = partsToObject(parts.slice(1), value)
  return obj
}

module.exports = function (defaults) {
  let _defaults = Object.assign(Object.assign({}, _defaultOptions), defaults || {})

  log(_defaults)

  return function (schema, options) {
    options = prepOptions(options, _defaults)
    log(options)

    let schemaPaths = {}
    let paths = getPathnames(options, schema)

    log(paths)

    let transformer = function (target, prevTransform) {
      return function (doc, transformed, opt) {
        if (typeof doc.ownerDocument === 'function') {
          return transformed
        }

        log(transformed)

        // Apply existing transformer
        let finalTransform = {}
        if (typeof prevTransform === 'function') {
          log(target + ': running existing transform function')
          finalTransform = prevTransform(doc, transformed, opt)
          log(finalTransform)
        }

        // Copy real values
        paths.forEach(function (pathname) {
          let schemaType = schema.path(pathname)
          if (shouldHide(schemaType, options, target, doc, transformed, pathname)) {
            log(target + ': hiding "' + pathname + '"')
            deletePath(finalTransform, pathname)
          } else {
            log(target + ': copy "' + pathname + '"')
            setPath(finalTransform, pathname, getPath(transformed, pathname))
          }
        })

        // Copy virtual values
        for (let key in transformed) {
          if (schema.pathType(key) === 'virtual'
            && (options.virtuals[key] !== hide && options.virtuals[key] !== (`hide${target}`))) {
            log(target + ': copy virtual "' + key + '"')
            setPath(finalTransform, key, getPath(transformed, key))
          }
        }

        log(finalTransform)
        return finalTransform
      }
    }

    let toJSONOptions = schema.get('toJSON') || {}

    schema.set('toJSON', {
      getters: toJSONOptions['getters'] || false,
      virtuals: toJSONOptions[virtuals] || false,
      transform: transformer('JSON', toJSONOptions['transform'] || null)
    })

    let toObjectOptions = schema.get('toObject') || {}

    schema.set('toObject', {
      getters: toObjectOptions['getters'] || false,
      virtuals: toObjectOptions[virtuals] || false,
      transform: transformer('Object', toObjectOptions['transform'] || null)
    })
  }
}

/* for testing */
module.exports['__test'] = {
  getPath: getPath,
  setPath: setPath,
  deletePath: deletePath,
}
<commit_msg>undefined is undefined in some node versions (possible fix of #24)<commit_after>'use strict';

const log = require('debug')('mongoose-hidden')

const hide = 'hide'
const hideObject = 'hideObject'
const hideJSON = 'hideJSON'
const hidden = 'hidden'
const defaultHidden = 'defaultHidden'
const virtuals = 'virtuals'

const _defaultOptions = {
  autoHide: true,
  autoHideJSON: true,
  autoHideObject: true,
  defaultHidden: { '_id': true, '__v': true },
  virtuals: {},
}

function shouldHide(schemaType, options, target, doc, transformed, pathname) {
  let hideTarget = hide + target

  // If hiding has been disabled ignore other settings
  if (!options[hide] || !options[hideTarget]) {
    return false
  }

  // Test hide by option or schema
  return testOptions(options, hideTarget, pathname)
    || testSchema(schemaType, hide, doc, transformed)
    || testSchema(schemaType, hideTarget, doc, transformed)
}

function testOptions(options, hideTarget, pathname) {
  return !!options.defaultHidden[pathname] || !!options.virtuals[pathname]
}

function testSchema(schemaType, key, doc, transformed) {
  if (typeof schemaType === 'undefined' || ! key in schemaType.options) {
    return false
  }
  return schemaType.options[key] === true || testSchemaFunc(schemaType, key, doc, transformed)
}

function testSchemaFunc(schemaType, key, doc, transformed) {
  if (typeof schemaType.options[key] === 'function') {
    return schemaType.options[key](doc, transformed)
  }
  return false
}

function getPathnames(options, schema) {
  let paths = Object.keys(schema.paths)
  Object.keys(options["defaultHidden"]).forEach(path => {
    if (paths.indexOf(path) === -1) {
      paths.push(path)
    }
  })
  return paths
}

function prepOptions(options, defaults) {
  let _options = options = options || {}

  // Set defaults from options and default
  options = {
    hide: hide in options ? !!options[hide] : defaults.autoHide,
    hideJSON: hideJSON in options ? !!options[hideJSON] : defaults.autoHideJSON,
    hideObject: hideObject in options ? !!options[hideObject] : defaults.autoHideObject,
    defaultHidden: Object.assign({}, (defaultHidden in options ? options[defaultHidden] : defaults.defaultHidden)),
    virtuals: virtuals in options ? options[virtuals] : defaults.virtuals,
  }

  // Add to default hidden
  if (typeof _options[hidden] === 'object') {
    options[defaultHidden] = Object.assign(options[defaultHidden], _options[hidden])
  }

  // Set defaults based on hide
  options[hideJSON] = !options[hide] ? false : options[hideJSON]
  options[hideObject] = !options[hide] ? false : options[hideObject]

  return options
}

const getPath = function (obj, path) {
  let parts = path.split('.')
  while (parts.length) {
    obj = obj[parts.shift()]
    if (typeof obj !== 'object' && parts.length) {
      return ;
    }
  }
  return obj
}

const deletePath = function (obj, path) {
  let parts = path.split('.')
  while (parts.length > 1) {
    obj = obj[parts.shift()]
    if (typeof obj !== 'object' && parts.length) {
      return false
    }
  }
  delete obj[parts[0]]
  return true
}

const setPath = function (obj, path, value) {
  if (typeof value === 'undefined') {
    return false
  }

  let parts = path.split('.')
  if (parts.length === 1) {
    obj[path] = value
    return true
  }

  while (parts.length > 1 && typeof obj[parts[0]] === 'object') {
    obj = obj[parts.shift()]
  }

  if (parts.length === 1) {
    obj[parts[0]] = value
  } else {
    obj[parts[0]] = partsToObject(parts.slice(1), value)
  }
  return true
}

const partsToObject = function (parts, value) {
  if (parts.length === 0) {
    return value
  }
  let obj = {}
  obj[parts[0]] = partsToObject(parts.slice(1), value)
  return obj
}

module.exports = function (defaults) {
  let _defaults = Object.assign(Object.assign({}, _defaultOptions), defaults || {})

  log(_defaults)

  return function (schema, options) {
    options = prepOptions(options, _defaults)
    log(options)

    let schemaPaths = {}
    let paths = getPathnames(options, schema)

    log(paths)

    let transformer = function (target, prevTransform) {
      return function (doc, transformed, opt) {
        if (typeof doc.ownerDocument === 'function') {
          return transformed
        }

        log(transformed)

        // Apply existing transformer
        let finalTransform = {}
        if (typeof prevTransform === 'function') {
          log(target + ': running existing transform function')
          finalTransform = prevTransform(doc, transformed, opt)
          log(finalTransform)
        }

        // Copy real values
        paths.forEach(function (pathname) {
          let schemaType = schema.path(pathname)
          if (shouldHide(schemaType, options, target, doc, transformed, pathname)) {
            log(target + ': hiding "' + pathname + '"')
            deletePath(finalTransform, pathname)
          } else {
            log(target + ': copy "' + pathname + '"')
            setPath(finalTransform, pathname, getPath(transformed, pathname))
          }
        })

        // Copy virtual values
        for (let key in transformed) {
          if (schema.pathType(key) === 'virtual'
            && (options.virtuals[key] !== hide && options.virtuals[key] !== (`hide${target}`))) {
            log(target + ': copy virtual "' + key + '"')
            setPath(finalTransform, key, getPath(transformed, key))
          }
        }

        log(finalTransform)
        return finalTransform
      }
    }

    let toJSONOptions = schema.get('toJSON') || {}

    schema.set('toJSON', {
      getters: toJSONOptions['getters'] || false,
      virtuals: toJSONOptions[virtuals] || false,
      transform: transformer('JSON', toJSONOptions['transform'] || null)
    })

    let toObjectOptions = schema.get('toObject') || {}

    schema.set('toObject', {
      getters: toObjectOptions['getters'] || false,
      virtuals: toObjectOptions[virtuals] || false,
      transform: transformer('Object', toObjectOptions['transform'] || null)
    })
  }
}

/* for testing */
module.exports['__test'] = {
  getPath: getPath,
  setPath: setPath,
  deletePath: deletePath,
}
<|endoftext|>


<commit_before>describe('tenant-component', function() {
  var $componentController, vm, miqService, API;

  describe('when the vm.recordId is not defined', function () {

    beforeEach(module('ManageIQ'));
    beforeEach(inject(function (_$componentController_, _API_, _miqService_, $q) {
      $componentController = _$componentController_;
      API = _API_;
      miqService = _miqService_;

      spyOn(miqService.redirectBack, 'bind');

      var deferred = $q.defer();
      spyOn(API, 'post').and.callFake(function() {return deferred.promise;});

      var bindings = {redirectUrl: '/controller/go_back', divisible: true};
      vm = $componentController('tenantComponent', null, bindings);
      vm.$onInit();
    }));

    it('sets newRecord to true', function () {
      expect(vm.newRecord).toBe(true);
    });

    it('sets afterGet', function () {
      expect(vm.afterGet).toBe(true);
    });

    it('adds a Tenant record', function () {
      vm.tenantModel.name = 'newTenant';
      vm.tenantModel.description = 'newTenant_desc';
      vm.tenantModel.parent = null;
      vm.addClicked();
      expect(API.post).toHaveBeenCalledWith('/api/tenants/', {name: vm.tenantModel.name, description: vm.tenantModel.description, divisible: true, parent: {id: vm.tenantModel.parent}});
      expect(miqService.redirectBack.bind).toHaveBeenCalledWith(vm, 'Tenant \"newTenant\" has been successfully added.', 'success', vm.redirectUrl, true);
    });
  });

  describe('when the vm.recordId is defined', function () {
    beforeEach(module('ManageIQ'));
    beforeEach(inject(function (_$componentController_, _API_, _miqService_) {
      $componentController = _$componentController_;
      API = _API_;
      miqService = _miqService_;

      spyOn(miqService.redirectBack, 'bind');

      var tenantFormResponse = {
        name: 'abc',
        description: 'abc_desc',
        divisible: true
      };

      spyOn(API, 'get').and.callFake(function() {
        return {
          then: function (callback) {
            callback(tenantFormResponse);
            return {catch: function() {}};
          }
        };
      });

      spyOn(API, 'put').and.callFake(function() {
        return {
          then: function () {
            miqService.redirectBack();
            return {catch: function() {}};
          }
        };
      });

      var bindings = {recordId: 1111, redirectUrl: '/controller/go_back', divisible: true};
      vm = $componentController('tenantComponent', null, bindings);
      vm.$onInit();
    }));

    it('sets newRecord to true', function () {
      expect(vm.newRecord).toBe(false);
    });

    it('calls API.get with the appropriate URL', function () {
      expect(API.get).toHaveBeenCalledWith('/api/tenants/1111');
    });

    it('sets vm.tenantModel.name', function () {
      expect(vm.tenantModel.name).toBe('abc');
    });

    it('sets vm.tenantModel.description', function () {
      expect(vm.tenantModel.description).toBe('abc_desc');
    });

    it('updates a Tenant record', function () {
      vm.tenantModel.name = 'xyz';
      vm.tenantModel.description = 'xyz_desc';
      vm.saveClicked();
      expect(API.put).toHaveBeenCalledWith('/api/tenants/1111', {name: vm.tenantModel.name, description: vm.tenantModel.description});
      expect(miqService.redirectBack.bind).toHaveBeenCalledWith(vm, 'Tenant \"xyz\" has been successfully saved.', 'success', vm.redirectUrl, true);
    });
  });
});
<commit_msg>Fix specs based on changes made in the component<commit_after>describe('tenant-component', function() {
  var $componentController, vm, miqService, API;

  describe('when the vm.recordId is not defined', function () {

    beforeEach(module('ManageIQ'));
    beforeEach(inject(function (_$componentController_, _API_, _miqService_, $q) {
      $componentController = _$componentController_;
      API = _API_;
      miqService = _miqService_;

      spyOn(miqService.redirectBack, 'bind');

      var deferred = $q.defer();
      spyOn(API, 'post').and.callFake(function() {return deferred.promise;});

      var bindings = {redirectUrl: '/controller/go_back', divisible: true};
      vm = $componentController('tenantComponent', null, bindings);
      vm.$onInit();
    }));

    it('sets newRecord to true', function () {
      expect(vm.newRecord).toBe(true);
    });

    it('sets afterGet', function () {
      expect(vm.afterGet).toBe(true);
    });

    it('adds a Tenant record', function () {
      vm.tenantModel.name = 'newTenant';
      vm.tenantModel.description = 'newTenant_desc';
      vm.tenantModel.ancestry = null;
      vm.addClicked();
      expect(API.post).toHaveBeenCalledWith('/api/tenants/', {name: vm.tenantModel.name, description: vm.tenantModel.description, divisible: true, parent: {id: vm.tenantModel.ancestry}});
      expect(miqService.redirectBack.bind).toHaveBeenCalledWith(vm, 'Tenant \"newTenant\" has been successfully added.', 'success', vm.redirectUrl, true);
    });
  });

  describe('when the vm.recordId is defined', function () {
    beforeEach(module('ManageIQ'));
    beforeEach(inject(function (_$componentController_, _API_, _miqService_) {
      $componentController = _$componentController_;
      API = _API_;
      miqService = _miqService_;

      spyOn(miqService.redirectBack, 'bind');

      var tenantFormResponse = {
        name: 'abc',
        description: 'abc_desc',
        divisible: true
      };

      spyOn(API, 'get').and.callFake(function() {
        return {
          then: function (callback) {
            callback(tenantFormResponse);
            return {catch: function() {}};
          }
        };
      });

      spyOn(API, 'put').and.callFake(function() {
        return {
          then: function () {
            miqService.redirectBack();
            return {catch: function() {}};
          }
        };
      });

      var bindings = {recordId: 1111, redirectUrl: '/controller/go_back', divisible: true};
      vm = $componentController('tenantComponent', null, bindings);
      vm.$onInit();
    }));

    it('sets newRecord to true', function () {
      expect(vm.newRecord).toBe(false);
    });

    it('calls API.get with the appropriate URL', function () {
      expect(API.get).toHaveBeenCalledWith('/api/tenants/1111');
    });

    it('sets vm.tenantModel.name', function () {
      expect(vm.tenantModel.name).toBe('abc');
    });

    it('sets vm.tenantModel.description', function () {
      expect(vm.tenantModel.description).toBe('abc_desc');
    });

    it('updates a Tenant record', function () {
      vm.tenantModel.name = 'xyz';
      vm.tenantModel.description = 'xyz_desc';
      vm.saveClicked();
      expect(API.put).toHaveBeenCalledWith('/api/tenants/1111', {
        name: vm.tenantModel.name,
        description: vm.tenantModel.description,
        use_config_for_attributes: vm.tenantModel.use_config_for_attributes,});
      expect(miqService.redirectBack.bind).toHaveBeenCalledWith(vm, 'Tenant \"xyz\" has been successfully saved.', 'success', vm.redirectUrl, true);
    });
  });
});
<|endoftext|>