Best JavaScript code snippet using playwright-internal
options.globalsettings.js
Source:options.globalsettings.js  
1//var foxyProxy = chrome.extension.getBackgroundPage().foxyProxy;23var foxyProxy;4var settings;5var lastTabName;67// listen for settings message from extension8chrome.runtime.onMessage.addListener(function( request, sender, sendResponse) {9    if (request.settings) {10        11        settings = request.settings;12        13        var tabName = lastTabName;14        // onTabShow15        if ('pageQuick' == tabName) {16            $("#enabledQA").setChecked(settings.enabledQA);17            $("#patternTemporaryQA").setChecked(settings.patternTemporaryQA);18            if(settings.enabledQA)19                $('#QASettingsContainer *').each(function(){ $(this).prop('disabled', false); });20            else21                $('#QASettingsContainer *').each(function(){  $(this).attr('disabled','disabled'); });22            $("#patternTemplateQA").val(settings.patternTemplateQA);23            $("#patternUrlQA").val("http://fred:secret@mail.foo.com:8080/inbox/msg102.htm#subject?style=elegant").change();24            $("#patternNameQA").val(settings.patternNameQA);25            $("#patternProxyQA *").remove();26            $.each(list, function(i, proxy){27                if(!proxy.data.readonly)28                {29                $("#patternProxyQA").append( $('<option value="'+i+'">'+proxy.data.name+'</option>'));30                }31            });3233            $("#patternProxyQA option[value='"+settings.patternProxyQA+"']").attr("selected", "selected");34            //$("#patternProxyQA").change();3536            $("input[name='patternWhitelistQA'][value='"+settings.patternWhitelistQA+"']").setChecked(true);37            $("input[name='patternTypeQA'][value='"+settings.patternTypeQA+"']").setChecked(true);38        }3940        if ('pageGlobal' == tabName) {41            if (foxyProxy.getFoxyProxyEdition && foxyProxy.getFoxyProxyEdition() != 'Basic') {42                $("input[name='advancedMenuCheck']").attr('checked', settings.useAdvancedMenus);43                $("input[name='showContextMenuCheck']").attr('checked', settings.showContextMenu);44            } else {45                $("input[name='advancedMenuCheck']").hide();46                $("input[name='showContextMenuCheck']").hide();47                $("label[for='advancedMenuCheck']").hide();48                $("label[for='showContextMenuCheck']").hide();49            }50            $("input[name='useChromeSyncCheck']").attr('checked', settings.useSyncStorage);51            $("input[name='animateIconCheck']").attr('checked', settings.animateIcon);52            $("input[name='showUpdatesCheck']").attr('checked', settings.showUpdates);53            $("input[name='usageOptOutCheck']").attr('checked', !settings.usageOptOut);54        }55    }56});5758chrome.runtime.getBackgroundPage(function( bgPage) {59    foxyProxy = bgPage.foxyProxy;60    61    foxyProxy.getSettings();62    63    if (foxyProxy.getFoxyProxyEdition() != 'Basic') {64        $("#tabQuick").show();65    }66});6768function saveSettings(){69    console.log("saveSettings");70    foxyProxy.updateSettings({ "settings": settings});71}727374function genPattern(url, strTemplate, caseSensitive) {75    76    var flags = caseSensitive ? "gi" : "g";77    var parsedUrl = parseUri(url);78    parsedUrl.hostport = parsedUrl.domain ? parsedUrl.domain + (parsedUrl.port ? ":"+parsedUrl.port: "") : "";79    parsedUrl.prePath = (parsedUrl.protocol?parsedUrl.protocol+"://":"")+ parsedUrl.authority;80    var ret = strTemplate.replace("${0}", parsedUrl.protocol?parsedUrl.protocol:"", flags);    81    ret = ret.replace("${1}", parsedUrl.user ? parsedUrl.user : "", flags);    82    ret = ret.replace("${2}", parsedUrl.password ? parsedUrl.password : "", flags); 83    ret = ret.replace("${3}", parsedUrl.userInfo ? parsedUrl.userInfo + "@" : "", flags); 84    ret = ret.replace("${4}", parsedUrl.domain ? parsedUrl.domain : "", flags); 85    ret = ret.replace("${5}", parsedUrl.port ? parsedUrl.port : "", flags); 86    ret = ret.replace("${6}", parsedUrl.hostport ? parsedUrl.hostport : "", flags); 87    ret = ret.replace("${7}", parsedUrl.prePath ? parsedUrl.prePath : "", flags);                 88    ret = ret.replace("${8}", parsedUrl.directory ? parsedUrl.directory : "", flags); 89    ret = ret.replace("${9}", parsedUrl.file ? parsedUrl.file : "", flags); 90    ret = ret.replace("${10}", parsedUrl.file ? parsedUrl.file : "", flags); 91    ret = ret.replace("${11}", parsedUrl.file ? parsedUrl.file : "", flags); 92    ret = ret.replace("${12}", parsedUrl.path ? parsedUrl.path : "", flags); 93    ret = ret.replace("${13}", parsedUrl.anchor ? parsedUrl.anchor : "", flags);      94    ret = ret.replace("${14}", parsedUrl.query?parsedUrl.query:"", flags);       95    ret = ret.replace("${15}", parsedUrl.source?parsedUrl.source:"", flags);9697    return ret;98}99100function onTabShow(tabName) {101    console.log("tagName is", tabName);102    103    lastTabName = tabName;104    105    if (tabName) {106        $("#" + tabName).show();107    }108    109    chrome.runtime.getBackgroundPage(function( bgPage) {110        foxyProxy = bgPage.foxyProxy;111112        foxyProxy.getSettings();113        foxyProxy.getProxyList();114    });115    116    chrome.runtime.sendMessage({ trackEvent: {117        "category": "Options",118        "action": "tabShow",119        "label": "tabName",120        "value": tabName121    }});122123}124125$(document).ready(function() {126    127    $(".tabPage").hide(); // hide all tabs until we get settings loaded.128    129    $("#enabledQA").click(function(){130        if(list.length<=1) {131            alert("You must have entered at least one proxy in order to use QuickAdd");132            return false;133        }134135        settings.enabledQA = $(this).is(":checked");136    137        saveSettings();138        139        if (settings.enabledQA)140            $('#QASettingsContainer *').each(function(){ $(this).prop('disabled', false); });141        else142            $('#QASettingsContainer *').each(function(){  $(this).attr('disabled','disabled'); });143    });144145    $("#patternTemporaryQA").click(function(){146        settings.patternTemporaryQA = $(this).is(":checked");147        saveSettings();148    });149    150    $("#patternTemplateQA").keyup(function(){151        settings.patternTemplateQA=$(this).val();152        saveSettings();153        $("#patternResultQA").val(genPattern($("#patternUrlQA").val(),settings.patternTemplateQA));154    });155156    157    $("#patternUrlQA").change(function(){158        $("#patternResultQA").val(genPattern($(this).val(),settings.patternTemplateQA));159    });160    161    $("#patternNameQA").change(function(){162        settings.patternNameQA=$(this).val();163        saveSettings();164    });165    166    $("input[name='patternWhitelistQA']").click(function(){167        settings.patternWhitelistQA = $(this).val();168        saveSettings();169    });170    171    $("input[name='patternTypeQA']").click(function(){172        settings.patternTypeQA = $(this).val();173        saveSettings();174    });175    176    $("#patternProxyQA, #dialogPatternProxyQA").change(function(){177        settings.patternProxyQA = $(this).val();178        saveSettings();179    });180181182    $("#proxyTypeDirect").click(function(){183        if($(this).is(":checked")) {184            $(".proxyTypeManualGroup *").attr('disabled','disabled');185            $(".proxyTypeAutoGroup *").attr('disabled','disabled');186            $("#proxyDNS").attr('disabled','disabled');187        }188    });189    $("#proxyTypeManual").click(function(){190        if($(this).is(":checked")) {191            $(".proxyTypeManualGroup *").prop('disabled', false);192            $(".proxyTypeAutoGroup *").attr('disabled','disabled');193            $("#proxyDNS").prop('disabled', false);194        }195    });196    $("#proxyTypeAuto").click(function(){197        if($(this).is(":checked")) {198            $(".proxyTypeManualGroup *").attr('disabled','disabled');199            $(".proxyTypeAutoGroup *").prop('disabled', false);200            $("#proxyDNS").prop('disabled', false);201        }202    });203    204    205    $(document.body).keydown(function (e) {206        var s, 207            tables,208            dialogs = $('.ui-dialog:visible');209            210        if(dialogs.size()>0)211        {212            tables = $('.dataTables_wrapper > table',dialogs).filter(':visible');213        }214        else215        {216            tables = $('.dataTables_wrapper > table').filter(':visible');217        }218    219        var activeTable = tables;220        if (e.keyCode == 38) {221            s = activeTable.find("tbody tr.selected_row");222            s.toggleClass("selected_row");223            if(s.length && !s.is(":first-child"))224                s.prev().toggleClass("selected_row").click();225            else226                activeTable.find("tbody tr:last").toggleClass("selected_row").click();227        }228        if (e.keyCode == 40) {229            s = activeTable.find("tbody tr.selected_row");230            s.toggleClass("selected_row");231            if(s.length && !s.is(":last-child"))232                s.next().toggleClass("selected_row").click();233            else234                activeTable.find("tbody tr:first").toggleClass("selected_row").click();235        }236    });237    238    $("#proxyModeGlobal").change(function () {239        var newState = $("option:selected",this).val();240        foxyProxy.state = newState;241    });242    243    $("input[name='advancedMenuCheck']").click(function() {244        foxyProxy.toggleAdvancedMenus();245    });246    247    $("input[name='showContextMenuCheck']").click(function() {248        foxyProxy.toggleShowContextMenu();249    });250    251    $("input[name='useChromeSyncCheck']").click(function() {252        foxyProxy.toggleSyncStorage();253    });254    255    256    $("input[name='animateIconCheck']").click(function() {257        foxyProxy.toggleAnimateIcon();258    });259    260    261    $("input[name='showUpdatesCheck']").click(function() {262        foxyProxy.toggleShowUpdates();263    });264    265    $("input[name='usageOptOutCheck']").click(function() {266        foxyProxy.toggleUsageOptOut();267    });268    269    $("#resetButton").click(function() {270        if (confirm("Are you sure you want to reload all settings?")) {271            foxyProxy.reloadSettings();272        }273    });274    275    $("#resetDefaultsButton").click(function() {276        if (confirm("This will reset all settings and remove any proxies that were added! Are you sure you want to reset?")) {277            foxyProxy.resetToDefaults();278        }279    });280    281    282    onTabShow('');283});284285function exportConfig()286{287    var settingsString = chrome.extension.getBackgroundPage().foxyProxy.settingsToXml();288    chrome.extension.getBackgroundPage().foxyProxy.saveToFile(settingsString);  289    290    // chrome.runtime.sendMessage({ trackEvent: {291    //     "category": "Options",292    //     "action": "export"293    // }});
...ParsedURL.js
Source:ParsedURL.js  
1/*2 * Copyright (C) 2012 Google Inc. All rights reserved.3 *4 * Redistribution and use in source and binary forms, with or without5 * modification, are permitted provided that the following conditions are6 * met:7 *8 * 1. Redistributions of source code must retain the above copyright9 * notice, this list of conditions and the following disclaimer.10 *11 * 2. Redistributions in binary form must reproduce the above12 * copyright notice, this list of conditions and the following disclaimer13 * in the documentation and/or other materials provided with the14 * distribution.15 *16 * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS CONTRIBUTORS17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC.20 * OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.27 */28/**29 * @constructor30 * @param {string} url31 */32WebInspector.ParsedURL = function(url)33{34    this.isValid = false;35    this.url = url;36    this.scheme = "";37    this.host = "";38    this.port = "";39    this.path = "";40    this.queryParams = "";41    this.fragment = "";42    this.folderPathComponents = "";43    this.lastPathComponent = "";44    // RegExp groups:45    // 1 - scheme (using the RFC3986 grammar)46    // 2 - hostname47    // 3 - ?port48    // 4 - ?path49    // 5 - ?fragment50    var match = url.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^\s\/:]*)(?::([\d]+))?(?:(\/[^#]*)(?:#(.*))?)?$/i);51    if (match) {52        this.isValid = true;53        this.scheme = match[1].toLowerCase();54        this.host = match[2];55        this.port = match[3];56        this.path = match[4] || "/";57        this.fragment = match[5];58    } else {59        if (this.url.startsWith("data:")) {60            this.scheme = "data";61            return;62        }63        if (this.url === "about:blank") {64            this.scheme = "about";65            return;66        }67        this.path = this.url;68    }69    // First cut the query params.70    var path = this.path;71    var indexOfQuery = path.indexOf("?");72    if (indexOfQuery !== -1) {73        this.queryParams = path.substring(indexOfQuery + 1);74        path = path.substring(0, indexOfQuery);75    }76    // Then take last path component.77    var lastSlashIndex = path.lastIndexOf("/");78    if (lastSlashIndex !== -1) {79        this.folderPathComponents = path.substring(0, lastSlashIndex);80        this.lastPathComponent = path.substring(lastSlashIndex + 1);81    } else82        this.lastPathComponent = path;83}84/**85 * @param {string} url86 * @return {string}87 */88WebInspector.ParsedURL._decodeIfPossible = function(url)89{90    var decodedURL = url;91    try {92        decodedURL = decodeURI(url);93    } catch (e) { }94    return decodedURL;95}96/**97 * @param {string} url98 * @return {!Array.<string>}99 */100WebInspector.ParsedURL.splitURLIntoPathComponents = function(url)101{102    var decodedURL = WebInspector.ParsedURL._decodeIfPossible(url);103    var parsedURL = new WebInspector.ParsedURL(decodedURL);104    var origin;105    var folderPath;106    var name;107    if (parsedURL.isValid) {108        origin = parsedURL.scheme + "://" + parsedURL.host;109        if (parsedURL.port)110            origin += ":" + parsedURL.port;111        folderPath = parsedURL.folderPathComponents;112        name = parsedURL.lastPathComponent;113        if (parsedURL.queryParams)114            name += "?" + parsedURL.queryParams;115    } else {116        origin = "";117        folderPath = "";118        name = url;119    }120    var result = [origin];121    var splittedPath = folderPath.split("/");122    for (var i = 1; i < splittedPath.length; ++i) {123        if (!splittedPath[i])124            continue;125        result.push(splittedPath[i]);126    }127    result.push(name);128    return result;129}130/**131 * @param {string} baseURL132 * @param {string} href133 * @return {?string}134 */135WebInspector.ParsedURL.completeURL = function(baseURL, href)136{137    if (href) {138        // Return special URLs as-is.139        var trimmedHref = href.trim();140        if (trimmedHref.startsWith("data:") || trimmedHref.startsWith("blob:") || trimmedHref.startsWith("javascript:"))141            return href;142        // Return absolute URLs as-is.143        var parsedHref = trimmedHref.asParsedURL();144        if (parsedHref && parsedHref.scheme)145            return trimmedHref;146    } else {147        return baseURL;148    }149    var parsedURL = baseURL.asParsedURL();150    if (parsedURL) {151        if (parsedURL.isDataURL())152            return href;153        var path = href;154        var query = path.indexOf("?");155        var postfix = "";156        if (query !== -1) {157            postfix = path.substring(query);158            path = path.substring(0, query);159        } else {160            var fragment = path.indexOf("#");161            if (fragment !== -1) {162                postfix = path.substring(fragment);163                path = path.substring(0, fragment);164            }165        }166        if (!path) {  // empty path, must be postfix167            var basePath = parsedURL.path;168            if (postfix.charAt(0) === "?") {169                // A href of "?foo=bar" implies "basePath?foo=bar".170                // With "basePath?a=b" and "?foo=bar" we should get "basePath?foo=bar".171                var baseQuery = parsedURL.path.indexOf("?");172                if (baseQuery !== -1)173                    basePath = basePath.substring(0, baseQuery);174            } // else it must be a fragment175            return parsedURL.scheme + "://" + parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "") + basePath + postfix;176        } else if (path.charAt(0) !== "/") {  // relative path177            var prefix = parsedURL.path;178            var prefixQuery = prefix.indexOf("?");179            if (prefixQuery !== -1)180                prefix = prefix.substring(0, prefixQuery);181            prefix = prefix.substring(0, prefix.lastIndexOf("/")) + "/";182            path = prefix + path;183        } else if (path.length > 1 && path.charAt(1) === "/") {184            // href starts with "//" which is a full URL with the protocol dropped (use the baseURL protocol).185            return parsedURL.scheme + ":" + path + postfix;186        }  // else absolute path187        return parsedURL.scheme + "://" + parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "") + normalizePath(path) + postfix;188    }189    return null;190}191WebInspector.ParsedURL.prototype = {192    get displayName()193    {194        if (this._displayName)195            return this._displayName;196        if (this.isDataURL())197            return this.dataURLDisplayName();198        if (this.isAboutBlank())199            return this.url;200        this._displayName = this.lastPathComponent;201        if (!this._displayName)202            this._displayName = (this.host || "") + "/";203        if (this._displayName === "/")204            this._displayName = this.url;205        return this._displayName;206    },207    /**208     * @return {string}209     */210    dataURLDisplayName: function()211    {212        if (this._dataURLDisplayName)213            return this._dataURLDisplayName;214        if (!this.isDataURL())215            return "";216        this._dataURLDisplayName = this.url.trimEnd(20);217        return this._dataURLDisplayName;218    },219    /**220     * @return {boolean}221     */222    isAboutBlank: function()223    {224        return this.url === "about:blank";225    },226    /**227     * @return {boolean}228     */229    isDataURL: function()230    {231        return this.scheme === "data";232    },233    /**234     * @return {string}235     */236    lastPathComponentWithFragment: function()237    {238       return this.lastPathComponent + (this.fragment ? "#" + this.fragment : "");239    }240}241/**242 * @param {string} string243 * @return {!{url: string, lineNumber: (number|undefined), columnNumber: (number|undefined)}}244 */245WebInspector.ParsedURL.splitLineAndColumn = function(string)246{247    var lineColumnRegEx = /(?::(\d+))?(?::(\d+))?$/;248    var lineColumnMatch = lineColumnRegEx.exec(string);249    var lineNumber;250    var columnNumber;251    console.assert(lineColumnMatch);252    if (typeof(lineColumnMatch[1]) === "string") {253        lineNumber = parseInt(lineColumnMatch[1], 10);254        // Immediately convert line and column to 0-based numbers.255        lineNumber = isNaN(lineNumber) ? undefined : lineNumber - 1;256    }257    if (typeof(lineColumnMatch[2]) === "string") {258        columnNumber = parseInt(lineColumnMatch[2], 10);259        columnNumber = isNaN(columnNumber) ? undefined : columnNumber - 1;260    }261    return {url: string.substring(0, string.length - lineColumnMatch[0].length), lineNumber: lineNumber, columnNumber: columnNumber};262}263/**264 * @return {?WebInspector.ParsedURL}265 */266String.prototype.asParsedURL = function()267{268    var parsedURL = new WebInspector.ParsedURL(this.toString());269    if (parsedURL.isValid)270        return parsedURL;271    return null;...lmsearchplacename.js
Source:lmsearchplacename.js  
1var conf = require('../conf/config');2var request = require('request');3var rp = require('request-promise');4var Bluebird = require('bluebird');5const url = require('url');6var getMunicipality = require('../lib/utils/municipality');7var objectIds;8var username;9var password;10// Token holder11let token;12let scope;13var proxyUrl = 'lmsearchplacename';14var configOptions;15var srid = '3006';16objectIds = [];17// Doesn't need the async for now18const lmSearchPlacename = async (req, res) => {19  if (conf[proxyUrl]) {20    configOptions = Object.assign({}, conf[proxyUrl]);21    // Get a token from LM22    await getTokenAsyncCall(configOptions.consumer_key, configOptions.consumer_secret, configOptions.scope);23    const parsedUrl = url.parse(decodeURI(req.url), true);24    var kommunkod = '';25    if ('kommunkod' in parsedUrl.query) {26      kommunkod = parsedUrl.query.kommunkod;27      var kommunkod = parsedUrl.query.kommunkod;28      var municipalityArray = kommunkod.split(',');29      if (municipalityArray.length > 0) {30        var lmuser = parsedUrl.query.lmuser;31        var q = parsedUrl.query.q;32        var page = parsedUrl.query.page;33        var start = parsedUrl.query.start;34        var limit = parsedUrl.query.limit;35        var lang = parsedUrl.query.lang;36        var nametype = parsedUrl.query.nametype;37        if ('srid' in parsedUrl.query) {38          srid = parsedUrl.query.srid;39        } else {40          srid = '3006';41        }42        if ('matchtype' in parsedUrl.query) {43          matchtype = parsedUrl.query.matchtype;44        } else {45          matchtype = 'contains';46        }47        var searchUrl = '/kriterier?';48        if ( q.length > 0 ) {49          searchUrl = searchUrl + 'namn=' + q + '&match=' + matchtype;50        }51        // Set language for result52        if ( lang ) {53          searchUrl = searchUrl + '&sprak=' + lang;54        }55        // Limit the hits to nametypes56        if ( nametype ) {57          searchUrl = searchUrl + '&namntyp=' + nametype;58        }59        // Get the result based on pages60        if ( limit ) {61          searchUrl = searchUrl + '&maxHits=' + limit;62        }63        searchUrl = searchUrl + '&srid=' + srid;64        doSearchAsyncCall(req, res, municipalityArray, searchUrl);65      } else {66        console.log('Skip');67        res.send({});68      }69    } else {70      console.log('Skip');71      res.send({});72    }73  }74}75// Export the module76module.exports = lmSearchPlacename;77function getTokenWait(options) {78  // Return promise to be invoked for authenticating on service requests79  return new Promise((resolve, reject) => {80      // Requesting the token service object81      request(options, (error, response, body) => {82          if (error) {83            console.log('Error token:' + error);84            reject('An error occured collecting token: ', error);85          } else {86            token = body.access_token;87            // console.log('Got token ' + token);88            resolve(body.access_token);89          }90      })91  })92}93async function getTokenAsyncCall(consumer_key, consumer_secret, scope) {94  // Request a token from Lantmateriet API95  const options = {96      url: configOptions.url_token,97      method: 'POST',98      headers: {99         'Authorization': 'Basic ' + Buffer.from(consumer_key + ':' + consumer_secret).toString('base64')100      },101      form: {102          'scope': scope,103          'grant_type': 'client_credentials'104      },105      json: true106  }107  var result = await getTokenWait(options);108  return result;109}110async function doSearchAsyncCall(req, res, municipalityArray, urlParams) {111  var returnValue = [];112  var promiseArray = [];113  // Split all the separate municipality given to individual searches114  municipalityArray.forEach(function(municipality) {115    var searchUrl = encodeURI(configOptions.url + urlParams + '&kommunkod=' + municipality)116    // Setup the search call and wait for result117    const options = {118        url: searchUrl,119        method: 'GET',120        headers: {121          'content-type': 'application/json',122          'Authorization': `Bearer ${token}`,123          'scope': `${scope}`124        }125    }126    promiseArray.push(127      rp(options)128      .then(function (result) {129        var parameters = JSON.parse(result);130        var newRes = [];131        newRes = concatResult(parameters.features, municipality);132        return newRes;133      })134      .catch(function (err) {135        console.log(err);136        console.log('ERROR doSearchAsyncCall!');137        res.send({});138      })139    )140  });141  await Promise.all(promiseArray)142    .then(function (resArr) {143        // Save the response to be handled in finally144        returnValue = resArr;145    })146    .catch(function (err) {147        // If fail return empty array148        res.send([]);149    })150    .finally(function () {151        // When all search has finished concat them to a single array of object Ids152        var newArray = [];153        returnValue.forEach(function(search) {154          newArray = newArray.concat(search);155        });156        res.send(newArray);157    });158}159function concatResult(placenames, municipality) {160  const result = [];161  // Check to see if there are multiple hits or a single162  if (Array.isArray(placenames)) {163    placenames.forEach((placename) => {164      result.push(getOrtnamn(placename, municipality));165    })166  } else {167    if (typeof placenames === 'undefined') {168      // placenames is undefined do nothing169    } else {170      result.push(getOrtnamn(placenames, municipality));171    }172  }173  return result;174}175function getOrtnamn(placename, municipality) {176  const id = placename.id;177  const namn = placename.properties.namn;178  let lanskod = '';179  let kommunkod = '';180  let kommunnamn = '';181  let coordinatesNE = [];182  // Check to see if feature has none or multiple coordinates183  if ('placering' in placename.properties) {184    // OBS! If there is a multipoint in the response it only uses the first coordinates185    const coordinates = placename.properties.placering[0].punkt.coordinates;186    coordinatesNE.push([coordinates[1], coordinates[0]]);187    lanskod = placename.properties.placering[0].lankod;188    kommunkod = placename.properties.placering[0].kommunkod;189    kommunnamn = placename.properties.placering[0].kommunnamn;190  }191  // If the kommunkod wasn't supplied in request get the municipality from the response192  if (municipality.countyCode === '00') {193    municipality = getMunicipality(lanskod.padStart(2, '0')+kommunkod.padStart(2, '0'));194  }195  // Build the object to return196  let object = {};197  if (coordinatesNE.length !== 0) {198    if (coordinatesNE.length === 1) {199      object['geometry'] = {200        coordinates: coordinatesNE[0],201        type: 'Point'202      };203    } else {204      object['geometry'] = {205        coordinates: coordinatesNE,206        type: 'MultiPoint'207      };208    }209  }210  object['properties'] = {211      id: id,212      name: namn,213      municipality: kommunnamn214  };215  object['type'] = 'Feature';216  return object;...getAdditionalEntries.js
Source:getAdditionalEntries.js  
1const querystring = require('querystring');2/**3 * @typedef {Object} AdditionalEntries4 * @property {string[]} prependEntries5 * @property {string[]} overlayEntries6 */7/**8 * Creates an object that contains two entry arrays: the prependEntries and overlayEntries9 * @param {Object} optionsContainer This is the container for the options to this function10 * @param {import('../types').NormalizedPluginOptions} optionsContainer.options Configuration options for this plugin.11 * @param {import('webpack').Compiler["options"]["devServer"]} [optionsContainer.devServer] The webpack devServer config12 * @returns {AdditionalEntries} An object that contains the Webpack entries for prepending and the overlay feature13 */14function getAdditionalEntries({ devServer, options }) {15  /** @type {Record<string, string | number>} */16  let resourceQuery = {};17  if (devServer) {18    const { client, https, http2, sockHost, sockPath, sockPort } = devServer;19    let { host, path, port } = devServer;20    let protocol = https || http2 ? 'https' : 'http';21    if (sockHost) host = sockHost;22    if (sockPath) path = sockPath;23    if (sockPort) port = sockPort;24    if (client && client.webSocketURL != null) {25      let parsedUrl = client.webSocketURL;26      if (typeof parsedUrl === 'string') parsedUrl = new URL(parsedUrl);27      let auth;28      if (parsedUrl.username) {29        auth = parsedUrl.username;30        if (parsedUrl.password) {31          auth += ':' + parsedUrl.password;32        }33      }34      if (parsedUrl.hostname != null) {35        host = [auth != null && auth, parsedUrl.hostname].filter(Boolean).join('@');36      }37      if (parsedUrl.pathname != null) {38        path = parsedUrl.pathname;39      }40      if (parsedUrl.port != null) {41        port = String(parsedUrl.port) !== '0' ? parsedUrl.port : undefined;42      }43      if (parsedUrl.protocol != null) {44        protocol = parsedUrl.protocol !== 'auto' ? parsedUrl.protocol.replace(':', '') : 'ws';45      }46    }47    if (host) resourceQuery.sockHost = host;48    if (path) resourceQuery.sockPath = path;49    if (port) resourceQuery.sockPort = port;50    resourceQuery.sockProtocol = protocol;51  }52  if (options.overlay) {53    const { sockHost, sockPath, sockPort, sockProtocol } = options.overlay;54    if (sockHost) resourceQuery.sockHost = sockHost;55    if (sockPath) resourceQuery.sockPath = sockPath;56    if (sockPort) resourceQuery.sockPort = sockPort;57    if (sockProtocol) resourceQuery.sockProtocol = sockProtocol;58  }59  // We don't need to URI encode the resourceQuery as it will be parsed by Webpack60  const queryString = querystring.stringify(resourceQuery, undefined, undefined, {61    /**62     * @param {string} string63     * @returns {string}64     */65    encodeURIComponent(string) {66      return string;67    },68  });69  const prependEntries = [70    // React-refresh runtime71    require.resolve('../../client/ReactRefreshEntry'),72  ];73  const overlayEntries = [74    // Error overlay runtime75    options.overlay &&76      options.overlay.entry &&77      `${require.resolve(options.overlay.entry)}${queryString ? `?${queryString}` : ''}`,78  ].filter(Boolean);79  return { prependEntries, overlayEntries };80}...redirect.js
Source:redirect.js  
1'use strict';2const url = require('url');3const formatters = {4    forceWww: function forceWww (req) {5        const parsedUrl = url.parse(req.url);6        const host = parsedUrl.host && !parsedUrl.host.match(/^www/);7        const pathname = parsedUrl.pathname && !parsedUrl.pathname.match(/^www/);8        if (parsedUrl && (host || pathname)) {9            if (pathname && !host) {10                parsedUrl.pathname = `//www.${parsedUrl.pathname}`;11            } else {12                parsedUrl.host = `www.${parsedUrl.host}`;13            }14            // generate new url with www15            const newUrl = url.format(parsedUrl);16            logger.info('Force www url %s', newUrl);17            return newUrl;18        }19        return false;20    },21    trailingSlash: function trailingSlash (req) {22        const parsedUrl = url.parse(req.url);23        // match everything except home page24        if (parsedUrl.pathname.match(/\/$/) && parsedUrl.pathname.length > 1) {25            // remove trailing slash26            parsedUrl.pathname = parsedUrl.pathname.slice(0, -1);27            // generate new url without trailing slash28            const newUrl = url.format(parsedUrl);29            logger.info('Force url without trailing slash %s', newUrl);30            return newUrl;31        }32        return false;33    },34    forceSecure: function forceSecure (req) {35        const header = req.headers['x-forwarded-proto'] || req.headers.host;36        if (header && header !== 'https') {37            const parsedUrl = url.parse(req.url);38            parsedUrl.protocol = 'https:';39            // generate new url with https protocol40            const newUrl = url.format(parsedUrl);41            logger.info('Force url with https protocol %s', newUrl);42            return newUrl;43        }44        return false;45    }46};47// Handle redirection for case when we want forceSecure, trailingSlash and forceWww48// @TODO - forceWww is not working49module.exports = (options) => {50    return (req, res, next) => {51        const oldUrl = req.url;52        Object.keys(options).forEach((key) => {53            if (formatters[key] && options[key] === true) {54                // call formatter55                const formattedUrl = formatters[key](req);56                if (formattedUrl) {57                    req.url = formattedUrl;58                }59            }60        });61        if (oldUrl === req.url) {62            next();63        } else {64            res.redirect(301, req.url);65        }66    };...url.js
Source:url.js  
1'use strict'2const querystring = require('querystring')3const url = require('url')4const dn = require('./dn')5const filter = require('./filters/')6module.exports = {7  parse: function (urlStr, parseDN) {8    let parsedURL9    try {10      parsedURL = new url.URL(urlStr)11    } catch (error) {12      throw new TypeError(urlStr + ' is an invalid LDAP url (scope)')13    }14    if (!parsedURL.protocol || !(parsedURL.protocol === 'ldap:' || parsedURL.protocol === 'ldaps:')) { throw new TypeError(urlStr + ' is an invalid LDAP url (protocol)') }15    const u = {16      protocol: parsedURL.protocol,17      hostname: parsedURL.hostname,18      port: parsedURL.port,19      pathname: parsedURL.pathname,20      search: parsedURL.search,21      href: parsedURL.href22    }23    u.secure = (u.protocol === 'ldaps:')24    if (!u.hostname) { u.hostname = 'localhost' }25    if (!u.port) {26      u.port = (u.secure ? 636 : 389)27    } else {28      u.port = parseInt(u.port, 10)29    }30    if (u.pathname) {31      u.pathname = querystring.unescape(u.pathname.substr(1))32      u.DN = parseDN ? dn.parse(u.pathname) : u.pathname33    }34    if (u.search) {35      u.attributes = []36      const tmp = u.search.substr(1).split('?')37      if (tmp && tmp.length) {38        if (tmp[0]) {39          tmp[0].split(',').forEach(function (a) {40            u.attributes.push(querystring.unescape(a.trim()))41          })42        }43      }44      if (tmp[1]) {45        if (tmp[1] !== 'base' && tmp[1] !== 'one' && tmp[1] !== 'sub') { throw new TypeError(urlStr + ' is an invalid LDAP url (scope)') }46        u.scope = tmp[1]47      }48      if (tmp[2]) {49        u.filter = querystring.unescape(tmp[2])50      }51      if (tmp[3]) {52        u.extensions = querystring.unescape(tmp[3])53      }54      if (!u.scope) { u.scope = 'base' }55      if (!u.filter) { u.filter = filter.parseString('(objectclass=*)') } else { u.filter = filter.parseString(u.filter) }56    }57    return u58  }...ProductRegistry.js
Source:ProductRegistry.js  
1// Copyright 2017 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4/**5 * @return {!Promise<!ProductRegistry.Registry>}6 */7ProductRegistry.instance = function() {8  var extension = self.runtime.extension(ProductRegistry.Registry);9  if (extension)10    return extension.instance();11  return Promise.resolve(self.singleton(ProductRegistry.RegistryStub));12};13/**14 * @interface15 */16ProductRegistry.Registry = function() {};17ProductRegistry.Registry.prototype = {18  /**19   * @param {!Common.ParsedURL} parsedUrl20   * @return {?string}21   */22  nameForUrl: function(parsedUrl) {},23  /**24   * @param {!Common.ParsedURL} parsedUrl25   * @return {?ProductRegistry.Registry.ProductEntry}26   */27  entryForUrl: function(parsedUrl) {},28  /**29   * @param {!Common.ParsedURL} parsedUrl30   * @return {?number}31   */32  typeForUrl: function(parsedUrl) {}33};34/**35 * @implements {ProductRegistry.Registry}36 */37ProductRegistry.RegistryStub = class {38  /**39   * @override40   * @param {!Common.ParsedURL} parsedUrl41   * @return {?string}42   */43  nameForUrl(parsedUrl) {44    return null;45  }46  /**47   * @override48   * @param {!Common.ParsedURL} parsedUrl49   * @return {?ProductRegistry.Registry.ProductEntry}50   */51  entryForUrl(parsedUrl) {52    return null;53  }54  /**55   * @override56   * @param {!Common.ParsedURL} parsedUrl57   * @return {?number}58   */59  typeForUrl(parsedUrl) {60    return null;61  }62};63/** @typedef {!{name: string, type: ?number}} */...url.helper.js
Source:url.helper.js  
1import parseUrl from 'url-parse';2export const addOrSetQueryStringParameter = (url, param, value) => {3  const parsedUrl = parseUrl(url, true);4  parsedUrl.query[param] = value;5  return parsedUrl.toString();6};7export const removeQueryStringParameter = (url, param) => {8  const parsedUrl = parseUrl(url, true);9  parsedUrl.query[param] = undefined;10  return parsedUrl.toString();11};12export const setUrlPath = (url, path) => {13  const parsedUrl = parseUrl(url, true);14  parsedUrl.set('pathname', path);15  return parsedUrl.toString();16};17export const filterUrlParams = (url, params) => {18  const parsedUrl = parseUrl(url, true);19  const query = {};20  Object.keys(parsedUrl.query).map(k => {21    if (!params.find(e => e == k)) query[k] = parsedUrl.query[k];22  });23  parsedUrl.query = query;24  return parsedUrl.toString();25};26export const removeParameters = url => {27  const parsedUrl = parseUrl(url, true);28  parsedUrl.query = {};29  return parsedUrl.toString();30};31export const getCurrentQueryStringParameter = param => {32  const parsedUrl = parseUrl(window.location.href, true);33  return parsedUrl.query[param];34};35export const getPath = url => {36  const parsedUrl = parseUrl(url, true);37  return (38    parsedUrl.pathname +39    (parsedUrl.toString().indexOf('?') > 040      ? `?${parsedUrl.toString().split('?')[1]}`41      : '')42  );...Using AI Code Generation
1const { parseURL } = require('playwright-core/lib/utils/utils');2console.log(parsedURL);3const { parseURL } = require('playwright-core/lib/utils/utils');4console.log(parsedURL);5const { parseURL } = require('playwright-core/lib/utils/utils');6console.log(parsedURL);7const { parseURL } = require('playwright-core/lib/utils/utils');8console.log(parsedURL);9const { parseURL } = require('playwright-core/lib/utils/utils');10console.log(parsedURL);11const { parseURL } = require('playwright-core/lib/utils/utils');12console.log(parsedURL);13const { parseURL } = require('playwright-core/lib/utils/utils');14console.log(parsedURL);15const { parseURL } = require('playwright-core/lib/utils/utils');16console.log(parsedURL);17const { parseURL } = require('playwright-core/lib/utils/utils');18console.log(parsedURL);19const { parseURL } = require('playwright-core/lib/utils/utils');20console.log(parsedURL);21const { parseURL } = require('playwright-core/lib/utils/utils');22console.log(parsedURL);Using AI Code Generation
1const { parseURL } = require('playwright/lib/utils/utils');2console.log(parsedURL);3const { parseURL } = require('playwright/lib/utils/utils');4console.log(parsedURL);5const { parseURL } = require('playwright/lib/utils/utils');6console.log(parsedURL);7const { parseURL } = require('playwright/lib/utils/utils');8console.log(parsedURL);9const { parseURL } = require('playwright/lib/utils/utils');10console.log(parsedURL);11const { parseURL } = require('playwright/lib/utils/utils');12console.log(parsedURL);13const { parseURL } = require('playwright/lib/utils/utils');14console.log(parsedURL);15const { parseURL } = require('playwright/lib/utils/utils');16console.log(parsedURL);17const { parseURL } = require('playwright/lib/utils/utils');18console.log(parsedURL);19const { parseURL } = require('playwright/lib/utils/utils');20console.log(parsedURL);Using AI Code Generation
1const { parsedURL } = require('playwright-core/lib/utils/utils');2const parsed = parsedURL(url);3console.log(parsed);4  hash: '' }5const { URL } = require('url');6const parsed = new URL(url);7console.log(parsed);8URL {9  searchParams: URLSearchParams {},10  hash: '' }11const { URLSearchParams } = require('url');12const parsed = new URLSearchParams(url);13console.log(parsed);14URLSearchParams { 'version' => 'v1.10.0Using AI Code Generation
1const {URL} = require('url');2console.log(parsedURL.hostname);3const {URL} = require('url');4console.log(parsedURL.hostname);5const {URL} = require('url');6console.log(parsedURL.hostname);7const {URL} = require('url');8console.log(parsedURL.hostname);9const {URL} = require('url');10console.log(parsedURL.hostname);11const {URL} = require('url');12console.log(parsedURL.hostname);13const {URL} = require('url');14console.log(parsedURL.hostname);15const {URL} = require('url');16console.log(parsedURL.hostname);17const {URL} = require('url');18console.log(parsedURL.hostname);19const {URL} = require('url');20console.log(parsedURL.hostname);21const {URL} = require('url');22console.log(parsedURL.hostname);23const {URL} = require('url');24console.log(parsedURL.hostname);25const {URL} =Using AI Code Generation
1const { parseURL } = require("playwright/lib/utils/utils");2console.log(parsedURL);3const { parseURL } = require("playwright/lib/utils/utils");4console.log(parsedURL);5const { parseURL } = require("playwright/lib/utils/utils");6console.log(parsedURL);7const { parseURL } = require("playwright/lib/utils/utils");8console.log(parsedURL);9const { parseURL } = require("playwright/lib/utils/utils");10console.log(parsedURL);11const { parseURL } = require("playwright/lib/utils/utils");12console.log(parsedURL);13const { parseURL } = require("playwright/lib/utils/utils");14console.log(parsedURL);15const { parseURL } = require("playwright/lib/utils/utils");16console.log(parsedURL);17const { parseURL } = require("playwright/lib/utils/utils");18console.log(parsedURL);19const { parseURL } = require("playwright/lib/utils/utils");20console.log(parsedURL);21const { parseURL } = requireLambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
