<commit_before>(function () {
  'use strict';

  function action (firstSelector, secondSelector) {
    $.removeNodes('iframe, #adblock_detect, .popupOverlay');

    var node = $.$(firstSelector);
    if (node) {
      // first pass
      _.wait(500).then(function () {
        node.removeAttribute('disabled');
        return _.wait(500);
      }).then(function () {
        // HACK some sites can not receive the click event without focus
        node.focus();
        // HACK some sites needs to click multiple times
        node.click();
        node.click();
        node.click();
      });
      return;
    }

    // second pass
    var i = $(secondSelector);
    $.openImage(i.src);
  }

  var defaultAction = _.P(action, '#continuetoimage > form input', 'img[class^=centred]');

  $.register({
    rule: [
      {
        host: [
          // com
          // starts with image
          /^image(ontime|corn|picsa|horse)\.com$/,
          // ends with image
          /^(zonezeed|zelje|croft|myhot|bok|hostur|greasy)image\.com$/,
          // starts with img
          /^img(icy|next|savvy|\.spicyzilla|twyti|xyz|devil|tzar|ban|pu|beer|wet|tornado|kicks|-pay|nimz|binbou|2share|22|cover|hit|main|trial|blank|-uploads)\.com$/,
          // starts with img-
          /^img-(zone|planet)\.com$/,
          // starts with www
          /^www\.img(blow|lemon|4sharing)\.com$/,
          /^www\.imagefolks\.com$/,
          // starts with xxx
          /^xxx(imagenow|screens)\.com$/,
          // else
          /^(picstwist|ericsony|wpc8|uplimg|lexiit|thumbnailus|newimagepost|fapingpics|dimtus|tinizo)\.com$/,
          /^((i|hentai)\.)?imgslip\.com$/,
          /^(i|xxx)\.hentaiyoutube\.com$/,
          /^(go|er)imge\.com$/,
          /^(like\.)?08lkk\.com$/,
          /^(www\.)?\.imgult\.com$/,
          /^nim(plus|zshare)\.com$/,
          /^nudeximg\.com$/,
          /imgseeds?\.com$/,
          /xxxsparrow?\.com$/,
          /damimage\.com$/,
          /imagedecode\.com$/,
          // net
          /^img(serve|coin|fap|candy|master|-view|run|boom|project|python|pics)\.net$/,
          /^(imagesouls|naughtygate|gallerycloud|imagelaser|picture-bang|project-photo|pix-link|funimg|golfpit|xximg)\.net$/,
          // org
          /^(shot|adult)img\.org$/,
          /^img(studio|spot)\.org$/,
          /^image(\.adlock|on|team)\.org$/,
          /^(drag|teen|mega)image\.org$/,
          /^teenshot\.org$/,
          // else
          /^(hotimages|55888)\.eu$/,
          /^img(cloud|mag)\.co$/,
          /^pixup\.us$/,
          /^(bulkimg|photo-up|myimg|pop-img|img-pop|ads-img)\.info$/,
          /^img\.yt$/,
          /^vava\.in$/,
          /^(pixxx|picspornfree|imgload|fapat)\.me$/,
          /^(domaink|pic2pic|porno-pirat|24avarii|loftlm|18pron|imgplus)\.ru$/,
          /^www\.hotimage\.uk$/,
          /^imgease\.re$/,
          /^goimg\.xyz$/,
          /^pic2pic\.site$/,
          /^darpix\.ga$/,
          /^sxpics\.nl$/,
          /^darpix\.desi$/,
          /^pic4you\.top$/,
          /^imgsen\.se$/,
        ],
        path: /^\/img-.*\.html/,
      },
      {
        host: [
          /^img(run|twyti)\.net$/,
          /^imgtwyti\.com$/,
          /^hentai-pop\.com$/,
          /^(jav|img)-hentai\.host$/,
          /^hentai-king\.host$/,
          /^img-king\.xyz$/,
        ],
        path: /^\/[ti]\/img-.*\.html/,
      },
      {
        host: /^imgking\.co$/,
        path: /^\/img-.*\.html/,
      },
      {
        host: /^imgbb\.net$/,
        path: /^\/.-.+$/,
      },
      {
        host: /^cdn\.javtotal\.com$/,
        path: /^\/img\/.+$/,
      },
    ],
    ready: defaultAction,
  });

  $.register({
    rule: {
      host: /^imgrat\.com$/,
      path: /^\/img-.*\.html/,
    },
    ready: _.P(action, '#close', '#main_image img.center-block.img-responsive'),
  });

  $.register({
    rule: {
      host: /^imageporn\.eu$/,
      path: /^\/img-.*\.html/,
    },
    start: function () {
      // HACK break script injection
      $.window.document.createElement = null;
    },
    ready: defaultAction,
  });

  // TODO need to refactor the cookie rule
  $.register({
    rule: {
      host: [
        /^www\.img(taxi|adult|wallet)\.com$/,
        /^www\.imgdrive\.net$/,
      ],
      path: /^\/img-.*\.html$/,
    },
    start: function () {
      var c = $.getCookie('img_c_d') || $.getCookie('img_p_d');
      if (c) {
        return;
      }
      $.post(window.location.href.toString(), {
        cti: 1,
        ref: '',
        rc: 1,
      }).then(function (data) {
        window.location.reload();
      });
    },
    ready: function () {
      $.removeNodes('iframe');

      var node = $.$('#continuetoimage > form input');
      if (node) {
        // first pass
        node.click();
        // somehow imgrun.net need to click twice
        node.click();
        return;
      }

      // the cookies are shared in the whole domain
      // we have to reset cookies to prevent wrong state
      $.resetCookies();

      // second pass
      var i = $('img[class^=centred]');
      $.openImage(i.src);
    },
  });

  function helper () {
    // crack the shitty qqc.co visitScript 5440
    $.window.setTimeout = _.nop;

    // this site checks cookie that caculate from session
    // do an AJAX to skip checking
    return $.get(window.location.toString()).then(function (data) {
      return $.toDOM(data);
    });
  }

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/Photo\/img-.+\.html$/,
    },
    start: function () {
      helper().then(function (page) {
        var i = $('img[class^=centred]', page);
        $.openImage(i.src);
      });
    },
  });

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/\d+\/img-.*\.html$/,
    },
    start: function () {
      helper().then(function (page) {
        var bbcode = $.$('#imagecodes input', page);
        bbcode = bbcode.value.match(/.+\[IMG\]([^\[]+)\[\/IMG\].+/);
        bbcode = bbcode[1];
        bbcode = bbcode.replace('small', 'big');

        $.openImage(bbcode);
      });
    },
  });

  $.register({
    rule: [
      {
        host: /^imgking\.co$/,
        path: /^\/img3-.*\.html/,
      },
      {
        host: /^imgkings\.com$/,
        path: /^\/img-.*\.html/,
      },
    ],
    ready: function () {
      var url = $.window.linkid;
      $.openImage(url);
    },
  });

  $.register({
    rule: [
      {
        host: /^imgking\.co$/,
        path: /^\/img4-.*\.html/,
      },
      {
        host: /^imgkings\.com$/,
        path: /^\/img2-.*\.html/,
      },
    ],
    ready: defaultAction,
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>imgreputa.com<commit_after>(function () {
  'use strict';

  function action (firstSelector, secondSelector) {
    $.removeNodes('iframe, #adblock_detect, .popupOverlay');

    var node = $.$(firstSelector);
    if (node) {
      // first pass
      _.wait(500).then(function () {
        node.removeAttribute('disabled');
        return _.wait(500);
      }).then(function () {
        // HACK some sites can not receive the click event without focus
        node.focus();
        // HACK some sites needs to click multiple times
        node.click();
        node.click();
        node.click();
      });
      return;
    }

    // second pass
    var i = $(secondSelector);
    $.openImage(i.src);
  }

  var defaultAction = _.P(action, '#continuetoimage > form input', 'img[class^=centred]');

  $.register({
    rule: [
      {
        host: [
          // com
          // starts with image
          /^image(ontime|corn|picsa|horse)\.com$/,
          // ends with image
          /^(zonezeed|zelje|croft|myhot|bok|hostur|greasy)image\.com$/,
          // starts with img
          /^img(icy|next|savvy|\.spicyzilla|twyti|xyz|devil|tzar|ban|pu|beer|wet|tornado|kicks|-pay|nimz|binbou|2share|22|cover|hit|main|trial|blank|-uploads|reputa)\.com$/,
          // starts with img-
          /^img-(zone|planet)\.com$/,
          // starts with www
          /^www\.img(blow|lemon|4sharing)\.com$/,
          /^www\.imagefolks\.com$/,
          // starts with xxx
          /^xxx(imagenow|screens)\.com$/,
          // else
          /^(picstwist|ericsony|wpc8|uplimg|lexiit|thumbnailus|newimagepost|fapingpics|dimtus|tinizo)\.com$/,
          /^((i|hentai)\.)?imgslip\.com$/,
          /^(i|xxx)\.hentaiyoutube\.com$/,
          /^(go|er)imge\.com$/,
          /^(like\.)?08lkk\.com$/,
          /^(www\.)?\.imgult\.com$/,
          /^nim(plus|zshare)\.com$/,
          /^nudeximg\.com$/,
          /imgseeds?\.com$/,
          /xxxsparrow?\.com$/,
          /damimage\.com$/,
          /imagedecode\.com$/,
          // net
          /^img(serve|coin|fap|candy|master|-view|run|boom|project|python|pics)\.net$/,
          /^(imagesouls|naughtygate|gallerycloud|imagelaser|picture-bang|project-photo|pix-link|funimg|golfpit|xximg)\.net$/,
          // org
          /^(shot|adult)img\.org$/,
          /^img(studio|spot)\.org$/,
          /^image(\.adlock|on|team)\.org$/,
          /^(drag|teen|mega)image\.org$/,
          /^teenshot\.org$/,
          // else
          /^(hotimages|55888)\.eu$/,
          /^img(cloud|mag)\.co$/,
          /^pixup\.us$/,
          /^(bulkimg|photo-up|myimg|pop-img|img-pop|ads-img)\.info$/,
          /^img\.yt$/,
          /^vava\.in$/,
          /^(pixxx|picspornfree|imgload|fapat)\.me$/,
          /^(domaink|pic2pic|porno-pirat|24avarii|loftlm|18pron|imgplus)\.ru$/,
          /^www\.hotimage\.uk$/,
          /^imgease\.re$/,
          /^goimg\.xyz$/,
          /^pic2pic\.site$/,
          /^darpix\.ga$/,
          /^sxpics\.nl$/,
          /^darpix\.desi$/,
          /^pic4you\.top$/,
          /^imgsen\.se$/,
        ],
        path: /^\/img-.*\.html/,
      },
      {
        host: [
          /^img(run|twyti)\.net$/,
          /^imgtwyti\.com$/,
          /^hentai-pop\.com$/,
          /^(jav|img)-hentai\.host$/,
          /^hentai-king\.host$/,
          /^img-king\.xyz$/,
        ],
        path: /^\/[ti]\/img-.*\.html/,
      },
      {
        host: /^imgking\.co$/,
        path: /^\/img-.*\.html/,
      },
      {
        host: /^imgbb\.net$/,
        path: /^\/.-.+$/,
      },
      {
        host: /^cdn\.javtotal\.com$/,
        path: /^\/img\/.+$/,
      },
    ],
    ready: defaultAction,
  });

  $.register({
    rule: {
      host: /^imgrat\.com$/,
      path: /^\/img-.*\.html/,
    },
    ready: _.P(action, '#close', '#main_image img.center-block.img-responsive'),
  });

  $.register({
    rule: {
      host: /^imageporn\.eu$/,
      path: /^\/img-.*\.html/,
    },
    start: function () {
      // HACK break script injection
      $.window.document.createElement = null;
    },
    ready: defaultAction,
  });

  // TODO need to refactor the cookie rule
  $.register({
    rule: {
      host: [
        /^www\.img(taxi|adult|wallet)\.com$/,
        /^www\.imgdrive\.net$/,
      ],
      path: /^\/img-.*\.html$/,
    },
    start: function () {
      var c = $.getCookie('img_c_d') || $.getCookie('img_p_d');
      if (c) {
        return;
      }
      $.post(window.location.href.toString(), {
        cti: 1,
        ref: '',
        rc: 1,
      }).then(function (data) {
        window.location.reload();
      });
    },
    ready: function () {
      $.removeNodes('iframe');

      var node = $.$('#continuetoimage > form input');
      if (node) {
        // first pass
        node.click();
        // somehow imgrun.net need to click twice
        node.click();
        return;
      }

      // the cookies are shared in the whole domain
      // we have to reset cookies to prevent wrong state
      $.resetCookies();

      // second pass
      var i = $('img[class^=centred]');
      $.openImage(i.src);
    },
  });

  function helper () {
    // crack the shitty qqc.co visitScript 5440
    $.window.setTimeout = _.nop;

    // this site checks cookie that caculate from session
    // do an AJAX to skip checking
    return $.get(window.location.toString()).then(function (data) {
      return $.toDOM(data);
    });
  }

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/Photo\/img-.+\.html$/,
    },
    start: function () {
      helper().then(function (page) {
        var i = $('img[class^=centred]', page);
        $.openImage(i.src);
      });
    },
  });

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/\d+\/img-.*\.html$/,
    },
    start: function () {
      helper().then(function (page) {
        var bbcode = $.$('#imagecodes input', page);
        bbcode = bbcode.value.match(/.+\[IMG\]([^\[]+)\[\/IMG\].+/);
        bbcode = bbcode[1];
        bbcode = bbcode.replace('small', 'big');

        $.openImage(bbcode);
      });
    },
  });

  $.register({
    rule: [
      {
        host: /^imgking\.co$/,
        path: /^\/img3-.*\.html/,
      },
      {
        host: /^imgkings\.com$/,
        path: /^\/img-.*\.html/,
      },
    ],
    ready: function () {
      var url = $.window.linkid;
      $.openImage(url);
    },
  });

  $.register({
    rule: [
      {
        host: /^imgking\.co$/,
        path: /^\/img4-.*\.html/,
      },
      {
        host: /^imgkings\.com$/,
        path: /^\/img2-.*\.html/,
      },
    ],
    ready: defaultAction,
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>(function() {

  function warnMessage(entry) {
    var markup = "";
    if (entry.warn_message) {
      markup += ""
    }
    return markup;
  }

  function userEntryDefaultFormatter(entry) {
    var markup = "";
    if (entry.displayIcon && entry.type) {
      if (entry.type == "USER_TYPE") {
        markup += "";
      } else if (entry.type == "GROUP_TYPE") {
        markup += "";
      }
    }
    markup += entry.displayLabel;
    markup += " " + entry.id + "";
    markup += warnMessage(entry);
    return markup;
  }

  function docEntryDefaultFormatter(doc) {
    var markup = "

";
    markup += "
";
    if (doc.properties && doc.properties['common:icon']) {
      markup += ""
    }
    markup += "	";
    markup += doc.title;
    markup += warnMessage(doc);
    if (doc.path) {
      markup += "" + doc.path + "";
    }
    markup += "

"
    return markup;
  }

  function dirEntryDefaultFormatter(entry) {
    var markup = entry.displayLabel;
    markup += warnMessage(entry);
    return markup;
  }

  var userSelectionDefaultFormatter = userEntryDefaultFormatter;

  function docSelectionDefaultFormatter(doc) {
    var markup = "";
    if (doc.properties && doc.properties['common:icon']) {
      markup += ""
    }
    markup += getDocLinkElt(doc);
    markup += warnMessage(doc);
    return markup;
  }

  function dirSelectionDefaultFormatter(entry) {
    var markup = entry.absoluteLabel;
    markup += warnMessage(entry);
    return markup;
  }

  function getOperationName(params) {
    var opName = params.operationId;
    if (typeof (opName) == 'undefined' || opName == '') {
      if (params.directoryName && params.directoryName.length > 0) {
        opName = 'Directory.SuggestEntries';
      } else {
        opName = 'Document.PageProvider';
      }
    }
    return opName;
  }

  function getDocLinkElt(doc) {
    if (doc.contextParameters) {
      var url = doc.contextParameters.documentURL;
      var markup = "" + doc.title + ""
      return markup;
    } else {
      return doc.title;
    }
  }

  function getUrlWithConversationId(url) {
    return url + "?conversationId=" + currentConversationId;
  }

  function configureOperationParameters(op, params, query) {
    var restoreSeamCtx = params.restoreSeamCtx == 'true';
    var temp = {};
    jQuery.extend(temp, params);
    temp.lang = currentUserLang;
    if (params.operationId == 'Directory.SuggestEntries') {
      // build default operation for Directory
      temp.searchTerm = query.term;
    } else if (params.operationId == 'UserGroup.Suggestion') {
      temp.searchTerm = query.term;
      temp.searchType = params.userSuggestionSearchType;
    } else if (params.operationId == 'Document.PageProvider') {
      // build default operation for Document
      temp.searchTerm = query.term + "%";
      temp.query = params.query;
      temp.providerName = params.pageProviderName;
      temp.page = "0";
      temp.pageSize = "20";
    } else {
      // custom operation, pass at least the query term
      temp.searchTerm = query.term;
    }
    if (restoreSeamCtx && typeof currentConversationId != 'undefined') {
      // Give needed info to restore Seam context
      op.addParameter("id", getOperationName(params));
      op.addParameter("conversationId", currentConversationId);
      op.opts.automationParams.context = temp;
    } else {
      op.addParameters(temp);
    }
  }

  function fillResult(results, data, params) {
    if (typeof(data.length) != "undefined") {
      // default result parsing for Directory entries
      for (i = 0; i < data.length; i++) {
        var entry = data[i];
        results.push(entry);
      }
    } else if (typeof(data.entries) != "undefined") {
      // default result parsing for Documents
      for (i = 0; i < data.entries.length; i++) {
        var doc = data.entries[i];
        results.push(doc);
      }
    } else {
      alert("Error with suggestion widget");
    }
  }

  function getDefaultLabel(item) {
    if (item.displayLabel) {
      return item.displayLabel;
    } else {
      return item.title;
    }
  }

  function getDefaultId(item) {
    if (item.computedId) {
      return item.computedId;
    } else if (item.uid) {
      return item.uid;
    } else {
      return item.id;
    }
  }

  function initSelect2Widget(el) {
    // Make sure we don't initialize the element twice
    if (el.data('s2Done')) {
      return;
    }
    el.data('s2Done', true);

    // retrieve parameters from Html
    var elid = el.attr("id");
    var params = {};

    var paramId = (elid + "_params").split(":").join("\\:");
    var paramsHolder = jQuery("#" + paramId);
    params = JSON.parse(paramsHolder.val());

    var readonly = params.readonly == 'true';
    var required = params.required == 'true';
    var restoreSeamCtx = params.restoreSeamCtx == 'true';

    var initId = (elid + "_init").split(":").join("\\:");
    var initHolder = jQuery("#" + initId);
    var initDoc = null;
    try {
      initDoc = JSON.parse(initHolder.val());
    } catch (err) {
      // console.log("Unable to parse initvalue", err, initHolder.val())
    }

    // set style on select
    el.css("width", params.width);

    // determine operation name
    var opName = getOperationName(params);

    // define automation params
    var automationParams = {
      "documentSchemas" : params.documentSchemas
    };

    if (params.repository) {
      automationParams.repository = params.repository;
    }

    // init Automation Operation
    var op = null;
    if (restoreSeamCtx && typeof currentConversationId != 'undefined') {
      // If Seam context is available, let's restore it
      op = jQuery().automation('Seam.RunOperation', automationParams);
    } else {
      op = jQuery().automation(opName, automationParams);
    }

    // detect if we need custom selection formatting
    var selectionFormatterFunction = null;
    if (params.selectionFormatter && params.selectionFormatter.length > 0) {
      selectionFormatterFunction = eval(params.selectionFormatter);
    }
    // detect if we need custom suggestion formatting
    var suggestionFormatterFunction = null;
    if (params.suggestionFormatter && params.suggestionFormatter.length > 0) {
      suggestionFormatterFunction = eval(params.suggestionFormatter);
    }

    // build select2 parameters
    var select2_params = {
      containerCssClass : params.containerCssClass,
      dropdownCssClass : params.dropdownCssClass,
      minimumInputLength : params.minChars,
      query : function(query) {

        configureOperationParameters(op, params, query);

        op.execute(function(data, textStatus, xhr) {
          var results = [];
          fillResult(results, data, params)
          query.callback({
            results : results
          });
        });
      }
    }

    // append custom selection formatter if needed
    if (selectionFormatterFunction != null) {
      select2_params.formatSelection = selectionFormatterFunction;
    } else {
      select2_params.formatSelection = function(doc) {
        if (select2_params.labelFieldName != null) {
          return doc.properties[select2_params.labelFieldName];
        } else {
          return getDefaultLabel(doc)
        }
      };
    }
    // append custom suggestion formatter if needed
    if (suggestionFormatterFunction != null) {
      select2_params.formatResult = suggestionFormatterFunction;
    } else {
      select2_params.formatResult = getDefaultLabel;
    }

    // append id formatter if needed
    if (params.idProperty && params.idProperty.length > 0) {
      select2_params.id = function(doc) {
        return doc.properties[params.idProperty];
      };
    } else if (params.idFunction) {
      select2_params.id = eval(params.idFunction);
    } else if (params.prefixed) {
      select2_params.id = function(item) {
        return item.prefixed_id;
      };
    } else {
      select2_params.id = getDefaultId;
    }

    if (initDoc != null) {
      select2_params.initSelection = function(element, callback) {
        callback(initDoc);
      };
    }

    if (params.multiple == 'true') {
      select2_params.maximumSelectionSize = params.maximumSelectionSize;
      select2_params.multiple = true;
    }

    if (params.placeholder && !readonly) {
      select2_params.placeholder = params.placeholder;
      select2_params.allowClear = !required;
    }

    // dropdown on arrow only
    if (params.dropdownOnArrow == 'true' && params.multiple == 'false') {
      select2_params.dropdownOnArrow = true;
    }

    // separator
    if (params.separator) {
      select2_params.separator = params.separator;
    }

    // init select2
    el.select2(select2_params);

    // view or edit mode
    if (readonly) {
      el.select2("readonly", true);
    }

    if (!readonly) {

      // Make selected items sortable
      if (params.multiple == 'true' && params.orderable == 'true') {
        el.select2("container").find("ul.select2-choices").sortable({
          containment : 'parent',
          start : function() {
            el.select2("onSortStart");
          },
          update : function() {
            el.select2("onSortEnd");
          }
        });
      }

      // Handle onclick widget property
      el.on("select2-opening", function(e) {
        if (params.onclick) {
          eval(params.onclick);
        }
      });

      // trigger for safeEdit restore
      el.on("change", function(e) {
        if (e) {
          if (e.added) {
            var newValue;
            if (select2_params.multiple) {
              var newObj = JSON.parse(initHolder.val());
              newObj.push(e.added);
              var newValue = JSON.stringify(newObj);
            } else {
              newValue = JSON.stringify(e.added);
            }
            initHolder.val(newValue);
          }

          if (e.removed) {
            var removedId = select2_params.id(e.removed);
            if (select2_params.multiple) {
              var newValue = '';
              var tempObj = JSON.parse(initHolder.val());
              jQuery.each(tempObj, function(index, result) {
                if (result) {
                  if (select2_params.id(result) == removedId) {
                    tempObj.splice(index, 1);
                  }
                }
              });
              newValue = JSON.stringify(tempObj);
              initHolder.val(newValue);
            } else {
              if (initHolder.val() == removedId) {
                initHolder.val('');
              }
            }
          }
        }

        // ReRender any jsf component if needed.
        if (params.reRenderFunctionName) {
          window[params.reRenderFunctionName]();
        }

        // Handle onchange widget property
        if (params.onchange) {
          eval(params.onchange);
        }

      });
    }

    var $parentForm = jQuery(el).closest("form");
    if ($parentForm.hasClass("safeEditEnabled")) {
        // Register postRestore function for safeEdit
        jQuery(el).closest("form").registerPostRestoreCallBacks(function(data) {
          initSelect2Widget(jQuery(el));
        });
      }
  }

  window.initSelect2AjaxWidget = function initSelect2AjaxWidget(widgetId, index) {

    var selector = "input[type='hidden'][id$=";

    if (index != null && index.length > 0) {
      selector = selector + index + "\\:";
    }
    selector = selector + widgetId + "_select2]";

    jQuery(selector).each(function(idx, el) {
      initSelect2Widget(jQuery(el));
    });

  }

  window.initSelect2Widgets = function initSelect2Widgets() {
    jQuery("input[type='hidden'][id$=select2]").each(function(idx, el) {
      initSelect2Widget(jQuery(el));
    });
  }

})();
<commit_msg>NXP-14030: adapt safeEdit restore callback<commit_after>(function() {

  function warnMessage(entry) {
    var markup = "";
    if (entry.warn_message) {
      markup += ""
    }
    return markup;
  }

  function userEntryDefaultFormatter(entry) {
    var markup = "";
    if (entry.displayIcon && entry.type) {
      if (entry.type == "USER_TYPE") {
        markup += "";
      } else if (entry.type == "GROUP_TYPE") {
        markup += "";
      }
    }
    markup += entry.displayLabel;
    markup += " " + entry.id + "";
    markup += warnMessage(entry);
    return markup;
  }

  function docEntryDefaultFormatter(doc) {
    var markup = "

";
    markup += "
";
    if (doc.properties && doc.properties['common:icon']) {
      markup += ""
    }
    markup += "	";
    markup += doc.title;
    markup += warnMessage(doc);
    if (doc.path) {
      markup += "" + doc.path + "";
    }
    markup += "

"
    return markup;
  }

  function dirEntryDefaultFormatter(entry) {
    var markup = entry.displayLabel;
    markup += warnMessage(entry);
    return markup;
  }

  var userSelectionDefaultFormatter = userEntryDefaultFormatter;

  function docSelectionDefaultFormatter(doc) {
    var markup = "";
    if (doc.properties && doc.properties['common:icon']) {
      markup += ""
    }
    markup += getDocLinkElt(doc);
    markup += warnMessage(doc);
    return markup;
  }

  function dirSelectionDefaultFormatter(entry) {
    var markup = entry.absoluteLabel;
    markup += warnMessage(entry);
    return markup;
  }

  function getOperationName(params) {
    var opName = params.operationId;
    if (typeof (opName) == 'undefined' || opName == '') {
      if (params.directoryName && params.directoryName.length > 0) {
        opName = 'Directory.SuggestEntries';
      } else {
        opName = 'Document.PageProvider';
      }
    }
    return opName;
  }

  function getDocLinkElt(doc) {
    if (doc.contextParameters) {
      var url = doc.contextParameters.documentURL;
      var markup = "" + doc.title + ""
      return markup;
    } else {
      return doc.title;
    }
  }

  function getUrlWithConversationId(url) {
    return url + "?conversationId=" + currentConversationId;
  }

  function configureOperationParameters(op, params, query) {
    var restoreSeamCtx = params.restoreSeamCtx == 'true';
    var temp = {};
    jQuery.extend(temp, params);
    temp.lang = currentUserLang;
    if (params.operationId == 'Directory.SuggestEntries') {
      // build default operation for Directory
      temp.searchTerm = query.term;
    } else if (params.operationId == 'UserGroup.Suggestion') {
      temp.searchTerm = query.term;
      temp.searchType = params.userSuggestionSearchType;
    } else if (params.operationId == 'Document.PageProvider') {
      // build default operation for Document
      temp.searchTerm = query.term + "%";
      temp.query = params.query;
      temp.providerName = params.pageProviderName;
      temp.page = "0";
      temp.pageSize = "20";
    } else {
      // custom operation, pass at least the query term
      temp.searchTerm = query.term;
    }
    if (restoreSeamCtx && typeof currentConversationId != 'undefined') {
      // Give needed info to restore Seam context
      op.addParameter("id", getOperationName(params));
      op.addParameter("conversationId", currentConversationId);
      op.opts.automationParams.context = temp;
    } else {
      op.addParameters(temp);
    }
  }

  function fillResult(results, data, params) {
    if (typeof(data.length) != "undefined") {
      // default result parsing for Directory entries
      for (i = 0; i < data.length; i++) {
        var entry = data[i];
        results.push(entry);
      }
    } else if (typeof(data.entries) != "undefined") {
      // default result parsing for Documents
      for (i = 0; i < data.entries.length; i++) {
        var doc = data.entries[i];
        results.push(doc);
      }
    } else {
      alert("Error with suggestion widget");
    }
  }

  function getDefaultLabel(item) {
    if (item.displayLabel) {
      return item.displayLabel;
    } else {
      return item.title;
    }
  }

  function getDefaultId(item) {
    if (item.computedId) {
      return item.computedId;
    } else if (item.uid) {
      return item.uid;
    } else {
      return item.id;
    }
  }

  function initSelect2Widget(el) {
    // Make sure we don't initialize the element twice
    if (el.data('s2Done')) {
      return;
    }
    el.data('s2Done', true);

    // retrieve parameters from Html
    var elid = el.attr("id");
    var params = {};

    var paramId = (elid + "_params").split(":").join("\\:");
    var paramsHolder = jQuery("#" + paramId);
    params = JSON.parse(paramsHolder.val());

    var readonly = params.readonly == 'true';
    var required = params.required == 'true';
    var restoreSeamCtx = params.restoreSeamCtx == 'true';

    var initId = (elid + "_init").split(":").join("\\:");
    var initHolder = jQuery("#" + initId);
    var initDoc = null;
    try {
      initDoc = JSON.parse(initHolder.val());
    } catch (err) {
      // console.log("Unable to parse initvalue", err, initHolder.val())
    }

    // set style on select
    el.css("width", params.width);

    // determine operation name
    var opName = getOperationName(params);

    // define automation params
    var automationParams = {
      "documentSchemas" : params.documentSchemas
    };

    if (params.repository) {
      automationParams.repository = params.repository;
    }

    // init Automation Operation
    var op = null;
    if (restoreSeamCtx && typeof currentConversationId != 'undefined') {
      // If Seam context is available, let's restore it
      op = jQuery().automation('Seam.RunOperation', automationParams);
    } else {
      op = jQuery().automation(opName, automationParams);
    }

    // detect if we need custom selection formatting
    var selectionFormatterFunction = null;
    if (params.selectionFormatter && params.selectionFormatter.length > 0) {
      selectionFormatterFunction = eval(params.selectionFormatter);
    }
    // detect if we need custom suggestion formatting
    var suggestionFormatterFunction = null;
    if (params.suggestionFormatter && params.suggestionFormatter.length > 0) {
      suggestionFormatterFunction = eval(params.suggestionFormatter);
    }

    // build select2 parameters
    var select2_params = {
      containerCssClass : params.containerCssClass,
      dropdownCssClass : params.dropdownCssClass,
      minimumInputLength : params.minChars,
      query : function(query) {

        configureOperationParameters(op, params, query);

        op.execute(function(data, textStatus, xhr) {
          var results = [];
          fillResult(results, data, params)
          query.callback({
            results : results
          });
        });
      }
    }

    // append custom selection formatter if needed
    if (selectionFormatterFunction != null) {
      select2_params.formatSelection = selectionFormatterFunction;
    } else {
      select2_params.formatSelection = function(doc) {
        if (select2_params.labelFieldName != null) {
          return doc.properties[select2_params.labelFieldName];
        } else {
          return getDefaultLabel(doc)
        }
      };
    }
    // append custom suggestion formatter if needed
    if (suggestionFormatterFunction != null) {
      select2_params.formatResult = suggestionFormatterFunction;
    } else {
      select2_params.formatResult = getDefaultLabel;
    }

    // append id formatter if needed
    if (params.idProperty && params.idProperty.length > 0) {
      select2_params.id = function(doc) {
        return doc.properties[params.idProperty];
      };
    } else if (params.idFunction) {
      select2_params.id = eval(params.idFunction);
    } else if (params.prefixed) {
      select2_params.id = function(item) {
        return item.prefixed_id;
      };
    } else {
      select2_params.id = getDefaultId;
    }

    if (initDoc != null) {
      select2_params.initSelection = function(element, callback) {
        callback(initDoc);
      };
    }

    if (params.multiple == 'true') {
      select2_params.maximumSelectionSize = params.maximumSelectionSize;
      select2_params.multiple = true;
    }

    if (params.placeholder && !readonly) {
      select2_params.placeholder = params.placeholder;
      select2_params.allowClear = !required;
    }

    // dropdown on arrow only
    if (params.dropdownOnArrow == 'true' && params.multiple == 'false') {
      select2_params.dropdownOnArrow = true;
    }

    // separator
    if (params.separator) {
      select2_params.separator = params.separator;
    }

    // init select2
    el.select2(select2_params);

    // view or edit mode
    if (readonly) {
      el.select2("readonly", true);
    }

    if (!readonly) {

      // Make selected items sortable
      if (params.multiple == 'true' && params.orderable == 'true') {
        el.select2("container").find("ul.select2-choices").sortable({
          containment : 'parent',
          start : function() {
            el.select2("onSortStart");
          },
          update : function() {
            el.select2("onSortEnd");
          }
        });
      }

      // Handle onclick widget property
      el.on("select2-opening", function(e) {
        if (params.onclick) {
          eval(params.onclick);
        }
      });

      // trigger for safeEdit restore
      el.on("change", function(e) {
        if (e) {
          if (e.added) {
            var newValue;
            if (select2_params.multiple) {
              var newObj = JSON.parse(initHolder.val());
              newObj.push(e.added);
              var newValue = JSON.stringify(newObj);
            } else {
              newValue = JSON.stringify(e.added);
            }
            initHolder.val(newValue);
          }

          if (e.removed) {
            var removedId = select2_params.id(e.removed);
            if (select2_params.multiple) {
              var newValue = '';
              var tempObj = JSON.parse(initHolder.val());
              jQuery.each(tempObj, function(index, result) {
                if (result) {
                  if (select2_params.id(result) == removedId) {
                    tempObj.splice(index, 1);
                  }
                }
              });
              newValue = JSON.stringify(tempObj);
              initHolder.val(newValue);
            } else {
              if (initHolder.val() == removedId) {
                initHolder.val('');
              }
            }
          }
        }

        // ReRender any jsf component if needed.
        if (params.reRenderFunctionName) {
          window[params.reRenderFunctionName]();
        }

        // Handle onchange widget property
        if (params.onchange) {
          eval(params.onchange);
        }

      });
    }

    var $parentForm = jQuery(el).closest("form");
    if ($parentForm.hasClass("safeEditEnabled")) {
        // Register postRestore function for safeEdit
        jQuery(el).closest("form").registerPostRestoreCallBacks(function(data) {
          el.data('s2Done', false);
          initSelect2Widget(jQuery(el));
        });
      }
  }

  window.initSelect2AjaxWidget = function initSelect2AjaxWidget(widgetId, index) {

    var selector = "input[type='hidden'][id$=";

    if (index != null && index.length > 0) {
      selector = selector + index + "\\:";
    }
    selector = selector + widgetId + "_select2]";

    jQuery(selector).each(function(idx, el) {
      initSelect2Widget(jQuery(el));
    });

  }

  window.initSelect2Widgets = function initSelect2Widgets() {
    jQuery("input[type='hidden'][id$=select2]").each(function(idx, el) {
      initSelect2Widget(jQuery(el));
    });
  }

})();
<|endoftext|>


<commit_before>var gulp = require('gulp');
var fs = require('fs');
var mocha = require('gulp-mocha');

var stageLoader = require('./core/stage-loader');
var fancyStages = require('./core/fancy-stages');
// TODO: Where is the correct place to trigger loading of core phases?
var phaseLib = require('./core/phase-lib');
var stream = require('./core/stream');
var options = require('./core/options');
var trace = require('./core/trace');

var tasks = {};

function buildTestTask(name, reporter) {
  gulp.task(name, function() {
    return gulp.src(['tests/*.js', 'tests/pipeline/*.js'], {read: false})
        .pipe(mocha({
          ui: 'bdd',
          ignoreLeaks: true,
          reporter: reporter
      }));
  });
}

buildTestTask('test', 'nyan');
buildTestTask('travis-test', 'spec');

function buildTask(name, stageList) {
  tasks[name] = stageList;
  gulp.task(name, function(incb) {
    var cb = function(data) {
      trace.dump();
      incb();
    };
    stageList = stageList.map(stageLoader.stageSpecificationToStage);
    stageLoader.processStages(stageList, cb, function(e) { throw e; });
  });
};

/*
 * Some example pipelines.
 */
buildTask('html', ['JSON:' + options.file, 'HTMLWriter', 'output:result.html.html']);
buildTask('js', ['JSON:' + options.file, 'JSWriter', 'output:result.js.html']);
buildTask('stats', ['JSON:' + options.file, 'StatsWriter', 'consoleOutput']);

/*
 * examples using filters
 */
buildTask('compactComputedStyle', ['JSON:' + options.file, 'StyleFilter', 'output:' + options.file + '.filter']);
buildTask('extractStyle', ['JSON:' + options.file, 'StyleMinimizationFilter', 'output:' + options.file + '.filter']);
buildTask('tokenStyles', ['JSON:' + options.file, 'StyleTokenizerFilter', 'output:' + options.file + '.filter']);
buildTask('nukeIFrame', ['JSON:' + options.file, 'NukeIFrameFilter', 'output:' + options.file + '.filter']);

/*
 * example of fabrication
 */
buildTask('generate', ['JSON:' + options.file, 'SchemaBasedFabricator', 'output:' + options.file + '.gen']);

/*
 * examples using device telemetry
 */
buildTask('get', ['immediate:' + options.url, 'telemetrySave', 'output:result.json']);
buildTask('perf', ['immediate:' + options.url, 'telemetryPerf', 'output:trace.json']);
buildTask('endToEnd', ['immediate:' + options.url, 'telemetrySave', 'HTMLWriter', 'simplePerfer', 'output:trace.json']);

/*
 * running an experiment
 */
buildTask('runExperiment', ['file:' + options.file, 'doExperiment']);

/*
 * ejs fabrication
 */
gulp.task('ejs', function(incb) {
  var cb = function(data) { incb(); };
  stageLoader.processStages(
    [
      stageLoader.stageSpecificationToStage('file:' + options.file),
      stageLoader.stageSpecificationToStage('ejsFabricator'),
      stageLoader.stageSpecificationToStage('writeStringFile', {tag: 'ejsFabricator'})
    ], cb, function(e) { throw e; });
});

/*
 * TODO: Refactor stage-loader so it can load fancy stages too.
 *
 * example of using stages directly
 */

function tagFilename() {
  return stream.tag(function(data, tags) { return {key: 'filename', value: data} });
}

function genFilename() {
  return stream.tag(function(data, tags) {
    var filename = tags['filename'].replace(new RegExp(options.inputSpec), options.outputSpec);
    return {key: 'filename', value: filename} });
}

gulp.task('mhtml', function(incb) {
  var cb = function(data) { incb(); };
  stageLoader.processStages(
      [
        stream.streamedStage(fancyStages.fileInputs(options.inputSpec)),
        tagFilename(),
        stageLoader.stageSpecificationToStage('fileToJSON'),
        stageLoader.stageSpecificationToStage('HTMLWriter'),
        genFilename(),
        stream.write()
      ], cb, function(e) { throw e; });
});

gulp.task('processLogs', function(incb) {
  var cb = function(data) { incb(); };
  stageLoader.processStages(
      [
        stream.streamedStage(fancyStages.fileInputs(options.inputSpec)),
        stream.streamedStage(stageLoader.stage(
            [
              stageLoader.stageSpecificationToStage('fileToJSON'),
              stageLoader.stageSpecificationToStage('traceFilter'),
              stageLoader.stageSpecificationToStage('tracePIDSplitter'),
              fancyStages.valueMap(stageLoader.stageSpecificationToStage('traceTree')),
              fancyStages.valueMap(stageLoader.stageSpecificationToStage('tracePrettyPrint')),
            ])),
        stream.streamedStage(fancyStages.valueMap(stageLoader.stageSpecificationToStage('consoleOutput')))
      ], cb, function(e) { throw e; });
});

module.exports.tasks = tasks;
<commit_msg>Made a simple gulp task.<commit_after>var gulp = require('gulp');
var fs = require('fs');
var mocha = require('gulp-mocha');

var stageLoader = require('./core/stage-loader');
var fancyStages = require('./core/fancy-stages');
// TODO: Where is the correct place to trigger loading of core phases?
var phaseLib = require('./core/phase-lib');
var stream = require('./core/stream');
var options = require('./core/options');
var trace = require('./core/trace');

var tasks = {};

function buildTestTask(name, reporter) {
  gulp.task(name, function() {
    return gulp.src(['tests/*.js', 'tests/pipeline/*.js'], {read: false})
        .pipe(mocha({
          ui: 'bdd',
          ignoreLeaks: true,
          reporter: reporter
      }));
  });
}

buildTestTask('test', 'nyan');
buildTestTask('travis-test', 'spec');

function buildTask(name, stageList) {
  tasks[name] = stageList;
  gulp.task(name, function(incb) {
    var cb = function(data) {
      trace.dump();
      incb();
    };
    stageList = stageList.map(stageLoader.stageSpecificationToStage);
    stageLoader.processStages(stageList, cb, function(e) { throw e; });
  });
};

/*
 * Some example pipelines.
 */
buildTask('html', ['JSON:' + options.file, 'HTMLWriter', 'output:result.html.html']);
buildTask('js', ['JSON:' + options.file, 'JSWriter', 'output:result.js.html']);
buildTask('stats', ['JSON:' + options.file, 'StatsWriter', 'consoleOutput']);

/*
 * examples using filters
 */
buildTask('compactComputedStyle', ['JSON:' + options.file, 'StyleFilter', 'output:' + options.file + '.filter']);
buildTask('extractStyle', ['JSON:' + options.file, 'StyleMinimizationFilter', 'output:' + options.file + '.filter']);
buildTask('tokenStyles', ['JSON:' + options.file, 'StyleTokenizerFilter', 'output:' + options.file + '.filter']);
buildTask('nukeIFrame', ['JSON:' + options.file, 'NukeIFrameFilter', 'output:' + options.file + '.filter']);

/*
 * example of fabrication
 */
buildTask('generate', ['JSON:' + options.file, 'SchemaBasedFabricator', 'output:' + options.file + '.gen']);

/*
 * examples using device telemetry
 */
buildTask('get', ['immediate:' + options.url, 'telemetrySave', 'output:result.json']);
buildTask('perf', ['immediate:' + options.url, 'telemetryPerf', 'output:trace.json']);
buildTask('endToEnd', ['immediate:' + options.url, 'telemetrySave', 'HTMLWriter', 'simplePerfer', 'output:trace.json']);

/*
 * running an experiment
 */
buildTask('runExperiment', ['file:' + options.file, 'doExperiment']);

/*
 * ejs fabrication
 */
gulp.task('ejs', function(incb) {
  var cb = function(data) { incb(); };
  stageLoader.processStages(
    [
      stageLoader.stageSpecificationToStage('file:' + options.file),
      stageLoader.stageSpecificationToStage('ejsFabricator'),
      stageLoader.stageSpecificationToStage('writeStringFile', {tag: 'ejsFabricator'})
    ], cb, function(e) { throw e; });
});

/*
 * TODO: Refactor stage-loader so it can load fancy stages too.
 *
 * example of using stages directly
 */

function tagFilename() {
  return stream.tag(function(data, tags) { return {key: 'filename', value: data} });
}

function genFilename() {
  return stream.tag(function(data, tags) {
    var filename = tags['filename'].replace(new RegExp(options.inputSpec), options.outputSpec);
    return {key: 'filename', value: filename} });
}

gulp.task('mhtml', function(incb) {
  var cb = function(data) { incb(); };
  stageLoader.processStages(
      [
        stream.streamedStage(fancyStages.fileInputs(options.inputSpec)),
        tagFilename(),
        stageLoader.stageSpecificationToStage('fileToJSON'),
        stageLoader.stageSpecificationToStage('HTMLWriter'),
        genFilename(),
        stream.write()
      ], cb, function(e) { throw e; });
});

gulp.task('processLogs', function(incb) {
  var cb = function(data) { incb(); };
  stageLoader.processStages(
      [
        stream.streamedStage(fancyStages.fileInputs(options.inputSpec)),
        stream.streamedStage(stageLoader.stage(
            [
              stageLoader.stageSpecificationToStage('fileToJSON'),
              stageLoader.stageSpecificationToStage('traceFilter'),
              stageLoader.stageSpecificationToStage('tracePIDSplitter'),
              fancyStages.valueMap(stageLoader.stageSpecificationToStage('traceTree')),
              fancyStages.valueMap(stageLoader.stageSpecificationToStage('tracePrettyPrint')),
            ])),
        stream.streamedStage(fancyStages.valueMap(stageLoader.stageSpecificationToStage('consoleOutput')))
      ], cb, function(e) { throw e; });
});

// TODO(dglazkov): Turn into a phase.
gulp.task('buildChromium', function(cb) {
  var spawn = require('child_process').spawn;
  var chromiumPath = options.chromium;
  if (!chromiumPath)
    throw new Error('Path to Chromium repo (--chromium=[path/to/cr/src]) is required.');
  // TODO(dglazkov): Release/Debug and Target should be configurable.
  // TODO(dglazkov): Support building for android as well.
  var command = {
    cmd: 'ninja',
    args: [ '-C', 'out/Release', 'chrome' ],
    toString: function() {
      return this.cmd + ' ' + this.args.join(' ');
    }
  };
  var child = spawn(command.cmd, command.args, {
    cwd: chromiumPath,
    stdio: 'ignore',
  });
  child.on('error', function(err) {
    console.log('Unable to execute "' + command + '"');
    console.log('Is your path correct?');
  });
  // TODO(dglazkov): Detect success/failure and report errors.
  var buffer = [];
  child.on('close', function(code) {
    if (code) {
      console.log('"' + command + '" returned a non-zero exit code.');
      console.log('This is likely a Chromium build error.');
    }
    cb();
  });
});

module.exports.tasks = tasks;
<|endoftext|>


<commit_before>"use strict";

var use = require("alamid-plugin/use.js");
var path = require("path");
var argv = require("minimist")(process.argv.slice(2));

function dynamicConfig(basePath, fileName) {
    var env = dynamicConfig.getEnv();
    var filePath = dynamicConfig.getFilePath(basePath, env, fileName);
    var config;

    if (dynamicConfig.options.log) {
        console.log("Loading configuration '" + fileName + "'  from path '" + filePath + "'");
    }

    config = dynamicConfig.loadConfig(filePath);

    dynamicConfig.resolvedConfigPath = filePath;

    return config;
}

dynamicConfig.getEnv = function () { // eslint-disable-line complexity
    var envName = dynamicConfig.options.envName;

    return argv[envName] || argv[envName.toUpperCase()] || process.env[envName] || process.env[envName.toUpperCase()] || process.env.NODE_ENV || dynamicConfig.options.defaultEnv;
};

dynamicConfig.getFilePath = function (basePath, env, fileName) {
    return path.join(basePath, env, fileName);
};

dynamicConfig.loadConfig = function (filePath) {
    var config;

    try {
        config = require(filePath);
    } catch (err) {
        // handle only not found errors, throw the rest
        if (err.code === "MODULE_NOT_FOUND") {
            throw new Error("Config not found at '" + filePath + "'");
        }

        throw err;
    }

    return config;
};

dynamicConfig.options = {
    defaultEnv: "develop",
    envName: "env",
    log: false
};

dynamicConfig.use = use;

module.exports = dynamicConfig;
<commit_msg>remove try/catch block to give better error messages<commit_after>"use strict";

var use = require("alamid-plugin/use.js");
var path = require("path");
var argv = require("minimist")(process.argv.slice(2));

function dynamicConfig(basePath, fileName) {
    var env = dynamicConfig.getEnv();
    var filePath = dynamicConfig.getFilePath(basePath, env, fileName);
    var config;

    if (dynamicConfig.options.log) {
        console.log("Loading configuration '" + fileName + "'  from path '" + filePath + "'");
    }

    config = dynamicConfig.loadConfig(filePath);

    dynamicConfig.resolvedConfigPath = filePath;

    return config;
}

dynamicConfig.getEnv = function () { // eslint-disable-line complexity
    var envName = dynamicConfig.options.envName;

    return argv[envName] || argv[envName.toUpperCase()] || process.env[envName] || process.env[envName.toUpperCase()] || process.env.NODE_ENV || dynamicConfig.options.defaultEnv;
};

dynamicConfig.getFilePath = function (basePath, env, fileName) {
    return path.join(basePath, env, fileName);
};

dynamicConfig.loadConfig = function (filePath) {
    return require(filePath);
};

dynamicConfig.options = {
    defaultEnv: "develop",
    envName: "env",
    log: false
};

dynamicConfig.use = use;

module.exports = dynamicConfig;
<|endoftext|>


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

require("amd-loader");
try {
    require("heapdump");
} catch(e) {}

var path = require("path");
var architect = require("architect");
var optimist = require("optimist");
var async = require("async");
var os = require("os");
var urls = require("c9/urls");
require("c9/setup_paths.js");

if (process.version.match(/^v0/) && parseFloat(process.version.substr(3)) < 10) {
    console.warn("You're using Node.js version " + process.version
        + ". Version 0.10 or higher is recommended. Some features will not work.");
}

var DEFAULT_CONFIG = "s";
var DEFAULT_SETTINGS = getDefaultSettings();

var shortcuts = {
    "dev":       ["ide", "preview", "user-content", "vfs", "api", "sapi", "proxy", "redis", "profile", "oldclient", "homepage", "apps-proxy", "-s", "devel"],
    "onlinedev": ["ide", "preview", "user-content", "vfs", "api", "proxy", "oldclient", "homepage", "apps-proxy", "profile", "worker", "-s", "onlinedev"],
    "beta":      ["ide", "preview", "user-content", "vfs", "proxy", "-s", "beta"],
    "s":         ["standalone", "-s", "standalone"]
};
shortcuts.odev = shortcuts.onlinedev; // For backwards compatibility, if you see this in 2016 remove this line
var delayLoadConfigs = ["preview", "user-content", "api", "oldclient", "apps-proxy", "worker"];

module.exports = main;

if (!module.parent)
    main(process.argv.slice(2));

function getDefaultSettings() {
    var hostname = os.hostname();

    var suffix = hostname.trim().split("-").pop() || "";
    var modes = {
        "prod": "deploy",
        "beta": "beta",
        "dev": "devel",
        "onlinedev": "onlinedev"
    };
    return modes[suffix] || "devel";
}

module.exports.getDefaultSettings = getDefaultSettings;

function main(argv, config, onLoaded) {
    var inContainer = os.hostname().match(/-\d+$/);

    var options = optimist(argv)
        .usage("Usage: $0 [CONFIG_NAME] [--help]")
        .alias("s", "settings")
        .default("settings", DEFAULT_SETTINGS)
        .describe("settings", "Settings file to use")
        .describe("dump", "dump config file as JSON")
        .describe("domains", "Primary and any secondary top-level domains to use (e.g, c9.io,c9.dev)")
        .describe("exclude", "Exclude specified service")
        .default("domains", inContainer && process.env.C9_HOSTNAME || process.env.C9_DOMAINS)
        .boolean("help")
        .describe("help", "Show command line options.");

    var configs = options.argv._;
    if (!configs.length)
        configs = [config || DEFAULT_CONFIG];
    if (options.argv.exclude && !Array.isArray(options.argv.exclude.length))
        options.argv.exclude = [options.argv.exclude];

    var expanded = expandShortCuts(configs);
    if (expanded.length > configs.length)
        return main(expanded.concat(argv.filter(function(arg) {
            return !shortcuts[arg];
        })), config, onLoaded);

    var delayed = expanded.filter(function(c) { return delayLoadConfigs.indexOf(c) !== -1 });
    var notDelayed = expanded.filter(function(c) { return delayLoadConfigs.indexOf(c) === -1 });

    startConfigs(notDelayed, function() {
        startConfigs(delayed, function() {});
    });

    function startConfigs(configs, done) {
        async.each(configs, function(config, next) {
            if (options.argv.exclude && options.argv.exclude.indexOf(config) > -1)
                return next();
            start(config, options, function(err, result, path) {
                onLoaded && onLoaded(err, result, path);
                next(err);
            });
        }, done);
    }
}

function expandShortCuts(configs) {
    var results = configs.slice();
    for (var i = 0; i < results.length; i++) {
        var expanded = shortcuts[results[i]];
        if (expanded) {
            results.splice.apply(results, [i, 1].concat(expanded));
            i += expanded.length - 1;
        }
    }
    return results;
}

function start(configName, options, callback) {
    console.log("Starting", configName);

    var argv = options.argv;
    var settingsName = argv.settings;

    if (typeof settingsName != "string")
        settingsName = settingsName.pop();

    var configPath = configName;
    if (configPath[0] !== "/")
        configPath = path.join(__dirname, "/configs/", configName);

    var settings = require(path.join(__dirname, "./settings", settingsName))();

    argv.domains = argv.domains || settings.domains;
    if (settings.c9 && argv.domains)
        urls.replaceDomains(settings, argv.domains);

    var plugins = require(configPath)(settings, options);

    if (argv.help) {
        options.usage("Usage: $0 " + configName);
        options.showHelp();
    }

    if (!plugins)
        return;

    if (module.exports.onResolvePlugins)
        module.exports.onResolvePlugins(plugins, __dirname + "/plugins");

    architect.resolveConfig(plugins, __dirname + "/plugins", function(err, config) {
        if (err) {
            console.error(err);
            process.exit(1);
        }

        if (argv.dump) {
            console.log(JSON.stringify(config, null, 2));
            return callback && callback(null, config);
        }

        if (argv._getConfig)
            return callback && callback(null, config, configPath);

        var app = architect.createApp(config, function (err, app) {
            if (err) {
                console.trace("Error while starting '%s':", configPath);
                console.log(err, err.stack);
                process.exit(1);
            }
            console.log("Started '%s' with config '%s'!", configPath, settingsName);

            callback && callback(null, app);
        });

        app.on("service", function(name, plugin) {
            if (typeof plugin !== "function")
                plugin.name = name;
        });
    });
}<commit_msg>Add test mode settings for services-test server<commit_after>#!/usr/bin/env node
"use strict";

require("amd-loader");
try {
    require("heapdump");
} catch(e) {}

var path = require("path");
var architect = require("architect");
var optimist = require("optimist");
var async = require("async");
var os = require("os");
var urls = require("c9/urls");
require("c9/setup_paths.js");

if (process.version.match(/^v0/) && parseFloat(process.version.substr(3)) < 10) {
    console.warn("You're using Node.js version " + process.version
        + ". Version 0.10 or higher is recommended. Some features will not work.");
}

var DEFAULT_CONFIG = "s";
var DEFAULT_SETTINGS = getDefaultSettings();

var shortcuts = {
    "dev":       ["ide", "preview", "user-content", "vfs", "api", "sapi", "proxy", "redis", "profile", "oldclient", "homepage", "apps-proxy", "-s", "devel"],
    "onlinedev": ["ide", "preview", "user-content", "vfs", "api", "proxy", "oldclient", "homepage", "apps-proxy", "profile", "worker", "-s", "onlinedev"],
    "beta":      ["ide", "preview", "user-content", "vfs", "proxy", "-s", "beta"],
    "s":         ["standalone", "-s", "standalone"]
};
shortcuts.odev = shortcuts.onlinedev; // For backwards compatibility, if you see this in 2016 remove this line
var delayLoadConfigs = ["preview", "user-content", "api", "oldclient", "apps-proxy", "worker"];

module.exports = main;

if (!module.parent)
    main(process.argv.slice(2));

function getDefaultSettings() {
    var hostname = os.hostname();

    var suffix = hostname.trim().split("-").pop() || "";
    var modes = {
        "prod": "deploy",
        "beta": "beta",
        "dev": "devel",
        "onlinedev": "onlinedev",
        "test": "test"
    };
    return modes[suffix] || "devel";
}

module.exports.getDefaultSettings = getDefaultSettings;

function main(argv, config, onLoaded) {
    var inContainer = os.hostname().match(/-\d+$/);

    var options = optimist(argv)
        .usage("Usage: $0 [CONFIG_NAME] [--help]")
        .alias("s", "settings")
        .default("settings", DEFAULT_SETTINGS)
        .describe("settings", "Settings file to use")
        .describe("dump", "dump config file as JSON")
        .describe("domains", "Primary and any secondary top-level domains to use (e.g, c9.io,c9.dev)")
        .describe("exclude", "Exclude specified service")
        .default("domains", inContainer && process.env.C9_HOSTNAME || process.env.C9_DOMAINS)
        .boolean("help")
        .describe("help", "Show command line options.");

    var configs = options.argv._;
    if (!configs.length)
        configs = [config || DEFAULT_CONFIG];
    if (options.argv.exclude && !Array.isArray(options.argv.exclude.length))
        options.argv.exclude = [options.argv.exclude];

    var expanded = expandShortCuts(configs);
    if (expanded.length > configs.length)
        return main(expanded.concat(argv.filter(function(arg) {
            return !shortcuts[arg];
        })), config, onLoaded);

    var delayed = expanded.filter(function(c) { return delayLoadConfigs.indexOf(c) !== -1 });
    var notDelayed = expanded.filter(function(c) { return delayLoadConfigs.indexOf(c) === -1 });

    startConfigs(notDelayed, function() {
        startConfigs(delayed, function() {});
    });

    function startConfigs(configs, done) {
        async.each(configs, function(config, next) {
            if (options.argv.exclude && options.argv.exclude.indexOf(config) > -1)
                return next();
            start(config, options, function(err, result, path) {
                onLoaded && onLoaded(err, result, path);
                next(err);
            });
        }, done);
    }
}

function expandShortCuts(configs) {
    var results = configs.slice();
    for (var i = 0; i < results.length; i++) {
        var expanded = shortcuts[results[i]];
        if (expanded) {
            results.splice.apply(results, [i, 1].concat(expanded));
            i += expanded.length - 1;
        }
    }
    return results;
}

function start(configName, options, callback) {
    console.log("Starting", configName);

    var argv = options.argv;
    var settingsName = argv.settings;

    if (typeof settingsName != "string")
        settingsName = settingsName.pop();

    var configPath = configName;
    if (configPath[0] !== "/")
        configPath = path.join(__dirname, "/configs/", configName);

    var settings = require(path.join(__dirname, "./settings", settingsName))();

    argv.domains = argv.domains || settings.domains;
    if (settings.c9 && argv.domains)
        urls.replaceDomains(settings, argv.domains);

    var plugins = require(configPath)(settings, options);

    if (argv.help) {
        options.usage("Usage: $0 " + configName);
        options.showHelp();
    }

    if (!plugins)
        return;

    if (module.exports.onResolvePlugins)
        module.exports.onResolvePlugins(plugins, __dirname + "/plugins");

    architect.resolveConfig(plugins, __dirname + "/plugins", function(err, config) {
        if (err) {
            console.error(err);
            process.exit(1);
        }

        if (argv.dump) {
            console.log(JSON.stringify(config, null, 2));
            return callback && callback(null, config);
        }

        if (argv._getConfig)
            return callback && callback(null, config, configPath);

        var app = architect.createApp(config, function (err, app) {
            if (err) {
                console.trace("Error while starting '%s':", configPath);
                console.log(err, err.stack);
                process.exit(1);
            }
            console.log("Started '%s' with config '%s'!", configPath, settingsName);

            callback && callback(null, app);
        });

        app.on("service", function(name, plugin) {
            if (typeof plugin !== "function")
                plugin.name = name;
        });
    });
}<|endoftext|>


<commit_before>import React from 'react'
import * as hljs from 'highlight.js'
import ResizeObserver from 'resize-observer-polyfill'
import debounce from 'lodash.debounce'
import ms from 'ms'
import { Controlled as CodeMirror } from 'react-codemirror2'

import WindowControls from '../components/WindowControls'
import Watermark from '../components/svg/Watermark'
import { COLORS, LANGUAGE_MODE_HASH, LANGUAGE_NAME_HASH, DEFAULT_SETTINGS } from '../lib/constants'

const handleLanguageChange = (newCode, props) => {
  if (props.config.language === 'auto') {
    // try to set the language
    const detectedLanguage = hljs.highlightAuto(newCode).language
    const languageMode =
      LANGUAGE_MODE_HASH[detectedLanguage] || LANGUAGE_NAME_HASH[detectedLanguage]

    if (languageMode) {
      return { language: languageMode.mime || languageMode.mode }
    }
  }
  return { language: props.config.language }
}

class Carbon extends React.PureComponent {
  constructor(props) {
    super(props)

    this.state = {
      ...handleLanguageChange(this.props.children, this.props)
    }

    this.handleTitleBarChange = this.handleTitleBarChange.bind(this)
    this.codeUpdated = this.codeUpdated.bind(this)
    this.onBeforeChange = this.onBeforeChange.bind(this)
    this.handleLanguageChange = this.handleLanguageChange.bind(this)
  }

  componentDidMount() {
    const ro = new ResizeObserver(entries => {
      const cr = entries[0].contentRect
      this.props.onAspectRatioChange(cr.width / cr.height)
    })
    ro.observe(this.exportContainerNode)
  }

  codeUpdated(newCode) {
    this.handleLanguageChange(newCode, this.props)
    this.props.updateCode(newCode)
  }

  handleTitleBarChange(newTitle) {
    this.props.updateTitleBar(newTitle)
  }

  handleLanguageChange = debounce(
    (...args) => this.setState(handleLanguageChange(...args)),
    ms('300ms'),
    { trailing: true }
  )

  onBeforeChange(editor, meta, code) {
    return this.codeUpdated(code)
  }

  render() {
    const config = { ...DEFAULT_SETTINGS, ...this.props.config }
    const options = {
      lineNumbers: config.lineNumbers,
      mode: this.state.language || 'plaintext',
      theme: config.theme,
      scrollBarStyle: null,
      viewportMargin: Infinity,
      lineWrapping: true,
      extraKeys: {
        'Shift-Tab': 'indentLess'
      }
    }
    const backgroundImage =
      (this.props.config.backgroundImage && this.props.config.backgroundImageSelection) ||
      this.props.config.backgroundImage

    const content = (

        {config.windowControls ? (
          <WindowControls
            titleBar={this.props.titleBar}
            theme={config.windowTheme}
            handleTitleBarChange={this.handleTitleBarChange}
          />
        ) : null}
        <CodeMirror
          className={`CodeMirror__container window-theme__${config.windowTheme}`}
          onBeforeChange={this.onBeforeChange}
          value={this.props.children}
          options={options}
        />
        {config.watermark && <Watermark />}

    )

    return (

 (this.exportContainerNode = ele)}>
          {content}

    )
  }
}

export default Carbon
<commit_msg>Make carbon a stateless component, move highlight.js calc into render (#479)<commit_after>import React from 'react'
import * as hljs from 'highlight.js'
import ResizeObserver from 'resize-observer-polyfill'
import debounce from 'lodash.debounce'
import ms from 'ms'
import { Controlled as CodeMirror } from 'react-codemirror2'

import WindowControls from '../components/WindowControls'
import Watermark from '../components/svg/Watermark'
import { COLORS, LANGUAGE_MODE_HASH, LANGUAGE_NAME_HASH, DEFAULT_SETTINGS } from '../lib/constants'

class Carbon extends React.PureComponent {
  componentDidMount() {
    const ro = new ResizeObserver(entries => {
      const cr = entries[0].contentRect
      this.props.onAspectRatioChange(cr.width / cr.height)
    })
    ro.observe(this.exportContainerNode)
  }

  handleLanguageChange = debounce(
    (newCode, language) => {
      if (language === 'auto') {
        // try to set the language
        const detectedLanguage = hljs.highlightAuto(newCode).language
        const languageMode =
          LANGUAGE_MODE_HASH[detectedLanguage] || LANGUAGE_NAME_HASH[detectedLanguage]

        if (languageMode) {
          return languageMode.mime || languageMode.mode
        }
      }

      return language
    },
    ms('300ms'),
    {
      leading: true,
      trailing: true
    }
  )

  onBeforeChange = (editor, meta, code) => this.props.updateCode(code)

  render() {
    const config = { ...DEFAULT_SETTINGS, ...this.props.config }

    const languageMode = this.handleLanguageChange(this.props.children, config.language)

    const options = {
      lineNumbers: config.lineNumbers,
      mode: languageMode || 'plaintext',
      theme: config.theme,
      scrollBarStyle: null,
      viewportMargin: Infinity,
      lineWrapping: true,
      extraKeys: {
        'Shift-Tab': 'indentLess'
      }
    }
    const backgroundImage =
      (this.props.config.backgroundImage && this.props.config.backgroundImageSelection) ||
      this.props.config.backgroundImage

    const content = (

        {config.windowControls ? (
          <WindowControls
            titleBar={this.props.titleBar}
            theme={config.windowTheme}
            handleTitleBarChange={this.props.updateTitleBar}
          />
        ) : null}
        <CodeMirror
          className={`CodeMirror__container window-theme__${config.windowTheme}`}
          onBeforeChange={this.onBeforeChange}
          value={this.props.children}
          options={options}
        />
        {config.watermark && <Watermark />}

    )

    return (

 (this.exportContainerNode = ele)}>
          {content}

    )
  }
}

export default Carbon
<|endoftext|>


<commit_before>/* eslint-env node */

const autoprefixer = require('autoprefixer'),
      bluebird     = require('bluebird'),
      eslint       = require('gulp-eslint'),
      fractal      = require('@frctl/fractal').create(),
      fs           = require('fs-extra'),
      globby       = require('globby'),
      gulp         = require('gulp'),
      gulpif       = require('gulp-if'),
      hbsEngine    = fractal.components.engine(),
      logger       = fractal.cli.console,
      mandelbrot   = require('@frctl/mandelbrot'),
      notify       = require('gulp-notify'),
      plumber      = require('gulp-plumber'),
      postcss      = require('gulp-postcss'),
      reporter     = require('postcss-reporter'),
      runSequence  = require('run-sequence'),
      sass         = require('gulp-sass'),
      sassError    = require('gulp-sass-error'),
      sassLint     = require('gulp-sass-lint'),
      sourcemaps   = require('gulp-sourcemaps'),
      stylelint    = require('stylelint'),
      svgSprite    = require('gulp-svg-sprite'),
      util         = require('gulp-util');

// Turn off Bluebird unhandled promises warnings
bluebird.config({
  warnings: false
});

// Fractal configuration
fractal.set('project.title', 'Alpaca UI Components for Magento 2');
fractal.components.set('path', __dirname + '/components');
fractal.docs.set('path', __dirname + '/docs');
fractal.web.set('static.path', __dirname + '/public');
fractal.web.set('builder.dest', __dirname + '/dest');
fractal.web.theme(mandelbrot({ skin: 'black' }));

// Handlebars helpers
hbsEngine.handlebars.registerHelper('static', (file, data) => {
  return '/components/raw/' + data.data.root._self.baseHandle + '/' + file;
});

hbsEngine.handlebars.registerHelper('svg', icon => {
  return '/images/icons-sprite.svg#' + icon;
});

// Fractal gulp tasks
gulp.task('fractal:start', ['inheritance', 'svg-sprite', 'sass', 'watch'], () => {
  const server = fractal.web.server({
    sync: true,
    port: 4000
  });
  server.on('error', err => logger.error(err.message));

  return server.start().then(() => {
    logger.success(`Fractal server is now running at ${server.url}`);
  });
});

gulp.task('fractal:build', ['inheritance', 'svg-sprite', 'sass'], () => {
  const builder = fractal.web.builder();

  builder.on('progress', (completed, total) => {
    return logger.update(`Exported ${completed} of ${total} items`, 'info');
  });

  builder.on('error', err => logger.error(err.message));

  return builder.build().then(() => {
    logger.success('Fractal build completed!');
  });
});

// Gulp tasks
gulp.task('watch', () => {
  gulp.watch([
    fractal.components.get('path') + '/**/*.scss',
    fractal.docs.get('path') + '/styles/**/*.scss'
  ], () => {
    runSequence('sass-lint', 'sass', 'css-lint');
  });

  gulp.watch(fractal.components.get('path') + '/**/*.js', () => {
    runSequence('js-lint');
  });

  gulp.watch(fractal.components.get('path') + '/01-globals/icons/files/*.svg', () => {
    runSequence('svg-sprite');
  });
});

gulp.task('sass', () => {
  return gulp.src(fractal.docs.get('path') + '/styles/**/*.scss')
    .pipe(
      gulpif(!util.env.ci,
        plumber({
          errorHandler: notify.onError('Error: <%= error.message %>')
        })
      )
    )
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sassError.gulpSassError(util.env.ci || false)))
    .pipe(sass())
    .pipe(postcss([autoprefixer()]))
    .pipe(sourcemaps.write('cssmaps'))
    .pipe(gulp.dest(fractal.web.get('static.path') + '/css'));
});

gulp.task('sass-lint', () => {
  return gulp.src(fractal.components.get('path') + '/**/*.scss')
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(gulpif(util.env.ci, sassLint.failOnError()));
});

gulp.task('css-lint', () => {
  return gulp.src(fractal.web.get('static.path') + '/**/*.css')
    .pipe(postcss([
      stylelint(),
      reporter({ throwError: util.env.ci || false })
    ]));
});

gulp.task('js-lint', () => {
  return gulp.src(fractal.components.get('path') + '/**/*.js')
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(gulpif(util.env.ci, eslint.failAfterError()));
});

gulp.task('svg-sprite', () => {
  return gulp.src(fractal.components.get('path') + '/01-globals/icons/files/*.svg')
    .pipe(svgSprite({
      mode: {
        symbol: {
          dest: 'images',
          sprite: 'icons-sprite.svg'
        }
      }
    }))
    .pipe(gulp.dest(fractal.web.get('static.path')));
});

gulp.task('inheritance', () => {
  // Check if configuration file exist
  if (fs.existsSync('./modules.json')) {
    // Remove old build directory
    fs.removeSync('./build');

    // Find all local files
    globby
      .sync([
        fractal.components.get('path') + '/**',
        fractal.docs.get('path') + '/**',
        fractal.web.get('static.path') + '/**'
      ], { nodir: true })
      .forEach(file => {
        // Symlink all local files to build dir
        fs.ensureSymlinkSync(
          file,
          file.replace(__dirname, __dirname + '/build')
        );
      });

    // Read modules configuration file
    const modules = require('./modules.json');

    // Go through array of module paths
    modules.forEach(path => {
      // Find all module files
      path = path.replace(__dirname, '');
      globby
        .sync([
          path + fractal.components.get('path').replace(__dirname, '') + '/**',
          path + fractal.docs.get('path').replace(__dirname, '') + '/**',
          path + fractal.web.get('static.path').replace(__dirname, '') + '/**'
        ], { nodir: true })
        .forEach(file => {
          const srcPath = __dirname + '/' + file,
                destPath = srcPath.replace(path, 'build');

          // Symlink all module files to build dir
          fs.ensureSymlinkSync(srcPath, destPath);
        });
    });

    // Set new paths for Fractal and methods depending on this params
    fractal.components.set('path', __dirname + '/build/components');
    fractal.docs.set('path', __dirname + '/build/docs');
    fractal.web.set('static.path', __dirname + '/build/public');
    fractal.web.set('builder.dest', __dirname + '/build/dest');
  }
});
<commit_msg>Better tools setup for CI/CD env<commit_after>/* eslint-env node */

const autoprefixer = require('autoprefixer'),
      bluebird     = require('bluebird'),
      eslint       = require('gulp-eslint'),
      fractal      = require('@frctl/fractal').create(),
      fs           = require('fs-extra'),
      globby       = require('globby'),
      gulp         = require('gulp'),
      gulpif       = require('gulp-if'),
      hbsEngine    = fractal.components.engine(),
      logger       = fractal.cli.console,
      mandelbrot   = require('@frctl/mandelbrot'),
      notify       = require('gulp-notify'),
      plumber      = require('gulp-plumber'),
      postcss      = require('gulp-postcss'),
      reporter     = require('postcss-reporter'),
      runSequence  = require('run-sequence'),
      sass         = require('gulp-sass'),
      sassError    = require('gulp-sass-error'),
      sassLint     = require('gulp-sass-lint'),
      sourcemaps   = require('gulp-sourcemaps'),
      stylelint    = require('stylelint'),
      svgSprite    = require('gulp-svg-sprite'),
      util         = require('gulp-util');

// Turn off Bluebird unhandled promises warnings
bluebird.config({
  warnings: false
});

// Fractal configuration
fractal.set('project.title', 'Alpaca UI Components for Magento 2');
fractal.components.set('path', __dirname + '/components');
fractal.docs.set('path', __dirname + '/docs');
fractal.web.set('static.path', __dirname + '/public');
fractal.web.set('builder.dest', __dirname + '/dest');
fractal.web.theme(mandelbrot({ skin: 'black' }));

// Handlebars helpers
hbsEngine.handlebars.registerHelper('static', (file, data) => {
  return '/components/raw/' + data.data.root._self.baseHandle + '/' + file;
});

hbsEngine.handlebars.registerHelper('svg', icon => {
  return '/images/icons-sprite.svg#' + icon;
});

// Fractal gulp tasks
gulp.task('fractal:start', ['inheritance', 'svg-sprite', 'sass', 'watch'], () => {
  const server = fractal.web.server({
    sync: true,
    port: 4000
  });
  server.on('error', err => logger.error(err.message));

  return server.start().then(() => {
    logger.success(`Fractal server is now running at ${server.url}`);
  });
});

gulp.task('fractal:build', ['inheritance', 'svg-sprite', 'sass'], () => {
  const builder = fractal.web.builder();

  builder.on('progress', (completed, total) => {
    return logger.update(`Exported ${completed} of ${total} items`, 'info');
  });

  builder.on('error', err => logger.error(err.message));

  return builder.build().then(() => {
    logger.success('Fractal build completed!');
  });
});

// Gulp tasks
gulp.task('watch', () => {
  gulp.watch([
    fractal.components.get('path') + '/**/*.scss',
    fractal.docs.get('path') + '/styles/**/*.scss'
  ], () => {
    runSequence('sass-lint', 'sass', 'css-lint');
  });

  gulp.watch(fractal.components.get('path') + '/**/*.js', () => {
    runSequence('js-lint');
  });

  gulp.watch(fractal.components.get('path') + '/01-globals/icons/files/*.svg', () => {
    runSequence('svg-sprite');
  });
});

gulp.task('sass', () => {
  if (util.env.ci) {
    runSequence('paths');
  }

  return gulp.src(fractal.docs.get('path') + '/styles/**/*.scss')
    .pipe(
      gulpif(!util.env.ci,
        plumber({
          errorHandler: notify.onError('Error: <%= error.message %>')
        })
      )
    )
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sassError.gulpSassError(util.env.ci || false)))
    .pipe(sass())
    .pipe(postcss([autoprefixer()]))
    .pipe(sourcemaps.write('cssmaps'))
    .pipe(gulp.dest(fractal.web.get('static.path') + '/css'));
});

gulp.task('sass-lint', () => {
  if (util.env.ci) {
    runSequence('paths');
  }

  return gulp.src(fractal.components.get('path') + '/**/*.scss')
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(gulpif(util.env.ci, sassLint.failOnError()));
});

gulp.task('css-lint', () => {
  if (util.env.ci) {
    runSequence('paths');
  }

  return gulp.src(fractal.web.get('static.path') + '/**/*.css')
    .pipe(postcss([
      stylelint(),
      reporter({ throwError: util.env.ci || false })
    ]));
});

gulp.task('js-lint', () => {
  if (util.env.ci) {
    runSequence('paths');
  }

  return gulp.src(fractal.components.get('path') + '/**/*.js')
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(gulpif(util.env.ci, eslint.failAfterError()));
});

gulp.task('svg-sprite', () => {
  return gulp.src(fractal.components.get('path') + '/01-globals/icons/files/*.svg')
    .pipe(svgSprite({
      mode: {
        symbol: {
          dest: 'images',
          sprite: 'icons-sprite.svg'
        }
      }
    }))
    .pipe(gulp.dest(fractal.web.get('static.path')));
});

gulp.task('inheritance', () => {
  // Check if configuration file exist
  if (fs.existsSync('./modules.json')) {
    // Remove old build directory
    fs.removeSync('./build');

    // Find all local files
    globby
      .sync([
        fractal.components.get('path') + '/**',
        fractal.docs.get('path') + '/**',
        fractal.web.get('static.path') + '/**'
      ], { nodir: true })
      .forEach(file => {
        // Symlink all local files to build dir
        fs.ensureSymlinkSync(
          file,
          file.replace(__dirname, __dirname + '/build')
        );
      });

    // Read modules configuration file
    const modules = require('./modules.json');

    // Go through array of module paths
    modules.forEach(path => {
      // Find all module files
      path = path.replace(__dirname, '');
      globby
        .sync([
          path + fractal.components.get('path').replace(__dirname, '') + '/**',
          path + fractal.docs.get('path').replace(__dirname, '') + '/**',
          path + fractal.web.get('static.path').replace(__dirname, '') + '/**'
        ], { nodir: true })
        .forEach(file => {
          const srcPath = __dirname + '/' + file,
                destPath = srcPath.replace(path, 'build');

          // Symlink all module files to build dir
          fs.ensureSymlinkSync(srcPath, destPath);
        });
    });
  }
  runSequence('paths');
});

gulp.task('paths', () => {
  if (fs.existsSync('./modules.json')) {
    // Set new paths for Fractal
    fractal.components.set('path', __dirname + '/build/components');
    fractal.docs.set('path', __dirname + '/build/docs');
    fractal.web.set('static.path', __dirname + '/build/public');
  }
});
<|endoftext|>


<commit_before>(function () {
  'use strict';

  function ready () {
    $.removeNodes('iframe');

    var node = $.$('#continuetoimage > form input');
    if (node) {
      // first pass
      setTimeout(function () {
        node.click();
      }, 1000);
      return;
    }

    // second pass
    var i = $('img[class^=centred]');
    $.openImage(i.src);
  }

  $.register({
    rule: [
      {
        host: [
          // com
          // starts with image
          /^image(ontime|corn|picsa)\.com$/,
          // ends with image
          /^(zonezeed|zelje|croft|myhot|bok|hostur|greasy)image\.com$/,
          // starts with img
          /^img(next|savvy|\.spicyzilla|twyti|xyz|devil|tzar|ban|pu|beer|wet|tornado|kicks|-pay|nimz)\.com$/,
          // starts with img-
          /^img-(zone|planet)\.com$/,
          // starts with www
          /^www\.(imagefolks|img(blow|lemon))\.com$/,
          // else
          /^(picstwist|ericsony|wpc8|uplimg|xxx\.pornprimehd|lexiit|thumbnailus|nimplus|newimagepost|xxximagenow)\.com$/,
          /^((i|hentai)\.)?imgslip\.com$/,
          /^(i|xxx)\.hentaiyoutube\.com$/,
          /^(go|er)imge\.com$/,
          /^(like\.)?08lkk\.com$/,
          /^(www\.)?\.imgult\.com$/,
          /^nudeximg\.com$/,
          /imgseeds\.com$/,
          /damimage\.com$/,
          /imagedecode\.com$/,
          // net
          /^img(serve|coin|fap|candy|master|-view|run|boom)\.net$/,
          /^(gallerycloud|imagelaser|project-photo|pix-link|funimg|golfpit)\.net$/,
          // org
          /^shotimg\.org$/,
          /^img(studio|spot)\.org$/,
          /^image(\.adlock|on|team)\.org$/,
          /^(drag|teen|mega)image\.org$/,
          /^teenshot\.org$/,
          // else
          /^(hotimages|55888)\.eu$/,
          /^imgcloud\.co$/,
          /^pixup\.us$/,
          /^bulkimg\.info$/,
          /^img\.yt$/,
          /^vava\.in$/,
          /^(pixxx|picspornfree|imgload)\.me$/,
          /^(porno-pirat|24avarii)\.ru$/,
          /^hotimage\.uk$/,
          /^imgease\.re$/,
          /^goimg\.xyz$/,
        ],
        path: /^\/img-.*\.html$/,
      },
      {
        host: [
          /^img(run|twyti)\.net$/,
          /^imgtwyti\.com$/,
        ],
        path: /^\/t\/img-.*\.html$/,
      },
      {
        host: /^imgking\.co$/,
        path: /^\/img-.*\.htmls?$/,
      },
      {
        host: /^imgbb\.net$/,
        path: /^\/.-.+$/,
      },
    ],
    ready: ready,
  });

  // TODO need to refactor the cookie rule
  $.register({
    rule: {
      host: [
        /^www\.img(taxi|adult)\.com$/,
        /^www\.imgdrive\.net$/,
      ],
      path: /^\/img-.*\.html$/,
    },
    start: function () {
      var c = $.getCookie('img_c_d') || $.getCookie('img_p_d');
      if (c) {
        return;
      }
      $.post(window.location.href.toString(), {
        cti: 1,
        ref: '',
        rc: 1,
      }).then(function (data) {
        window.location.reload();
      });
    },
    ready: function () {
      $.removeNodes('iframe');

      var node = $.$('#continuetoimage > form input');
      if (node) {
        // first pass
        node.click();
        // somehow imgrun.net need to click twice
        node.click();
        return;
      }

      // the cookies are shared in the whole domain
      // we have to reset cookies to prevent wrong state
      $.resetCookies();

      // second pass
      var i = $('img[class^=centred]');
      $.openImage(i.src);
    },
  });

  function helper () {
    // crack the shitty qqc.co visitScript 5440
    $.window.setTimeout = _.nop;

    // this site checks cookie that caculate from session
    // do an AJAX to skip checking
    return $.get(window.location.toString()).then(function (data) {
      return $.toDOM(data);
    });
  }

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/Photo\/img-.+\.html$/,
    },
    start: function () {
      helper().then(function (page) {
        var i = $('img[class^=centred]', page);
        $.openImage(i.src);
      });
    },
  });

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/\d+\/img-.*\.html$/,
    },
    start: function () {
      helper().then(function (page) {
        var bbcode = $.$('#imagecodes input', page);
        bbcode = bbcode.value.match(/.+\[IMG\]([^\[]+)\[\/IMG\].+/);
        bbcode = bbcode[1];
        bbcode = bbcode.replace('small', 'big');

        $.openImage(bbcode);
      });
    },
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>loftlm.ru<commit_after>(function () {
  'use strict';

  function ready () {
    $.removeNodes('iframe');

    var node = $.$('#continuetoimage > form input');
    if (node) {
      // first pass
      setTimeout(function () {
        node.click();
      }, 1000);
      return;
    }

    // second pass
    var i = $('img[class^=centred]');
    $.openImage(i.src);
  }

  $.register({
    rule: [
      {
        host: [
          // com
          // starts with image
          /^image(ontime|corn|picsa)\.com$/,
          // ends with image
          /^(zonezeed|zelje|croft|myhot|bok|hostur|greasy)image\.com$/,
          // starts with img
          /^img(next|savvy|\.spicyzilla|twyti|xyz|devil|tzar|ban|pu|beer|wet|tornado|kicks|-pay|nimz)\.com$/,
          // starts with img-
          /^img-(zone|planet)\.com$/,
          // starts with www
          /^www\.(imagefolks|img(blow|lemon))\.com$/,
          // else
          /^(picstwist|ericsony|wpc8|uplimg|xxx\.pornprimehd|lexiit|thumbnailus|nimplus|newimagepost|xxximagenow)\.com$/,
          /^((i|hentai)\.)?imgslip\.com$/,
          /^(i|xxx)\.hentaiyoutube\.com$/,
          /^(go|er)imge\.com$/,
          /^(like\.)?08lkk\.com$/,
          /^(www\.)?\.imgult\.com$/,
          /^nudeximg\.com$/,
          /imgseeds\.com$/,
          /damimage\.com$/,
          /imagedecode\.com$/,
          // net
          /^img(serve|coin|fap|candy|master|-view|run|boom)\.net$/,
          /^(gallerycloud|imagelaser|project-photo|pix-link|funimg|golfpit)\.net$/,
          // org
          /^shotimg\.org$/,
          /^img(studio|spot)\.org$/,
          /^image(\.adlock|on|team)\.org$/,
          /^(drag|teen|mega)image\.org$/,
          /^teenshot\.org$/,
          // else
          /^(hotimages|55888)\.eu$/,
          /^imgcloud\.co$/,
          /^pixup\.us$/,
          /^bulkimg\.info$/,
          /^img\.yt$/,
          /^vava\.in$/,
          /^(pixxx|picspornfree|imgload)\.me$/,
          /^(porno-pirat|24avarii|loftlm)\.ru$/,
          /^hotimage\.uk$/,
          /^imgease\.re$/,
          /^goimg\.xyz$/,
        ],
        path: /^\/img-.*\.html$/,
      },
      {
        host: [
          /^img(run|twyti)\.net$/,
          /^imgtwyti\.com$/,
        ],
        path: /^\/t\/img-.*\.html$/,
      },
      {
        host: /^imgking\.co$/,
        path: /^\/img-.*\.htmls?$/,
      },
      {
        host: /^imgbb\.net$/,
        path: /^\/.-.+$/,
      },
    ],
    ready: ready,
  });

  // TODO need to refactor the cookie rule
  $.register({
    rule: {
      host: [
        /^www\.img(taxi|adult)\.com$/,
        /^www\.imgdrive\.net$/,
      ],
      path: /^\/img-.*\.html$/,
    },
    start: function () {
      var c = $.getCookie('img_c_d') || $.getCookie('img_p_d');
      if (c) {
        return;
      }
      $.post(window.location.href.toString(), {
        cti: 1,
        ref: '',
        rc: 1,
      }).then(function (data) {
        window.location.reload();
      });
    },
    ready: function () {
      $.removeNodes('iframe');

      var node = $.$('#continuetoimage > form input');
      if (node) {
        // first pass
        node.click();
        // somehow imgrun.net need to click twice
        node.click();
        return;
      }

      // the cookies are shared in the whole domain
      // we have to reset cookies to prevent wrong state
      $.resetCookies();

      // second pass
      var i = $('img[class^=centred]');
      $.openImage(i.src);
    },
  });

  function helper () {
    // crack the shitty qqc.co visitScript 5440
    $.window.setTimeout = _.nop;

    // this site checks cookie that caculate from session
    // do an AJAX to skip checking
    return $.get(window.location.toString()).then(function (data) {
      return $.toDOM(data);
    });
  }

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/Photo\/img-.+\.html$/,
    },
    start: function () {
      helper().then(function (page) {
        var i = $('img[class^=centred]', page);
        $.openImage(i.src);
      });
    },
  });

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/\d+\/img-.*\.html$/,
    },
    start: function () {
      helper().then(function (page) {
        var bbcode = $.$('#imagecodes input', page);
        bbcode = bbcode.value.match(/.+\[IMG\]([^\[]+)\[\/IMG\].+/);
        bbcode = bbcode[1];
        bbcode = bbcode.replace('small', 'big');

        $.openImage(bbcode);
      });
    },
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>