<commit_before>/**
 * All this does is add a Date.getTimezone() which makes
 *  a guess at the timezone.  That's all.  Uses [some] Olson
 *  zone data.  Works mostly.
 */
Date.prototype.getTimezone = function() {
	var timezones = {
	//  "OFFSET:DST_AMOUNT:DST_START": "TIMEZONE_ID
		"-39600:0:0":"Pacific/Midway",
		"-36000:3600:1331467200":"America/Adak",
		"-36000:0:0":"Pacific/Honolulu",
		"-34200:0:0":"Pacific/Marquesas",
		"-32400:3600:1331463600":"America/Juneau",
		"-32400:0:0":"Pacific/Gambier",
		"-28800:3600:1333274400":"America/Santa_Isabel",
		"-28800:3600:1331460000":"America/Los_Angeles",
		"-28800:0:0":"America/Metlakatla",
		"-25200:3600:1333270800":"America/Chihuahua",
		"-25200:3600:1331456400":"America/Denver",
		"-25200:0:0":"America/Phoenix",
		"-21600:3600:1333267200":"America/Mexico_City",
		"-21600:3600:1331452800":"America/Chicago",
		"-21600:0:0":"America/Guatemala",
		"-18000:3600:1331449200":"America/New_York",
		"-18000:3600:1331442000":"America/Havana",
		"-18000:0:0":"America/Cayman",
		"-18000:-3600:1331434800":"Pacific/Easter",
		"-16200:0:0":"America/Caracas",
		"-14400:3600:1331445600":"Atlantic/Bermuda",
		"-14400:0:0":"America/Puerto_Rico",
		"-12600:3600:1331443800":"America/St_Johns",
		"-10800:3600:1332637200":"America/Godthab",
		"-10800:3600:1331442000":"America/Miquelon",
		"-10800:0:0":"America/Fortaleza",
		"-10800:-3600:1334466000":"Atlantic/Stanley",
		"-10800:-3600:1333854000":"America/Asuncion",
		"-10800:-3600:1331434800":"America/Santiago",
		"-10800:-3600:1330225200":"America/Campo_Grande",
		"-7200:0:0":"America/Noronha",
		"-7200:-3600:1331438400":"America/Montevideo",
		"-7200:-3600:1330221600":"America/Bahia",
		"-3600:3600:1332637200":"America/Scoresbysund",
		"-3600:0:0":"Atlantic/Cape_Verde",
		"0:0:0":"UTC",
		"0:3600:1332637200":"Europe/London",
		"3600:0:0":"Africa/Algiers",
		"3600:3600:1332637200":"Europe/Stockholm",
		"7200:-3600:1333238400":"Africa/Windhoek",
		"7200:0:0":"Africa/Cairo",
		"7200:3600:1332626400":"Asia/Beirut",
		"7200:3600:1332637200":"Europe/Kiev",
		"7200:3600:1333058400":"Asia/Amman",
		"7200:3600:1333065600":"Asia/Jerusalem",
		"7200:3600:1333663200":"Asia/Damascus",
		"10800:0:0":"Africa/Nairobi",
		"12600:3600:1332275400":"Asia/Tehran",
		"14400:0:0":"Asia/Dubai",
		"14400:3600:1332626400":"Asia/Yerevan",
		"14400:3600:1332633600":"Asia/Baku",
		"16200:0:0":"Asia/Kabul",
		"18000:0:0":"Asia/Karachi",
		"19800:0:0":"Asia/Colombo",
		"20700:0:0":"Asia/Kathmandu",
		"21600:0:0":"Asia/Dhaka",
		"23400:0:0":"Asia/Rangoon",
		"25200:0:0":"Asia/Bangkok",
		"28800:0:0":"Asia/Hong_Kong",
		"31500:0:0":"Australia/Eucla",
		"32400:0:0":"Asia/Tokyo",
		"34200:0:0":"Australia/Darwin",
		"36000:0:0":"Australia/Brisbane",
		"37800:-3600:1333211400":"Australia/Broken_Hill",
		"39600:-1800:1333206000":"Australia/Lord_Howe",
		"39600:-3600:1333209600":"Australia/Sydney",
		"39600:0:0":"Pacific/Pohnpei",
		"41400:0:0":"Pacific/Norfolk",
		"43200:0:0":"Asia/Anadyr",
		"46800:-3600:1327154400":"Pacific/Fiji",
		"46800:-3600:1333202400":"Antarctica/South_Pole",
		"46800:0:0":"Pacific/Enderbury",
		"49500:-3600:1333202400":"Pacific/Chatham",
		"50400:-3600:1333202400":"Pacific/Apia",
		"50400:0:0":"Pacific/Kiritimati",
	};

	var getJanuaryTimezoneOffset = function() {
		return new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0).getTimezoneOffset() * -60;
	}

	var getJuneTimezoneOffset = function() {
		return new Date(new Date().getFullYear(), 5, 1, 0, 0, 0, 0).getTimezoneOffset() * -60;
	}

	var getDSTOffset = function() {
		return getJuneTimezoneOffset() - getJanuaryTimezoneOffset();
	}

	var tzKey = getJanuaryTimezoneOffset() + ':' + getDSTOffset();

	for (var a in timezones) {
		if (a.indexOf(tzKey) != 0)
			continue;

		var tzInfo = a.split(':');

		if (tzInfo[1] == 0)
			return timezones[a];

		var before = new Date();
		before.setTime((parseInt(tzInfo[2]) - 1) * 1000);

		var after = new Date();
		after.setTime(parseInt(tzInfo[2]) * 1000);

		if (before.getTimezoneOffset() != after.getTimezoneOffset())
			return timezones[a];
	}

	return null;
}
<commit_msg>wrap the script in a function<commit_after>/**
 * All this does is add a Date.getTimezone() which makes
 *  a guess at the timezone.  That's all.  Uses [some] Olson
 *  zone data.  Works mostly.
 */
(function(Date) {
	Date.prototype.getTimezone = function() {
		var timezones = {
		//  "OFFSET:DST_AMOUNT:DST_START": "TIMEZONE_ID
			"-39600:0:0":"Pacific/Midway",
			"-36000:3600:1331467200":"America/Adak",
			"-36000:0:0":"Pacific/Honolulu",
			"-34200:0:0":"Pacific/Marquesas",
			"-32400:3600:1331463600":"America/Juneau",
			"-32400:0:0":"Pacific/Gambier",
			"-28800:3600:1333274400":"America/Santa_Isabel",
			"-28800:3600:1331460000":"America/Los_Angeles",
			"-28800:0:0":"America/Metlakatla",
			"-25200:3600:1333270800":"America/Chihuahua",
			"-25200:3600:1331456400":"America/Denver",
			"-25200:0:0":"America/Phoenix",
			"-21600:3600:1333267200":"America/Mexico_City",
			"-21600:3600:1331452800":"America/Chicago",
			"-21600:0:0":"America/Guatemala",
			"-18000:3600:1331449200":"America/New_York",
			"-18000:3600:1331442000":"America/Havana",
			"-18000:0:0":"America/Cayman",
			"-18000:-3600:1331434800":"Pacific/Easter",
			"-16200:0:0":"America/Caracas",
			"-14400:3600:1331445600":"Atlantic/Bermuda",
			"-14400:0:0":"America/Puerto_Rico",
			"-12600:3600:1331443800":"America/St_Johns",
			"-10800:3600:1332637200":"America/Godthab",
			"-10800:3600:1331442000":"America/Miquelon",
			"-10800:0:0":"America/Fortaleza",
			"-10800:-3600:1334466000":"Atlantic/Stanley",
			"-10800:-3600:1333854000":"America/Asuncion",
			"-10800:-3600:1331434800":"America/Santiago",
			"-10800:-3600:1330225200":"America/Campo_Grande",
			"-7200:0:0":"America/Noronha",
			"-7200:-3600:1331438400":"America/Montevideo",
			"-7200:-3600:1330221600":"America/Bahia",
			"-3600:3600:1332637200":"America/Scoresbysund",
			"-3600:0:0":"Atlantic/Cape_Verde",
			"0:0:0":"UTC",
			"0:3600:1332637200":"Europe/London",
			"3600:0:0":"Africa/Algiers",
			"3600:3600:1332637200":"Europe/Stockholm",
			"7200:-3600:1333238400":"Africa/Windhoek",
			"7200:0:0":"Africa/Cairo",
			"7200:3600:1332626400":"Asia/Beirut",
			"7200:3600:1332637200":"Europe/Kiev",
			"7200:3600:1333058400":"Asia/Amman",
			"7200:3600:1333065600":"Asia/Jerusalem",
			"7200:3600:1333663200":"Asia/Damascus",
			"10800:0:0":"Africa/Nairobi",
			"12600:3600:1332275400":"Asia/Tehran",
			"14400:0:0":"Asia/Dubai",
			"14400:3600:1332626400":"Asia/Yerevan",
			"14400:3600:1332633600":"Asia/Baku",
			"16200:0:0":"Asia/Kabul",
			"18000:0:0":"Asia/Karachi",
			"19800:0:0":"Asia/Colombo",
			"20700:0:0":"Asia/Kathmandu",
			"21600:0:0":"Asia/Dhaka",
			"23400:0:0":"Asia/Rangoon",
			"25200:0:0":"Asia/Bangkok",
			"28800:0:0":"Asia/Hong_Kong",
			"31500:0:0":"Australia/Eucla",
			"32400:0:0":"Asia/Tokyo",
			"34200:0:0":"Australia/Darwin",
			"36000:0:0":"Australia/Brisbane",
			"37800:-3600:1333211400":"Australia/Broken_Hill",
			"39600:-1800:1333206000":"Australia/Lord_Howe",
			"39600:-3600:1333209600":"Australia/Sydney",
			"39600:0:0":"Pacific/Pohnpei",
			"41400:0:0":"Pacific/Norfolk",
			"43200:0:0":"Asia/Anadyr",
			"46800:-3600:1327154400":"Pacific/Fiji",
			"46800:-3600:1333202400":"Antarctica/South_Pole",
			"46800:0:0":"Pacific/Enderbury",
			"49500:-3600:1333202400":"Pacific/Chatham",
			"50400:-3600:1333202400":"Pacific/Apia",
			"50400:0:0":"Pacific/Kiritimati",
		};

		var getJanuaryTimezoneOffset = function() {
			return new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0).getTimezoneOffset() * -60;
		}

		var getJuneTimezoneOffset = function() {
			return new Date(new Date().getFullYear(), 5, 1, 0, 0, 0, 0).getTimezoneOffset() * -60;
		}

		var getDSTOffset = function() {
			return getJuneTimezoneOffset() - getJanuaryTimezoneOffset();
		}

		var tzKey = getJanuaryTimezoneOffset() + ':' + getDSTOffset();

		for (var a in timezones) {
			if (a.indexOf(tzKey) != 0)
				continue;

			var tzInfo = a.split(':');

			if (tzInfo[1] == 0)
				return timezones[a];

			var before = new Date();
			before.setTime((parseInt(tzInfo[2]) - 1) * 1000);

			var after = new Date();
			after.setTime(parseInt(tzInfo[2]) * 1000);

			if (before.getTimezoneOffset() != after.getTimezoneOffset())
				return timezones[a];
		}

		return null;
	}
})(Date);
<|endoftext|>


<commit_before>const Pagetest = require('./Pagetest');
const credentials = require('./credentials');

exports.call = function (db, data, req) {
    const API = new Pagetest.API(credentials.wpt_dns, credentials.wpt_api_key);
    const testUrl = data.url;
    const testLocation = data.location;
    const isClone = data.isClone == 'true';
    const caching = data.caching == 'true';

    const testScript =
`setActivityTimeout\t150
logData\t0
navigate\t${testUrl}&noCaching=true&blockExternal=true
navigate\tabout:blank
clearCache
logData\t1
navigate\t${testUrl}`;

    const testEntity = isClone ? testScript : testUrl;

    db.log.info('starting test for ' + testUrl + ' and location ' + testLocation);
    db.log.info('Test entity ' + testEntity);
    return API.runTest(testEntity, {
        connectivity: 'Native',
        location: testLocation,
        firstViewOnly: !caching,
        runs: 1,
        video: true,
        disableOptimization: true,
        pageSpeed: false,
        requests: false,
        breakDown: false,
        domains: false,
        saveResponseBodies: false,
        tcpDump: false,
        timeline: false,
        chromeTrace: false,
        netLog: false,
        disableHTTPHeaders: true,
        disableScreenshot: true,
        jpegQuality: 100,
        pingback: 'https://makefast.app.baqend.com/v1/code/testPingback'
    }).then(result => {
        db.log.info('Started Testid: ' + result.data.testId + ' for ' + testUrl);
        return {testId: result.data.testId};
    });
};<commit_msg>Devide test script into prewarm and test run.<commit_after>const Pagetest = require('./Pagetest');
const credentials = require('./credentials');

exports.call = function (db, data, req) {
    const API = new Pagetest.API(credentials.wpt_dns, credentials.wpt_api_key);
    const testUrl = data.url;
    const testLocation = data.location;
    const isClone = data.isClone == 'true';
    const caching = data.caching == 'true';

    const testOptions = {
        connectivity: 'Native',
        location: testLocation,
        firstViewOnly: !caching,
        runs: 1,
        video: true,
        disableOptimization: true,
        pageSpeed: false,
        requests: false,
        breakDown: false,
        domains: false,
        saveResponseBodies: false,
        tcpDump: false,
        timeline: false,
        chromeTrace: false,
        netLog: false,
        disableHTTPHeaders: true,
        disableScreenshot: true,
        jpegQuality: 100,
        pingback: 'https://makefast.app.baqend.com/v1/code/testPingback'
    };

    // test cloned website
    if (isClone) {
        const prewarmScript = `logData\t0\nnavigate\t${testUrl}`;

        const makefastUrl = testUrl.substr(testUrl.indexOf('?'));
        const testScript =
`setActivityTimeout\t150
logData\t0
navigate\t${makefastUrl}
navigate\tabout:blank
logData\t1
navigate\t${testUrl}`;

        return API.runTest(prewarmScript, Object.assign({}, testOptions, {pingback: ''})).then(() => {
            return API.runTest(testScript, testOptions);
        }).then(result => {
            db.log.info(`Clone test, id: ${result.data.testId} script:\n${testScript}`);
            return {testId: result.data.testId};
        });
    }

    // test original website
    return API.runTest(testUrl, testOptions).then(result => {
        db.log.info(`Original test, id: ${result.data.testId} url:\n${testUrl}`);
        db.log.info('Started Testid: ' + result.data.testId + ' for ' + testUrl);
        return {testId: result.data.testId};
    });
};<|endoftext|>


<commit_before>const error_div_class = "form-group required company_class form-class has-feedback has-error";
const error_input_icon = "form-control col-md-6 glyphicon glyphicon-remove";
const ok_div_class = "form-group required company_class form-class has-feedback has-success";
const ok_input_icon = "form-control col-md-6 glyphicon glyphicon-ok";

$(function() {
  new WOW().init();

  var prod = window.location.hostname.indexOf("metronus.es") !== -1;

  function custom_reload() {
    var cur_href = window.location.href;
    if(cur_href.endsWith("#")) {
      window.location.href = cur_href.substring(0, cur_href.length - 1);
    } else {
      window.location.href = cur_href;
    }
  }

  $("#flag_es").click(function() {
    if(prod) Cookies.set('lang', 'es-es', {domain: '.metronus.es'});
    else Cookies.set('lang', 'es-es');
    custom_reload();
  });

  $("#flag_en").click(function() {
    if(prod) Cookies.set('lang', 'en-us', {domain: '.metronus.es'});
    else Cookies.set('lang', 'en-us');
    custom_reload();
  });

  // Cuando el AJAX da error pero se cambia, se quita el error del ajax para limpiar
  $("input").on('input', function(){
    if($(this).parent().find(".ajax-error").is(":visible")){
      $(this).parent().find(".ajax-error").hide();
      $(this).removeClass('glyphicon-remove')
    }
  });

  //Lor numericos
  $('.precio').each(function(i) {
    $(this).val($(this).attr("value").replace(",", "."));
  });

  //search event
  $('#searcher').on('keyup',function() {
    var modelo=$('#searcher_model').val();
    search_list(modelo);
  });
  //search event
  $('#search_button').on('click',function() {
    var modelo=$('#searcher_model').val();
    search_list(modelo);
  });
});

function initAjax(field, field_str, url){
  field.change(function(){
    ajaxValidation($(this), field_str, url);
  });
}

// It sets all the necessary to perform ajax validations
function ajaxValidation(field, field_str, url){
  var div = $(field).parent().parent();
  var msg_div = $(field).parent().find(".ajax-error");
  var data = { };

  // If the field is incorrect by Bootstrap Validator or is empty, it is just incorrect
  if(field.val() == "" || field.hasClass('glyphicon-remove')){
    return;
  }

  data[field_str] = field.val();

  $.ajax({
    url: url,
    data: data,
    dataType: 'json',
    success: function (data) {
      setValidationState(data.is_taken, div, msg_div);
    }
  });
}

// AUXILIAR FUNCTION TO SET VALIDATION STATE
function setValidationState(error, div, message){
  if(error){
    div.removeClass().addClass(error_div_class);
    div.find("input").removeClass().addClass(error_input_icon);
    div.find("i").removeClass("glyphicon-ok").addClass("glyphicon-remove");
    message.show();
  } else {
    div.removeClass().addClass(ok_div_class);
    div.find("input").removeClass().addClass(ok_input_icon);
    div.find("i").removeClass("glyphicon-remove").addClass("glyphicon-ok");
    message.hide();
  }
  div.find("input").removeClass("glyphicon");
}

// Collapse the last collapsible if there is more than one
function autocollapse() {
  var collapse_buttons = $("a.collapse-link");
  if(collapse_buttons.length > 1) {
      collapse_buttons.last().click();
  }
}
//Hace una busqueda al modelo(project,department,etc.) con el valor del buscador
function search_list(modelo){
  //get value
  var buscador=document.getElementById("searcher");
  var cadena=buscador.value;
  //do search
  $.get({url:"/"+modelo+"/search/"+cadena+"/",
    success: function(data){

      $('#table_search').html($.parseHTML(data.trim()));

      simpletext = new RegExp("(" + cadena + ")","gi");

      //those with searchable class should contain only text,
      //otherwise magic will happen
      //not good magic, you know
      $('.searchable').each(function(i,el){

        var html=$(el).html();
        //highlight matches
        $(el).hide().html(html.replace(simpletext,"$1")).fadeIn();

      });
    }});
}
// Añadir el icono de info a los tooltips de información
$(function() {
  $("div.help-tooltip > p").first().prepend(" ");
  $("div.help-tooltip > p").slice(1).prepend(" ");
});
<commit_msg>Fixed AJAX behaviour<commit_after>const error_div_class = "form-group required company_class form-class has-feedback has-error";
const error_input_icon = "form-control col-md-6 glyphicon glyphicon-remove";
const ok_div_class = "form-group required company_class form-class has-feedback has-success";
const ok_input_icon = "form-control col-md-6 glyphicon glyphicon-ok";

$(function() {
  new WOW().init();

  var prod = window.location.hostname.indexOf("metronus.es") !== -1;

  function custom_reload() {
    var cur_href = window.location.href;
    if(cur_href.endsWith("#")) {
      window.location.href = cur_href.substring(0, cur_href.length - 1);
    } else {
      window.location.href = cur_href;
    }
  }

  $("#flag_es").click(function() {
    if(prod) Cookies.set('lang', 'es-es', {domain: '.metronus.es'});
    else Cookies.set('lang', 'es-es');
    custom_reload();
  });

  $("#flag_en").click(function() {
    if(prod) Cookies.set('lang', 'en-us', {domain: '.metronus.es'});
    else Cookies.set('lang', 'en-us');
    custom_reload();
  });

  // Cuando el AJAX da error pero se cambia, se quita el error del ajax para limpiar
  $("input").on('input', function(){
    if($(this).parent().find(".ajax-error").is(":visible")){
      $(this).parent().find(".ajax-error").hide();
      $(this).removeClass('glyphicon-remove')
    }
  });

  //Lor numericos
  $('.precio').each(function(i) {
    $(this).val($(this).attr("value").replace(",", "."));
  });

  //search event
  $('#searcher').on('keyup',function() {
    var modelo=$('#searcher_model').val();
    search_list(modelo);
  });
  //search event
  $('#search_button').on('click',function() {
    var modelo=$('#searcher_model').val();
    search_list(modelo);
  });
});

function initAjax(field, field_str, url){
  field.change(function(){
    ajaxValidation($(this), field_str, url);
  });
}

// It sets all the necessary to perform ajax validations
function ajaxValidation(field, field_str, url){
  var div = $(field).parent().parent();
  var msg_div = $(field).parent().find(".ajax-error");
  var indicator = $(field).next("i");
  var data = { };

  // If the field is incorrect by Bootstrap Validator or is empty, it is just incorrect
  if(field.val() == "" || indicator.hasClass('glyphicon-remove')){
    return;
  }

  data[field_str] = field.val();

  $.ajax({
    url: url,
    data: data,
    dataType: 'json',
    success: function (data) {
      setValidationState(data.is_taken, div, msg_div);
    }
  });
}

// AUXILIAR FUNCTION TO SET VALIDATION STATE
function setValidationState(error, div, message){
  if(error){
    div.removeClass().addClass(error_div_class);
    div.find("input").removeClass().addClass(error_input_icon);
    div.find("i").removeClass("glyphicon-ok").addClass("glyphicon-remove");
    message.show();
  } else {
    div.removeClass().addClass(ok_div_class);
    div.find("input").removeClass().addClass(ok_input_icon);
    div.find("i").removeClass("glyphicon-remove").addClass("glyphicon-ok");
    message.hide();
  }
  div.find("input").removeClass("glyphicon");
}

// Collapse the last collapsible if there is more than one
function autocollapse() {
  var collapse_buttons = $("a.collapse-link");
  if(collapse_buttons.length > 1) {
      collapse_buttons.last().click();
  }
}
//Hace una busqueda al modelo(project,department,etc.) con el valor del buscador
function search_list(modelo){
  //get value
  var buscador=document.getElementById("searcher");
  var cadena=buscador.value;
  //do search
  $.get({url:"/"+modelo+"/search/"+cadena+"/",
    success: function(data){

      $('#table_search').html($.parseHTML(data.trim()));

      simpletext = new RegExp("(" + cadena + ")","gi");

      //those with searchable class should contain only text,
      //otherwise magic will happen
      //not good magic, you know
      $('.searchable').each(function(i,el){

        var html=$(el).html();
        //highlight matches
        $(el).hide().html(html.replace(simpletext,"$1")).fadeIn();

      });
    }});
}
// Añadir el icono de info a los tooltips de información
$(function() {
  $("div.help-tooltip > p").first().prepend(" ");
  $("div.help-tooltip > p").slice(1).prepend(" ");
});
<|endoftext|>


<commit_before>/**
 * AdSenseModuleStatus component.
 *
 * Site Kit by Google, Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://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.
 */

import PropTypes from 'prop-types';
import SvgIcon from 'GoogleUtil/svg-icon';
import { getAdSenseAccountStatus } from '../util';
import ProgressBar from 'GoogleComponents/progress-bar';
import AdSenseSetupInstructions from '../setup/adsense-setup-instructions';
import AdSenseInProcessStatus from './adsense-in-process-status';
import {
	getExistingTag,
} from 'GoogleUtil';

const { Component, Fragment } = wp.element;
const { __ } = wp.i18n;

class AdSenseModuleStatus extends Component {

	constructor( props ) {
		super( props );
		this.state = {
			loadStatus: __( 'Loading…', 'google-site-kit' ),
			existingTag: false,
		};
		this.updateLoadStatus      = this.updateLoadStatus.bind( this );
		this.handleComponentRender = this.handleComponentRender.bind( this );
		this.continueSetup         = this.continueSetup.bind( this );
		this.goBack                = this.goBack.bind( this );
	}

	// Update the load status as the user status is determined.
	updateLoadStatus( loadStatus ) {
		this.setState( { ...this.state, loadStatus } );
	}

	async componentDidMount() {
		const existingTag = await getExistingTag( 'adsense' );

		this.setState(
			{ existingTag: 'no tag' === existingTag ? false : existingTag },
			() => {
				getAdSenseAccountStatus( this.updateLoadStatus, this.state.existingTag ).then( ( results ) => {
					this.setState( results );
				} );
			}
		);
	}

	/**
	 * If setup requires a continue step, the method repopulates state with the new data.
	 */
	continueSetup( continueData ) {
		continueData.existingState = this.state;
		this.setState( continueData );
	}

	/**
	 * Go back to the previous (existing) state.
	 */
	goBack() {
		const { existingState } = this.state;
		if ( existingState ) {
			existingState.existingState = false;
			this.setState( existingState );
		}
	}

	handleComponentRender() {
		const {
			accountStatus,
			loadStatus,
		} = this.state;

		if ( ! googlesitekit.canAdsRun && ! googlesitekit.modules.adsense.setupComplete ) {
			return (
				<Fragment>

						<SvgIcon id="error" height="20" width="23"/> { __( 'Ad blocker detected, you need to disable it in order to setup AdSense.', 'google-site-kit' ) }

				</Fragment>
			);
		}

		if ( ! accountStatus ) {
			return (
				<Fragment>
					{ loadStatus }
					<ProgressBar/>
				</Fragment>
			);
		}
		if ( 'account-pending-review' === accountStatus ) {
			return (
				<AdSenseInProcessStatus status='incomplete' />
			);
		}

		if ( 'account-required-action' === accountStatus ) {
			return (
				<AdSenseInProcessStatus status='requiredAction' />
			);
		}

		if ( 'ads-display-pending' === accountStatus ) {
			return (
				<AdSenseInProcessStatus status='adsDisplayPending' />
			);
		}

		return (
			<AdSenseSetupInstructions
				{ ...this.state }
				continueSetup={ this.continueSetup }
				goBack={ this.goBack }
			/>
		);
	}

	render() {
		return (

						<SvgIcon id="adsense" width="33" height="33"/>

						{ __( 'AdSense', 'google-site-kit' ) }

					{ this.handleComponentRender() }

		);
	}
}

AdSenseModuleStatus.propTypes = {
	status: PropTypes.string,
	module: PropTypes.string
};

export default AdSenseModuleStatus;
<commit_msg>remove set state callback<commit_after>/**
 * AdSenseModuleStatus component.
 *
 * Site Kit by Google, Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://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.
 */

import PropTypes from 'prop-types';
import SvgIcon from 'GoogleUtil/svg-icon';
import { getAdSenseAccountStatus } from '../util';
import ProgressBar from 'GoogleComponents/progress-bar';
import AdSenseSetupInstructions from '../setup/adsense-setup-instructions';
import AdSenseInProcessStatus from './adsense-in-process-status';
import {
	getExistingTag,
} from 'GoogleUtil';

const { Component, Fragment } = wp.element;
const { __ } = wp.i18n;

class AdSenseModuleStatus extends Component {

	constructor( props ) {
		super( props );
		this.state = {
			loadStatus: __( 'Loading…', 'google-site-kit' ),
			existingTag: false,
		};
		this.updateLoadStatus      = this.updateLoadStatus.bind( this );
		this.handleComponentRender = this.handleComponentRender.bind( this );
		this.continueSetup         = this.continueSetup.bind( this );
		this.goBack                = this.goBack.bind( this );
	}

	// Update the load status as the user status is determined.
	updateLoadStatus( loadStatus ) {
		this.setState( { ...this.state, loadStatus } );
	}

	async componentDidMount() {
		let existingTag = await getExistingTag( 'adsense' );
		existingTag = 'no tag' === existingTag ? false : existingTag;

		this.setState( { existingTag } );

		getAdSenseAccountStatus( this.updateLoadStatus, existingTag ).then( ( results ) => {
			this.setState( results );
		} );
	}

	/**
	 * If setup requires a continue step, the method repopulates state with the new data.
	 */
	continueSetup( continueData ) {
		continueData.existingState = this.state;
		this.setState( continueData );
	}

	/**
	 * Go back to the previous (existing) state.
	 */
	goBack() {
		const { existingState } = this.state;
		if ( existingState ) {
			existingState.existingState = false;
			this.setState( existingState );
		}
	}

	handleComponentRender() {
		const {
			accountStatus,
			loadStatus,
		} = this.state;

		if ( ! googlesitekit.canAdsRun && ! googlesitekit.modules.adsense.setupComplete ) {
			return (
				<Fragment>

						<SvgIcon id="error" height="20" width="23"/> { __( 'Ad blocker detected, you need to disable it in order to setup AdSense.', 'google-site-kit' ) }

				</Fragment>
			);
		}

		if ( ! accountStatus ) {
			return (
				<Fragment>
					{ loadStatus }
					<ProgressBar/>
				</Fragment>
			);
		}
		if ( 'account-pending-review' === accountStatus ) {
			return (
				<AdSenseInProcessStatus status='incomplete' />
			);
		}

		if ( 'account-required-action' === accountStatus ) {
			return (
				<AdSenseInProcessStatus status='requiredAction' />
			);
		}

		if ( 'ads-display-pending' === accountStatus ) {
			return (
				<AdSenseInProcessStatus status='adsDisplayPending' />
			);
		}

		return (
			<AdSenseSetupInstructions
				{ ...this.state }
				continueSetup={ this.continueSetup }
				goBack={ this.goBack }
			/>
		);
	}

	render() {
		return (

						<SvgIcon id="adsense" width="33" height="33"/>

						{ __( 'AdSense', 'google-site-kit' ) }

					{ this.handleComponentRender() }

		);
	}
}

AdSenseModuleStatus.propTypes = {
	status: PropTypes.string,
	module: PropTypes.string
};

export default AdSenseModuleStatus;
<|endoftext|>


<commit_before>/**
 * Copyright 2018, 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.
 */

'use strict';

const Compute = require('@google-cloud/compute');
const http = require('http');

const compute = new Compute();

const zone = compute.zone('us-central1-a');

// callback(error, externalIp)
function createVm(name, callback) {
  // Create a new VM, using default ubuntu image. The startup script
  // installs apache and a custom homepage.
  const config = {
    os: 'ubuntu',
    http: true,
    metadata: {
      items: [
        {
          key: 'startup-script',
          value: `#! /bin/bash

        # Installs apache and a custom homepage
        apt-get update
        apt-get install -y apache2
        cat <<EOF > /var/www/html/index.html

Hello World

This page was created from a simple start up script!

        `,
        },
      ],
    },
  };

  const vm = zone.vm(name);

  vm
    .create(config)
    .then(data => {
      const operation = data[1];
      return operation.promise();
    })
    .then(() => {
      return vm.getMetadata();
    })
    .then(data => {
      const metadata = data[0];

      // External IP of the VM.
      const ip = metadata['networkInterfaces'][0]['accessConfigs'][0]['natIP'];
      console.log('Booting new VM with IP http://' + ip + '...');

      // Ping the VM to determine when the HTTP server is ready.
      let waiting = true;
      const timer = setInterval(
        ip => {
          http
            .get('http://' + ip, res => {
              const statusCode = res.statusCode;
              if (statusCode === 200 && waiting) {
                waiting = false;
                clearTimeout(timer);
                // HTTP server is ready.
                console.log('Ready!');
                callback(null, ip);
              }
            })
            .on('error', () => {
              // HTTP server is not ready yet.
              process.stdout.write('.');
            });
        },
        2000,
        ip
      );
    })
    .catch(err => callback(err));
}

// List all VMs and their external IPs in a given zone.
// callback(error, [[name, ip], [name, ip], ...])
function listVms(callback) {
  zone
    .getVMs()
    .then(data => {
      const vms = data[0];
      let results = vms.map(vm => vm.getMetadata());
      return Promise.all(results);
    })
    .then(res =>
      callback(
        null,
        res.map(data => {
          return {
            ip: data[0]['networkInterfaces'][0]['accessConfigs']
              ? data[0]['networkInterfaces'][0]['accessConfigs'][0]['natIP']
              : 'no external ip',
            name: data[0].name,
          };
        })
      )
    )
    .catch(err => callback(err));
}

function deleteVm(name, callback) {
  const vm = zone.vm(name);
  vm
    .delete()
    .then(data => {
      console.log('Deleting ...');
      const operation = data[0];
      return operation.promise();
    })
    .then(() => {
      // VM deleted
      callback(null, name);
    })
    .catch(err => callback(err));
}

exports.create = (name, cb) => {
  createVm(name, cb);
};

exports.list = cb => {
  listVms(cb);
};

exports.delete = (name, cb) => {
  deleteVm(name, cb);
};
<commit_msg>Simplify JS and use HTML standard (#91)<commit_after>/**
 * Copyright 2018, 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.
 */

'use strict';

const Compute = require('@google-cloud/compute');
const http = require('http');

const compute = new Compute();

const zone = compute.zone('us-central1-a');

// callback(error, externalIp)
function createVm(name, callback) {
  // Create a new VM, using default ubuntu image. The startup script
  // installs apache and a custom homepage.
  const config = {
    os: 'ubuntu',
    http: true,
    metadata: {
      items: [
        {
          key: 'startup-script',
          value: `#! /bin/bash

        # Installs apache and a custom homepage
        apt-get update
        apt-get install -y apache2
        cat <<EOF > /var/www/html/index.html
        <!doctype html>

Hello World

This page was created from a simple start-up script!
`,
        },
      ],
    },
  };

  const vm = zone.vm(name);

  vm
    .create(config)
    .then(data => {
      const operation = data[1];
      return operation.promise();
    })
    .then(() => {
      return vm.getMetadata();
    })
    .then(data => {
      const metadata = data[0];

      // External IP of the VM.
      const ip = metadata.networkInterfaces[0].accessConfigs[0].natIP;
      console.log(`Booting new VM with IP http://${ip}...`);

      // Ping the VM to determine when the HTTP server is ready.
      let waiting = true;
      const timer = setInterval(
        ip => {
          http
            .get('http://' + ip, res => {
              const statusCode = res.statusCode;
              if (statusCode === 200 && waiting) {
                waiting = false;
                clearTimeout(timer);
                // HTTP server is ready.
                console.log('Ready!');
                callback(null, ip);
              }
            })
            .on('error', () => {
              // HTTP server is not ready yet.
              process.stdout.write('.');
            });
        },
        2000,
        ip
      );
    })
    .catch(err => callback(err));
}

// List all VMs and their external IPs in a given zone.
// callback(error, [[name, ip], [name, ip], ...])
function listVms(callback) {
  zone
    .getVMs()
    .then(data => {
      const vms = data[0];
      let results = vms.map(vm => vm.getMetadata());
      return Promise.all(results);
    })
    .then(res =>
      callback(
        null,
        res.map(data => {
          return {
            ip: data[0]['networkInterfaces'][0]['accessConfigs']
              ? data[0]['networkInterfaces'][0]['accessConfigs'][0]['natIP']
              : 'no external ip',
            name: data[0].name,
          };
        })
      )
    )
    .catch(err => callback(err));
}

function deleteVm(name, callback) {
  const vm = zone.vm(name);
  vm
    .delete()
    .then(data => {
      console.log('Deleting ...');
      const operation = data[0];
      return operation.promise();
    })
    .then(() => {
      // VM deleted
      callback(null, name);
    })
    .catch(err => callback(err));
}

exports.create = (name, cb) => {
  createVm(name, cb);
};

exports.list = cb => {
  listVms(cb);
};

exports.delete = (name, cb) => {
  deleteVm(name, cb);
};
<|endoftext|>


<commit_before>/*
	Module for Robo motion control
*/

var five = require("johnny-five"),
    board = new five.Board();

board.on("ready", function() {
  var leftFront, rightFront, leftBack, rightBack;
  /*
    Bi-Directional Motors can be initialized by:

      new five.Motor([ 3, 12 ]);

    ...is the same as...

      new five.Motor({
        pins: [ 3, 12 ]
      });

    ...is the same as...

      new five.Motor({
        pins: {
          pwm: 3,
          dir: 12
        }
      });

   */

  leftFront = new five.Motor({
    pins: {
      pwm: 11,
      dir: 12
    }
  });

  rightFront = new five.Motor({
    pins: {
      pwm: 9,
      dir: 8
    }
  });

  leftBack = new five.Motor({
    pins: {
      pwm: 6,
      dir: 7
    }
  });

  rightBack = new five.Motor({
    pins: {
      pwm: 3,
      dir: 2
    }
  });

  board.repl.inject({
    leftFront: leftFront,
    rightFront: rightFront,
    leftBack: leftBack,
    rightBack: rightBack
  });

  leftFront.on("start", function(err, timestamp) {
    console.log("leftFront start", timestamp);
  });

  rightFront.on("start", function(err, timestamp) {
    console.log("rightFront start", timestamp);
  });

  leftBack.on("start", function(err, timestamp) {
    console.log("leftBack start", timestamp);
  });

  rightBack.on("start", function(err, timestamp) {
    console.log("rightBack start", timestamp);
  });

  leftFront.on("stop", function(err, timestamp) {
    console.log("leftFront stop", timestamp);
  });

  rightFront.on("stop", function(err, timestamp) {
    console.log("rightFront stop", timestamp);
  });

  leftBack.on("stop", function(err, timestamp) {
    console.log("leftBack stop", timestamp);
  });

  rightBack.on("stop", function(err, timestamp) {
    console.log("rightBack stop", timestamp);
  });

});

/* Moves the robo forward */
exports.forward = function(){
	console.log('moving forward');
  leftFront.forward(255);
  rightFront.forward(255);
  leftBack.forward(255);
  rightBack.forward(255);
}

/* Moves the robo backword */
exports.back = function(){
	console.log('moving back');
  leftFront.reverse(255);
  rightFront.reverse(255);
  leftBack.reverse(255);
  rightBack.reverse(255);
}

/* Turns the robo to left direction */
exports.turnLeft = function(){
	console.log('turning left');
}

/* Turns the robo towards right */
exports.turnRight = function(){
	console.log('turning right');
}

/* Stop the robo */
exports.stop = function(){
	console.log('stopping');
  leftFront.stop();
  rightFront.stop();
  leftBack.stop();
  rightBack.stop();
}

<commit_msg>correcting scope issue for motion control<commit_after>/*
	Module for Robo motion control
*/

var five = require("johnny-five"),
    board = new five.Board();

board.on("ready", function() {
  var leftFront, rightFront, leftBack, rightBack;
  /*
    Bi-Directional Motors can be initialized by:

      new five.Motor([ 3, 12 ]);

    ...is the same as...

      new five.Motor({
        pins: [ 3, 12 ]
      });

    ...is the same as...

      new five.Motor({
        pins: {
          pwm: 3,
          dir: 12
        }
      });

   */

  leftFront = new five.Motor({
    pins: {
      pwm: 11,
      dir: 12
    }
  });

  rightFront = new five.Motor({
    pins: {
      pwm: 9,
      dir: 8
    }
  });

  leftBack = new five.Motor({
    pins: {
      pwm: 6,
      dir: 7
    }
  });

  rightBack = new five.Motor({
    pins: {
      pwm: 3,
      dir: 2
    }
  });

  board.repl.inject({
    leftFront: leftFront,
    rightFront: rightFront,
    leftBack: leftBack,
    rightBack: rightBack
  });

  leftFront.on("start", function(err, timestamp) {
    console.log("leftFront start", timestamp);
  });

  rightFront.on("start", function(err, timestamp) {
    console.log("rightFront start", timestamp);
  });

  leftBack.on("start", function(err, timestamp) {
    console.log("leftBack start", timestamp);
  });

  rightBack.on("start", function(err, timestamp) {
    console.log("rightBack start", timestamp);
  });

  leftFront.on("stop", function(err, timestamp) {
    console.log("leftFront stop", timestamp);
  });

  rightFront.on("stop", function(err, timestamp) {
    console.log("rightFront stop", timestamp);
  });

  leftBack.on("stop", function(err, timestamp) {
    console.log("leftBack stop", timestamp);
  });

  rightBack.on("stop", function(err, timestamp) {
    console.log("rightBack stop", timestamp);
  });

  /* Moves the robo forward */
  exports.forward = function(){
    console.log('moving forward');
    leftFront.forward(255);
    rightFront.forward(255);
    leftBack.forward(255);
    rightBack.forward(255);
  }

  /* Moves the robo backword */
  exports.back = function(){
    console.log('moving back');
    leftFront.reverse(255);
    rightFront.reverse(255);
    leftBack.reverse(255);
    rightBack.reverse(255);
  }

  /* Turns the robo to left direction */
  exports.turnLeft = function(){
    console.log('turning left');
  }

  /* Turns the robo towards right */
  exports.turnRight = function(){
    console.log('turning right');
  }

  /* Stop the robo */
  exports.stop = function(){
    console.log('stopping');
    leftFront.stop();
    rightFront.stop();
    leftBack.stop();
    rightBack.stop();
  }

});

<|endoftext|>


<commit_before>/**
 * Copyright 2014, 2015 IBM Corp.
 *
 * 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.
 **/

var express = require("express");
var bodyParser = require("body-parser");
var util = require('util');
var path = require('path');
var passport = require('passport');
var when = require('when');

var ui = require("./ui");
var nodes = require("./nodes");
var flows = require("./flows");
var flow = require("./flow");
var library = require("./library");
var info = require("./info");
var theme = require("./theme");
var locales = require("./locales");
var credentials = require("./credentials");
var comms = require("./comms");

var auth = require("./auth");
var needsPermission = auth.needsPermission;

var i18n;
var log;
var adminApp;
var nodeApp;
var server;

var errorHandler = function(err,req,res,next) {
    if (err.message === "request entity too large") {
        log.error(err);
    } else {
        console.log(err.stack);
    }
    log.audit({event: "api.error",error:err.code||"unexpected_error",message:err.toString()},req);
    res.status(400).json({error:"unexpected_error", message:err.toString()});
};

function init(_server,runtime) {
    server = _server;
    var settings = runtime.settings;
    i18n = runtime.i18n;
    log = runtime.log;
    if (settings.httpNodeRoot !== false) {
        nodeApp = express();
    }
    if (settings.httpAdminRoot !== false) {
        comms.init(server,runtime);
        adminApp = express();
        auth.init(runtime);
        credentials.init(runtime);
        flows.init(runtime);
        flow.init(runtime);
        info.init(runtime);
        library.init(adminApp,runtime);
        locales.init(runtime);
        nodes.init(runtime);

        // Editor
        if (!settings.disableEditor) {
            ui.init(runtime);
            var editorApp = express();
            editorApp.get("/",ui.ensureSlash,ui.editor);
            editorApp.get("/icons/:icon",ui.icon);
            editorApp.post("/enableSession",ui.enableSession);
            theme.init(runtime);
            if (settings.editorTheme) {
                editorApp.use("/theme",theme.app());
            }
            editorApp.use("/",ui.editorResources);
            adminApp.use(editorApp);
        }
        var maxApiRequestSize = settings.apiMaxLength || '1mb';
        adminApp.use(bodyParser.json({limit:maxApiRequestSize}));
        adminApp.use(bodyParser.urlencoded({limit:maxApiRequestSize,extended:true}));

        adminApp.get("/auth/login",auth.login,errorHandler);

        if (settings.adminAuth) {
            //TODO: all passport references ought to be in ./auth
            adminApp.use(passport.initialize());
            adminApp.post("/auth/token",
                auth.ensureClientSecret,
                auth.authenticateClient,
                auth.getToken,
                auth.errorHandler
            );
            adminApp.post("/auth/revoke",needsPermission(""),auth.revoke,errorHandler);
        }

        // Flows
        adminApp.get("/flows",needsPermission("flows.read"),flows.get,errorHandler);
        adminApp.post("/flows",needsPermission("flows.write"),flows.post,errorHandler);

        adminApp.get("/flow/:id",needsPermission("flows.read"),flow.get,errorHandler);
        adminApp.post("/flow",needsPermission("flows.write"),flow.post,errorHandler);
        adminApp.delete("/flow/:id",needsPermission("flows.write"),flow.delete,errorHandler);
        adminApp.put("/flow/:id",needsPermission("flows.write"),flow.put,errorHandler);

        // Nodes
        adminApp.get("/nodes",needsPermission("nodes.read"),nodes.getAll,errorHandler);
        adminApp.post("/nodes",needsPermission("nodes.write"),nodes.post,errorHandler);

        adminApp.get("/nodes/:mod",needsPermission("nodes.read"),nodes.getModule,errorHandler);
        adminApp.put("/nodes/:mod",needsPermission("nodes.write"),nodes.putModule,errorHandler);
        adminApp.delete("/nodes/:mod",needsPermission("nodes.write"),nodes.delete,errorHandler);

        adminApp.get("/nodes/:mod/:set",needsPermission("nodes.read"),nodes.getSet,errorHandler);
        adminApp.put("/nodes/:mod/:set",needsPermission("nodes.write"),nodes.putSet,errorHandler);

        adminApp.get('/credentials/:type/:id', needsPermission("credentials.read"),credentials.get,errorHandler);

        adminApp.get(/locales\/(.+)\/?$/,locales.get,errorHandler);

        // Library
        adminApp.post(new RegExp("/library/flows\/(.*)"),needsPermission("library.write"),library.post,errorHandler);
        adminApp.get("/library/flows",needsPermission("library.read"),library.getAll,errorHandler);
        adminApp.get(new RegExp("/library/flows\/(.*)"),needsPermission("library.read"),library.get,errorHandler);

        // Settings
        adminApp.get("/settings",needsPermission("settings.read"),info.settings,errorHandler);

        // Error Handler
        //adminApp.use(errorHandler);
    }
}
function start() {
    return i18n.registerMessageCatalog("editor",path.resolve(path.join(__dirname,"locales")),"editor.json").then(function(){
        comms.start();
    });
}
function stop() {
    comms.stop();
    return when.resolve();
}
module.exports = {
    init: init,
    start: start,
    stop: stop,
    library: {
        register: library.register
    },
    auth: {
        needsPermission: auth.needsPermission
    },
    comms: {
        publish: comms.publish
    },
    get adminApp() { return adminApp; },
    get nodeApp() { return nodeApp; },
    get server() { return server; }
};
<commit_msg>fix request method<commit_after>/**
 * Copyright 2014, 2015 IBM Corp.
 *
 * 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.
 **/

var express = require("express");
var bodyParser = require("body-parser");
var util = require('util');
var path = require('path');
var passport = require('passport');
var when = require('when');

var ui = require("./ui");
var nodes = require("./nodes");
var flows = require("./flows");
var flow = require("./flow");
var library = require("./library");
var info = require("./info");
var theme = require("./theme");
var locales = require("./locales");
var credentials = require("./credentials");
var comms = require("./comms");

var auth = require("./auth");
var needsPermission = auth.needsPermission;

var i18n;
var log;
var adminApp;
var nodeApp;
var server;

var errorHandler = function(err,req,res,next) {
    if (err.message === "request entity too large") {
        log.error(err);
    } else {
        console.log(err.stack);
    }
    log.audit({event: "api.error",error:err.code||"unexpected_error",message:err.toString()},req);
    res.status(400).json({error:"unexpected_error", message:err.toString()});
};

function init(_server,runtime) {
    server = _server;
    var settings = runtime.settings;
    i18n = runtime.i18n;
    log = runtime.log;
    if (settings.httpNodeRoot !== false) {
        nodeApp = express();
    }
    if (settings.httpAdminRoot !== false) {
        comms.init(server,runtime);
        adminApp = express();
        auth.init(runtime);
        credentials.init(runtime);
        flows.init(runtime);
        flow.init(runtime);
        info.init(runtime);
        library.init(adminApp,runtime);
        locales.init(runtime);
        nodes.init(runtime);

        // Editor
        if (!settings.disableEditor) {
            ui.init(runtime);
            var editorApp = express();
            editorApp.get("/",ui.ensureSlash,ui.editor);
            editorApp.get("/icons/:icon",ui.icon);
            editorApp.get("/enableSession",ui.enableSession);
            theme.init(runtime);
            if (settings.editorTheme) {
                editorApp.use("/theme",theme.app());
            }
            editorApp.use("/",ui.editorResources);
            adminApp.use(editorApp);
        }
        var maxApiRequestSize = settings.apiMaxLength || '1mb';
        adminApp.use(bodyParser.json({limit:maxApiRequestSize}));
        adminApp.use(bodyParser.urlencoded({limit:maxApiRequestSize,extended:true}));

        adminApp.get("/auth/login",auth.login,errorHandler);

        if (settings.adminAuth) {
            //TODO: all passport references ought to be in ./auth
            adminApp.use(passport.initialize());
            adminApp.post("/auth/token",
                auth.ensureClientSecret,
                auth.authenticateClient,
                auth.getToken,
                auth.errorHandler
            );
            adminApp.post("/auth/revoke",needsPermission(""),auth.revoke,errorHandler);
        }

        // Flows
        adminApp.get("/flows",needsPermission("flows.read"),flows.get,errorHandler);
        adminApp.post("/flows",needsPermission("flows.write"),flows.post,errorHandler);

        adminApp.get("/flow/:id",needsPermission("flows.read"),flow.get,errorHandler);
        adminApp.post("/flow",needsPermission("flows.write"),flow.post,errorHandler);
        adminApp.delete("/flow/:id",needsPermission("flows.write"),flow.delete,errorHandler);
        adminApp.put("/flow/:id",needsPermission("flows.write"),flow.put,errorHandler);

        // Nodes
        adminApp.get("/nodes",needsPermission("nodes.read"),nodes.getAll,errorHandler);
        adminApp.post("/nodes",needsPermission("nodes.write"),nodes.post,errorHandler);

        adminApp.get("/nodes/:mod",needsPermission("nodes.read"),nodes.getModule,errorHandler);
        adminApp.put("/nodes/:mod",needsPermission("nodes.write"),nodes.putModule,errorHandler);
        adminApp.delete("/nodes/:mod",needsPermission("nodes.write"),nodes.delete,errorHandler);

        adminApp.get("/nodes/:mod/:set",needsPermission("nodes.read"),nodes.getSet,errorHandler);
        adminApp.put("/nodes/:mod/:set",needsPermission("nodes.write"),nodes.putSet,errorHandler);

        adminApp.get('/credentials/:type/:id', needsPermission("credentials.read"),credentials.get,errorHandler);

        adminApp.get(/locales\/(.+)\/?$/,locales.get,errorHandler);

        // Library
        adminApp.post(new RegExp("/library/flows\/(.*)"),needsPermission("library.write"),library.post,errorHandler);
        adminApp.get("/library/flows",needsPermission("library.read"),library.getAll,errorHandler);
        adminApp.get(new RegExp("/library/flows\/(.*)"),needsPermission("library.read"),library.get,errorHandler);

        // Settings
        adminApp.get("/settings",needsPermission("settings.read"),info.settings,errorHandler);

        // Error Handler
        //adminApp.use(errorHandler);
    }
}
function start() {
    return i18n.registerMessageCatalog("editor",path.resolve(path.join(__dirname,"locales")),"editor.json").then(function(){
        comms.start();
    });
}
function stop() {
    comms.stop();
    return when.resolve();
}
module.exports = {
    init: init,
    start: start,
    stop: stop,
    library: {
        register: library.register
    },
    auth: {
        needsPermission: auth.needsPermission
    },
    comms: {
        publish: comms.publish
    },
    get adminApp() { return adminApp; },
    get nodeApp() { return nodeApp; },
    get server() { return server; }
};
<|endoftext|>


<commit_before>jQuery(document).ready(
	function() {
		jQuery('input.ajaxQuantityField').each(
			function() {
				jQuery(this).removeAttr('disabled');
				jQuery(this).change(
					function() {
						var name = jQuery(this).attr('name')+ '_SetQuantityLink';
						var setQuantityLink = jQuery('[name=' + name + ']');
						if(jQuery(setQuantityLink).length > 0) {
							setQuantityLink = jQuery(setQuantityLink).get(0);
							if(! this.value) this.value = 0;
							else this.value = this.value.replace(/[^0-9]+/g, '');
							var url = jQuery('base').attr('href') + setQuantityLink.value + '?quantity=' + this.value;
							jQuery.getJSON(url, null, setChanges);
						}
					}
				);
			}
		);
		jQuery('select.ajaxCountryField').each(
			function() {
				jQuery(this).removeAttr('disabled');
				jQuery(this).change(
					function() {
						var id = '#' + jQuery(this).attr('id') + '_SetCountryLink';
						var setCountryLink = jQuery(id);
						if(jQuery(setCountryLink).length > 0) {
							setCountryLink = jQuery(setCountryLink).get(0);
							var url = jQuery('base').attr('href') + setCountryLink.value + '/' + this.value;
							jQuery.getJSON(url, null, setChanges);
						}
					}
				);
			}
		);
	}
);

function setChanges(changes) {
	for(var i in changes) {
		var change = changes[i];
		if(typeof(change.parameter) != 'undefined' && typeof(change.value) != 'undefined') {
			var parameter = change.parameter;
			var value = escapeHTML(change.value);
			if(change.id) {
				var id = '#' + change.id;
				if(parameter == 'innerHTML'){
					jQuery(id).html(value);
				}
				else{
					jQuery(id).attr(parameter, value);
				}
			}
			else if(change.name) {
				var name = change.name;
				jQuery('[name=' + name + ']').each(
					function() {
						jQuery(this).attr(parameter, value);
					}
				);
			}
		}
	}
}

function escapeHTML(str) {
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}<commit_msg>BUG: When you enter a value using the cart quantity field, it breaks. This is because the setquantity url is not formed properly in the ecommerce.js file.<commit_after>jQuery(document).ready(
	function() {
		jQuery('input.ajaxQuantityField').each(
			function() {
				jQuery(this).removeAttr('disabled');
				jQuery(this).change(
					function() {
						var name = jQuery(this).attr('name')+ '_SetQuantityLink';
						var setQuantityLink = jQuery('[name=' + name + ']');
						if(jQuery(setQuantityLink).length > 0) {
							setQuantityLink = jQuery(setQuantityLink).get(0);
							if(! this.value) this.value = 0;
							else this.value = this.value.replace(/[^0-9]+/g, '');
							var url = jQuery('base').attr('href') + setQuantityLink.value;
							var parts = url.split("?");
							if(parts.length > 1){
								url += '&quantity=' + this.value;
							}else{
								url += '?quantity=' + this.value;
							}
							jQuery.getJSON(url, null, setChanges);
						}
					}
				);
			}
		);
		jQuery('select.ajaxCountryField').each(
			function() {
				jQuery(this).removeAttr('disabled');
				jQuery(this).change(
					function() {
						var id = '#' + jQuery(this).attr('id') + '_SetCountryLink';
						var setCountryLink = jQuery(id);
						if(jQuery(setCountryLink).length > 0) {
							setCountryLink = jQuery(setCountryLink).get(0);
							var url = jQuery('base').attr('href') + setCountryLink.value + '/' + this.value;
							jQuery.getJSON(url, null, setChanges);
						}
					}
				);
			}
		);
	}
);

function setChanges(changes) {
	for(var i in changes) {
		var change = changes[i];
		if(typeof(change.parameter) != 'undefined' && typeof(change.value) != 'undefined') {
			var parameter = change.parameter;
			var value = escapeHTML(change.value);
			if(change.id) {
				var id = '#' + change.id;
				if(parameter == 'innerHTML'){
					jQuery(id).html(value);
				}
				else{
					jQuery(id).attr(parameter, value);
				}
			}
			else if(change.name) {
				var name = change.name;
				jQuery('[name=' + name + ']').each(
					function() {
						jQuery(this).attr(parameter, value);
					}
				);
			}
		}
	}
}

function escapeHTML(str) {
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}<|endoftext|>


<commit_before>jQuery.entwine("linkfield", function($) {

	$("input.link").entwine({
		Loading: null,
		Dialog:  null,
		URL:  null,
		onmatch: function() {
			var self = this;
			this.setDialog(self.siblings('.linkfield-dialog:first'));

			var formUrl = this.parents('form').attr('action'),
				formUrlParts = formUrl.split('?'),
				formUrl = formUrlParts[0],
				url = encodeURI(formUrl) + '/field/' + this.attr('name') + '/LinkFormHTML';

			if(self.val().length){
				url = url + '?LinkID=' + self.val();
			}else{
				url = url + '?LinkID=0';
			}

			if(typeof formUrlParts[1] !== 'undefined') {
				url = url + '&' + formUrlParts[1];
			}

			this.setURL(url);

			// configure the dialog
			var windowHeight = $(window).height();

			this.getDialog().data("field", this).dialog({
				autoOpen: 	false,
				width:   	$(window).width()  * 80 / 100,
				height:   	$(window).height() * 80 / 100,
				modal:    	true,
				title: 		this.data('dialog-title'),
				position: 	{ my: "center", at: "center", of: window }
			});

			// submit button loading state while form is submitting
			this.getDialog().on("click", "button", function() {
				$(this).addClass("loading ui-state-disabled");
			});

			// handle dialog form submission
			this.getDialog().on("submit", "form", function() {

				var dlg = self.getDialog().dialog(),
					options = {};

				options.success = function(response) {
					if($(response).is(".field")) {
						self.getDialog().empty().dialog("close");
						self.parents('.field:first').replaceWith(response);
					} else {
						self.getDialog().html(response);
					}
				}

				$(this).ajaxSubmit(options);

				return false;
			});
		},

		showDialog: function(url) {
			var dlg = this.getDialog();

			dlg.empty().dialog("open").parent().addClass("loading");

			dlg.load(this.getURL(), function(){
				dlg.parent().removeClass("loading");
			});
		}
	});

	$(".linkfield-button").entwine({
		onclick: function() {
			this.siblings('input.link').showDialog();
			return false;
		},
	});

	$(".linkfield-remove-button").entwine({
		onclick: function() {
			var formUrl = this.parents('form').attr('action'),
				formUrlParts = formUrl.split('?'),
				formUrl = formUrlParts[0],
				url = encodeURI(formUrl) + '/field/' + this.siblings('input:first').prop('name') + '/doRemoveLink';

			if(typeof formUrlParts[1] !== 'undefined') {
				url = url + '&' + formUrlParts[1];
			}
			var holder = this.parents('.field:first');
			this.parents('.middleColumn:first').html("");
			holder.load(url);
			return false;
		},
	});
});

<commit_msg>remove linkfield dialog once the modal window is closed<commit_after>jQuery.entwine("linkfield", function($) {

	$("input.link").entwine({
		Loading: null,
		Dialog:  null,
		URL:  null,
		onmatch: function() {
			var self = this;
			this.setDialog(self.siblings('.linkfield-dialog:first'));

			var formUrl = this.parents('form').attr('action'),
				formUrlParts = formUrl.split('?'),
				formUrl = formUrlParts[0],
				url = encodeURI(formUrl) + '/field/' + this.attr('name') + '/LinkFormHTML';

			if(self.val().length){
				url = url + '?LinkID=' + self.val();
			}else{
				url = url + '?LinkID=0';
			}

			if(typeof formUrlParts[1] !== 'undefined') {
				url = url + '&' + formUrlParts[1];
			}

			this.setURL(url);

			// configure the dialog
			var windowHeight = $(window).height();

			this.getDialog().data("field", this).dialog({
				autoOpen: 	false,
				width:   	$(window).width()  * 80 / 100,
				height:   	$(window).height() * 80 / 100,
				modal:    	true,
				title: 		this.data('dialog-title'),
				position: 	{ my: "center", at: "center", of: window }
			});

			// submit button loading state while form is submitting
			this.getDialog().on("click", "button", function() {
				$(this).addClass("loading ui-state-disabled");
			});

			// handle dialog form submission
			this.getDialog().on("submit", "form", function() {

				var dlg = self.getDialog().dialog(),
					options = {};

				options.success = function(response) {
					if($(response).is(".field")) {
						self.getDialog().empty().dialog("close");
						self.parents('.field:first').replaceWith(response);
					} else {
						self.getDialog().html(response);
					}
				}

				$(this).ajaxSubmit(options);

				return false;
			});
		},
		onunmatch: function () {
			$('.linkfield-dialog').remove();
		},
		showDialog: function(url) {
			var dlg = this.getDialog();

			dlg.empty().dialog("open").parent().addClass("loading");

			dlg.load(this.getURL(), function(){
				dlg.parent().removeClass("loading");
			});
		}
	});

	$(".linkfield-button").entwine({
		onclick: function() {
			this.siblings('input.link').showDialog();
			return false;
		},
	});

	$(".linkfield-remove-button").entwine({
		onclick: function() {
			var formUrl = this.parents('form').attr('action'),
				formUrlParts = formUrl.split('?'),
				formUrl = formUrlParts[0],
				url = encodeURI(formUrl) + '/field/' + this.siblings('input:first').prop('name') + '/doRemoveLink';

			if(typeof formUrlParts[1] !== 'undefined') {
				url = url + '&' + formUrlParts[1];
			}
			var holder = this.parents('.field:first');
			this.parents('.middleColumn:first').html("");
			holder.load(url);
			return false;
		},
	});
});
<|endoftext|>


<commit_before>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 */
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define(["require", "../deep"], function(require, deep) {

	// all sitemap of content that is used to produce routed views tree (IOC from deep-routes).
	return {
		home: {
			navigation: false,
			route: "/$",
			how: '
'
		},
		layers: {
			subs: {
				overview: {
					route: "/layers/$",
					how: "docs::/pages/layers/overview.html"
				},
				"up-bottom": {
					how: "docs::/pages/layers/up-bottom.html"
				},
				compositions: {
					how: "docs::/pages/layers/compositions.html"
				},
				colliders: {
					how: "docs::/pages/layers/colliders.html"
				},
				flatten: {
					how: "docs::/pages/layers/flatten.html"
				},
				shared: {
					how: "docs::/pages/layers/shared.html"
				},
				classes: {
					how: "docs::/pages/layers/classes.html"
				}
			}
		},
		queries: {
			subs: {
				overview: {
					route: "/queries/$",
					how: "docs::/pages/queries/overview.html"
				},
				query: {
					separated: true,
					how: "docs::/pages/queries/deep-query.html"
				},
				rql: {
					how: "docs::/pages/queries/rql.html"
				},
				traversal: {
					separated: true,
					how: "docs::/pages/queries/traversal.html"
				},
				selectors: {
					how: "docs::/pages/queries/selectors.html"
				},
				descriptors: {
					separated: true,
					how: "docs::/pages/queries/nodes.html"
				}
			}
		},
		chains: {
			subs: {
				overview: {
					route: "/chains/$",
					how: "docs::/pages/chains/overview.html"
				},
				fundamentals: {
					how: "docs::/pages/chains/base.html"
				},
				promise: {
					how: "docs::/pages/chains/promises.html"
				},
				identities: {
					how: "docs::/pages/chains/identities.html"
				},
				deep: {
					separated: true,
					label: "deep chain",
					how: "docs::/pages/chains/deep.html"
				},
				patterns: {
					separated: true,
					label: "usage patterns",
					how: "docs::/pages/chains/subtilities.html"
				},
				others: {
					separated: true,
					label: "other chains",
					how: "docs::/pages/chains/others.html"
				}
			}
		},
		context: {
			subs: {
				overview: {
					route: "/context/$",
					how: "docs::/pages/context/overview.html"
				},
				base: {
					how: "docs::/pages/context/base.html"
				},
				logger: {
					how: "docs::/pages/context/logger.html"
				}
			}
		},
		protocols: {
			subs: {
				overview: {
					route: "/protocols/$",
					how: "docs::/pages/protocols/overview.html"
				},
				base: {
					how: "docs::/pages/protocols/base.html"
				},
				natives: {
					how: "docs::/pages/protocols/natives.html"
				},
				templates: {
					separated: true,
					how: "docs::/pages/protocols/templates.html"
				},
				nodejs: {
					how: "docs::/pages/protocols/nodejs.html"
				},
				browser: {
					how: "docs::/pages/protocols/browser.html"
				}
			}
		},
		sheets: {
			subs: {
				overview: {
					route: "/sheets/$",
					how: "docs::/pages/sheets/overview.html"
				},
				base: {
					how: "docs::/pages/sheets/base.html"
				},
				sheeter: {
					label: "deep-sheeter",
					how: "docs::/pages/sheets/sheeter.html"
				}
			}
		},
		ocm: {
			subs: {
				concepts: {
					route: "/ocm/$",
					how: "docs::/pages/ocm/introduction.html"
				},
				modes: {
					how: "docs::/pages/ocm/modes.html"
				},
				compilation: {
					how: "docs::/pages/ocm/compilation.html"
				},
				classes: {
					how: "docs::/pages/ocm/classes.html"
				},
				design: {
					separated: true,
					label: "design patterns",
					how: "docs::/pages/ocm/design.html"
				},
			}
		},
		utils: {
			subs: {
				log: {
					how: "docs::/pages/utils/log.html"
				},
				interpret: {
					how: "docs::/pages/utils/interpret.html"
				},
				deepLoad: {
					how: "docs::/pages/utils/deepload.html"
				},
				"json-schema": {
					how: "docs::/pages/utils/schema.html"
				},
				errors: {
					how: "docs::/pages/utils/errors.html"
				},
				"media-cache": {
					label: "media cache",
					how: "docs::/pages/protocols/cache.html"
				},
				tests: {
					how: "docs::/pages/tests.html",
					run: function(verbose) {
						var $ = deep.context.$;
						deep.Unit.run(null, {
							verbose: verbose ? true : false
						})
							.done(function(report) {
								// console.log("report : ", report);
								report.reports = null;
								$("#reports-container").html("
Tests result :
" + JSON.stringify(report, null, ' ') + '

')
									.slideDown(200);
							});
					}
				}
			}
		},
		restful: {
			separated: true,
			subs: {
				overview: {
					route: "/restful/$",
					how: "
restful overview
"
				},
				collection: {
					how: "docs::/pages/restful/collection.html"
				},
				object: {
					how: "docs::/pages/restful/object.html"
				},
				validation: {
					how: "docs::/pages/restful/validation.html"
				},
				constraints: {
					how: "docs::/pages/restful/constraints.html"
				},
				relations: {
					how: "docs::/pages/restful/relations.html"
				},
				ocm: {
					how: "docs::/pages/restful/ocm.html"
				},
				chain: {
					label: "restful chain",
					how: "docs::/pages/restful/chain.html"
				},
				wrappers: {
					separated: true,
					how: "docs::/pages/restful/wrappers.html"
				}
			}
		},
		views: {
			separated: true,
			subs: {
				overview: {
					route: "/views/$",
					how: "
views basics
"
				},
				api: {
					how: "docs::/pages/views/api.html"
				},
				"dom-protocol": {
					label: "dom.xxx",
					how: "docs::/pages/views/dom-protocol.html"
				},
				directives: {
					how: "docs::/pages/views/directives.html"
				},
				concurrency: {
					how: "docs::/pages/views/concurrency.html"
				},
				"dom-sheeter": {
					label: "dom.sheeter",
					how: "docs::/pages/views/dom-protocol.html"
				}
			}
		},
		routes: {
			subs: {
				overview: {
					route: "/routes/$",
					how: "
routes basics
"
				},
				path: {
					how: "docs::/pages/routes/path.html"
				},
				map: {
					how: "docs::/pages/routes/map.html"
				},
				ocm: {
					how: "docs::/pages/routes/ocm.html"
				}
			}
		},
		more: {
			separated: true,
			subs: {
				overview: {
					route: "/more/$",
					how: '
you could install one of the 5 environnements or try online one of the 2 other sandboxes (autobahn and browser)
'
				},
				environnements: {
					how: "docs::/pages/more/environnements.html"
				},
				sandboxes: {
					how: "docs::/pages/more/sandboxes.html"
				},
				tutorials: {
					how: "docs::/pages/more/tutorials.html"
				},
				discussions: {
					how: "docs::/pages/more/discussions.html"
				}
			}
		}
	};
});<commit_msg>clean jquery catch pattern<commit_after>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 */
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define(["require", "../deep"], function(require, deep) {

	// all sitemap of content that is used to produce routed views tree (IOC from deep-routes).
	return {
		home: {
			navigation: false,
			route: "/$",
			how: '
'
		},
		layers: {
			subs: {
				overview: {
					route: "/layers/$",
					how: "docs::/pages/layers/overview.html"
				},
				"up-bottom": {
					how: "docs::/pages/layers/up-bottom.html"
				},
				compositions: {
					how: "docs::/pages/layers/compositions.html"
				},
				colliders: {
					how: "docs::/pages/layers/colliders.html"
				},
				flatten: {
					how: "docs::/pages/layers/flatten.html"
				},
				shared: {
					how: "docs::/pages/layers/shared.html"
				},
				classes: {
					how: "docs::/pages/layers/classes.html"
				}
			}
		},
		queries: {
			subs: {
				overview: {
					route: "/queries/$",
					how: "docs::/pages/queries/overview.html"
				},
				query: {
					separated: true,
					how: "docs::/pages/queries/deep-query.html"
				},
				rql: {
					how: "docs::/pages/queries/rql.html"
				},
				traversal: {
					separated: true,
					how: "docs::/pages/queries/traversal.html"
				},
				selectors: {
					how: "docs::/pages/queries/selectors.html"
				},
				descriptors: {
					separated: true,
					how: "docs::/pages/queries/nodes.html"
				}
			}
		},
		chains: {
			subs: {
				overview: {
					route: "/chains/$",
					how: "docs::/pages/chains/overview.html"
				},
				fundamentals: {
					how: "docs::/pages/chains/base.html"
				},
				promise: {
					how: "docs::/pages/chains/promises.html"
				},
				identities: {
					how: "docs::/pages/chains/identities.html"
				},
				deep: {
					separated: true,
					label: "deep chain",
					how: "docs::/pages/chains/deep.html"
				},
				patterns: {
					separated: true,
					label: "usage patterns",
					how: "docs::/pages/chains/subtilities.html"
				},
				others: {
					separated: true,
					label: "other chains",
					how: "docs::/pages/chains/others.html"
				}
			}
		},
		context: {
			subs: {
				overview: {
					route: "/context/$",
					how: "docs::/pages/context/overview.html"
				},
				base: {
					how: "docs::/pages/context/base.html"
				},
				logger: {
					how: "docs::/pages/context/logger.html"
				}
			}
		},
		protocols: {
			subs: {
				overview: {
					route: "/protocols/$",
					how: "docs::/pages/protocols/overview.html"
				},
				base: {
					how: "docs::/pages/protocols/base.html"
				},
				natives: {
					how: "docs::/pages/protocols/natives.html"
				},
				templates: {
					separated: true,
					how: "docs::/pages/protocols/templates.html"
				},
				nodejs: {
					how: "docs::/pages/protocols/nodejs.html"
				},
				browser: {
					how: "docs::/pages/protocols/browser.html"
				}
			}
		},
		sheets: {
			subs: {
				overview: {
					route: "/sheets/$",
					how: "docs::/pages/sheets/overview.html"
				},
				base: {
					how: "docs::/pages/sheets/base.html"
				},
				sheeter: {
					label: "deep-sheeter",
					how: "docs::/pages/sheets/sheeter.html"
				}
			}
		},
		ocm: {
			subs: {
				concepts: {
					route: "/ocm/$",
					how: "docs::/pages/ocm/introduction.html"
				},
				modes: {
					how: "docs::/pages/ocm/modes.html"
				},
				compilation: {
					how: "docs::/pages/ocm/compilation.html"
				},
				classes: {
					how: "docs::/pages/ocm/classes.html"
				},
				design: {
					separated: true,
					label: "design patterns",
					how: "docs::/pages/ocm/design.html"
				},
			}
		},
		utils: {
			subs: {
				log: {
					how: "docs::/pages/utils/log.html"
				},
				interpret: {
					how: "docs::/pages/utils/interpret.html"
				},
				deepLoad: {
					how: "docs::/pages/utils/deepload.html"
				},
				"json-schema": {
					how: "docs::/pages/utils/schema.html"
				},
				errors: {
					how: "docs::/pages/utils/errors.html"
				},
				"media-cache": {
					label: "media cache",
					how: "docs::/pages/protocols/cache.html"
				},
				tests: {
					how: "docs::/pages/tests.html",
					run: function(verbose) {
						var $ = deep.$();
						deep.Unit.run(null, {
							verbose: verbose ? true : false
						})
							.done(function(report) {
								// console.log("report : ", report);
								report.reports = null;
								$("#reports-container").html("
Tests result :
" + JSON.stringify(report, null, ' ') + '

')
									.slideDown(200);
							});
					}
				}
			}
		},
		restful: {
			separated: true,
			subs: {
				overview: {
					route: "/restful/$",
					how: "
restful overview
"
				},
				collection: {
					how: "docs::/pages/restful/collection.html"
				},
				object: {
					how: "docs::/pages/restful/object.html"
				},
				validation: {
					how: "docs::/pages/restful/validation.html"
				},
				constraints: {
					how: "docs::/pages/restful/constraints.html"
				},
				relations: {
					how: "docs::/pages/restful/relations.html"
				},
				ocm: {
					how: "docs::/pages/restful/ocm.html"
				},
				chain: {
					label: "restful chain",
					how: "docs::/pages/restful/chain.html"
				},
				wrappers: {
					separated: true,
					how: "docs::/pages/restful/wrappers.html"
				}
			}
		},
		views: {
			separated: true,
			subs: {
				overview: {
					route: "/views/$",
					how: "
views basics
"
				},
				api: {
					how: "docs::/pages/views/api.html"
				},
				"dom-protocol": {
					label: "dom.xxx",
					how: "docs::/pages/views/dom-protocol.html"
				},
				directives: {
					how: "docs::/pages/views/directives.html"
				},
				concurrency: {
					how: "docs::/pages/views/concurrency.html"
				},
				"dom-sheeter": {
					label: "dom.sheeter",
					how: "docs::/pages/views/dom-protocol.html"
				}
			}
		},
		routes: {
			subs: {
				overview: {
					route: "/routes/$",
					how: "
routes basics
"
				},
				path: {
					how: "docs::/pages/routes/path.html"
				},
				map: {
					how: "docs::/pages/routes/map.html"
				},
				ocm: {
					how: "docs::/pages/routes/ocm.html"
				}
			}
		},
		more: {
			separated: true,
			subs: {
				overview: {
					route: "/more/$",
					how: '
you could install one of the 5 environnements or try online one of the 2 other sandboxes (autobahn and browser)
'
				},
				environnements: {
					how: "docs::/pages/more/environnements.html"
				},
				sandboxes: {
					how: "docs::/pages/more/sandboxes.html"
				},
				tutorials: {
					how: "docs::/pages/more/tutorials.html"
				},
				discussions: {
					how: "docs::/pages/more/discussions.html"
				}
			}
		}
	};
});<|endoftext|>


<commit_before>// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import * as Components from '../components/components.js';
import * as i18n from '../i18n/i18n.js';
import * as SDK from '../sdk/sdk.js';
import * as UI from '../ui/ui.js';

export const UIStrings = {
  /**
  *@description Text in Request Initiator View of the Network panel
  */
  thisRequestHasNoInitiatorData: 'This request has no initiator data.',
  /**
  *@description Title of a section in Request Initiator view of the Network Panel
  */
  requestCallStack: 'Request call stack',
  /**
  *@description Title of a section in Request Initiator view of the Network Panel
  */
  requestInitiatorChain: 'Request initiator chain',
};
const str_ = i18n.i18n.registerUIStrings('network/RequestInitiatorView.js', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
export class RequestInitiatorView extends UI.Widget.VBox {
  /**
   * @param {!SDK.NetworkRequest.NetworkRequest} request
   */
  constructor(request) {
    super();
    this.registerRequiredCSS('network/requestInitiatorView.css', {enableLegacyPatching: false});
    this.element.classList.add('request-initiator-view');
    /** @type {!Components.Linkifier.Linkifier} */
    this._linkifier = new Components.Linkifier.Linkifier();
    this._request = request;
    this._emptyWidget = new UI.EmptyWidget.EmptyWidget(i18nString(UIStrings.thisRequestHasNoInitiatorData));
    this._emptyWidget.show(this.element);
    this._hasShown = false;
  }

  /**
   * @param {!SDK.NetworkRequest.NetworkRequest} request
   * @param {!Components.Linkifier.Linkifier} linkifier
   * @param {boolean=} focusableLink
   * @param {function()=} callback
   * @return {?{element: !Element, links: !Array<!Element>}}
   */
  static createStackTracePreview(request, linkifier, focusableLink, callback) {
    const initiator = request.initiator();
    if (!initiator || !initiator.stack) {
      return null;
    }
    const networkManager = SDK.NetworkManager.NetworkManager.forRequest(request);
    const target = networkManager ? networkManager.target() : null;
    const stackTrace = Components.JSPresentationUtils.buildStackTracePreviewContents(
        target, linkifier, {stackTrace: initiator.stack, contentUpdated: callback, tabStops: focusableLink});
    return stackTrace;
  }

  /**
   * @return {!UI.TreeOutline.TreeOutlineInShadow}
   */
  _createTree() {
    const treeOutline = new UI.TreeOutline.TreeOutlineInShadow();
    treeOutline.registerRequiredCSS('network/requestInitiatorViewTree.css', {enableLegacyPatching: false});
    treeOutline.contentElement.classList.add('request-initiator-view-tree');

    return treeOutline;
  }

  /**
   * @param {!SDK.NetworkLog.InitiatorGraph} initiatorGraph
   * @param {string} title
   * @param {!UI.TreeOutline.TreeOutlineInShadow} tree
   */
  _buildRequestChainTree(initiatorGraph, title, tree) {
    const root = new UI.TreeOutline.TreeElement(title);

    tree.appendChild(root);

    if (root.titleElement instanceof HTMLElement) {
      root.titleElement.classList.add('request-initiator-view-section-title');
    }

    const initiators = initiatorGraph.initiators;
    /** @type {!UI.TreeOutline.TreeElement} */
    let parent = root;
    for (const request of Array.from(initiators).reverse()) {
      const treeElement = new UI.TreeOutline.TreeElement(request.url());
      parent.appendChild(treeElement);
      parent.expand();
      parent = treeElement;
    }

    root.expand();
    parent.select();
    const titleElement = parent.titleElement;
    if (titleElement instanceof HTMLElement) {
      titleElement.style.fontWeight = 'bold';
    }

    const initiated = initiatorGraph.initiated;
    this._depthFirstSearchTreeBuilder(initiated, /** @type {!UI.TreeOutline.TreeElement} */ (parent), this._request);
    return root;
  }

  /**
   * @param {!Map<!SDK.NetworkRequest.NetworkRequest, !SDK.NetworkRequest.NetworkRequest>} initiated
   * @param {!UI.TreeOutline.TreeElement} parentElement
   * @param {!SDK.NetworkRequest.NetworkRequest} parentRequest
   */
  _depthFirstSearchTreeBuilder(initiated, parentElement, parentRequest) {
    const visited = new Set();
    // this._request should be already in the tree when build initiator part
    visited.add(this._request);
    for (const request of initiated.keys()) {
      if (initiated.get(request) === parentRequest) {
        const treeElement = new UI.TreeOutline.TreeElement(request.url());
        parentElement.appendChild(treeElement);
        parentElement.expand();
        // only do dfs when we haven't done one
        if (!visited.has(request)) {
          visited.add(request);
          this._depthFirstSearchTreeBuilder(initiated, treeElement, request);
        }
      }
    }
  }

  /**
   * @param {!Element} content
   * @param {string} title
   * @param {!UI.TreeOutline.TreeOutlineInShadow} tree
   */
  _buildStackTraceSection(content, title, tree) {
    const root = new UI.TreeOutline.TreeElement(title);
    tree.appendChild(root);

    if (root.titleElement instanceof HTMLElement) {
      root.titleElement.classList.add('request-initiator-view-section-title');
    }

    const contentElement = new UI.TreeOutline.TreeElement(content, false);

    root.appendChild(contentElement);
    root.expand();
  }

  /**
   * @override
   */
  wasShown() {
    if (this._hasShown) {
      return;
    }
    let initiatorDataPresent = false;
    const containerTree = this._createTree();

    const stackTracePreview = RequestInitiatorView.createStackTracePreview(this._request, this._linkifier, true);

    if (stackTracePreview) {
      initiatorDataPresent = true;
      this._buildStackTraceSection(stackTracePreview.element, i18nString(UIStrings.requestCallStack), containerTree);
    }

    const initiatorGraph = SDK.NetworkLog.NetworkLog.instance().initiatorGraphForRequest(this._request);

    if (initiatorGraph.initiators.size > 1 || initiatorGraph.initiated.size > 1) {
      initiatorDataPresent = true;
      this._buildRequestChainTree(initiatorGraph, i18nString(UIStrings.requestInitiatorChain), containerTree);
    }

    const firstChild = containerTree.firstChild();

    if (firstChild) {
      firstChild.select(true);
    }

    if (initiatorDataPresent) {
      this.element.appendChild(containerTree.element);
      this._emptyWidget.hideWidget();
    }
    this._hasShown = true;
  }
}
<commit_msg>Fix Initiator request call stack behavior<commit_after>// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import * as Components from '../components/components.js';
import * as i18n from '../i18n/i18n.js';
import * as SDK from '../sdk/sdk.js';
import * as UI from '../ui/ui.js';

export const UIStrings = {
  /**
  *@description Text in Request Initiator View of the Network panel
  */
  thisRequestHasNoInitiatorData: 'This request has no initiator data.',
  /**
  *@description Title of a section in Request Initiator view of the Network Panel
  */
  requestCallStack: 'Request call stack',
  /**
  *@description Title of a section in Request Initiator view of the Network Panel
  */
  requestInitiatorChain: 'Request initiator chain',
};
const str_ = i18n.i18n.registerUIStrings('network/RequestInitiatorView.js', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
export class RequestInitiatorView extends UI.Widget.VBox {
  /**
   * @param {!SDK.NetworkRequest.NetworkRequest} request
   */
  constructor(request) {
    super();
    this.registerRequiredCSS('network/requestInitiatorView.css', {enableLegacyPatching: false});
    this.element.classList.add('request-initiator-view');
    /** @type {!Components.Linkifier.Linkifier} */
    this._linkifier = new Components.Linkifier.Linkifier();
    this._request = request;
    this._emptyWidget = new UI.EmptyWidget.EmptyWidget(i18nString(UIStrings.thisRequestHasNoInitiatorData));
    this._emptyWidget.show(this.element);
    this._hasShown = false;
  }

  /**
   * @param {!SDK.NetworkRequest.NetworkRequest} request
   * @param {!Components.Linkifier.Linkifier} linkifier
   * @param {boolean=} focusableLink
   * @param {function()=} callback
   * @return {?{element: !Element, links: !Array<!Element>}}
   */
  static createStackTracePreview(request, linkifier, focusableLink, callback) {
    const initiator = request.initiator();
    if (!initiator || !initiator.stack) {
      return null;
    }
    const networkManager = SDK.NetworkManager.NetworkManager.forRequest(request);
    const target = networkManager ? networkManager.target() : null;
    const stackTrace = Components.JSPresentationUtils.buildStackTracePreviewContents(
        target, linkifier, {stackTrace: initiator.stack, contentUpdated: callback, tabStops: focusableLink});
    return stackTrace;
  }

  /**
   * @return {!UI.TreeOutline.TreeOutlineInShadow}
   */
  _createTree() {
    const treeOutline = new UI.TreeOutline.TreeOutlineInShadow();
    treeOutline.registerRequiredCSS('network/requestInitiatorViewTree.css', {enableLegacyPatching: false});
    treeOutline.contentElement.classList.add('request-initiator-view-tree');

    return treeOutline;
  }

  /**
   * @param {!SDK.NetworkLog.InitiatorGraph} initiatorGraph
   * @param {string} title
   * @param {!UI.TreeOutline.TreeOutlineInShadow} tree
   */
  _buildRequestChainTree(initiatorGraph, title, tree) {
    const root = new UI.TreeOutline.TreeElement(title);

    tree.appendChild(root);

    if (root.titleElement instanceof HTMLElement) {
      root.titleElement.classList.add('request-initiator-view-section-title');
    }

    const initiators = initiatorGraph.initiators;
    /** @type {!UI.TreeOutline.TreeElement} */
    let parent = root;
    for (const request of Array.from(initiators).reverse()) {
      const treeElement = new UI.TreeOutline.TreeElement(request.url());
      parent.appendChild(treeElement);
      parent.expand();
      parent = treeElement;
    }

    root.expand();
    parent.select();
    const titleElement = parent.titleElement;
    if (titleElement instanceof HTMLElement) {
      titleElement.style.fontWeight = 'bold';
    }

    const initiated = initiatorGraph.initiated;
    this._depthFirstSearchTreeBuilder(initiated, /** @type {!UI.TreeOutline.TreeElement} */ (parent), this._request);
    return root;
  }

  /**
   * @param {!Map<!SDK.NetworkRequest.NetworkRequest, !SDK.NetworkRequest.NetworkRequest>} initiated
   * @param {!UI.TreeOutline.TreeElement} parentElement
   * @param {!SDK.NetworkRequest.NetworkRequest} parentRequest
   */
  _depthFirstSearchTreeBuilder(initiated, parentElement, parentRequest) {
    const visited = new Set();
    // this._request should be already in the tree when build initiator part
    visited.add(this._request);
    for (const request of initiated.keys()) {
      if (initiated.get(request) === parentRequest) {
        const treeElement = new UI.TreeOutline.TreeElement(request.url());
        parentElement.appendChild(treeElement);
        parentElement.expand();
        // only do dfs when we haven't done one
        if (!visited.has(request)) {
          visited.add(request);
          this._depthFirstSearchTreeBuilder(initiated, treeElement, request);
        }
      }
    }
  }

  /**
   * @param {!Element} content
   * @param {string} title
   * @param {!UI.TreeOutline.TreeOutlineInShadow} tree
   */
  _buildStackTraceSection(content, title, tree) {
    const root = new UI.TreeOutline.TreeElement(title);
    tree.appendChild(root);

    if (root.titleElement instanceof HTMLElement) {
      root.titleElement.classList.add('request-initiator-view-section-title');
    }

    const contentElement = new UI.TreeOutline.TreeElement(content, false);
    contentElement.selectable = false;

    root.appendChild(contentElement);
    root.expand();
  }

  /**
   * @override
   */
  wasShown() {
    if (this._hasShown) {
      return;
    }
    let initiatorDataPresent = false;
    const containerTree = this._createTree();

    const stackTracePreview = RequestInitiatorView.createStackTracePreview(this._request, this._linkifier, true);

    if (stackTracePreview) {
      initiatorDataPresent = true;
      this._buildStackTraceSection(stackTracePreview.element, i18nString(UIStrings.requestCallStack), containerTree);
    }

    const initiatorGraph = SDK.NetworkLog.NetworkLog.instance().initiatorGraphForRequest(this._request);

    if (initiatorGraph.initiators.size > 1 || initiatorGraph.initiated.size > 1) {
      initiatorDataPresent = true;
      this._buildRequestChainTree(initiatorGraph, i18nString(UIStrings.requestInitiatorChain), containerTree);
    }

    const firstChild = containerTree.firstChild();

    if (firstChild) {
      firstChild.select(true);
    }

    if (initiatorDataPresent) {
      this.element.appendChild(containerTree.element);
      this._emptyWidget.hideWidget();
    }
    this._hasShown = true;
  }
}
<|endoftext|>