Best JavaScript code snippet using playwright-internal
api.js
Source:api.js
1const debugMode = false;2const axios = require('axios');3axios.defaults.baseURL = 'https://sharedsheets.henrybrink.de/api';4axios.defaults.timeout = 10000;5axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';6const request = async (url, params, method) => {7 switch (method) {8 case 'GET':9 return await axios.get(url, null, {params: params});10 break;11 case 'POST':12 return await axios.post(url, params, null);13 break;14 case 'POST_UPLOAD':15 return await axios.post(url, params, {headers: {'Content-Type': 'multipart/form-data'}})16 break;17 case 'PUT':18 return await axios.put(url, null, {params: params});19 break;20 case 'DELETE':21 return await axios.delete(url, null, {params: params});22 break;23 24 default:25 return await axios.post(url, null, {params: params});26 break;27 }28}29export const setAuthenticationToken = (token) => {30 axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;31}32/**************************************************************************33 USER AUTHENTICATION API34 **************************************************************************/35export const api_login = async (username, password) => {36 if (debugMode) console.log('api_login...');37 try {38 const response = await request('/users/login/web', {username: username, password: password});39 const token = response.data.token;40 axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;41 return token;42 } catch (error) {43 if (debugMode) console.log(error);44 /*if (error.response.data.status === 'error') {45 if (debugMode) console.log(error.response.data.errors);46 }*/47 }48}49export const api_register = async (username, password, email, device_name, secret) => {50 if (debugMode) console.log('api_register...');51 try {52 const response = await request('/users/register', {username: username, password: password, email: email, device_name: device_name, secret: secret});53 const token = response.data.token;54 axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;55 return token;56 } catch (error) {57 if (debugMode) console.log(error);58 /*if (error.response.data.status === 'error') {59 if (debugMode) console.log(error.response.data.errors);60 }*/61 }62}63export const api_logout = async () => {64 if (debugMode) console.log('api_logout...');65 try {66 const response = await request('/users/logout/web', null, 'GET');67 const status = (response.status === 204);68 if (status) axios.defaults.headers.common['Authorization'] = null;69 return (status);70 } catch (error) {71 if (debugMode) console.log(error);72 /*if (error.response.data.status === 'error') {73 if (debugMode) console.log(error.response.data.errors);74 }*/75 }76}77/**************************************************************************78 SHEET API79 **************************************************************************/80export const api_load_available_sheets = async () => {81 if (debugMode) console.log('api_load_available_sheets');82 try {83 const response = await request('/sheets', null, 'GET');84 return response.data;85 } catch (error) {86 if (debugMode) console.log(error);87 } 88}89export const api_load_sheet_by_id = async (id) => {90 if (debugMode) console.log('api_load_sheet_by_id');91 try {92 const response = await request(`/sheets/${id}`, null, 'GET');93 return response.data;94 } catch (error) {95 if (debugMode) console.log(error);96 } 97}98export const api_create_new_sheet = async (title, description, due) => {99 if (debugMode) console.log('api_create_new_sheet');100 try {101 const response = await request('/sheets', {title: title, description: description, due: due}, 'POST');102 return response.data.id;103 } catch (error) {104 if (debugMode) console.log(error);105 }106}107export const api_delete_sheet = async (id) => {108 if (debugMode) console.log('api_delete_sheet');109 try {110 const response = await request(`/sheets/${id}`, null, 'DELETE');111 const status = (response.status === 204);112 return status;113 } catch (error) {114 //if (debugMode) console.log(error);115 }116}117/**************************************************************************118 WIDGET API119 **************************************************************************/120export const api_create_new_widget = async (sheetID, widgetObj) => {121 if (debugMode) console.log('api_create_new_widget');122 try {123 const response = await request(`/sheets/${sheetID}/widgets`, widgetObj, 'POST');124 const status = (response.status === 201);125 return status;126 } catch (error) {127 if (debugMode) console.log(error);128 }129}130export const api_update_widget = async (widgetID, widgetObj) => {131 if (debugMode) console.log('api_update_widget');132 try {133 const response = await request(`/widgets/${widgetID}`, widgetObj, 'PUT');134 const status = (response.status === 200);135 return status;136 } catch (error) {137 if (debugMode) console.log(error);138 }139}140export const api_move_widget = async (widgetID, direction) => {141 if (debugMode) console.log('api_move_widget');142 try {143 const response = await request(`/widgets/${widgetID}/move`, {direction: direction}, 'POST');144 const status = (response.status === 204);145 return status;146 } catch (error) {147 if (debugMode) console.log(error);148 }149}150export const api_load_widget_by_id = async (id) => {151 if (debugMode) console.log('api_load_widget_by_id');152 try {153 const response = await request(`/widgets/${id}`, null, 'GET');154 return response.data;155 } catch (error) {156 // TODO: Fix error (code: 405)157 if (debugMode) console.log(error);158 } 159}160export const api_delete_widget = async (id) => {161 if (debugMode) console.log('api_delete_widget');162 try {163 const response = await request(`/widgets/${id}`, null, 'DELETE');164 const status = (response.status === 204);165 return status;166 } catch (error) {167 if (debugMode) console.log(error);168 }169}170/**************************************************************************171 COURSE API172 **************************************************************************/173export const api_load_available_courses = async () => {174 if (debugMode) console.log('api_load_available_courses');175 try {176 const response = await request('/courses', null, 'GET');177 return response.data;178 } catch (error) {179 if (debugMode) console.log(error);180 } 181}182export const api_create_new_course = async (courseName) => {183 if (debugMode) console.log('api_create_new_course');184 try {185 const response = await request('/courses', {name: courseName}, 'POST');186 const status = (response.status === 201);187 return status;188 } catch (error) {189 if (debugMode) console.log(error);190 }191}192export const api_load_course_by_id = async (courseID) => {193 if (debugMode) console.log('api_load_course_by_id');194 try {195 const response = await request(`/courses/${courseID}`, null, 'GET');196 return response.data;197 } catch (error) {198 if (debugMode) console.log(error);199 } 200}201export const api_delete_course = async (courseID) => {202 if (debugMode) console.log('api_delete_course');203 try {204 const response = await request(`/courses/${courseID}`, null, 'DELETE');205 const status = (response.status === 204);206 return status;207 } catch (error) {208 if (debugMode) console.log(error);209 }210}211export const api_create_new_invite_token = async (courseID) => {212 if (debugMode) console.log('api_create_new_invite_token');213 try {214 const response = await request(`/courses/${courseID}/invites`, null, 'POST');215 return response.data?.token;216 } catch (error) {217 if (debugMode) console.log(error);218 }219}220export const api_join_course_with_token = async (inviteToken) => {221 if (debugMode) console.log('api_join_course_with_token');222 try {223 const response = await request(`/courses/join`, {token: inviteToken}, 'POST');224 return response.status;225 } catch (error) {226 if (debugMode) console.log(error);227 }228}229/**************************************************************************230 SOLUTION API231 **************************************************************************/232export const api_load_solutions_by_widget_id = async (widgetId) => {233 if (debugMode) console.log('api_load_solutions_by_widget_id');234 try {235 const response = await request(`/widgets/${widgetId}/solutions`, null, 'GET');236 return response.data;237 } catch (error) {238 if (debugMode) console.log(error);239 } 240}241export const api_load_all_available_solutions_by_sheet_id = async (sheetId) => {242 if (debugMode) console.log('api_load_all_available_solutions_by_sheet_id');243 try {244 const response = await request(`/sheets/${sheetId}/solutions`, null, 'GET');245 return response.data;246 } catch (error) {247 if (debugMode) console.log(error);248 } 249}250export const api_create_new_solution = async (widgetId, type, contentObj) => {251 if (debugMode) console.log('api_create_new_solution');252 try {253 const response = await request(`/widgets/${widgetId}/solutions`, {type: type, content: contentObj}, 'POST');254 const status = (response.status === 201);255 return status;256 } catch (error) {257 if (debugMode) console.log(error);258 }259}260export const api_upload_new_solution = async (widgetId, formData) => {261 if (debugMode) console.log('api_upload_new_solution');262 try {263 const response = await request(`/widgets/${widgetId}/solutions/upload`, formData, 'POST_UPLOAD');264 const status = (response.status === 201);265 return status;266 } catch (error) {267 if (debugMode) console.log(error);268 }269}270export const api_download_solution_by_solution_id = async (solutionId) => {271 if (debugMode) console.log('api_download_solution_by_solution_id');272 try {273 const response = await request(`/solutions/${solutionId}/download`, null, 'GET');274 if (debugMode) console.log(response)275 const url = window.URL.createObjectURL(new Blob([response.data]));276 const link = document.createElement('a');277 link.href = url;278 const fileType = response.headers['content-disposition'].split('.')[1];279 link.setAttribute('download', `${solutionId}.${fileType}`);280 document.body.appendChild(link);281 link.click();282 link.parentNode.removeChild(link);283 return true;284 } catch (error) {285 if (debugMode) console.log(error);286 } 287}288export const api_delete_solution = async (solutionID) => {289 if (debugMode) console.log('api_delete_solution');290 try {291 const response = await request(`/solutions/${solutionID}`, null, 'DELETE');292 const status = (response.status === 204);293 return status;294 } catch (error) {295 if (debugMode) console.log(error);296 }...
ChatStore.js
Source:ChatStore.js
1import {observable, computed, action, useStrict} from "mobx";2import _ from 'lodash';3import moment from 'moment';4import 'moment/locale/fr';5import 'moment/locale/nl';6import config from './ChatStore.Config';7import ChatClient from './../Services/ChatAxiosClient';8import { startParametersModel } from '../Services/ChatCommonResponseModels';9useStrict();10const storeSessionStorageKey = config.storeSessionStorageKey;11const debugMode = config.debugMode;12const chatClient = new ChatClient({mock: debugMode}); //set mocked api for debug13class ChatStore {14 @observable pollWait = 2000; //default 3s;15 @observable messages = [];16 @observable participants = [];17 @observable language = "en";18 @observable pollingActive = false;19 @observable participantId = "";20 chatId = "";21 participantUserName = "none";22 pollingid = -1;23 headerText = "Chat";24 25 getThemeName = () => {26 let p = JSON.parse(sessionStorage.getItem(storeSessionStorageKey));27 if (debugMode) console.log(`getting theme "${p.theme}"...`); 28 //got params object29 return p.theme;30 }31 32 connect = () => { 33 let p = JSON.parse(sessionStorage.getItem(storeSessionStorageKey));34 if (debugMode) console.log("store connecting with config =", storeSessionStorageKey, sessionStorage.getItem(storeSessionStorageKey)); 35 //got params object36 if (!!p) {37 if (debugMode) console.log("global widget params found:" , p);38 let params = startParametersModel; 39 params.CustomerIdentifier = p.customeridentifier;40 41 //override language42 if (debugMode) console.log(`Widget Language:${p.language} - Browser Language:${navigator.language}`);43 this.language = !!p.language ? p.language : (navigator.language || navigator.userAgent.language);44 if (debugMode) console.log(`Setting language to ${this.language}`); 45 params.WebSiteInfo.Language = p.language;46 47 //create title text param48 this.headerText = (p.title || this.headerText) + " (" + this.language.toUpperCase() + ")";49 50 //override participant username if any51 this.participantUserName = !!p.username ? p.username : this.participantUserName;52 params.Participant.LastName = this.participantUserName;53 params.Participant.Firstname = this.participantUserName;54 if (debugMode) console.log("connecting store to chatapi...", params);55 chatClient.start(params)56 .then(this.connectOk);57 }58 }59 @action connectOk = (connectResponse) => {60 if (!!connectResponse && !!connectResponse.data && connectResponse.data.chat.status.type==="success") {61 let chat = connectResponse.data.chat;62 if (debugMode) console.log("started chat: ", chat.status.type);63 if (debugMode) console.log("updating chat properties: ", chat.status.type);64 //this.messages.length = 0;65 this.chatId = chat.chatID;66 this.participantId = chat.participantID;67 this.pollWait = chat.pollWaitSuggestion; 68 this.parseResponse("start", chat); 69 } else {70 if (debugMode) console.warn("start chat failed: ", connectResponse.data || connectResponse);71 //what to do if failed start? 72 }73 }74 @action startPolling = () => {75 if (this.pollingid!==-1) return; 76 if (debugMode) console.log("start polling:",this.pollWait, this.pollingid);77 this.pollingActive = true;78 this.pollingid = window.setInterval(this.poll, this.pollWait); 79 }80 @action stopPolling = () => { 81 if (debugMode) console.log("stopped polling");82 this.pollingActive = false;83 window.clearInterval(this.pollingid);84 this.pollingid = -1;85 }86 poll = () => {87 if (debugMode) console.log("store polling check: active, pid, pollingId, messages", this.pollingActive, this.participantId, this.pollingid, this.messagesCount);88 if (!this.pollingActive || !this.participantId) return;89 if (debugMode) console.log(`polling ${this.participantId}...`);90 chatClient.poll(this.participantId)91 .then((response) => { 92 let chat = response.data.chat;93 if (debugMode) console.log("poll response:", chat);94 this.parseResponse("poll", chat);95 }96 );97 }98 parseResponse = (action, chat) => {99 if (chat.events && chat.events.length > 0) {100 if (debugMode) console.log(`parsing "${action}" response: ${chat.events.length} events `);101 if (debugMode) console.table(chat.events);102 this.parseEvents(chat.events);103 }104 }105 @action updateParticipants = (event) => {106 if (event.type==="participantState" || event.participantType==="System" ) return;107 let newp = { key:event.participantID, name: event.displayName || "", type: event.participantType || "None", typing: event.state==="active" || false };108 let found = _.find(this.participants, (p) => {return p.key===newp.key} );109 if (found) {110 if (debugMode) console.log("participant found", found);111 //this.participants = _.remove(this.participants, (p) => {return p.key===found.key});112 } else {113 this.participants = _.concat(this.participants, newp);114 } 115 }116 @action parseEvents = (events) => {117 if (debugMode) console.log(`parsing ${events.length} event(s)`, events);118 //this.events = _.concat(this.events, events);119 _.map(_.orderBy(events,e => {return e.sequenceNumber}), (event) => {120 if (event.displayName && event.participantType) this.updateParticipants(event); 121 //todo complete & improve 122 switch (event.type) {123 case "text":124 if (event.value) 125 {126 let sender = (event.participantType==="WebUser") ? 1 : 2;127 let timeStamp = new moment(); timeStamp.locale(this.language);128 this.messages = this.messages.concat([{129 key:event.sequenceNumber, 130 sender:sender, 131 displayName:event.displayName, 132 message:event.value, 133 timeStamp: timeStamp134 }]);135 } 136 break;137 case "participantStateChanged":138 if (debugMode) console.log("participant state:",event);139 break;140 case "typingIndicator":141 if (debugMode) console.log("typing:",event);142 break;143 default:144 break;145 }146 }); 147 }148 149 @action sendMessage(message) {150 message.timeStamp = new moment(); 151 message.timeStamp.locale(this.language);152 chatClient.send(this.particpantId, message.message)153 .then((response) => { 154 if (debugMode) console.log("received send reponse:", response);155 if (!!response.data && !!response.data.chat) this.parseResponse("send", response.data.chat)156 });157 }158 @action disconnect() { 159 if (debugMode) console.log("disconnecting:", this.pollingid, this.participantId);160 if (this.pollingid) window.clearInterval(this.pollingid); 161 chatClient.disconnect(this.participantId)162 .then((response) => this.parseResponse("exit", response.data.chat));163 }164 @computed get messagesCount() {165 return this.messages.length;166 }167 @computed get connected() {168 return !!(this.chatId && this.participantId )169 }170 @computed get participantsList() {171 return this.participants.map((p) => {return p.name});172 }173}...
app.settings.js
Source:app.settings.js
1"use strict";2/**3 * Copyright (C) Patrik Forsberg <patrik.forsberg@coldmind.com> - All Rights Reserved4 * Unauthorized copying of this file, via any medium is strictly prohibited5 * Proprietary and confidential6 */7var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {8 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;9 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);10 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;11 return c > 3 && r && Object.defineProperty(target, key, r), r;12};13var __metadata = (this && this.__metadata) || function (k, v) {14 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);15};16var AppSettings_1;17Object.defineProperty(exports, "__esModule", { value: true });18exports.AppSettings = exports.ServerMode = exports.Networking = void 0;19const cli_commander_1 = require("@cli/cli.commander");20const cli_config_file_1 = require("@cli/cli.config-file");21const cli_logger_1 = require("@cli/cli.logger");22const server_mode_typing_1 = require("@core/settings/server-mode.typing");23const io_utils_1 = require("@core/utils/io-utils");24const inversify_1 = require("inversify");25var Networking;26(function (Networking) {27 //export const webServerPort = 80;28 //export const socketIOPort = process.env.PORT || 5000;29 Networking.socketIOPort = 9090;30 Networking.webSocketPort = 6060;31 Networking.tcpPort = 1681;32 Networking.adminPort = 3000;33})(Networking = exports.Networking || (exports.Networking = {}));34var ServerMode;35(function (ServerMode) {36 ServerMode["Unset"] = "unset";37 ServerMode["Test"] = "test";38 ServerMode["Local"] = "local";39 ServerMode["Live"] = "live";40})(ServerMode = exports.ServerMode || (exports.ServerMode = {}));41var DebugMode;42(function (DebugMode) {43 DebugMode[DebugMode["None"] = 0] = "None";44 DebugMode[DebugMode["All"] = 1] = "All";45 DebugMode[DebugMode["Error"] = 2] = "Error";46 DebugMode[DebugMode["Warning"] = 3] = "Warning";47 DebugMode[DebugMode["Notice"] = 4] = "Notice";48})(DebugMode || (DebugMode = {}));49let AppSettings = AppSettings_1 = class AppSettings {50 constructor() {51 let cliConfig = new cli_config_file_1.CliConfigFile();52 let jsonStr = cliConfig.getConfig(true);53 this.appConfig = this.jsonToAppConfig(jsonStr);54 this.checkSettings();55 }56 /**57 * Sets the Server Mode, the config is populated when the mode is set58 * @param mode59 */60 setServerMode(mode) {61 if (mode === ServerMode.Unset) {62 mode = ServerMode.Local;63 }64 this.applyAppModeSettings(mode);65 // Set DebugMode66 this.debugMode = DebugMode.All;67 switch (this.modeSettings.debugMode) {68 case "none":69 this.debugMode = DebugMode.None;70 break;71 case "all":72 this.debugMode = DebugMode.All;73 break;74 case "error":75 this.debugMode = DebugMode.Error;76 break;77 case "warning":78 this.debugMode = DebugMode.Warning;79 break;80 case "notice":81 this.debugMode = DebugMode.Notice;82 break;83 }84 // Set the static DbSettings85 AppSettings_1.dbSettings = this.modeSettings.database;86 if (AppSettings_1.verboseDebug) {87 cli_logger_1.Logger.logCyan('Mode Settings ::', this.modeSettings);88 }89 }90 applyAppModeSettings(mode) {91 let scope = this;92 function applySettings(settings) {93 // Make sure that the wwwRoot ends with a platform specific slash94 settings.wwwRoot = io_utils_1.IoUtils.ensureTrailingPathDelimiter(settings.wwwRoot);95 scope.modeSettings = new server_mode_typing_1.ServerModeSettings(settings.cors, settings.database, settings.debugMode, settings.domain, settings.listenHost, settings.listenPort, settings.wwwRoot);96 }97 function applyLocalSettings() {98 applySettings(scope.appConfig.serverMode.local);99 }100 function applyLiveSettings() {101 applySettings(scope.appConfig.serverMode.live);102 }103 switch (mode) {104 case ServerMode.Local:105 cli_logger_1.Logger.logGreen("Using Local Settings");106 applyLocalSettings();107 break;108 case ServerMode.Live:109 cli_logger_1.Logger.logGreen("Using Live Settings");110 applyLiveSettings();111 break;112 }113 }114 checkSettings() {115 let mode = cli_commander_1.CliCommander.getParamByName("mode");116 let result = ServerMode.Live;117 switch (mode) {118 case ServerMode.Local:119 result = ServerMode.Local;120 break;121 case ServerMode.Live:122 result = ServerMode.Live;123 break;124 }125 this.setServerMode(result);126 }127 jsonToAppConfig(json) {128 return JSON.parse(json);129 }130};131AppSettings.debug = true;132AppSettings.verboseDebug = true;133AppSettings = AppSettings_1 = __decorate([134 inversify_1.injectable(),135 __metadata("design:paramtypes", [])136], AppSettings);...
restCall.js
Source:restCall.js
1/* This creates a Logger object that can be used to standardise the log output in workflows.2* @Author Yattong Wu3* @Date 18 April 2019 4* @param {REST:RESTHOST} restHost - The Host for REST connections5* @param {string} restMethod - The REST Method: GET/PUT/PATCH/DELETE6* @param {string} restUri - Url for rest command7* @param {string} acceptType - Accept Type response8* @param {string} contentType - Format of content type being sent9* @param {string} content - Content being sent10* @param {Properties} headers - Rest Call Headers11* @param {boolean} throwOnError - Throw error on incorrect response code?12* @return {Any} - The Rest Call Response.13*/14// Set Standard Logging15var objType = "Action";16var objName = "RestCall"; // This must be set to the name of the action17var Logger = System.getModule("london.clouding.logging").standardisedLogger();18var log = new Logger(objType, objName);19// Start logging20log.debug("------ Starting " + objType + " : " + objName + " ------");21// Create Object22function RestCall(restHost, acceptType, contentType, headers){23 // Set Rest Host24 this.restHost = restHost;25 26 // Set headers27 function setHeaders(request,headers,debugMode){28 for each (headerKey in headers.keys){29 var headerValue = headers.get(headerKey);30 if(debugMode == true) log.debug("REST Header: " + headerKey + ":" + headerValue);31 request.setHeader(headerKey, headerValue);32 }33 }34 function logOut(fullUrl,method,content,contentType,acceptType){35 log.debug("URL : "+fullUrl);36 log.debug("REST Method : "+method);37 log.debug("Accept Type : "+acceptType);38 log.debug("Content Type : "+contentType);39 content = (content.match(/password/i) ? JSON.stringify(JSON.parse(content)["password"] = "************") : content;40 log.debug("Content : "+content);41 }42 function execute(request,throwOnError,debugMode){43 var i=0;44 var max=5;45 var interval=(10*1000) // 10 seconds46 var response;47 do{48 log.debug("Attempt "+(i+1)+" of "+max+" REST request execution...");49 response = request.execute();50 i++;51 if(response == null || response >= 400) System.sleep(interval);52 } while ((response == null || response >= 400) && i < max);53 if(response == null || response == >= 400){54 if(throwOnError == true){55 log.error("REST Status Code : "+response.statusCode+"\nREST Response : "+response.ContentAsString);56 } else {57 log.warn("REST Status Code : "+response.statusCode);58 log.warn("REST Response : "+response.ContentAsString);59 }60 }61 if(debugMode == true){62 log.debug("REST Status Code : "+response.statusCode);63 log.debug("REST Response : "+response.ContentAsString);64 }65 return response;66 }67 // function68 this.GET = function (restUri,acceptType,headers,throwOnError,debugMode){69 var request = this.restHost.createRequest("GET", restUri);70 debugMode = (debugMode == null) ? true : false;71 request.setHeader("Accept",acceptType);72 if(headers.keys.length > 0) setHeaders(request,headers,debugMode);73 if(debugMode == true) logOut(request.fullUrl,request.getMethod(),"","",acceptType);74 return execute(request,throwOnError,debugMode);75 }76 77 this.DELETE = function (restUri,acceptType,content,contentType,headers,throwOnError,debugMode){78 var request = this.restHost.createRequest("DELETE", restUri);79 debugMode = (debugMode == null) ? true : false;80 request.setHeader("Accept",acceptType);81 if(headers.keys.length > 0) setHeaders(request,headers,debugMode);82 if(debugMode == true) logOut(request.fullUrl,request.getMethod(),content,contentType,acceptType);83 return execute(request,throwOnError,debugMode);84 }85 this.PATCH = function (restUri,acceptType,content,contentType,headers,throwOnError,debugMode){86 var request = this.restHost.createRequest("PATCH", restUri);87 debugMode = (debugMode == null) ? true : false;88 request.setHeader("Accept",acceptType);89 if(headers.keys.length > 0) setHeaders(request,headers,debugMode);90 if(debugMode == true) logOut(request.fullUrl,request.getMethod(),content,contentType,acceptType);91 return execute(request,throwOnError,debugMode);92 }93 this.PUT = function (restUri,acceptType,content,contentType,headers,throwOnError,debugMode){94 var request = this.restHost.createRequest("PUT", restUri);95 debugMode = (debugMode == null) ? true : false;96 request.setHeader("Accept",acceptType);97 if(headers.keys.length > 0) setHeaders(request,headers,debugMode);98 if(debugMode == true) logOut(request.fullUrl,request.getMethod(),content,contentType,acceptType);99 return execute(request,throwOnError,debugMode);100 }101 this.POST = function (restUri,acceptType,content,contentType,headers,throwOnError,debugMode){102 var request = this.restHost.createRequest("POST", restUri);103 debugMode = (debugMode == null) ? true : false;104 request.setHeader("Accept",acceptType);105 if(headers.keys.length > 0) setHeaders(request,headers,debugMode);106 if(debugMode == true) logOut(request.fullUrl,request.getMethod(),content,contentType,acceptType);107 return execute(request,throwOnError,debugMode);108 }109}...
Github助手.user.js-6e9ca911a9fea97c6ba82991025f007b-debug.js
Source:Github助手.user.js-6e9ca911a9fea97c6ba82991025f007b-debug.js
1// ==UserScript==2// @name debug3// @namespace https://github.com/yeomanye4// @version 0.95// @include *://*6// @description ç¨äºè°è¯çèæ¬åº7// @author Ming Ye8// ==/UserScript==9(function(context) {10 var debugD = true; //debugé»è®¤è®¾ç½®11 //å建åç»æå°12 var consoleFactory = function(groupName, styleStr, type, debugMode) {13 debugMode = (debugMode === undefined) ? myDebugger.debugD : debugMode;14 type = type || 'log';15 /**16 * å建çåç»æå°æ¥å¿17 * @param {bool} debugMode æ¯å¦å¯ç¨æ¥å¿18 */19 var log = function() {20 //åå§åæä½21 log.init();22 if (log.debugMode) {23 var argArr = Array.prototype.slice.apply(arguments);24 console[type].apply(null, argArr);25 }26 }27 log.debugMode = debugMode;28 /**29 * åå§åæä½30 */31 log.init = function(){32 if (!log.nFirst) {33 log.nFirst = true;34 log.groupName = log.groupName || groupName;35 console.group('%c' + log.groupName, styleStr);36 }37 }38 /**39 * æå°å¯¹è±¡40 * @param {string} desc 对象æè¿°41 * @param {object} obj 对象æ°æ®42 */43 log.logObj = function(desc, obj) {44 log.init();45 if (this.debugMode) {46 var argArr = [].slice.call(arguments);47 var desc = argArr.shift();48 argArr.unshift('color:green');49 argArr.unshift(`%c[${desc}]`);50 console.log.apply(console,argArr);51 }52 }53 /**54 * æå°æ°ç»55 * @param {string} desc æ°ç»æè¿°56 * @param {array} arr æ°ç»ç±»å57 */58 log.logArr = function(desc, arr) {59 log.init();60 if (this.debugMode) {61 var argArr = [].slice.call(arguments);62 var desc = argArr.shift();63 console.group(`%c[${desc}]`, 'color:blue;font-size:13px');64 argArr.forEach(item=>{65 console.table(item);66 });67 console.groupEnd();68 }69 }70 /**71 * éç½®åç»æ¥å¿72 * @param {string} groupName æ¥å¿å73 * @param {Boolean} debugMode æ¯å¦å¯ç¨æ¥å¿74 */75 log.reset = function(groupName, debugMode) {76 console.groupEnd();77 log.nFirst = false;78 log.debugMode = (debugMode === undefined) || true;79 log.groupName = groupName || this.groupName;80 }81 /**82 * æè¨83 * @param {bool} expr 表达å¼84 * @param {string} msg æ¶æ¯85 * @param {bool} debugMode æ¯å¦å¯ç¨86 */87 log.assert = function(expr,msg,debugMode){88 debugMode = (debugMode === undefined) || this.debugMode;89 if(debugMode){90 console.assert(expr,msg);91 }92 }93 /**94 * å¼ºè° ç¨äºçªåºæ¾ç¤ºçåºå95 * @param {string} desc 强è°å
容96 * @param {string} bgColor é¢è²97 */98 log.em = function(desc, bgColor) {99 log.init();100 bgColor = bgColor || 'green';101 if (debugMode) {102 console.log(`%c${desc}`, `font-size:18px;background-color:${bgColor};color:white;padding:4px`);103 }104 }105 return log;106 }107 // å½åæ°ä¸ºtrueæ¶å¼å¯è°è¯108 var debugTrue = function(debugMode) {109 debugMode = (debugMode === undefined) ? myDebugger.debugD : debugMode;110 if (debugMode) debugger;111 }112 var myDebugger = {113 consoleFactory: consoleFactory,114 debugTrue: debugTrue,115 debugD:debugD116 };117 context.myDebugger = myDebugger;...
background.js
Source:background.js
1let updtIconAndDescription = (tabId, debugMode) => {2 browser.storage.sync.get(["iconOption"], (result) => {3 let iconOption = 'default';4 if (typeof result !== 'undefined') {5 iconOption = result.iconOption || 'default';6 }7 if (debugMode == '0' || !debugMode || debugMode == '') {8 browser.browserAction.setTitle({ title: 'Click to activate odoo debug mode' });9 browser.browserAction.setIcon({ path: '../icons/' + iconOption + '-off.png', tabId: tabId });10 } else if (debugMode == 'assets') {11 browser.browserAction.setTitle({ title: 'Click to desactivate debug mode with assets' });12 browser.browserAction.setIcon({ path: '../icons/' + iconOption + '-on-assets.png', tabId: tabId });13 } else if (debugMode == '1') {14 browser.browserAction.setTitle({ title: 'Click to desactivate debug mode' });15 browser.browserAction.setIcon({ path: '../icons/' + iconOption + '-on.png', tabId: tabId });16 }17 });18};19// old means before V1320var odooVersion = 'old';21var debugMode = '';22let getVarsAndUpdtIcon = () => {23 browser.tabs.query({24 active: true,25 currentWindow: true26 }, tabs => {27 if (tabs[0]) {28 const tabId = tabs[0].id;29 browser.tabs.sendMessage(tabId, { message: 'get_odoo_data' }, response => {30 if (!browser.runtime.lastError && response) {31 odooVersion = response.odoo_version;32 debugMode = response.debug_mode;33 console.log('odooVersion', odooVersion, 'debugMode', debugMode)34 updtIconAndDescription(tabId, debugMode);35 }36 });37 };38 });39}40let alreadyClicked = false;41let timer;42let updtURL = () => {43 browser.tabs.query({44 active: true,45 currentWindow: true46 }, (tabs) => {47 if (tabs[0]) {48 const tab = tabs[0];49 let newState = '';50 if (alreadyClicked) {51 // if 2 clicks52 clearTimeout(timer);53 if (debugMode == '0' || !debugMode || debugMode == '' || debugMode == '1') {54 newState = 'assets';55 } else {56 newState = 'normal';57 }58 alreadyClicked = false;59 } else {60 // if 1 click61 if (debugMode == '0' || !debugMode || debugMode == '') {62 newState = 'debug';63 } else if (debugMode == '1') {64 newState = 'normal';65 }66 alreadyClicked = true67 // add timer to detect next click68 timer = setTimeout(() => {69 clearTimeout(timer);70 alreadyClicked = false71 }, 250);72 }73 let newStateStr = '';74 if (odooVersion == 'old') {75 if (newState == 'debug') {76 newStateStr = '?debug='77 } else if (newState == 'assets') {78 newStateStr = '?debug=assets'79 }80 } else if (odooVersion == 'new') {81 if (newState == 'normal' && debugMode == '1') {82 newStateStr = '?debug=0'83 } else if (newState == 'debug') {84 newStateStr = '?debug=1'85 } else if (newState == 'assets') {86 newStateStr = '?debug=assets'87 }88 }89 const tabURL = new URL(tab.url);90 browser.tabs.update(tab.id, { url: tab.url = tabURL.origin + tabURL.pathname + newStateStr + tabURL.hash });91 }92 });93};94let updtTabDebugMode = (ev) => {95 getVarsAndUpdtIcon();96 updtURL();97};98// on extension click listeners99browser.browserAction.onClicked.addListener(updtTabDebugMode);100// on key command listeners101browser.commands.onCommand.addListener((command) => {102 if (command == 'toggle-debug') {103 updtTabDebugMode();104 }105});106// on tabs listeners107browser.tabs.onActivated.addListener(getVarsAndUpdtIcon);...
Config.js
Source:Config.js
1/**2 * é»è®¤é
ç½®3 */4define("Config",function(exporter){5 var Config = {};6 7 Config.debugMode = true;8 9 Config.pages = [10 {link:"dataSource.html",enable:true},11 {link:"qualityAnalysis.html",enable:true},12 {link:"qualityMonitoring.html",enable:true},13 {link:"operationAnalysis.html",enable:true},14 {link:"operationMonitoring.html",enable:false},15 {link:"tools.html",enable:false}16 ];17 18 Config.request = {19 getDayKpi:Config.debugMode ? "src/assets/data/getDayKpi.json" :"http://140.205.57.130/portal/diagram/fp!getDayKpi.action",20 getDailyKpi:Config.debugMode ? "src/assets/data/getDailyKpi.json" : "http://140.205.57.130/portal/diagram/fp!getDailyKpi.action",21 getValidMileageRatioTotalMileage:Config.debugMode ? "src/assets/data/getValidMileageRatioTotalMileage.json" : "http://140.205.57.130/portal/diagram/fp!getValidMileageRatioTotalMileage.action",22 getDsPercent:Config.debugMode ? "src/assets/data/getDsPercent.json" : "http://140.205.57.130/portal/diagram/fp!getDsPercent.action",23 getCoveredCitys:Config.debugMode ? "src/assets/data/getCoveredCitys.json" : "http://140.205.57.130/portal/diagram/fp!getCoveredCitys.action",24 25 getRadioResult:Config.debugMode ? "src/assets/data/getRadioResult.json" : "http://140.205.57.130/portal/diagram/bi!getRadioResult.action",26 getPulseResult:Config.debugMode ? "src/assets/data/getPulseResult.json" : "http://140.205.57.130/portal/diagram/bi!getPulseResult.action",27 getRouteAvoidJamResult:Config.debugMode ? "src/assets/data/getRouteAvoidJamResult.json" : "http://140.205.57.130/portal/diagram/bi!getRouteAvoidJamResult.action",28 29 getTrafficFpData:Config.debugMode ? "src/assets/data/201511041845_110000/201511041845_110000.txt" :"../../dc/api/snapshot",30 getTrafficFpData1:Config.debugMode ? "src/assets/data/201511041845_110000/201511041845_110000.txt" :"http://140.205.176.207/TrafficFpData/getData",31 32 getDataSources:Config.debugMode ? "src/assets/data/getDSbyCity.json" : "http://140.205.57.130/portal/fp/component!getDSbyCity.action",33 34 getCitys:Config.debugMode ? "src/assets/data/city.json" : "http://140.205.57.130/portal/fp/component!getCitys.action",35 36 //äºä»¶æ¥å£37 getEventType:Config.debugMode ? "src/assets/data/getEventType.json" :"http://140.205.57.130/portal/diagram/ugc-query!getEventInfos.action",38 //getEventType:Config.debugMode ? "src/assets/data/getEventType.json" :"http://140.205.57.130/portal/diagram/ugc-query!getEventTypes.action",39 queryEventByCity:Config.debugMode ? "src/assets/data/queryEventByCity.json" : "http://140.205.57.130/portal/diagram/ugc-query!queryByCity.action",40 countEventByType:Config.debugMode ? "src/assets/data/countEventByType.json" : "http://140.205.57.130/portal/diagram/ugc-query!countByType.action",41 countEventBySource:Config.debugMode ? "src/assets/data/countEventBySource.json" : "http://140.205.57.130/portal/diagram/ugc-query!countDayCumulativeAndCurrEffective.action",42 countEventByCity:Config.debugMode ? "src/assets/data/countEventByCity.json" : "http://140.205.57.130/portal/diagram/ugc-query!countByCity.action",43 queryEventByCityAndId:Config.debugMode ? "src/assets/data/queryEventByCityAndId.json" : "http://140.205.57.130/portal/diagram/ugc-query!queryByCityAndId.action",44 45 };46 47 return Config;48});49//ç¨äºæ°æ®æºçå
¨å±åé50var cur_selectedIndex = 0;51var cur_selectedIndex1 = 0;52var cur_cityCode = "100000";53var cur_dsCodes;54var cur_dsCodesArr;55var cur_label;56var numShow=false;...
main.js
Source:main.js
1document.addEventListener('DOMContentLoaded', function (event) {2 DebugMode.init();3});4// From https://github.com/thewarpaint/caracteres/blob/master/assets/main.js5var DebugMode = (function () {6 function DebugMode() {}7 DebugMode.prototype.init = function () {8 // Primitive query string parameter check, but enough for our needs.9 // TODO: Add localstorage feature detection.10 if (window.location.search.indexOf('debugMode=true') !== -1) {11 localStorage.setItem('debugMode', 'true');12 } else if (window.location.search.indexOf('debugMode=false') !== -1) {13 localStorage.removeItem('debugMode');14 }15 }16 return new DebugMode();...
Using AI Code Generation
1const { debugMode } = require('playwright/lib/client/debugMode');2debugMode();3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: `example.png` });9 await browser.close();10})();
Using AI Code Generation
1const { debugMode } = require('playwright/lib/server/debug');2debugMode();3const { debugMode } = require('playwright');4debugMode();5const { debugMode } = require('playwright/lib/server/debug');6debugMode();7const { debugMode } = require('playwright/lib/server/debug');8debugMode();9const { debugMode } = require('playwright');10debugMode();11const { debugMode } = require('playwright/lib/server/debug');12debugMode();13const { debugMode } = require('playwright/lib/server/debug');14debugMode();15const { debugMode } = require('playwright');16debugMode();17const { debugMode } = require('playwright/lib/server/debug');18debugMode();19const { debugMode } = require('playwright/lib/server/debug');20debugMode();21const { debugMode } = require('playwright');22debugMode();23const { debugMode } = require('playwright/lib/server/debug');24debugMode();25const { debugMode } = require('playwright/lib/server/debug');26debugMode();27const { debugMode } = require('playwright');28debugMode();29const { debugMode } = require('playwright/lib/server/debug');30debugMode();31const { debugMode } = require('playwright/lib/server/debug');32debugMode();33const { debugMode } = require('playwright');34debugMode();35const { debugMode }
Using AI Code Generation
1const { debugMode } = require('@playwright/test/lib/server/debug');2(async () => {3 const { debugMode } = require('@playwright/test/lib/server/debug');4 const { debugMode } = require('@playwright/test/lib/server/debug');5 await debugMode({6 });7})();8const { test, expect } = require('@playwright/test');9test('Test', async ({ page }) => {10 expect(await page.title()).toBe('Google');11});
Using AI Code Generation
1const playwright = require('playwright');2const debugMode = require('playwright/lib/internal/debugMode');3debugMode.enable();4(async () => {5 const browser = await playwright.chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: 'example.png' });9 await browser.close();10})();11debugMode.disable();12Your name to display (optional):13Your name to display (optional):14const playwright = require('playwright');15const debugMode = require('playwright/lib/internal/debugMode');16debugMode.enable();17(async () => {18 const browser = await playwright.chromium.launch();19 const context = await browser.newContext();20 const page = await context.newPage();21 await page.screenshot({ path: 'example.png' });22 await browser.close();23})();24debugMode.disable();25Your name to display (optional):
LambdaTest’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!!