How to use rq method in wpt

Best JavaScript code snippet using wpt

shared.js

Source:shared.js Github

copy

Full Screen

1window.RQ = window.RQ || {};2window.RQ.configs = {3 "version": "20.3.16",4 "browser": "chrome",5 "storageType": "sync",6 "contextMenuContexts": [7 "browser_action"8 ],9 "env": "prod",10 "WEB_URL": "https://app.requestly.io",11 "firebaseConfig": {12 "apiKey": "AIzaSyC2WOxTtgKH554wCezEJ4plxnMNXaUSFXY",13 "authDomain": "app.requestly.io",14 "databaseURL": "https://requestly.firebaseio.com",15 "projectId": "project-7820168409702389920",16 "storageBucket": "project-7820168409702389920.appspot.com",17 "messagingSenderId": "911299702852"18 },19 "logLevel": "info"20};21window.RQ = window.RQ || {};22RQ.VERSION = 3;23RQ.FILE_PICKER_URL = "/library/filepicker";24RQ.VERSIONS = {25 REPLACE_RULE: 226};27RQ.PUBLIC_NAMESPACE = '__REQUESTLY__';28// Url which gets opened when User clicks on browserAction (requestly icon) in toolbar29RQ.RULES_PAGE_URL = RQ.configs.WEB_URL + "/rules/";30RQ.RULES_PAGE_URL_PATTERN = RQ.RULES_PAGE_URL + "*";31RQ.PRICING_PAGE_URL = RQ.configs.WEB_URL + "/pricing/";32RQ.GOODBYE_PAGE_URL = RQ.configs.WEB_URL + "/goodbye/";33RQ.BLACK_LIST_DOMAINS = ["requestly.in", "requestly.io"];34RQ.STRING_CONSTANTS = {35 SLASH: "/"36};37RQ.LIMITS = {38 NUMBER_SHARED_LISTS: 1039};40RQ.DEFAULTS = {41 APP_INIT_TIMEOUT: 500042};43RQ.OBJECT_TYPES = {44 GROUP: "group",45 RULE: "rule"46};47RQ.RULE_TYPES = {48 REDIRECT: "Redirect",49 CANCEL: "Cancel",50 REPLACE: "Replace",51 HEADERS: "Headers",52 USERAGENT: "UserAgent",53 SCRIPT: "Script",54 QUERYPARAM: "QueryParam",55 RESPONSE: "Response"56};57RQ.HEADER_NAMES = {58 USER_AGENT: "User-Agent"59};60RQ.RULE_STATUS = {61 ACTIVE: "Active",62 INACTIVE: "Inactive"63};64RQ.RULE_KEYS = {65 URL: "Url",66 HOST: "host",67 PATH: "path",68 HEADER: "Header",69 OVERWRITE: "Overwrite",70 IGNORE: "Ignore",71 PARAM: "param",72 VALUE: "value"73};74RQ.URL_COMPONENTS = {75 PROTOCOL: "Protocol",76 URL: "Url",77 HOST: "host",78 PATH: "path",79 QUERY: "query",80 HASH: "hash"81};82RQ.RULE_OPERATORS = {83 EQUALS: "Equals",84 CONTAINS: "Contains",85 MATCHES: "Matches",86 WILDCARD_MATCHES: "Wildcard_Matches"87};88RQ.RULE_SOURCE_FILTER_TYPES = {89 PAGE_URL: "pageUrl",90 RESOURCE_TYPE: "resourceType",91 REQUEST_METHOD: "requestMethod"92};93RQ.MODIFICATION_TYPES = {94 ADD: "Add",95 REMOVE: "Remove",96 REMOVE_ALL: "Remove All",97 MODIFY: "Modify",98 REPLACE: "Replace"99};100RQ.NEED_HELP_QUERY_TYPES = {101 FEEDBACK: "Feedback",102 BUG: "Bug",103 QUESTION: "Question",104 FEATURE_REQUEST: "FeatureRequest"105};106RQ.CLIENT_MESSAGES = {107 GET_SCRIPT_RULES: "getScriptRules",108 GET_USER_AGENT_RULE_PAIRS: "getUserAgentRulePairs",109 OVERRIDE_RESPONSE: "overrideResponse",110 NOTIFY_RULES_APPLIED: "notifyRulesApplied"111};112RQ.EXTENSION_MESSAGES = {113 FOCUS_TAB: "focusTab",114 GET_FULL_LOGS: "getFullLogs",115 CLEAR_LOGS_FOR_TAB: "clearLogsForTab",116 CLEAR_LOGS_FOR_DOMAIN: "clearLogsForDomain",117 GET_FAVOURITE_RULES: "getFavouriteRules",118 REMOTE_RULES_SETTINGS_CHANGED: 'remoteRulesSettingsChanged',119 GET_FLAGS: "getFlags"120};121RQ.HEADERS_TARGET = {122 REQUEST: "Request",123 RESPONSE: "Response"124};125RQ.REQUEST_TYPES = {126 MAIN_FRAME: "mainFrame",127 PAGE_REQUEST: "pageRequest"128};129RQ.SCRIPT_TYPES = {130 URL: "url",131 CODE: "code"132};133RQ.SCRIPT_CODE_TYPES = {134 JS: "js",135 CSS: "css"136};137RQ.SCRIPT_LOAD_TIME = {138 BEFORE_PAGE_LOAD: "beforePageLoad",139 AFTER_PAGE_LOAD: "afterPageLoad"140};141RQ.SCRIPT_LIBRARIES = {142 JQUERY: { name: "jQuery", src: "https://code.jquery.com/jquery-2.2.4.js" },143 UNDERSCORE: {144 name: "Underscore",145 src:146 "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"147 }148};149RQ.RESPONSE_CODES = {150 NOT_FOUND: 404151};152RQ.STORAGE_KEYS = {153 REQUESTLY_SETTINGS: "rq_settings",154 USER_INFO: "user_info",155 LATEST_NOTIFICATION_READ_BY_USER: "latestNotificationReadId"156};157RQ.MESSAGES = {158 DELETE_ITEMS_NO_SELECTION_WARNING:159 "Please select one or more rules to delete.",160 DELETE_ITEMS: "Are you sure you want to delete the selected items?",161 DELETE_GROUP_WITH_RULES_WARNING:162 "There are some rules contained in this group. Please delete or ungroup them before deleting the group.",163 DELETE_GROUP: "Are you sure you want to delete the group?",164 UNGROUP_ITEMS_NO_SELECTION_WARNING:165 "Please select one or more rules to ungroup.",166 UNGROUP_ITEMS: "Are you sure you want to ungroup the selected items?",167 SIGN_IN_TO_VIEW_SHARED_LISTS:168 "Please login to view your Shared Lists.",169 SIGN_IN_TO_CREATE_SHARED_LISTS:170 "Please login to share the selected rules",171 SIGN_IN_TO_SUBMIT_QUERY:172 "Please login to contact our support team.",173 ERROR_AUTHENTICATION:174 "Received some error in authentication. Please try again later!!",175 SHARED_LISTS_LIMIT_REACHED: `You can not create more than ${176 RQ.LIMITS.NUMBER_SHARED_LISTS177 } shared lists. 178 Please <a href="/pricing" target="_blank">upgrade your plan</a> to increase the limits.`,179 ERROR_TAB_FOCUS: "The tab cannot be focused, as it might have been closed.",180 DEACTIVATE_REQUESTLY_MENU_OPTION: "Deactivate Requestly"181};182RQ.RESOURCES = {183 EXTENSION_ICON: "/resources/images/48x48.png",184 EXTENSION_ICON_GREYSCALE: "/resources/images/48x48_greyscale.png",185 EXTENSION_ICON_GREEN: "/resources/images/48x48_green.png"186};187RQ.GA_EVENTS = {188 CATEGORIES: {189 RULES: "rules",190 RULE: "rule",191 GROUP: "group",192 USER: "user",193 SHARED_LIST: "shared list",194 RULE_LOGS: "rule logs",195 EXTENSION: "extension",196 IN_APP_NOTIFICATION: "InAppNotification",197 NEED_HELP_FEATURE: "need help feature"198 },199 ACTIONS: {200 MODIFIED: "modified",201 CREATED: "created",202 DELETED: "deleted",203 ACTIVATED: "activated",204 DEACTIVATED: "deactivated",205 IMPORTED: "imported",206 EXPORTED: "exported",207 LIMIT_REACHED: "limit reached",208 AUTHENTICATED: "authenticated",209 VIEWED: "viewed",210 CLICKED: "clicked",211 COPIED: "copied",212 MARKED_FAVOURITE: "marked favourite",213 UNMARKED_FAVOURITE: "unmarked favourite",214 WORKFLOW_STARTED: "workflow started",215 ALREADY_LOGIN: "already login",216 LOGIN_REQUESTED: "login requested",217 LOGIN_DONE: "login done",218 LOGIN_REJECTED: "login rejected",219 FORM_SUBMITTED: "form submitted",220 FORM_REJECTED: "form rejected",221 INVALID_SUBMIT: "invalid submit",222 GROUPED: "grouped",223 UNGROUPED: "ungrouped"224 }225};226RQ.USER = {227 AUTHORIZED: "authorized-user",228 UNAUTHORIZED: "unauthorized-user"229};230RQ.FIREBASE_NODES = {231 USERS: "users",232 PUBLIC: "public",233 SHARED_LISTS: "sharedLists",234 FEEDBACK: "feedback"235};236RQ.DATASTORE = {237 ACTIONS: {238 CHECK_USER_AUTH: "check:userAuthenticated",239 AUTHENTICATE: "authenticate",240 FETCH_USER_DETAILS: "fetchUserDetails",241 GETVALUE: "getValue",242 SETVALUE: "setValue"243 }244};245RQ.MESSAGE_HANDLER = {246 ACTIONS: {247 SUBMIT_EVENT: "submitEvent",248 SUBMIT_ATTR: "submitAttr"249 },250 MESSAGE_TYPES: {251 EVENT: "event",252 ATTRIBUTE: "attribute"253 },254 SINKS: {255 CUSTOMERLY: "customerly"256 }257};258RQ.htmlEncode = function(value) {259 return $("<div/>")260 .text(value)261 .html();262};263RQ.getSharedURL = function(shareId, sharedListName) {264 const formattedSharedListName = sharedListName265 .replace(new RegExp(" +|/+", "g"), "-")266 .replace(/-+/g, "-");267 return (268 RQ.RULES_PAGE_URL + "#sharedList/" + shareId + "-" + formattedSharedListName269 );270};271RQ.getSharedListTimestamp = function(sharedListId) {272 return sharedListId.split("-")[0];273};274RQ.fireAjax = function(requestURL, async) {275 return new Promise((resolve, reject) => {276 const request = new XMLHttpRequest();277 request.open('GET', requestURL, async);278 request.onreadystatechange = function () {279 if (this.readyState === 4) {280 if (this.status >= 200 && this.status < 400) {281 resolve(JSON.parse(this.responseText));282 } else {283 reject();284 }285 }286 };287 request.send();288 });289};290window.RQ = window.RQ || {};291RQ.Utils = RQ.Utils || {};292RQ.Utils.regexFormat = '^\/(.+)\/(|i|g|ig|gi)$';293RQ.Utils.isValidRegex = function(regexStr) {294 return regexStr.search(new RegExp(RQ.Utils.regexFormat)) !== -1;295};296RQ.Utils.toRegex = function(regexStr) {297 var isRegexStringValid = this.isValidRegex(regexStr),298 matchRegExp;299 if (!isRegexStringValid) {300 return null;301 }302 matchRegExp = regexStr.match(new RegExp(RQ.Utils.regexFormat));303 return new RegExp(matchRegExp[1], matchRegExp[2]);304};305RQ.Utils.isValidUrl = function(url) {306 return url.search(/^http:|https:|ftp:|javascript:/) === 0;307};308RQ.Utils.getId = function() {309 return Date.now();310};311RQ.Utils.getCurrentTime = function() {312 return Date.now();313};314RQ.Utils.formatDate = function(dateInMilis, format) {315 const d = new Date(dateInMilis);316 if (dateInMilis && format === 'yyyy-mm-dd') {317 let month = d.getMonth() + 1,318 date = d.getDate();319 date = (String(date).length) < 2 ? ('0' + date) : String(date);320 month = (String(month).length) < 2 ? ('0' + month) : String(month);321 return d.getFullYear() + '-' + month + '-' + date;322 }323};324RQ.Utils.reloadPage = function(wait) {325 wait = wait || 0;326 setTimeout(function () {327 window.location.reload();328 }, wait);329};330RQ.Utils.submitEvent = function(eventCategory, eventAction, eventLabel, eventValue) {331 if (!eventLabel) {332 eventLabel = eventCategory + ' ' + eventAction;333 }334 RQ.ContentScriptMessageHandler.sendMessage({335 action: RQ.MESSAGE_HANDLER.ACTIONS.SUBMIT_EVENT,336 eventCategory: eventCategory,337 eventAction: eventAction,338 eventLabel: eventLabel,339 eventValue: eventValue340 });341};342RQ.Utils.submitAttr = function(attr, value) {343 const messageToSend = {344 action: RQ.MESSAGE_HANDLER.ACTIONS.SUBMIT_ATTR,345 attr: attr,346 value: value347 };348 RQ.ContentScriptMessageHandler.sendMessage(messageToSend);349};350RQ.Utils.removeLastPart = function(str, separater) {351 str = str || '';352 // Return original string when separator is not present353 if (str.indexOf(separater) === -1) {354 return str;355 }356 str = str.split(separater);357 // Remove last part358 str.length--;359 return str.join(separater);360};361RQ.Utils.setCookie = function(name, value, maxAge) {362 document.cookie = name + '=' + value + '; path=/' + '; max-age=' + maxAge;363};364RQ.Utils.readCookie = function(name) {365 var nameEQ = name + '=';366 var ca = document.cookie.split(';');367 for(var i=0;i < ca.length;i++) {368 var c = ca[i];369 while (c.charAt(0)==' ') c = c.substring(1,c.length);370 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);371 }372 return null;373};374RQ.Utils.eraseCookie = function (name) {375 RQ.Utils.setCookie(name, '', 1);376};377/**378 *379 * @param url Url from which component has to be extracted380 * @param name Url component name - host, path, url, query, fragment etc.381 */382RQ.Utils.extractUrlComponent = function(url, name) {383 if (!window.dummyAnchor) {384 window.dummyAnchor = document.createElement('a');385 }386 window.dummyAnchor.href = url;387 switch(name) {388 case RQ.URL_COMPONENTS.URL: return url;389 case RQ.URL_COMPONENTS.PROTOCOL: return window.dummyAnchor.protocol;390 case RQ.URL_COMPONENTS.HOST: return window.dummyAnchor.host;391 case RQ.URL_COMPONENTS.PATH: return window.dummyAnchor.pathname;392 case RQ.URL_COMPONENTS.QUERY: return window.dummyAnchor.search;393 case RQ.URL_COMPONENTS.HASH: return window.dummyAnchor.hash;394 }395 console.error('Invalid source key', url, name);396};397/**398 *399 * @param queryString e.g. ?a=1&b=2 or a=1 or ''400 * @returns object { paramName -> [value1, value2] }401 */402RQ.Utils.getQueryParamsMap = function(queryString) {403 var map = {},404 queryParams;405 if (!queryString || queryString === '?') {406 return map;407 }408 if (queryString[0] === '?') {409 queryString = queryString.substr(1);410 }411 queryParams = queryString.split('&');412 queryParams.forEach(function(queryParam) {413 var paramName = queryParam.split('=')[0],414 paramValue = queryParam.split('=')[1];415 // We are keeping value of param as array so that in future we can support multiple param values of same name416 // And we do not want to lose the params if url already contains multiple params of same name417 map[paramName] = map[paramName] || [];418 map[paramName].push(paramValue);419 });420 return map;421};422/**423 * Convert a map to keyvalue pair string (Used for query params)424 * @param queryParamsMap425 * @returns {string}426 */427RQ.Utils.convertQueryParamMapToString = function(queryParamsMap) {428 var queryParamsArr = [];429 for (var paramName in queryParamsMap) {430 var values = queryParamsMap[paramName] || [];431 values.forEach(function(paramValue) {432 if (typeof paramValue === 'undefined') {433 queryParamsArr.push(paramName);434 } else {435 queryParamsArr.push(paramName + '=' + paramValue);436 }437 });438 }439 return queryParamsArr.join('&');440};441RQ.Utils.getUrlWithoutQueryParamsAndHash = function(url) {442 var urlWithoutHash = url.split('#')[0];443 return urlWithoutHash.split('?')[0];444};445window.RQ = window.RQ || {};446RQ.ContentScriptMessageHandler = {447 eventCallbackMap: {},448 requestId: 1,449 constants: {450 CONTENT_SCRIPT: 'content_script',451 PAGE_SCRIPT: 'page_script',452 DOMAIN: RQ.configs.WEB_URL,453 SOURCE_FIELD: 'source',454 ACTION_USER_LOGGED_IN: 'user:loggedIn'455 },456 addMessageListener: function() {457 window.addEventListener('message', this.handleMessageReceived.bind(this));458 },459 getSource: function() {460 return this.constants.CONTENT_SCRIPT;461 },462 registerCallback: function(message, callback) {463 if (!callback) return;464 // Message has requestId when we are sending response465 const requestIdToUse = this.requestId++;466 this.eventCallbackMap[message.action + '_' + requestIdToUse] = callback;467 message.requestId = requestIdToUse;468 },469 invokeCallback: function(event) {470 const callbackRef = this.eventCallbackMap[event.data.action + '_' + event.data.requestId];471 if (typeof callbackRef === 'function') {472 // We should remove the entry from map first before executing the callback otherwise we will store stale references of functions473 delete this.eventCallbackMap[event.data.action];474 callbackRef.call(this, event.data.response);475 }476 },477 sendMessage: function(message, callback) {478 if (!message.action) {479 Logger.error('Invalid message. Must contain some action');480 return;481 }482 this.registerCallback(message, callback);483 message[this.constants.SOURCE_FIELD] = this.getSource();484 window.postMessage(message, this.constants.DOMAIN);485 },486 sendResponse: function(originalEventData, response) {487 const message = {488 action: originalEventData.action,489 requestId: originalEventData.requestId,490 response: response491 };492 message[this.constants.SOURCE_FIELD] = this.constants.CONTENT_SCRIPT;493 window.postMessage(message, this.constants.DOMAIN);494 },495 handleMessageReceived: function(event) {496 const that = this;497 if (event && event.origin !== RQ.configs.WEB_URL) {498 if (RQ.configs.logLevel === 'debug') {499 console.log('Ignoring message from the following domain', event.origin, event.data);500 }501 return;502 }503 if (event && event.data && event.data.source === this.constants.PAGE_SCRIPT) {504 RQ.configs.logLevel === 'debug' && console.log('Received message:', event.data);505 // Check whether it is a response to invoke callback or a request to perform an action506 if (typeof event.data.response !== 'undefined') {507 return this.invokeCallback(event);508 }509 // Process actions510 if (event.data.action === 'GET_STORAGE_TYPE') {511 StorageService.getStorageType().then(storageType => {512 that.sendResponse(event.data, { storageType });513 });514 }515 else if (event.data.action === 'SET_STORAGE_TYPE') {516 StorageService.setStorageType(event.data.storageType).then(() => {517 that.sendResponse(event.data, {success: true});518 });519 }520 else if (event.data.action === 'GET_STORAGE_INFO') {521 StorageService.getStorageType().then(storageType => {522 chrome.storage[storageType].get(null, superObject => {523 const storageCachedRecords = [];524 for (let key in superObject) {525 if (superObject[key].hasOwnProperty('objectType') || superObject[key].hasOwnProperty('ruleType')) {526 storageCachedRecords.push(superObject[key]);527 }528 }529 that.sendResponse(event.data, {530 storageType: storageType,531 numItems: storageCachedRecords.length,532 bytesUsed: JSON.stringify(storageCachedRecords).length533 });534 });535 });536 }537 else if (event.data.action === 'GET_STORAGE_SUPER_OBJECT') {538 StorageService.getStorageType().then(storageType => {539 chrome.storage[storageType].get(null, superObject => {540 that.sendResponse(event.data, superObject);541 });542 });543 }544 else if (event.data.action === 'GET_STORAGE_OBJECT') {545 StorageService.getStorageType().then(storageType => {546 chrome.storage[storageType].get(event.data.key, obj => {547 that.sendResponse(event.data, obj[event.data.key]);548 });549 });550 }551 else if (event.data.action === 'SAVE_STORAGE_OBJECT') {552 StorageService.getStorageType().then(storageType => {553 chrome.storage[storageType].set(event.data.object, () => {554 that.sendResponse(event.data);555 });556 });557 }558 else if (event.data.action === 'REMOVE_STORAGE_OBJECT') {559 StorageService.getStorageType().then(storageType => {560 chrome.storage[storageType].remove(event.data.key, () => {561 that.sendResponse(event.data);562 });563 });564 }565 else if (event.data.action === 'CLEAR_STORAGE') {566 StorageService.getStorageType().then(storageType => {567 chrome.storage[storageType].clear(() => {568 that.sendResponse(event.data);569 });570 });571 }572 else if (event.data.action === 'GET_REMOTE_RULES_SETTINGS') {573 StorageService.getRecordFromStorage('remote_rules_settings', 'sync')574 .then(obj => that.sendResponse(event.data, obj || {}));575 }576 else if (event.data.action === 'SET_REMOTE_RULES_SETTINGS') {577 StorageService.saveRecordInStorage({ remote_rules_settings: event.data.remoteRulesSettings }, 'sync')578 .then(() => {579 // Inform background to start the import periodically580 return new Promise(resolve =>581 chrome.runtime.sendMessage({ action: RQ.EXTENSION_MESSAGES.REMOTE_RULES_SETTINGS_CHANGED }, resolve)582 );583 })584 .then(() => {585 // Send the response back to App UI to show notification586 that.sendResponse(event.data, { success: true });587 });588 }589 else if ([590 RQ.EXTENSION_MESSAGES.FOCUS_TAB,591 RQ.EXTENSION_MESSAGES.GET_FULL_LOGS,592 RQ.EXTENSION_MESSAGES.CLEAR_LOGS_FOR_TAB,593 RQ.EXTENSION_MESSAGES.CLEAR_LOGS_FOR_DOMAIN,594 RQ.EXTENSION_MESSAGES.GET_FLAGS595 ].includes(event.data.action)) {596 this.delegateMessageToBackground(event.data);597 }598 }599 },600 delegateMessageToBackground: function(message) {601 const that = this;602 chrome.runtime.sendMessage(message, bgResponse => {603 that.sendResponse(message, bgResponse);604 });605 },606 init: function() {607 this.addMessageListener();608 }609};610RQ.ContentScriptMessageHandler.init();611window.RQ = window.RQ || {};612RQ.DataStoreUtils = {613 isUserAuthenticated: function(callback) {614 RQ.ContentScriptMessageHandler.sendMessage({615 action: RQ.DATASTORE.ACTIONS.CHECK_USER_AUTH616 }, callback);617 },618 fetchUserDetails: function() {619 return new Promise((resolve, reject) => {620 try {621 RQ.ContentScriptMessageHandler.sendMessage({ action: RQ.DATASTORE.ACTIONS.FETCH_USER_DETAILS }, resolve);622 } catch(e) {623 reject(e);624 }625 });626 },627 authenticate: function(callback) {628 RQ.ContentScriptMessageHandler.sendMessage({ action: RQ.DATASTORE.ACTIONS.AUTHENTICATE }, callback);629 },630 getValue: function(pathArray) {631 return new Promise((resolve, reject) => {632 try {633 RQ.ContentScriptMessageHandler.sendMessage({ action: RQ.DATASTORE.ACTIONS.GETVALUE, pathArray: pathArray }, resolve);634 } catch(e) {635 reject(e)636 }637 });638 },639 setValue: function(pathArray, value, callback) {640 RQ.ContentScriptMessageHandler.sendMessage({ action: RQ.DATASTORE.ACTIONS.SETVALUE, pathArray: pathArray, value: value }, callback);641 }642};643window.RQ = window.RQ || {};644RQ.UserAgentLibrary = RQ.UserAgentLibrary || {};645RQ.UserAgentLibrary = {646 USER_AGENT: {647 device: {648 android: {649 name: 'Android',650 values: {651 phone: {652 name: 'Android Phone',653 value: 'Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Mobile Safari/537.36' // Pixel 2654 },655 tablet: {656 name: 'Android Tablet',657 value: 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' // Nexus 10658 }659 }660 },661 apple: {662 name: 'Apple',663 values: {664 iphone: {665 name: 'Apple iPhone',666 value: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1' // iPhone X667 },668 ipad: {669 name: 'Apple iPad',670 value: 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1'671 }672 }673 },674 windows: {675 name: 'Windows',676 values: {677 phone: {678 name: 'Windows Phone',679 value: 'Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920)'680 },681 tablet: {682 name: 'Windows Tablet',683 value: 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; Touch; NOKIA; Lumia 920)'684 }685 }686 },687 blackberry: {688 name: 'Blackberry',689 values: {690 phone: {691 name: 'Blackberry Phone',692 value: 'Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en-US) AppleWebKit/534.11 (KHTML, like Gecko) Version/7.0.0.187 Mobile Safari/534.11'693 },694 tablet: {695 name: 'Blackberry Tablet',696 value: 'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.0.0; en-US) AppleWebKit/535.8 (KHTML, like Gecko) Version/7.2.0.0 Safari/535.8'697 }698 }699 },700 symbian_phone: {701 name: 'Symbian Phone',702 value: 'Mozilla/5.0 (SymbianOS) AppleWebKit/533.4 (KHTML, like Gecko) NokiaBrowser/7.3.1.33 Mobile Safari/533.4 3gpp-gba'703 }704 },705 browser: {706 chrome: {707 name: 'Google Chrome',708 values: {709 windows: {710 name: 'Chrome on Windows',711 value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'712 },713 macintosh: {714 name: 'Chrome on Macintosh',715 value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'716 },717 linux: {718 name: 'Chrome on Linux',719 value: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'720 }721 }722 },723 firefox: {724 name: 'Mozilla Firefox',725 values: {726 windows: {727 name: 'Firefox on Windows',728 value: 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0'729 },730 macintosh: {731 name: 'Firfox on Macintosh',732 value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:52.0) Gecko/20100101 Firefox/52.0'733 },734 linux: {735 name: 'Firefox on Linux',736 value: 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'737 }738 }739 },740 safari: {741 name: 'Safari',742 value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8'743 },744 msie: {745 name: 'Microsoft Internet Explorer',746 values: {747 msie6: {748 name: 'Internet Explorer 6',749 value: 'Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1)'750 },751 msie7: {752 name: 'Internet Explorer 7',753 value: 'Mozilla/4.0(compatible; MSIE 7.0; Windows NT 6.0)'754 },755 msie8: {756 name: 'Internet Explorer 8',757 value: 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)'758 },759 msie9: {760 name: 'Internet Explorer 9',761 value: 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'762 },763 msie10: {764 name: 'Internet Explorer 10',765 value: 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'766 },767 msie11: {768 name: 'Internet Explorer 11',769 value: 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'770 }771 }772 },773 msedge: {774 name: 'Microsoft Edge',775 value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240'776 },777 opera: {778 name: 'Opera',779 value: 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36 OPR/15.0.1147.100'780 }781 }782 },783 getDefaultUserAgent: function() {784 return navigator && navigator.userAgent || '';785 }786};787window.RQ = window.RQ || {};788RQ.DOMUtils = RQ.DOMUtils || {};789/**790 *791 * @param $el Element on which class should be toggled792 * @param className Class to be toggled793 * @param condition Boolean Condition - When true class will be added otherwise removed794 */795RQ.DOMUtils.toggleClass = function($el, className, condition) {796 condition ? $el.addClass(className) : $el.removeClass(className);...

Full Screen

Full Screen

client.js

Source:client.js Github

copy

Full Screen

1window.RQ = window.RQ || {};2window.RQ.configs = {3 "version": "20.3.16",4 "browser": "chrome",5 "storageType": "sync",6 "contextMenuContexts": [7 "browser_action"8 ],9 "env": "prod",10 "WEB_URL": "https://app.requestly.io",11 "firebaseConfig": {12 "apiKey": "AIzaSyC2WOxTtgKH554wCezEJ4plxnMNXaUSFXY",13 "authDomain": "app.requestly.io",14 "databaseURL": "https://requestly.firebaseio.com",15 "projectId": "project-7820168409702389920",16 "storageBucket": "project-7820168409702389920.appspot.com",17 "messagingSenderId": "911299702852"18 },19 "logLevel": "info"20};21window.RQ = window.RQ || {};22RQ.VERSION = 3;23RQ.FILE_PICKER_URL = "/library/filepicker";24RQ.VERSIONS = {25 REPLACE_RULE: 226};27RQ.PUBLIC_NAMESPACE = '__REQUESTLY__';28// Url which gets opened when User clicks on browserAction (requestly icon) in toolbar29RQ.RULES_PAGE_URL = RQ.configs.WEB_URL + "/rules/";30RQ.RULES_PAGE_URL_PATTERN = RQ.RULES_PAGE_URL + "*";31RQ.PRICING_PAGE_URL = RQ.configs.WEB_URL + "/pricing/";32RQ.GOODBYE_PAGE_URL = RQ.configs.WEB_URL + "/goodbye/";33RQ.BLACK_LIST_DOMAINS = ["requestly.in", "requestly.io"];34RQ.STRING_CONSTANTS = {35 SLASH: "/"36};37RQ.LIMITS = {38 NUMBER_SHARED_LISTS: 1039};40RQ.DEFAULTS = {41 APP_INIT_TIMEOUT: 500042};43RQ.OBJECT_TYPES = {44 GROUP: "group",45 RULE: "rule"46};47RQ.RULE_TYPES = {48 REDIRECT: "Redirect",49 CANCEL: "Cancel",50 REPLACE: "Replace",51 HEADERS: "Headers",52 USERAGENT: "UserAgent",53 SCRIPT: "Script",54 QUERYPARAM: "QueryParam",55 RESPONSE: "Response"56};57RQ.HEADER_NAMES = {58 USER_AGENT: "User-Agent"59};60RQ.RULE_STATUS = {61 ACTIVE: "Active",62 INACTIVE: "Inactive"63};64RQ.RULE_KEYS = {65 URL: "Url",66 HOST: "host",67 PATH: "path",68 HEADER: "Header",69 OVERWRITE: "Overwrite",70 IGNORE: "Ignore",71 PARAM: "param",72 VALUE: "value"73};74RQ.URL_COMPONENTS = {75 PROTOCOL: "Protocol",76 URL: "Url",77 HOST: "host",78 PATH: "path",79 QUERY: "query",80 HASH: "hash"81};82RQ.RULE_OPERATORS = {83 EQUALS: "Equals",84 CONTAINS: "Contains",85 MATCHES: "Matches",86 WILDCARD_MATCHES: "Wildcard_Matches"87};88RQ.RULE_SOURCE_FILTER_TYPES = {89 PAGE_URL: "pageUrl",90 RESOURCE_TYPE: "resourceType",91 REQUEST_METHOD: "requestMethod"92};93RQ.MODIFICATION_TYPES = {94 ADD: "Add",95 REMOVE: "Remove",96 REMOVE_ALL: "Remove All",97 MODIFY: "Modify",98 REPLACE: "Replace"99};100RQ.NEED_HELP_QUERY_TYPES = {101 FEEDBACK: "Feedback",102 BUG: "Bug",103 QUESTION: "Question",104 FEATURE_REQUEST: "FeatureRequest"105};106RQ.CLIENT_MESSAGES = {107 GET_SCRIPT_RULES: "getScriptRules",108 GET_USER_AGENT_RULE_PAIRS: "getUserAgentRulePairs",109 OVERRIDE_RESPONSE: "overrideResponse",110 NOTIFY_RULES_APPLIED: "notifyRulesApplied"111};112RQ.EXTENSION_MESSAGES = {113 FOCUS_TAB: "focusTab",114 GET_FULL_LOGS: "getFullLogs",115 CLEAR_LOGS_FOR_TAB: "clearLogsForTab",116 CLEAR_LOGS_FOR_DOMAIN: "clearLogsForDomain",117 GET_FAVOURITE_RULES: "getFavouriteRules",118 REMOTE_RULES_SETTINGS_CHANGED: 'remoteRulesSettingsChanged',119 GET_FLAGS: "getFlags"120};121RQ.HEADERS_TARGET = {122 REQUEST: "Request",123 RESPONSE: "Response"124};125RQ.REQUEST_TYPES = {126 MAIN_FRAME: "mainFrame",127 PAGE_REQUEST: "pageRequest"128};129RQ.SCRIPT_TYPES = {130 URL: "url",131 CODE: "code"132};133RQ.SCRIPT_CODE_TYPES = {134 JS: "js",135 CSS: "css"136};137RQ.SCRIPT_LOAD_TIME = {138 BEFORE_PAGE_LOAD: "beforePageLoad",139 AFTER_PAGE_LOAD: "afterPageLoad"140};141RQ.SCRIPT_LIBRARIES = {142 JQUERY: { name: "jQuery", src: "https://code.jquery.com/jquery-2.2.4.js" },143 UNDERSCORE: {144 name: "Underscore",145 src:146 "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"147 }148};149RQ.RESPONSE_CODES = {150 NOT_FOUND: 404151};152RQ.STORAGE_KEYS = {153 REQUESTLY_SETTINGS: "rq_settings",154 USER_INFO: "user_info",155 LATEST_NOTIFICATION_READ_BY_USER: "latestNotificationReadId"156};157RQ.MESSAGES = {158 DELETE_ITEMS_NO_SELECTION_WARNING:159 "Please select one or more rules to delete.",160 DELETE_ITEMS: "Are you sure you want to delete the selected items?",161 DELETE_GROUP_WITH_RULES_WARNING:162 "There are some rules contained in this group. Please delete or ungroup them before deleting the group.",163 DELETE_GROUP: "Are you sure you want to delete the group?",164 UNGROUP_ITEMS_NO_SELECTION_WARNING:165 "Please select one or more rules to ungroup.",166 UNGROUP_ITEMS: "Are you sure you want to ungroup the selected items?",167 SIGN_IN_TO_VIEW_SHARED_LISTS:168 "Please login to view your Shared Lists.",169 SIGN_IN_TO_CREATE_SHARED_LISTS:170 "Please login to share the selected rules",171 SIGN_IN_TO_SUBMIT_QUERY:172 "Please login to contact our support team.",173 ERROR_AUTHENTICATION:174 "Received some error in authentication. Please try again later!!",175 SHARED_LISTS_LIMIT_REACHED: `You can not create more than ${176 RQ.LIMITS.NUMBER_SHARED_LISTS177 } shared lists. 178 Please <a href="/pricing" target="_blank">upgrade your plan</a> to increase the limits.`,179 ERROR_TAB_FOCUS: "The tab cannot be focused, as it might have been closed.",180 DEACTIVATE_REQUESTLY_MENU_OPTION: "Deactivate Requestly"181};182RQ.RESOURCES = {183 EXTENSION_ICON: "/resources/images/48x48.png",184 EXTENSION_ICON_GREYSCALE: "/resources/images/48x48_greyscale.png",185 EXTENSION_ICON_GREEN: "/resources/images/48x48_green.png"186};187RQ.GA_EVENTS = {188 CATEGORIES: {189 RULES: "rules",190 RULE: "rule",191 GROUP: "group",192 USER: "user",193 SHARED_LIST: "shared list",194 RULE_LOGS: "rule logs",195 EXTENSION: "extension",196 IN_APP_NOTIFICATION: "InAppNotification",197 NEED_HELP_FEATURE: "need help feature"198 },199 ACTIONS: {200 MODIFIED: "modified",201 CREATED: "created",202 DELETED: "deleted",203 ACTIVATED: "activated",204 DEACTIVATED: "deactivated",205 IMPORTED: "imported",206 EXPORTED: "exported",207 LIMIT_REACHED: "limit reached",208 AUTHENTICATED: "authenticated",209 VIEWED: "viewed",210 CLICKED: "clicked",211 COPIED: "copied",212 MARKED_FAVOURITE: "marked favourite",213 UNMARKED_FAVOURITE: "unmarked favourite",214 WORKFLOW_STARTED: "workflow started",215 ALREADY_LOGIN: "already login",216 LOGIN_REQUESTED: "login requested",217 LOGIN_DONE: "login done",218 LOGIN_REJECTED: "login rejected",219 FORM_SUBMITTED: "form submitted",220 FORM_REJECTED: "form rejected",221 INVALID_SUBMIT: "invalid submit",222 GROUPED: "grouped",223 UNGROUPED: "ungrouped"224 }225};226RQ.USER = {227 AUTHORIZED: "authorized-user",228 UNAUTHORIZED: "unauthorized-user"229};230RQ.FIREBASE_NODES = {231 USERS: "users",232 PUBLIC: "public",233 SHARED_LISTS: "sharedLists",234 FEEDBACK: "feedback"235};236RQ.DATASTORE = {237 ACTIONS: {238 CHECK_USER_AUTH: "check:userAuthenticated",239 AUTHENTICATE: "authenticate",240 FETCH_USER_DETAILS: "fetchUserDetails",241 GETVALUE: "getValue",242 SETVALUE: "setValue"243 }244};245RQ.MESSAGE_HANDLER = {246 ACTIONS: {247 SUBMIT_EVENT: "submitEvent",248 SUBMIT_ATTR: "submitAttr"249 },250 MESSAGE_TYPES: {251 EVENT: "event",252 ATTRIBUTE: "attribute"253 },254 SINKS: {255 CUSTOMERLY: "customerly"256 }257};258RQ.htmlEncode = function(value) {259 return $("<div/>")260 .text(value)261 .html();262};263RQ.getSharedURL = function(shareId, sharedListName) {264 const formattedSharedListName = sharedListName265 .replace(new RegExp(" +|/+", "g"), "-")266 .replace(/-+/g, "-");267 return (268 RQ.RULES_PAGE_URL + "#sharedList/" + shareId + "-" + formattedSharedListName269 );270};271RQ.getSharedListTimestamp = function(sharedListId) {272 return sharedListId.split("-")[0];273};274RQ.fireAjax = function(requestURL, async) {275 return new Promise((resolve, reject) => {276 const request = new XMLHttpRequest();277 request.open('GET', requestURL, async);278 request.onreadystatechange = function () {279 if (this.readyState === 4) {280 if (this.status >= 200 && this.status < 400) {281 resolve(JSON.parse(this.responseText));282 } else {283 reject();284 }285 }286 };287 request.send();288 });289};290RQ.Utils = RQ.Utils || {};291RQ.Utils.executeJS = function(code, shouldRemove) {292 const script = document.createElement('script');293 script.type = 'text/javascript';294 script.className = RQ.Utils.getScriptClassAttribute();295 script.appendChild(document.createTextNode(code));296 const parent = document.head || document.documentElement;297 parent.appendChild(script);298 if (shouldRemove) {299 parent.removeChild(script);300 }301};302RQ.Utils.addRemoteJS = function(src, callback) {303 var script = document.createElement('script');304 script.type = 'text/javascript';305 script.src = src;306 script.className = RQ.Utils.getScriptClassAttribute();307 if (typeof callback === 'function') {308 script.onload = callback;309 }310 (document.head || document.documentElement).appendChild(script);311 return script;312};313RQ.Utils.embedCSS = function(css) {314 var style = document.createElement('style');315 style.type = 'text/css';316 style.appendChild(document.createTextNode(css));317 style.className = RQ.Utils.getScriptClassAttribute();318 (document.head || document.documentElement).appendChild(style);319 return style;320};321RQ.Utils.addRemoteCSS = function(src) {322 var link = document.createElement('link');323 link.href = src;324 link.type = 'text/css';325 link.rel = 'stylesheet';326 link.className = RQ.Utils.getScriptClassAttribute();327 (document.head || document.documentElement).appendChild(link);328 return link;329};330RQ.Utils.onPageLoad = function() {331 return new Promise(function(resolve) {332 if (document.readyState === 'loading') {333 document.addEventListener('DOMContentLoaded', resolve);334 } else {335 resolve();336 }337 });338};339RQ.Utils.getScriptClassAttribute = function() {340 return RQ.PUBLIC_NAMESPACE + 'SCRIPT';341};342RQ.ScriptRuleHandler = {};343RQ.ScriptRuleHandler.handleRules = function(rules) {344 return new Promise(function(resolve) {345 var libraries = [],346 scripts = [];347 rules.forEach(function (rule) {348 var pair = rule.pairs[0];349 pair.libraries && pair.libraries.forEach(function(library) {350 if (!libraries.includes(library)) {351 libraries.push(library);352 }353 });354 scripts = scripts.concat(pair.scripts || []);355 });356 var cssScripts = scripts.filter(function (script) {357 return script.codeType === RQ.SCRIPT_CODE_TYPES.CSS;358 });359 var jsScripts = scripts.filter(function (script) {360 return !script.codeType || script.codeType === RQ.SCRIPT_CODE_TYPES.JS;361 });362 RQ.ScriptRuleHandler.handleCSSScripts(cssScripts)363 .then(function() { return RQ.ScriptRuleHandler.handleJSLibraries(libraries); })364 .then(function() { return RQ.ScriptRuleHandler.handleJSScripts(jsScripts); })365 .then(resolve);366 });367};368RQ.ScriptRuleHandler.handleCSSScripts = function(cssScripts) {369 return new Promise(function(resolve) {370 cssScripts.forEach(RQ.ScriptRuleHandler.includeCSS);371 resolve();372 });373};374RQ.ScriptRuleHandler.handleJSLibraries = function(libraries) {375 return new Promise(function(resolve) {376 RQ.ScriptRuleHandler.addLibraries(libraries, resolve);377 });378};379RQ.ScriptRuleHandler.handleJSScripts = function(jsScripts) {380 return new Promise(function(resolve) {381 var prePageLoadScripts = [],382 postPageLoadScripts = [];383 jsScripts.forEach(function(script) {384 if (script.loadTime === RQ.SCRIPT_LOAD_TIME.BEFORE_PAGE_LOAD) {385 prePageLoadScripts.push(script);386 } else {387 postPageLoadScripts.push(script);388 }389 });390 RQ.ScriptRuleHandler.includeJSScriptsInOrder(prePageLoadScripts, function() {391 RQ.Utils.onPageLoad().then(function() {392 RQ.ScriptRuleHandler.includeJSScriptsInOrder(postPageLoadScripts, resolve);393 });394 });395 });396};397RQ.ScriptRuleHandler.addLibraries = function(libraries, callback, index) {398 index = index || 0;399 if (index >= libraries.length) {400 typeof callback === 'function' && callback();401 return;402 }403 var libraryKey = libraries[index],404 library = RQ.SCRIPT_LIBRARIES[libraryKey],405 addNextLibraries = function() {406 RQ.ScriptRuleHandler.addLibraries(libraries, callback, index + 1);407 };408 if (library) {409 RQ.Utils.addRemoteJS(library.src, addNextLibraries);410 } else {411 addNextLibraries();412 }413};414RQ.ScriptRuleHandler.includeJSScriptsInOrder = function(scripts, callback, index) {415 index = index || 0;416 if (index >= scripts.length) {417 typeof callback === 'function' && callback();418 return;419 }420 RQ.ScriptRuleHandler.includeJS(scripts[index], function() {421 RQ.ScriptRuleHandler.includeJSScriptsInOrder(scripts, callback, index + 1);422 });423};424RQ.ScriptRuleHandler.includeJS = function(script, callback) {425 if (script.type === RQ.SCRIPT_TYPES.URL) {426 RQ.Utils.addRemoteJS(script.value, callback);427 return;428 }429 if (script.type === RQ.SCRIPT_TYPES.CODE) {430 RQ.Utils.executeJS(script.value);431 }432 typeof callback === 'function' && callback();433};434RQ.ScriptRuleHandler.includeCSS = function(script, callback) {435 if (script.type === RQ.SCRIPT_TYPES.URL) {436 RQ.Utils.addRemoteCSS(script.value);437 } else if (script.type === RQ.SCRIPT_TYPES.CODE) {438 RQ.Utils.embedCSS(script.value);439 }440 typeof callback === 'function' && callback();441};442RQ.UserAgentRuleHandler = {};443RQ.UserAgentRuleHandler.handleRulePairs = function(rulePairs) {444 var finalUserAgentRulePair = rulePairs[rulePairs.length - 1], // only last user agent will finally be applied445 userAgent = finalUserAgentRulePair.userAgent,446 platform = RQ.UserAgentRuleHandler.getPlatformFromUserAgent(userAgent),447 vendor = RQ.UserAgentRuleHandler.getVendorFromUserAgent(userAgent);448 RQ.Utils.executeJS(`Object.defineProperty(window.navigator, 'userAgent', { get: function() { return '${userAgent}'; } });`);449 RQ.Utils.executeJS(`Object.defineProperty(window.navigator, 'vendor', { get: function() { return '${vendor}'; } });`);450 if (platform) {451 // override platform only if it could be derived from userAgent452 RQ.Utils.executeJS(`Object.defineProperty(window.navigator, 'platform', { get: function() { return '${platform}'; } });`);453 }454};455RQ.UserAgentRuleHandler.getPlatformFromUserAgent = function(userAgent) {456 var PLATFORMS = {457 Macintosh: 'MacIntel',458 Android: 'Android',459 Linux: 'Linux',460 iPhone: 'iPhone',461 iPad: 'iPad',462 Windows: 'Win32'463 };464 for (var key in PLATFORMS) {465 if (userAgent.includes(key)) {466 return PLATFORMS[key];467 }468 }469};470RQ.UserAgentRuleHandler.getVendorFromUserAgent = function(userAgent) {471 var VENDORS = {472 iPhone: 'Apple Computer, Inc.',473 iPad: 'Apple Computer, Inc.',474 Chrome: 'Google Inc.'475 };476 for (var key in VENDORS) {477 if (userAgent.includes(key)) {478 return VENDORS[key];479 }480 }481 return ''; // vendor is empty string for others482};483RQ.ResponseRuleHandler = {};484RQ.ResponseRuleHandler.setup = function() {485 RQ.Utils.executeJS(`(${this.interceptAJAXRequests.toString()})('${RQ.PUBLIC_NAMESPACE}')`);486 window.addEventListener('message', function(event) {487 // We only accept messages from ourselves488 if (event.source !== window || event.data.from !== 'requestly') {489 return;490 }491 if (event.data.type === 'response_rule_applied') {492 chrome.runtime.sendMessage({493 action: RQ.CLIENT_MESSAGES.NOTIFY_RULES_APPLIED,494 url: window.location.href,495 ruleIds: [event.data.id]496 });497 }498 });499};500RQ.ResponseRuleHandler.handleOverrideResponseMessage = function(message) {501 RQ.Utils.executeJS(`window.${RQ.PUBLIC_NAMESPACE}.responseRules['${message.url}'] = ${JSON.stringify(message.rule)};`, true);502 // Set evaluator function in global scope when user selects code(or function)503 // We don't need this in case when user selects JSON response directly504 if (message.rule.response.type === 'code') {505 RQ.Utils.executeJS(`window.${RQ.PUBLIC_NAMESPACE}.responseRules['${message.url}'].evaluator = ${message.rule.response.value};`);506 }507};508/* Do not refer other function/variables from below function, as it will be injected in website */509RQ.ResponseRuleHandler.interceptAJAXRequests = function(namespace) {510 window[namespace] = window[namespace] || {};511 window[namespace].responseRules = {};512 let open = XMLHttpRequest.prototype.open;513 XMLHttpRequest.prototype.open = function(method) {514 this.addEventListener('readystatechange', function() {515 if (this.readyState === 4 && window[namespace].responseRules.hasOwnProperty(this.responseURL)) {516 const responseRule = window[namespace].responseRules[this.responseURL];517 const {response, id} = responseRule;518 const responseType = this.responseType;519 let customResponse;520 customResponse = response.type === 'code' ? responseRule.evaluator({521 method,522 url: this.responseURL,523 requestHeaders: this.requestHeaders,524 requestData: this.requestData,525 responseType: this.responseType,526 response: this.response527 }) : response.value;528 Object.defineProperty(this, 'response', {529 get: function () {530 if (response.type === 'static' && responseType === 'json') {531 return JSON.parse(customResponse);532 }533 return customResponse;534 }535 });536 if (responseType === '' || responseType === 'text') {537 Object.defineProperty(this, 'responseText', {538 get: function () {539 return customResponse;540 }541 });542 }543 window.postMessage({544 from: 'requestly',545 type: 'response_rule_applied',546 id547 }, window.location.href);548 }549 }, false);550 open.apply(this, arguments);551 };552 let send = XMLHttpRequest.prototype.send;553 XMLHttpRequest.prototype.send = function(data) {554 this.requestData = data;555 send.apply(this, arguments);556 };557 let setRequestHeader = XMLHttpRequest.prototype.setRequestHeader;558 XMLHttpRequest.prototype.setRequestHeader = function(header, value) {559 this.requestHeaders = this.requestHeaders || {};560 this.requestHeaders[header] = value;561 setRequestHeader.apply(this, arguments);562 }563};564(function executeScriptRules() {565 const message = { action: RQ.CLIENT_MESSAGES.GET_SCRIPT_RULES, url: window.location.href };566 chrome.runtime.sendMessage(message, function(rules) {567 if (rules && rules.constructor === Array) {568 RQ.ScriptRuleHandler.handleRules(rules);569 chrome.runtime.sendMessage({570 action: RQ.CLIENT_MESSAGES.NOTIFY_RULES_APPLIED,571 url: window.location.href,572 rules: rules573 });574 }575 });576})();577(function overrideUserAgent() {578 const message = { action: RQ.CLIENT_MESSAGES.GET_USER_AGENT_RULE_PAIRS, url: window.location.href };579 chrome.runtime.sendMessage(message, function (rulePairs) {580 if (rulePairs && rulePairs.constructor === Array && rulePairs.length > 0) {581 RQ.UserAgentRuleHandler.handleRulePairs(rulePairs);582 }583 });584})();585RQ.ResponseRuleHandler.setup();586chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {587 // return true is required from each case to use sendResponse asynchronously (https://developer.chrome.com/extensions/messaging)588 switch (message.action) {589 case RQ.CLIENT_MESSAGES.OVERRIDE_RESPONSE:590 RQ.ResponseRuleHandler.handleOverrideResponseMessage(message);591 sendResponse();592 return true;593 }...

Full Screen

Full Screen

httpRouter.test.js

Source:httpRouter.test.js Github

copy

Full Screen

1'use strict';2const mockrequire = require('mock-require');3const should = require('should');4const sinon = require('sinon');5const KuzzleMock = require('../../../mocks/kuzzle.mock');6const Router = require('../../../../lib/core/network/httpRouter');7const { HttpMessage } = require('../../../../lib/core/network/protocols/http');8const {9 Request,10 errors: { InternalError }11} = require('kuzzle-common-objects');12describe('core/network/httpRouter', () => {13 let14 router,15 handler,16 kuzzleMock,17 rq;18 beforeEach(() => {19 kuzzleMock = new KuzzleMock();20 router = new Router(kuzzleMock);21 handler = sinon.stub().yields();22 rq = new HttpMessage(23 { id: 'requestId' },24 { url: '', method: '', headers: {} });25 });26 afterEach(() => {27 mockrequire.stopAll();28 });29 describe('#adding routes', () => {30 it('should add a GET route when asked to', () => {31 router.get('/foo/bar', handler);32 should(router.routes.GET.subparts.foo.subparts.bar.handler).be.eql(handler);33 });34 it('should add a POST route when asked to', () => {35 router.post('/foo/bar', handler);36 should(router.routes.POST.subparts.foo.subparts.bar.handler).be.eql(handler);37 });38 it('should add a PUT route when asked to', () => {39 router.put('/foo/bar', handler);40 should(router.routes.PUT.subparts.foo.subparts.bar.handler).be.eql(handler);41 });42 it('should add a PATCH route when asked to', () => {43 router.patch('/foo/bar', handler);44 should(router.routes.PATCH.subparts.foo.subparts.bar.handler).be.eql(handler);45 });46 it('should add a DELETE route when asked to', () => {47 router.delete('/foo/bar', handler);48 should(router.routes.DELETE.subparts.foo.subparts.bar.handler).be.eql(handler);49 });50 it('should add a HEAD route when asked to', () => {51 router.head('/foo/bar', handler);52 should(router.routes.HEAD.subparts.foo.subparts.bar.handler).be.eql(handler);53 });54 it('should raise an internal error when trying to add a duplicate', () => {55 router.post('/foo/bar', handler);56 should(function () { router.post('/foo/bar', handler); })57 .throw(InternalError, { id: 'network.http.duplicate_url' });58 should(function () { router.post('/foo/bar/', handler); })59 .throw(InternalError, { id: 'network.http.duplicate_url' });60 });61 });62 describe('#default headers', () => {63 it('should define appropriate default HTTP headers', () => {64 should(router.defaultHeaders).eql({65 'content-type': 'application/json',66 'Accept-Encoding': 'gzip,deflate,identity',67 'Access-Control-Allow-Origin': '*',68 'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS,HEAD',69 'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, Content-Encoding, Content-Length, X-Kuzzle-Volatile'70 });71 });72 it('should update the list of accepted compression algorithms if compression is disabled', () => {73 kuzzleMock.config.server.protocols.http.allowCompression = false;74 router = new Router(kuzzleMock);75 should(router.defaultHeaders).eql({76 'content-type': 'application/json',77 'Accept-Encoding': 'identity',78 'Access-Control-Allow-Origin': '*',79 'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS,HEAD',80 'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, Content-Encoding, Content-Length, X-Kuzzle-Volatile'81 });82 });83 it('should take the value of the CORS headers from the config file, if set', () => {84 kuzzleMock.config.http.accessControlAllowOrigin = 'foobar';85 kuzzleMock.config.http.accessControlAllowMethods = 'METHOD';86 kuzzleMock.config.http.accessControlAllowHeaders = 'headers';87 router = new Router(kuzzleMock);88 should(router.defaultHeaders).eql({89 'content-type': 'application/json',90 'Accept-Encoding': 'gzip,deflate,identity',91 'Access-Control-Allow-Origin': 'foobar',92 'Access-Control-Allow-Methods': 'METHOD',93 'Access-Control-Allow-Headers': 'headers'94 });95 });96 });97 describe('#routing requests', () => {98 it('should invoke the registered handler on a known route', done => {99 router.post('/foo/bar', handler);100 rq.url = '/foo/bar';101 rq.method = 'POST';102 router.route(rq, () => {103 try {104 should(handler).be.calledOnce();105 should(handler.firstCall.args[0]).be.instanceOf(Request);106 done();107 }108 catch (e) {109 done(e);110 }111 });112 });113 it('should init request.context with the right values', done => {114 router.post('/foo/bar', handler);115 rq.url = '/foo/bar';116 rq.headers.foo = 'bar';117 rq.headers.Authorization = 'Bearer jwtFoobar';118 rq.headers['X-Kuzzle-Volatile'] = '{"modifiedBy": "John Doe", "reason": "foobar"}';119 rq.method = 'POST';120 router.route(rq, () => {121 try {122 should(handler).be.calledOnce();123 const apiRequest = handler.firstCall.args[0];124 should(apiRequest).be.instanceOf(Request);125 should(apiRequest.context.connection.protocol).be.exactly('http');126 should(apiRequest.context.connection.id).be.exactly('requestId');127 should(apiRequest.context.connection.misc.headers).be.eql({128 foo: 'bar',129 Authorization: 'Bearer jwtFoobar',130 'X-Kuzzle-Volatile': '{"modifiedBy": "John Doe", "reason": "foobar"}'});131 should(apiRequest.context.connection.misc.verb).eql('POST');132 should(apiRequest.input.jwt).be.exactly('jwtFoobar');133 should(apiRequest.input.volatile).be.eql({134 modifiedBy: 'John Doe',135 reason: 'foobar'136 });137 done();138 }139 catch (e) {140 done(e);141 }142 });143 });144 it('should properly handle querystrings (w/o url trailing slash)', done => {145 router.post('/foo/bar', handler);146 rq.url = '/foo/bar?foo=bar';147 rq.method = 'POST';148 router.route(rq, () => {149 try {150 should(handler).be.calledOnce();151 const payload = handler.firstCall.args[0];152 should(payload).be.instanceOf(Request);153 should(payload.input.args.foo).eql('bar');154 done();155 }156 catch (e) {157 done(e);158 }159 });160 });161 it('should properly handle querystrings (w/ url trailing slash)', done => {162 router.post('/foo/bar', handler);163 rq.url = '/foo/bar/?foo=bar';164 rq.method = 'POST';165 router.route(rq, () => {166 try {167 should(handler).be.calledOnce();168 const payload = handler.firstCall.args[0];169 should(payload).be.instanceOf(Request);170 should(payload.input.args.foo).eql('bar');171 done();172 }173 catch (e) {174 done(e);175 }176 });177 });178 it('should amend the request object if a body is found in the content', done => {179 router.post('/foo/bar', handler);180 rq.url = '/foo/bar';181 rq.method = 'POST';182 rq.headers['content-type'] = 'application/json';183 rq.addChunk('{"foo": "bar"}');184 router.route(rq, () => {185 try {186 should(handler).be.calledOnce();187 const apiRequest = handler.firstCall.args[0];188 should(apiRequest.id).match(rq.requestId);189 should(apiRequest.input.body).match({foo: 'bar'});190 should(apiRequest.input.headers['content-type']).eql('application/json');191 done();192 }193 catch (e) {194 done(e);195 }196 });197 });198 it('should return dynamic values for parametric routes', done => {199 router.post('/foo/:bar/:baz', handler);200 rq.url = '/foo/hello/world';201 rq.method = 'POST';202 rq.headers['content-type'] = 'application/json';203 rq.addChunk('{"foo": "bar"}');204 router.route(rq, () => {205 try {206 should(handler).be.calledOnce();207 const apiRequest = handler.firstCall.args[0];208 should(apiRequest.id).match(rq.requestId);209 should(apiRequest.input.body).match({foo: 'bar'});210 should(apiRequest.input.headers['content-type']).eql('application/json');211 should(apiRequest.input.args.bar).eql('hello');212 should(apiRequest.input.args.baz).eql('world');213 done();214 }215 catch (e) {216 done(e);217 }218 });219 });220 it('should unnescape dynamic values for parametric routes', done => {221 router.post('/foo/:bar/:baz', handler);222 rq.url = '/foo/hello/%25world';223 rq.method = 'POST';224 rq.headers['content-type'] = 'application/json; charset=utf-8';225 rq.addChunk('{"foo": "bar"}');226 router.route(rq, () => {227 try {228 should(handler).be.calledOnce();229 const apiRequest = handler.firstCall.args[0];230 should(apiRequest.id).match(rq.requestId);231 should(apiRequest.input.body).match({foo: 'bar'});232 should(apiRequest.input.headers['content-type']).eql('application/json; charset=utf-8');233 should(apiRequest.input.args.bar).eql('hello');234 should(apiRequest.input.args.baz).eql('%world');235 done();236 }237 catch (e) {238 done(e);239 }240 });241 });242 it('should trigger an event when handling an OPTIONS HTTP method', done => {243 rq.url = '/';244 rq.method = 'OPTIONS';245 rq.headers = {246 'content-type': 'application/json',247 foo: 'bar'248 };249 router.route(rq, result => {250 try {251 should(handler).not.be.called();252 should(result.response.toJSON()).match({253 raw: false,254 status: 200,255 requestId: rq.requestId,256 content: {257 error: null,258 requestId: 'requestId',259 result: {}260 },261 headers: router.defaultHeaders262 });263 should(result.input.headers).match(rq.headers);264 should(kuzzleMock.pipe)265 .be.calledOnce()266 .be.calledWith('http:options', sinon.match.instanceOf(Request));267 should(kuzzleMock.pipe.firstCall.args[1].input.headers.foo).eql('bar');268 done();269 }270 catch (e) {271 done(e);272 }273 });274 });275 it('should register a default / route with the HEAD verb', done => {276 rq.url = '/';277 rq.method = 'HEAD';278 rq.headers = {279 'content-type': 'application/json',280 foo: 'bar'281 };282 router.route(rq, result => {283 try {284 should(handler).not.be.called();285 should(result.response.toJSON()).match({286 raw: false,287 status: 200,288 requestId: rq.requestId,289 content: {290 error: null,291 requestId: 'requestId',292 result: {}293 },294 headers: router.defaultHeaders295 });296 should(result.input.headers).match(rq.headers);297 done();298 }299 catch (e) {300 done(e);301 }302 });303 });304 it('should return an error if the HTTP method is unknown', done => {305 router.post('/foo/bar', handler);306 rq.url = '/foo/bar';307 rq.method = 'FOOBAR';308 rq.headers['content-type'] = 'application/json';309 rq.addChunk('{"foo": "bar"}');310 router.route(rq, result => {311 try {312 should(handler).have.callCount(0);313 should(result.response.toJSON())314 .match({315 raw: false,316 status: 400,317 requestId: rq.requestId,318 content: {319 error: {320 status: 400,321 id: 'network.http.unsupported_verb'322 },323 requestId: 'requestId',324 result: null325 },326 headers: router.defaultHeaders327 });328 done();329 }330 catch (e) {331 done(e);332 }333 });334 });335 it('should return an error if unable to parse the incoming JSON content', done => {336 router.post('/foo/bar', handler);337 rq.url = '/foo/bar';338 rq.method = 'POST';339 rq.headers['content-type'] = 'application/json';340 rq.addChunk('{bad JSON syntax}');341 router.route(rq, result => {342 try {343 should(handler).not.be.called();344 should(result.response.toJSON()).be.match({345 raw: false,346 status: 400,347 requestId: rq.requestId,348 content: {349 error: {350 status: 400,351 id: 'network.http.body_parse_failed'352 },353 requestId: 'requestId',354 result: null355 },356 headers: router.defaultHeaders357 });358 done();359 }360 catch (e) {361 done(e);362 }363 });364 });365 it('should return an error if unable to parse x-kuzzle-volatile header', done => {366 router.get('/foo/bar', handler);367 rq.url = '/foo/bar';368 rq.method = 'GET';369 rq.headers['content-type'] = 'application/json';370 rq.headers['x-kuzzle-volatile'] = '{bad JSON syntax}';371 router.route(rq, result => {372 try {373 should(handler).not.be.called();374 should(result.response.toJSON()).be.match({375 raw: false,376 status: 400,377 requestId: rq.requestId,378 content: {379 error: {380 status: 400,381 id: 'network.http.volatile_parse_failed'382 },383 requestId: 'requestId',384 result: null385 },386 headers: router.defaultHeaders387 });388 done();389 }390 catch (e) {391 done(e);392 }393 });394 });395 it('should return an error if the content-type is not JSON', done => {396 router.post('/foo/bar', handler);397 rq.url = '/foo/bar';398 rq.method = 'POST';399 rq.headers['content-type'] = 'application/foobar';400 rq.addChunk('{"foo": "bar"}');401 router.route(rq, result => {402 try {403 should(handler).not.be.called();404 should(result.response.toJSON()).match({405 raw: false,406 status: 400,407 requestId: rq.requestId,408 content: {409 error: {410 status: 400,411 id: 'network.http.unsupported_content'412 },413 requestId: 'requestId',414 result: null415 },416 headers: router.defaultHeaders417 });418 done();419 }420 catch (e) {421 done(e);422 }423 });424 });425 it('should send an error if the charset is not utf-8', done => {426 router.post('/foo/bar', handler);427 rq.url = '/foo/bar';428 rq.method = 'POST';429 rq.headers['content-type'] = 'application/json; charset=iso8859-1';430 rq.addChunk('{"foo": "bar"}');431 router.route(rq, result => {432 try {433 should(handler).not.be.called();434 should(result.response.toJSON()).match({435 raw: false,436 status: 400,437 requestId: rq.requestId,438 content: {439 error: {440 status: 400,441 id: 'network.http.unsupported_charset'442 },443 requestId: 'requestId',444 result: null445 },446 headers: router.defaultHeaders447 });448 done();449 }450 catch (e) {451 done(e);452 }453 });454 });455 it('should return an error if the route does not exist', done => {456 router.post('/foo/bar', handler);457 rq.url = '/foo/bar';458 rq.method = 'PUT';459 rq.headers['content-type'] = 'application/json';460 rq.addChunk('{"foo": "bar"}');461 router.route(rq, result => {462 try {463 should(handler).not.be.called();464 should(result.response.toJSON()).match({465 raw: false,466 status: 404,467 requestId: rq.requestId,468 content: {469 error: {470 status: 404,471 id: 'network.http.url_not_found'472 },473 requestId: 'requestId',474 result: null475 },476 headers: router.defaultHeaders477 });478 done();479 }480 catch (e) {481 done(e);482 }483 });484 });485 it('should return an error if an exception is thrown', done => {486 const routeHandlerStub = class {487 get request () {488 throw new InternalError('HTTP internal exception.');489 }490 };491 mockrequire(492 '../../../../lib/core/network/httpRouter/routeHandler',493 routeHandlerStub);494 mockrequire.reRequire('../../../../lib/core/network/httpRouter/routePart');495 const MockRouter = mockrequire.reRequire('../../../../lib/core/network/httpRouter');496 router = new MockRouter(kuzzleMock);497 router.post('/foo/bar', handler);498 rq.url = '/foo/bar';499 rq.method = 'PUT';500 rq.headers['content-type'] = 'application/json';501 rq.addChunk('{"foo": "bar"}');502 router.route(rq, result => {503 try {504 should(handler).not.be.called();505 should(result.response.toJSON()).match({506 raw: false,507 status: 500,508 requestId: rq.requestId,509 content: {510 error: {511 status: 500,512 message: 'HTTP internal exception.'513 },514 requestId: 'requestId',515 result: null516 },517 headers: router.defaultHeaders518 });519 done();520 }521 catch (e) {522 done(e);523 }524 });525 });526 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 console.log('Test Results: %j', data);5});6var wpt = require('webpagetest');7var wpt = new WebPageTest('www.webpagetest.org');8 if (err) return console.error(err);9 console.log('Test Results: %j', data);10});11var wpt = require('webpagetest');12var wpt = new WebPageTest('www.webpagetest.org');13 if (err) return console.error(err);14 console.log('Test Results: %j', data);15});16var wpt = require('webpagetest');17var wpt = new WebPageTest('www.webpagetest.org');18 if (err) return console.error(err);19 console.log('Test Results: %j', data);20});21var wpt = require('webpagetest');22var wpt = new WebPageTest('www.webpagetest.org');23 if (err) return console.error(err);24 console.log('Test Results: %j', data);25});26var wpt = require('webpagetest');27var wpt = new WebPageTest('www.webpagetest.org');28 if (err) return console.error(err);29 console.log('Test Results: %j', data);30});

Full Screen

Using AI Code Generation

copy

Full Screen

1var WebPageTest = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var options = {4}5wpt.runTest(url, options, function(err, data) {6 if (err) return console.error(err);7 console.log('Test %s from %s completed at %s', data.data.id, data.data.from, data.data.completed);8});9 if (!error && response.statusCode == 200) {10 }11})*/

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var options = {3 qs: {4 }5};6request(options, function(error, response, body) {7 if (error) throw new Error(error);8 console.log(body);9});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful