repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
dockge | github_2023 | louislam | typescript | DockgeServer.initDataDir | initDataDir() {
if (! fs.existsSync(this.config.dataDir)) {
fs.mkdirSync(this.config.dataDir, { recursive: true });
}
// Check if a directory
if (!fs.lstatSync(this.config.dataDir).isDirectory()) {
throw new Error(`Fatal error: ${this.config.dataDir} is not a directory`);
}
// Create data/stacks directory
if (!fs.existsSync(this.stacksDir)) {
fs.mkdirSync(this.stacksDir, { recursive: true });
}
log.info("server", `Data Dir: ${this.config.dataDir}`);
} | /**
* Initialize the data directory
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L541-L557 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | DockgeServer.initJWTSecret | async initJWTSecret() : Promise<Bean> {
let jwtSecretBean = await R.findOne("setting", " `key` = ? ", [
"jwtSecret",
]);
if (!jwtSecretBean) {
jwtSecretBean = R.dispense("setting");
jwtSecretBean.key = "jwtSecret";
}
jwtSecretBean.value = generatePasswordHash(genSecret());
await R.store(jwtSecretBean);
return jwtSecretBean;
} | /**
* Init or reset JWT secret
* @returns JWT secret
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L563-L576 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | DockgeServer.sendStackList | async sendStackList(useCache = false) {
let socketList = this.io.sockets.sockets.values();
let stackList;
for (let socket of socketList) {
let dockgeSocket = socket as DockgeSocket;
// Check if the room is a number (user id)
if (dockgeSocket.userID) {
// Get the list only if there is a logged in user
if (!stackList) {
stackList = await Stack.getStackList(this, useCache);
}
let map : Map<string, object> = new Map();
for (let [ stackName, stack ] of stackList) {
map.set(stackName, stack.toSimpleJSON(dockgeSocket.endpoint));
}
log.debug("server", "Send stack list to user: " + dockgeSocket.id + " (" + dockgeSocket.endpoint + ")");
dockgeSocket.emitAgent("stackList", {
ok: true,
stackList: Object.fromEntries(map),
});
}
}
} | /**
* Send stack list to all connected sockets
* @param useCache
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L582-L611 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | DockgeServer.shutdownFunction | async shutdownFunction(signal : string | undefined) {
log.info("server", "Shutdown requested");
log.info("server", "Called signal: " + signal);
// TODO: Close all terminals?
await Database.close();
Settings.stopCacheCleaner();
} | /**
* Shutdown the application
* Stops all monitors and closes the database connection.
* @param signal The signal that triggered this function to be called.
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L643-L651 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | DockgeServer.finalFunction | finalFunction() {
log.info("server", "Graceful shutdown successful!");
} | /**
* Final function called before application exits
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L656-L658 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | DockgeServer.disconnectAllSocketClients | disconnectAllSocketClients(userID: number | undefined, currentSocketID? : string) {
for (const rawSocket of this.io.sockets.sockets.values()) {
let socket = rawSocket as DockgeSocket;
if ((!userID || socket.userID === userID) && socket.id !== currentSocketID) {
try {
socket.emit("refresh");
socket.disconnect();
} catch (e) {
}
}
}
} | /**
* Force connected sockets of a user to refresh and disconnect.
* Used for resetting password.
* @param {string} userID
* @param {string?} currentSocketID
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L666-L678 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Logger.constructor | constructor() {
if (typeof process !== "undefined" && process.env.DOCKGE_HIDE_LOG) {
const list = process.env.DOCKGE_HIDE_LOG.split(",").map(v => v.toLowerCase());
for (const pair of list) {
// split first "_" only
const values = pair.split(/_(.*)/s);
if (values.length >= 2) {
this.hideLog[values[0]].push(values[1]);
}
}
this.debug("server", "DOCKGE_HIDE_LOG is set");
this.debug("server", this.hideLog);
}
} | /**
*
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/log.ts#L81-L97 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Logger.log | log(module: string, msg: unknown, level: string) {
if (level === "DEBUG" && !isDev) {
return;
}
if (this.hideLog[level] && this.hideLog[level].includes(module.toLowerCase())) {
return;
}
module = module.toUpperCase();
level = level.toUpperCase();
let now;
if (dayjs.tz) {
now = dayjs.tz(new Date()).format();
} else {
now = dayjs().format();
}
const levelColor = consoleLevelColors[level];
const moduleColor = consoleModuleColors[intHash(module, consoleModuleColors.length)];
let timePart = CONSOLE_STYLE_FgCyan + now + CONSOLE_STYLE_Reset;
const modulePart = "[" + moduleColor + module + CONSOLE_STYLE_Reset + "]";
const levelPart = levelColor + `${level}:` + CONSOLE_STYLE_Reset;
if (level === "INFO") {
console.info(timePart, modulePart, levelPart, msg);
} else if (level === "WARN") {
console.warn(timePart, modulePart, levelPart, msg);
} else if (level === "ERROR") {
let msgPart : unknown;
if (typeof msg === "string") {
msgPart = CONSOLE_STYLE_FgRed + msg + CONSOLE_STYLE_Reset;
} else {
msgPart = msg;
}
console.error(timePart, modulePart, levelPart, msgPart);
} else if (level === "DEBUG") {
if (isDev) {
timePart = CONSOLE_STYLE_FgGray + now + CONSOLE_STYLE_Reset;
let msgPart : unknown;
if (typeof msg === "string") {
msgPart = CONSOLE_STYLE_FgGray + msg + CONSOLE_STYLE_Reset;
} else {
msgPart = msg;
}
console.debug(timePart, modulePart, levelPart, msgPart);
}
} else {
console.log(timePart, modulePart, msg);
}
} | /**
* Write a message to the log
* @param module The module the log comes from
* @param msg Message to write
* @param level Log level. One of INFO, WARN, ERROR, DEBUG or can be customized.
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/log.ts#L105-L157 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Logger.info | info(module: string, msg: unknown) {
this.log(module, msg, "info");
} | /**
* Log an INFO message
* @param module Module log comes from
* @param msg Message to write
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/log.ts#L164-L166 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Logger.warn | warn(module: string, msg: unknown) {
this.log(module, msg, "warn");
} | /**
* Log a WARN message
* @param module Module log comes from
* @param msg Message to write
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/log.ts#L173-L175 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Logger.error | error(module: string, msg: unknown) {
this.log(module, msg, "error");
} | /**
* Log an ERROR message
* @param module Module log comes from
* @param msg Message to write
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/log.ts#L182-L184 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Logger.debug | debug(module: string, msg: unknown) {
this.log(module, msg, "debug");
} | /**
* Log a DEBUG message
* @param module Module log comes from
* @param msg Message to write
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/log.ts#L191-L193 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Logger.exception | exception(module: string, exception: unknown, msg: unknown) {
let finalMessage = exception;
if (msg) {
finalMessage = `${msg}: ${exception}`;
}
this.log(module, finalMessage, "error");
} | /**
* Log an exception as an ERROR
* @param module Module log comes from
* @param exception The exception to include
* @param msg The message to write
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/log.ts#L201-L209 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | KumaRateLimiter.constructor | constructor(config : KumaRateLimiterOpts) {
this.errorMessage = config.errorMessage;
this.rateLimiter = new RateLimiter(config);
} | /**
* @param {object} config Rate limiter configuration object
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/rate-limiter.ts#L20-L23 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | KumaRateLimiter.pass | async pass(callback : KumaRateLimiterCallback, num = 1) {
const remainingRequests = await this.removeTokens(num);
log.info("rate-limit", "remaining requests: " + remainingRequests);
if (remainingRequests < 0) {
if (callback) {
callback({
ok: false,
msg: this.errorMessage,
});
}
return false;
}
return true;
} | /**
* Should the request be passed through
* @param callback Callback function to call with decision
* @param {number} num Number of tokens to remove
* @returns {Promise<boolean>} Should the request be allowed?
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/rate-limiter.ts#L37-L50 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | KumaRateLimiter.removeTokens | async removeTokens(num = 1) {
return await this.rateLimiter.removeTokens(num);
} | /**
* Remove a given number of tokens
* @param {number} num Number of tokens to remove
* @returns {Promise<number>} Number of remaining tokens
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/rate-limiter.ts#L57-L59 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Settings.get | static async get(key : string) {
// Start cache clear if not started yet
if (!Settings.cacheCleaner) {
Settings.cacheCleaner = setInterval(() => {
log.debug("settings", "Cache Cleaner is just started.");
for (key in Settings.cacheList) {
if (Date.now() - Settings.cacheList[key].timestamp > 60 * 1000) {
log.debug("settings", "Cache Cleaner deleted: " + key);
delete Settings.cacheList[key];
}
}
}, 60 * 1000);
}
// Query from cache
if (key in Settings.cacheList) {
const v = Settings.cacheList[key].value;
log.debug("settings", `Get Setting (cache): ${key}: ${v}`);
return v;
}
const value = await R.getCell("SELECT `value` FROM setting WHERE `key` = ? ", [
key,
]);
try {
const v = JSON.parse(value);
log.debug("settings", `Get Setting: ${key}: ${v}`);
Settings.cacheList[key] = {
value: v,
timestamp: Date.now()
};
return v;
} catch (e) {
return value;
}
} | /**
* Retrieve value of setting based on key
* @param key Key of setting to retrieve
* @returns Value
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/settings.ts#L31-L71 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Settings.set | static async set(key : string, value : object | string | number | boolean, type : string | null = null) {
let bean = await R.findOne("setting", " `key` = ? ", [
key,
]);
if (!bean) {
bean = R.dispense("setting");
bean.key = key;
}
bean.type = type;
bean.value = JSON.stringify(value);
await R.store(bean);
Settings.deleteCache([ key ]);
} | /**
* Sets the specified setting to specified value
* @param key Key of setting to set
* @param value Value to set to
* @param {?string} type Type of setting
* @returns {Promise<void>}
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/settings.ts#L80-L94 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Settings.getSettings | static async getSettings(type : string) {
const list = await R.getAll("SELECT `key`, `value` FROM setting WHERE `type` = ? ", [
type,
]);
const result : LooseObject = {};
for (const row of list) {
try {
result[row.key] = JSON.parse(row.value);
} catch (e) {
result[row.key] = row.value;
}
}
return result;
} | /**
* Get settings based on type
* @param type The type of setting
* @returns Settings
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/settings.ts#L101-L117 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Settings.setSettings | static async setSettings(type : string, data : LooseObject) {
const keyList = Object.keys(data);
const promiseList = [];
for (const key of keyList) {
let bean = await R.findOne("setting", " `key` = ? ", [
key
]);
if (bean == null) {
bean = R.dispense("setting");
bean.type = type;
bean.key = key;
}
if (bean.type === type) {
bean.value = JSON.stringify(data[key]);
promiseList.push(R.store(bean));
}
}
await Promise.all(promiseList);
Settings.deleteCache(keyList);
} | /**
* Set settings based on type
* @param type Type of settings to set
* @param data Values of settings
* @returns {Promise<void>}
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/settings.ts#L125-L150 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Settings.deleteCache | static deleteCache(keyList : string[]) {
for (const key of keyList) {
delete Settings.cacheList[key];
}
} | /**
* Delete selected keys from settings cache
* @param {string[]} keyList Keys to remove
* @returns {void}
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/settings.ts#L157-L161 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Settings.stopCacheCleaner | static stopCacheCleaner() {
if (Settings.cacheCleaner) {
clearInterval(Settings.cacheCleaner);
Settings.cacheCleaner = undefined;
}
} | /**
* Stop the cache cleaner if running
* @returns {void}
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/settings.ts#L167-L172 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Stack.ps | async ps() : Promise<object> {
let res = await childProcessAsync.spawn("docker", [ "compose", "ps", "--format", "json" ], {
cwd: this.path,
encoding: "utf-8",
});
if (!res.stdout) {
return {};
}
return JSON.parse(res.stdout.toString());
} | /**
* Get the status of the stack from `docker compose ps --format json`
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/stack.ts#L95-L104 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Stack.save | async save(isAdd : boolean) {
this.validate();
let dir = this.path;
// Check if the name is used if isAdd
if (isAdd) {
if (await fileExists(dir)) {
throw new ValidationError("Stack name already exists");
}
// Create the stack folder
await fsAsync.mkdir(dir);
} else {
if (!await fileExists(dir)) {
throw new ValidationError("Stack not found");
}
}
// Write or overwrite the compose.yaml
await fsAsync.writeFile(path.join(dir, this._composeFileName), this.composeYAML);
const envPath = path.join(dir, ".env");
// Write or overwrite the .env
// If .env is not existing and the composeENV is empty, we don't need to write it
if (await fileExists(envPath) || this.composeENV.trim() !== "") {
await fsAsync.writeFile(envPath, this.composeENV);
}
} | /**
* Save the stack to the disk
* @param isAdd
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/stack.ts#L178-L207 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Stack.composeFileExists | static async composeFileExists(stacksDir : string, filename : string) : Promise<boolean> {
let filenamePath = path.join(stacksDir, filename);
// Check if any compose file exists
for (const filename of acceptedComposeFileNames) {
let composeFile = path.join(filenamePath, filename);
if (await fileExists(composeFile)) {
return true;
}
}
return false;
} | /**
* Checks if a compose file exists in the specified directory.
* @async
* @static
* @param {string} stacksDir - The directory of the stack.
* @param {string} filename - The name of the directory to check for the compose file.
* @returns {Promise<boolean>} A promise that resolves to a boolean indicating whether any compose file exists.
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/stack.ts#L253-L263 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Stack.getStatusList | static async getStatusList() : Promise<Map<string, number>> {
let statusList = new Map<string, number>();
let res = await childProcessAsync.spawn("docker", [ "compose", "ls", "--all", "--format", "json" ], {
encoding: "utf-8",
});
if (!res.stdout) {
return statusList;
}
let composeList = JSON.parse(res.stdout.toString());
for (let composeStack of composeList) {
statusList.set(composeStack.Name, this.statusConvert(composeStack.Status));
}
return statusList;
} | /**
* Get the status list, it will be used to update the status of the stacks
* Not all status will be returned, only the stack that is deployed or created to `docker compose` will be returned
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/stack.ts#L338-L356 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Stack.statusConvert | static statusConvert(status : string) : number {
if (status.startsWith("created")) {
return CREATED_STACK;
} else if (status.includes("exited")) {
// If one of the service is exited, we consider the stack is exited
return EXITED;
} else if (status.startsWith("running")) {
// If there is no exited services, there should be only running services
return RUNNING;
} else {
return UNKNOWN;
}
} | /**
* Convert the status string from `docker compose ls` to the status number
* Input Example: "exited(1), running(1)"
* @param status
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/stack.ts#L363-L375 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Terminal.exit | protected exit = (res : {exitCode: number, signal?: number | undefined}) => {
for (const socketID in this.socketList) {
const socket = this.socketList[socketID];
socket.emitAgent("terminalExit", this.name, res.exitCode);
}
// Remove all clients
this.socketList = {};
Terminal.terminalMap.delete(this.name);
log.debug("Terminal", "Terminal " + this.name + " exited with code " + res.exitCode);
clearInterval(this.keepAliveInterval);
clearInterval(this.kickDisconnectedClientsInterval);
if (this.callback) {
this.callback(res.exitCode);
}
} | /**
* Exit event handler
* @param res
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/terminal.ts | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Terminal.getBuffer | getBuffer() : string {
if (this.buffer.length === 0) {
return "";
}
return this.buffer.join("");
} | /**
* Get the terminal output string
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/terminal.ts#L196-L201 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Terminal.getTerminal | public static getTerminal(name : string) : Terminal | undefined {
return Terminal.terminalMap.get(name);
} | /**
* Get a running and non-exited terminal
* @param name
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/terminal.ts#L213-L215 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | User.resetPassword | static async resetPassword(userID : number, newPassword : string) {
await R.exec("UPDATE `user` SET password = ? WHERE id = ? ", [
generatePasswordHash(newPassword),
userID
]);
} | /**
* Reset user password
* Fix #1510, as in the context reset-password.js, there is no auto model mapping. Call this static function instead.
* @param {number} userID ID of user to update
* @param {string} newPassword Users new password
* @returns {Promise<void>}
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/models/user.ts#L14-L19 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | User.resetPassword | async resetPassword(newPassword : string) {
await User.resetPassword(this.id, newPassword);
this.password = newPassword;
} | /**
* Reset this users password
* @param {string} newPassword
* @returns {Promise<void>}
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/models/user.ts#L26-L29 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | User.createJWT | static createJWT(user : User, jwtSecret : string) {
return jwt.sign({
username: user.username,
h: shake256(user.password, SHAKE256_LENGTH),
}, jwtSecret);
} | /**
* Create a new JWT for a user
* @param {User} user The User to create a JsonWebToken for
* @param {string} jwtSecret The key used to sign the JsonWebToken
* @returns {string} the JsonWebToken as a string
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/models/user.ts#L37-L42 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | copyYAMLCommentsItems | function copyYAMLCommentsItems(items: any, srcItems: any) {
if (!items || !srcItems) {
return;
}
// First pass - try to match items by their content
for (let i = 0; i < items.length; i++) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const item: any = items[i];
// Try to find matching source item by content
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const srcIndex = srcItems.findIndex((srcItem: any) =>
JSON.stringify(srcItem.value) === JSON.stringify(item.value) &&
JSON.stringify(srcItem.key) === JSON.stringify(item.key)
);
if (srcIndex !== -1) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const srcItem: any = srcItems[srcIndex];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const nextSrcItem: any = srcItems[srcIndex + 1];
if (item.key && srcItem.key) {
item.key.comment = srcItem.key.comment;
item.key.commentBefore = srcItem.key.commentBefore;
}
if (srcItem.comment) {
item.comment = srcItem.comment;
}
// Handle comments between array items
if (nextSrcItem && nextSrcItem.commentBefore) {
if (items[i + 1]) {
items[i + 1].commentBefore = nextSrcItem.commentBefore;
}
}
// Handle trailing comments after array items
if (srcItem.value && srcItem.value.comment) {
if (item.value) {
item.value.comment = srcItem.value.comment;
}
}
if (item.value && srcItem.value) {
if (typeof item.value === "object" && typeof srcItem.value === "object") {
item.value.comment = srcItem.value.comment;
item.value.commentBefore = srcItem.value.commentBefore;
if (item.value.items && srcItem.value.items) {
copyYAMLCommentsItems(item.value.items, srcItem.value.items);
}
}
}
}
}
} | /**
* Copy yaml comments from srcItems to items
* Attempts to preserve comments by matching content rather than just array indices
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/common/util-common.ts#L242-L300 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | traverseYAML | function traverseYAML(pair : Pair, env : DotenvParseOutput) : void {
// @ts-ignore
if (pair.value && pair.value.items) {
// @ts-ignore
for (const item of pair.value.items) {
if (item instanceof Pair) {
traverseYAML(item, env);
} else if (item instanceof Scalar) {
let value = item.value as unknown;
if (typeof(value) === "string") {
item.value = envsubst(value, env);
}
}
}
// @ts-ignore
} else if (pair.value && typeof(pair.value.value) === "string") {
// @ts-ignore
pair.value.value = envsubst(pair.value.value, env);
}
} | /**
* Used for envsubstYAML(...)
* @param pair
* @param env
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/common/util-common.ts#L409-L429 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | question | function question(question : string) : Promise<string> {
return new Promise((resolve) => {
rl.question(question, (answer) => {
resolve(answer);
});
});
} | /**
* Ask question of user
* @param question Question to ask
* @returns Users response
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/extra/reset-password.ts#L79-L85 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | commit | function commit(version) {
let msg = "Update to " + version;
let res = childProcess.spawnSync("git", [ "commit", "-m", msg, "-a" ]);
let stdout = res.stdout.toString().trim();
console.log(stdout);
if (stdout.includes("no changes added to commit")) {
throw new Error("commit error");
}
} | /**
* Commit updated files
* @param {string} version Version to update to
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/extra/update-version.ts#L30-L40 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | tag | function tag(version) {
let res = childProcess.spawnSync("git", [ "tag", version ]);
console.log(res.stdout.toString().trim());
} | /**
* Create a tag with the specified version
* @param {string} version Tag to create
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/extra/update-version.ts#L46-L49 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | tagExists | function tagExists(version) {
if (! version) {
throw new Error("invalid version");
}
let res = childProcess.spawnSync("git", [ "tag", "-l", version ]);
return res.stdout.toString().trim() === version;
} | /**
* Check if a tag exists for the specified version
* @param {string} version Version to check
* @returns {boolean} Does the tag already exist
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/extra/update-version.ts#L56-L64 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | rootApp | function rootApp() {
const toast = useToast();
return defineComponent({
mixins: [
socket,
lang,
theme,
],
data() {
return {
loggedIn: false,
allowLoginDialog: false,
username: null,
};
},
computed: {
},
methods: {
/**
* Show success or error toast dependant on response status code
* @param {object} res Response object
* @returns {void}
*/
toastRes(res) {
let msg = res.msg;
if (res.msgi18n) {
if (msg != null && typeof msg === "object") {
msg = this.$t(msg.key, msg.values);
} else {
msg = this.$t(msg);
}
}
if (res.ok) {
toast.success(msg);
} else {
toast.error(msg);
}
},
/**
* Show a success toast
* @param {string} msg Message to show
* @returns {void}
*/
toastSuccess(msg : string) {
toast.success(this.$t(msg));
},
/**
* Show an error toast
* @param {string} msg Message to show
* @returns {void}
*/
toastError(msg : string) {
toast.error(this.$t(msg));
},
},
render: () => h(App),
});
} | /**
* Root Vue component
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/frontend/src/main.ts#L43-L105 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | getTimezoneOffset | function getTimezoneOffset(timeZone : string) {
const now = new Date();
const tzString = now.toLocaleString("en-US", {
timeZone,
});
const localString = now.toLocaleString("en-US");
const diff = (Date.parse(localString) - Date.parse(tzString)) / 3600000;
const offset = diff + now.getTimezoneOffset() / 60;
return -offset;
} | /**
* Returns the offset from UTC in hours for the current locale.
* @param {string} timeZone Timezone to get offset for
* @returns {number} The offset from UTC in hours.
*
* Generated by Trelent
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/frontend/src/util-frontend.ts#L13-L22 | d451e06e8428f1bf987595bf51d65f82241294cd |
maxun | github_2023 | getmaxun | typescript | Interpreter.getSelectors | private getSelectors(workflow: Workflow): string[] {
const selectorsSet = new Set<string>();
if (workflow.length === 0) {
return [];
}
for (let index = workflow.length - 1; index >= 0; index--) {
const currentSelectors = workflow[index]?.where?.selectors;
if (currentSelectors && currentSelectors.length > 0) {
currentSelectors.forEach((selector) => selectorsSet.add(selector));
return Array.from(selectorsSet);
}
}
return [];
} | // } | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/interpret.ts#L159-L176 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | Interpreter.getState | private async getState(page: Page, workflowCopy: Workflow, selectors: string[]): Promise<PageState> {
/**
* All the selectors present in the current Workflow
*/
// const selectors = Preprocessor.extractSelectors(workflow);
// console.log("Current selectors:", selectors);
/**
* Determines whether the element targetted by the selector is [actionable](https://playwright.dev/docs/actionability).
* @param selector Selector to be queried
* @returns True if the targetted element is actionable, false otherwise.
*/
// const actionable = async (selector: string): Promise<boolean> => {
// try {
// const proms = [
// page.isEnabled(selector, { timeout: 10000 }),
// page.isVisible(selector, { timeout: 10000 }),
// ];
// return await Promise.all(proms).then((bools) => bools.every((x) => x));
// } catch (e) {
// // log(<Error>e, Level.ERROR);
// return false;
// }
// };
/**
* Object of selectors present in the current page.
*/
// const presentSelectors: SelectorArray = await Promise.all(
// selectors.map(async (selector) => {
// if (await actionable(selector)) {
// return [selector];
// }
// return [];
// }),
// ).then((x) => x.flat());
const presentSelectors: SelectorArray = await Promise.all(
selectors.map(async (selector) => {
try {
await page.waitForSelector(selector, { state: 'attached' });
return [selector];
} catch (e) {
return [];
}
}),
).then((x) => x.flat());
const action = workflowCopy[workflowCopy.length - 1];
// console.log("Next action:", action)
let url: any = page.url();
if (action && action.where.url !== url && action.where.url !== "about:blank") {
url = action.where.url;
}
return {
url,
cookies: (await page.context().cookies([page.url()]))
.reduce((p, cookie) => (
{
...p,
[cookie.name]: cookie.value,
}), {}),
selectors: presentSelectors,
};
} | /**
* Returns the context object from given Page and the current workflow.\
* \
* `workflow` is used for selector extraction - function searches for used selectors to
* look for later in the page's context.
* @param page Playwright Page object
* @param workflow Current **initialized** workflow (array of where-what pairs).
* @returns {PageState} State of the current page.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/interpret.ts#L188-L257 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | Interpreter.applicable | private applicable(where: Where, context: PageState, usedActions: string[] = []): boolean {
/**
* Given two arbitrary objects, determines whether `subset` is a subset of `superset`.\
* \
* For every key in `subset`, there must be a corresponding key with equal scalar
* value in `superset`, or `inclusive(subset[key], superset[key])` must hold.
* @param subset Arbitrary non-cyclic JS object (where clause)
* @param superset Arbitrary non-cyclic JS object (browser context)
* @returns `true` if `subset <= superset`, `false` otherwise.
*/
const inclusive = (subset: Record<string, unknown>, superset: Record<string, unknown>)
: boolean => (
Object.entries(subset).every(
([key, value]) => {
/**
* Arrays are compared without order (are transformed into objects before comparison).
*/
const parsedValue = Array.isArray(value) ? arrayToObject(value) : value;
const parsedSuperset: Record<string, unknown> = {};
parsedSuperset[key] = Array.isArray(superset[key])
? arrayToObject(<any>superset[key])
: superset[key];
// Every `subset` key must exist in the `superset` and
// have the same value (strict equality), or subset[key] <= superset[key]
return parsedSuperset[key]
&& (
(parsedSuperset[key] === parsedValue)
|| ((parsedValue).constructor.name === 'RegExp' && (<RegExp>parsedValue).test(<string>parsedSuperset[key]))
|| (
(parsedValue).constructor.name !== 'RegExp'
&& typeof parsedValue === 'object' && inclusive(<typeof subset>parsedValue, <typeof superset>parsedSuperset[key])
)
);
},
)
);
// Every value in the "where" object should be compliant to the current state.
return Object.entries(where).every(
([key, value]) => {
if (operators.includes(<any>key)) {
const array = Array.isArray(value)
? value as Where[]
: Object.entries(value).map((a) => Object.fromEntries([a]));
// every condition is treated as a single context
switch (key as keyof typeof operators) {
case '$and' as keyof typeof operators:
return array?.every((x) => this.applicable(x, context));
case '$or' as keyof typeof operators:
return array?.some((x) => this.applicable(x, context));
case '$not' as keyof typeof operators:
return !this.applicable(<Where>value, context); // $not should be a unary operator
default:
throw new Error('Undefined logic operator.');
}
} else if (meta.includes(<any>key)) {
const testRegexString = (x: string) => {
if (typeof value === 'string') {
return x === value;
}
return (<RegExp><unknown>value).test(x);
};
switch (key as keyof typeof meta) {
case '$before' as keyof typeof meta:
return !usedActions.find(testRegexString);
case '$after' as keyof typeof meta:
return !!usedActions.find(testRegexString);
default:
throw new Error('Undefined meta operator.');
}
} else {
// Current key is a base condition (url, cookies, selectors)
return inclusive({ [key]: value }, context);
}
},
);
} | /**
* Tests if the given action is applicable with the given context.
* @param where Tested *where* condition
* @param context Current browser context.
* @returns True if `where` is applicable in the given context, false otherwise
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/interpret.ts#L265-L346 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | inclusive | const inclusive = (subset: Record<string, unknown>, superset: Record<string, unknown>)
: boolean => (
Object.entries(subset).every(
([key, value]) => {
/**
* Arrays are compared without order (are transformed into objects before comparison).
*/
const parsedValue = Array.isArray(value) ? arrayToObject(value) : value;
const parsedSuperset: Record<string, unknown> = {};
parsedSuperset[key] = Array.isArray(superset[key])
? arrayToObject(<any>superset[key])
: superset[key];
// Every `subset` key must exist in the `superset` and
// have the same value (strict equality), or subset[key] <= superset[key]
return parsedSuperset[key]
&& (
(parsedSuperset[key] === parsedValue)
|| ((parsedValue).constructor.name === 'RegExp' && (<RegExp>parsedValue).test(<string>parsedSuperset[key]))
|| (
(parsedValue).constructor.name !== 'RegExp'
&& typeof parsedValue === 'object' && inclusive(<typeof subset>parsedValue, <typeof superset>parsedSuperset[key])
)
);
},
)
); | /**
* Given two arbitrary objects, determines whether `subset` is a subset of `superset`.\
* \
* For every key in `subset`, there must be a corresponding key with equal scalar
* value in `superset`, or `inclusive(subset[key], superset[key])` must hold.
* @param subset Arbitrary non-cyclic JS object (where clause)
* @param superset Arbitrary non-cyclic JS object (browser context)
* @returns `true` if `subset <= superset`, `false` otherwise.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/interpret.ts#L275-L302 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | Interpreter.carryOutSteps | private async carryOutSteps(page: Page, steps: What[]): Promise<void> {
/**
* Defines overloaded (or added) methods/actions usable in the workflow.
* If a method overloads any existing method of the Page class, it accepts the same set
* of parameters *(but can override some!)*\
* \
* Also, following piece of code defines functions to be run in the browser's context.
* Beware of false linter errors - here, we know better!
*/
const wawActions: Record<CustomFunctions, (...args: any[]) => void> = {
screenshot: async (params: PageScreenshotOptions) => {
const screenshotBuffer = await page.screenshot({
...params, path: undefined,
});
await this.options.binaryCallback(screenshotBuffer, 'image/png');
},
enqueueLinks: async (selector: string) => {
const links: string[] = await page.locator(selector)
.evaluateAll(
// @ts-ignore
(elements) => elements.map((a) => a.href).filter((x) => x),
);
const context = page.context();
for (const link of links) {
// eslint-disable-next-line
this.concurrency.addJob(async () => {
try {
const newPage = await context.newPage();
await newPage.goto(link);
await newPage.waitForLoadState('networkidle');
await this.runLoop(newPage, this.initializedWorkflow!);
} catch (e) {
// `runLoop` uses soft mode, so it recovers from it's own exceptions
// but newPage(), goto() and waitForLoadState() don't (and will kill
// the interpreter by throwing).
this.log(<Error>e, Level.ERROR);
}
});
}
await page.close();
},
scrape: async (selector?: string) => {
await this.ensureScriptsLoaded(page);
const scrapeResults: Record<string, string>[] = await page.evaluate((s) => window.scrape(s ?? null), selector);
await this.options.serializableCallback(scrapeResults);
},
scrapeSchema: async (schema: Record<string, { selector: string; tag: string, attribute: string; shadow: string}>) => {
await this.ensureScriptsLoaded(page);
const scrapeResult = await page.evaluate((schemaObj) => window.scrapeSchema(schemaObj), schema);
const newResults = Array.isArray(scrapeResult) ? scrapeResult : [scrapeResult];
newResults.forEach((result) => {
Object.entries(result).forEach(([key, value]) => {
const keyExists = this.cumulativeResults.some(
(item) => key in item && item[key] !== undefined
);
if (!keyExists) {
this.cumulativeResults.push({ [key]: value });
}
});
});
const mergedResult: Record<string, string>[] = [
Object.fromEntries(
Object.entries(
this.cumulativeResults.reduce((acc, curr) => {
Object.entries(curr).forEach(([key, value]) => {
// If the key doesn't exist or the current value is not undefined, add/update it
if (value !== undefined) {
acc[key] = value;
}
});
return acc;
}, {})
)
)
];
// Log cumulative results after each action
console.log("CUMULATIVE results:", this.cumulativeResults);
console.log("MERGED results:", mergedResult);
await this.options.serializableCallback(mergedResult);
// await this.options.serializableCallback(scrapeResult);
},
scrapeList: async (config: { listSelector: string, fields: any, limit?: number, pagination: any }) => {
await this.ensureScriptsLoaded(page);
if (!config.pagination) {
const scrapeResults: Record<string, any>[] = await page.evaluate((cfg) => window.scrapeList(cfg), config);
await this.options.serializableCallback(scrapeResults);
} else {
const scrapeResults: Record<string, any>[] = await this.handlePagination(page, config);
await this.options.serializableCallback(scrapeResults);
}
},
scrapeListAuto: async (config: { listSelector: string }) => {
await this.ensureScriptsLoaded(page);
const scrapeResults: { selector: string, innerText: string }[] = await page.evaluate((listSelector) => {
return window.scrapeListAuto(listSelector);
}, config.listSelector);
await this.options.serializableCallback(scrapeResults);
},
scroll: async (pages?: number) => {
await page.evaluate(async (pagesInternal) => {
for (let i = 1; i <= (pagesInternal ?? 1); i += 1) {
// @ts-ignore
window.scrollTo(0, window.scrollY + window.innerHeight);
}
}, pages ?? 1);
},
script: async (code: string) => {
const AsyncFunction: FunctionConstructor = Object.getPrototypeOf(
async () => { },
).constructor;
const x = new AsyncFunction('page', 'log', code);
await x(page, this.log);
},
flag: async () => new Promise((res) => {
this.emit('flag', page, res);
}),
};
const executeAction = async (invokee: any, methodName: string, args: any) => {
console.log("Executing action:", methodName, args);
if (methodName === 'press' || methodName === 'type') {
// Extract only the first two arguments for these methods
const limitedArgs = Array.isArray(args) ? args.slice(0, 2) : [args];
await (<any>invokee[methodName])(...limitedArgs);
return;
}
if (!args || Array.isArray(args)) {
await (<any>invokee[methodName])(...(args ?? []));
} else {
await (<any>invokee[methodName])(args);
}
};
for (const step of steps) {
this.log(`Launching ${String(step.action)}`, Level.LOG);
if (step.action in wawActions) {
// "Arrayifying" here should not be needed (TS + syntax checker - only arrays; but why not)
const params = !step.args || Array.isArray(step.args) ? step.args : [step.args];
await wawActions[step.action as CustomFunctions](...(params ?? []));
} else {
// Implements the dot notation for the "method name" in the workflow
const levels = String(step.action).split('.');
const methodName = levels[levels.length - 1];
let invokee: any = page;
for (const level of levels.splice(0, levels.length - 1)) {
invokee = invokee[level];
}
if (methodName === 'waitForLoadState') {
try {
await executeAction(invokee, methodName, step.args);
} catch (error) {
await executeAction(invokee, methodName, 'domcontentloaded');
}
} else if (methodName === 'click') {
try {
await executeAction(invokee, methodName, step.args);
} catch (error) {
try{
await executeAction(invokee, methodName, [step.args[0], { force: true }]);
} catch (error) {
continue
}
}
} else {
await executeAction(invokee, methodName, step.args);
}
}
await new Promise((res) => { setTimeout(res, 500); });
}
} | /**
* Given a Playwright's page object and a "declarative" list of actions, this function
* calls all mentioned functions on the Page object.\
* \
* Manipulates the iterator indexes (experimental feature, likely to be removed in
* the following versions of maxun-core)
* @param page Playwright Page object
* @param steps Array of actions.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/interpret.ts#L357-L549 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | debugLog | const debugLog = (message: string, ...args: any[]) => {
console.log(`[Page ${visitedUrls.size}] [URL: ${page.url()}] ${message}`, ...args);
}; | // 1 second delay between retries | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/interpret.ts#L564-L566 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | findWorkingButton | const findWorkingButton = async (selectors: string[], retryCount = 0): Promise<{
button: ElementHandle | null,
workingSelector: string | null
}> => {
for (const selector of selectors) {
try {
const button = await page.waitForSelector(selector, {
state: 'attached',
timeout: 10000 // Reduced timeout for faster checks
});
if (button) {
debugLog('Found working selector:', selector);
return { button, workingSelector: selector };
}
} catch (error) {
debugLog(`Selector failed: ${selector}`);
}
}
// Implement retry mechanism when no selectors work
if (selectors.length > 0 && retryCount < MAX_RETRIES) {
debugLog(`Retry attempt ${retryCount + 1} of ${MAX_RETRIES}`);
await page.waitForTimeout(RETRY_DELAY);
return findWorkingButton(selectors, retryCount + 1);
}
return { button: null, workingSelector: null };
}; | // Enhanced button finder with retry mechanism | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/interpret.ts#L589-L616 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | Interpreter.run | public async run(page: Page, params?: ParamType): Promise<void> {
this.log('Starting the workflow.', Level.LOG);
const context = page.context();
page.setDefaultNavigationTimeout(100000);
// Check proxy settings from context options
const contextOptions = (context as any)._options;
const hasProxy = !!contextOptions?.proxy;
this.log(`Proxy settings: ${hasProxy ? `Proxy is configured...` : 'No proxy configured...'}`);
if (hasProxy) {
if (contextOptions.proxy.username) {
this.log(`Proxy authenticated...`);
}
}
if (this.stopper) {
throw new Error('This Interpreter is already running a workflow. To run another workflow, please, spawn another Interpreter.');
}
/**
* `this.workflow` with the parameters initialized.
*/
this.initializedWorkflow = Preprocessor.initWorkflow(this.workflow, params);
await this.ensureScriptsLoaded(page);
this.stopper = () => {
this.stopper = null;
};
this.concurrency.addJob(() => this.runLoop(page, this.initializedWorkflow!));
await this.concurrency.waitForCompletion();
this.stopper = null;
} | /**
* Spawns a browser context and runs given workflow.
* \
* Resolves after the playback is finished.
* @param {Page} [page] Page to run the workflow on.
* @param {ParamType} params Workflow specific, set of parameters
* for the `{$param: nameofparam}` fields.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/interpret.ts#L1034-L1070 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | Preprocessor.getParams | static getParams(workflow: WorkflowFile): string[] {
const getParamsRecurse = (object: any): string[] => {
if (typeof object === 'object') {
// Recursion base case
if (object.$param) {
return [object.$param];
}
// Recursion general case
return (Object.values(object) as any[])
.reduce((p: string[], v: any): string[] => [...p, ...getParamsRecurse(v)], []);
}
return [];
};
return getParamsRecurse(workflow.workflow);
} | /**
* Extracts parameter names from the workflow.
* @param {WorkflowFile} workflow The given workflow
* @returns {String[]} List of parameters' names.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/preprocessor.ts#L54-L70 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | Preprocessor.extractSelectors | static extractSelectors(workflow: Workflow): SelectorArray {
/**
* Given a Where condition, this function extracts
* all the existing selectors from it (recursively).
*/
const selectorsFromCondition = (where: Where): SelectorArray => {
// the `selectors` field is either on the top level
let out = where.selectors ?? [];
if (!Array.isArray(out)) {
out = [out];
}
// or nested in the "operator" array
operators.forEach((op) => {
let condWhere = where[op];
if (condWhere) {
condWhere = Array.isArray(condWhere) ? condWhere : [condWhere];
(condWhere).forEach((subWhere) => {
out = [...out, ...selectorsFromCondition(subWhere)];
});
}
});
return out;
};
// Iterate through all the steps and extract the selectors from all of them.
return workflow.reduce((p: SelectorArray, step) => [
...p,
...selectorsFromCondition(step.where).filter((x) => !p.includes(x)),
], []);
} | // TODO : add recursive selector search (also in click/fill etc. events?) | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/preprocessor.ts#L77-L108 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | selectorsFromCondition | const selectorsFromCondition = (where: Where): SelectorArray => {
// the `selectors` field is either on the top level
let out = where.selectors ?? [];
if (!Array.isArray(out)) {
out = [out];
}
// or nested in the "operator" array
operators.forEach((op) => {
let condWhere = where[op];
if (condWhere) {
condWhere = Array.isArray(condWhere) ? condWhere : [condWhere];
(condWhere).forEach((subWhere) => {
out = [...out, ...selectorsFromCondition(subWhere)];
});
}
});
return out;
}; | /**
* Given a Where condition, this function extracts
* all the existing selectors from it (recursively).
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/preprocessor.ts#L82-L101 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | Preprocessor.initWorkflow | static initWorkflow(workflow: Workflow, params?: ParamType): Workflow {
const paramNames = this.getParams({ workflow });
if (Object.keys(params ?? {}).sort().join(',') !== paramNames.sort().join(',')) {
throw new Error(`Provided parameters do not match the workflow parameters
provided: ${Object.keys(params ?? {}).sort().join(',')},
expected: ${paramNames.sort().join(',')}
`);
}
/**
* A recursive method for initializing special `{key: value}` syntax objects in the workflow.
* @param object Workflow to initialize (or a part of it).
* @param k key to look for ($regex, $param)
* @param f function mutating the special `{}` syntax into
* its true representation (RegExp...)
* @returns Updated object
*/
const initSpecialRecurse = (
object: unknown,
k: string,
f: (value: string) => unknown,
): unknown => {
if (!object || typeof object !== 'object') {
return object;
}
const out = object;
// for every key (child) of the object
Object.keys(object!).forEach((key) => {
// if the field has only one key, which is `k`
if (Object.keys((<any>object)[key]).length === 1 && (<any>object)[key][k]) {
// process the current special tag (init param, hydrate regex...)
(<any>out)[key] = f((<any>object)[key][k]);
} else {
initSpecialRecurse((<any>object)[key], k, f);
}
});
return out;
};
// TODO: do better deep copy, this is hideous.
let workflowCopy = JSON.parse(JSON.stringify(workflow));
if (params) {
workflowCopy = initSpecialRecurse(
workflowCopy,
'$param',
(paramName) => {
if (params && params[paramName]) {
return params[paramName];
}
throw new SyntaxError(`Unspecified parameter found ${paramName}.`);
},
);
}
workflowCopy = initSpecialRecurse(
workflowCopy,
'$regex',
(regex) => new RegExp(regex),
);
return <Workflow>workflowCopy;
} | /**
* Recursively crawl `object` and initializes params - replaces the `{$param : paramName}` objects
* with the defined value.
* @returns {Workflow} Copy of the given workflow, modified (the initial workflow is left untouched).
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/preprocessor.ts#L115-L178 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | initSpecialRecurse | const initSpecialRecurse = (
object: unknown,
k: string,
f: (value: string) => unknown,
): unknown => {
if (!object || typeof object !== 'object') {
return object;
}
const out = object;
// for every key (child) of the object
Object.keys(object!).forEach((key) => {
// if the field has only one key, which is `k`
if (Object.keys((<any>object)[key]).length === 1 && (<any>object)[key][k]) {
// process the current special tag (init param, hydrate regex...)
(<any>out)[key] = f((<any>object)[key][k]);
} else {
initSpecialRecurse((<any>object)[key], k, f);
}
});
return out;
}; | /**
* A recursive method for initializing special `{key: value}` syntax objects in the workflow.
* @param object Workflow to initialize (or a part of it).
* @param k key to look for ($regex, $param)
* @param f function mutating the special `{}` syntax into
* its true representation (RegExp...)
* @returns Updated object
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/preprocessor.ts#L132-L153 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | Concurrency.constructor | constructor(maxConcurrency: number) {
this.maxConcurrency = maxConcurrency;
} | /**
* Constructs a new instance of concurrency manager.
* @param {number} maxConcurrency Maximum number of workers running in parallel.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/utils/concurrency.ts#L29-L31 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | Concurrency.runNextJob | private runNextJob(): void {
const job = this.jobQueue.pop();
if (job) {
// console.debug("Running a job...");
job().then(() => {
// console.debug("Job finished, running the next waiting job...");
this.runNextJob();
});
} else {
// console.debug("No waiting job found!");
this.activeWorkers -= 1;
if (this.activeWorkers === 0) {
// console.debug("This concurrency manager is idle!");
this.waiting.forEach((x) => x());
}
}
} | /**
* Takes a waiting job out of the queue and runs it.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/utils/concurrency.ts#L36-L53 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | Concurrency.addJob | addJob(job: () => Promise<any>): void {
// console.debug("Adding a worker!");
this.jobQueue.push(job);
if (!this.maxConcurrency || this.activeWorkers < this.maxConcurrency) {
this.runNextJob();
this.activeWorkers += 1;
} else {
// console.debug("No capacity to run a worker now, waiting!");
}
} | /**
* Pass a job (a time-demanding async function) to the concurrency manager. \
* The time of the job's execution depends on the concurrency manager itself
* (given a generous enough `maxConcurrency` value, it might be immediate,
* but this is not guaranteed).
* @param worker Async function to be executed (job to be processed).
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/utils/concurrency.ts#L62-L72 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | Concurrency.waitForCompletion | waitForCompletion(): Promise<void> {
return new Promise((res) => {
this.waiting.push(res);
});
} | /**
* Waits until there is no running nor waiting job. \
* If the concurrency manager is idle at the time of calling this function,
* it waits until at least one job is completed (can be "presubscribed").
* @returns Promise, resolved after there is no running/waiting worker.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/maxun-core/src/utils/concurrency.ts#L80-L84 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | measureFPS | const measureFPS = () => {
const currentTime = performance.now();
const elapsed = currentTime - this.lastFrameTime;
this.frameCount++;
if (elapsed >= 1000) { // Calculate FPS every second
const fps = Math.round((this.frameCount * 1000) / elapsed);
this.metrics.fps.push(fps);
this.frameCount = 0;
this.lastFrameTime = currentTime;
}
requestAnimationFrame(measureFPS);
}; | // Monitor FPS | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/perf/performance.ts#L28-L40 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | FrontendPerformanceMonitor.measureRenderTime | public measureRenderTime(renderFunction: () => void): void {
const startTime = performance.now();
renderFunction();
const endTime = performance.now();
this.metrics.renderTime.push(endTime - startTime);
} | // Monitor Canvas Render Time | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/perf/performance.ts#L57-L62 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | FrontendPerformanceMonitor.measureEventLatency | public measureEventLatency(event: MouseEvent | KeyboardEvent): void {
const latency = performance.now() - event.timeStamp;
this.metrics.eventLatency.push(latency);
} | // Monitor Event Latency | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/perf/performance.ts#L65-L68 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | FrontendPerformanceMonitor.getPerformanceReport | public getPerformanceReport(): PerformanceReport {
return {
averageFPS: this.calculateAverage(this.metrics.fps),
averageRenderTime: this.calculateAverage(this.metrics.renderTime),
averageEventLatency: this.calculateAverage(this.metrics.eventLatency),
memoryTrend: this.getMemoryTrend(),
lastMemoryUsage: this.metrics.memoryUsage[this.metrics.memoryUsage.length - 1]
};
} | // Get Performance Report | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/perf/performance.ts#L71-L79 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | handleWrapper | const handleWrapper = async (
handleCallback: (
generator: WorkflowGenerator,
page: Page,
args?: any
) => Promise<void>,
args?: any
) => {
const id = browserPool.getActiveBrowserId();
if (id) {
const activeBrowser = browserPool.getRemoteBrowser(id);
if (activeBrowser?.interpreter.interpretationInProgress() && !activeBrowser.interpreter.interpretationIsPaused) {
logger.log('debug', `Ignoring input, while interpretation is in progress`);
return;
}
const currentPage = activeBrowser?.getCurrentPage();
if (currentPage && activeBrowser) {
if (args) {
await handleCallback(activeBrowser.generator, currentPage, args);
} else {
await handleCallback(activeBrowser.generator, currentPage);
}
} else {
logger.log('warn', `No active page for browser ${id}`);
}
} else {
logger.log('warn', `No active browser for id ${id}`);
}
} | /**
* A wrapper function for handling user input.
* This function gets the active browser instance from the browser pool
* and passes necessary arguments to the appropriate handlers.
* e.g. {@link Generator}, {@link RemoteBrowser.currentPage}
*
* Also ignores any user input while interpretation is in progress.
*
* @param handleCallback The callback handler to be called
* @param args - arguments to be passed to the handler
* @category HelperFunctions
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L28-L56 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | onGenerateAction | const onGenerateAction = async (customActionEventData: CustomActionEventData) => {
logger.log('debug', `Generating ${customActionEventData.action} action emitted from client`);
await handleWrapper(handleGenerateAction, customActionEventData);
} | /**
* A wrapper function for handling custom actions.
* @param customActionEventData The custom action event data
* @category HelperFunctions
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L72-L75 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | handleGenerateAction | const handleGenerateAction =
async (generator: WorkflowGenerator, page: Page, { action, settings }: CustomActionEventData) => {
await generator.customAction(action, settings, page);
} | /**
* Handles the generation of a custom action workflow pair.
* @param generator The workflow generator
* @param page The active page
* @param action The custom action
* @param settings The custom action settings
* @category BrowserManagement
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L85-L88 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | onMousedown | const onMousedown = async (coordinates: Coordinates) => {
logger.log('debug', 'Handling mousedown event emitted from client');
await handleWrapper(handleMousedown, coordinates);
} | /**
* A wrapper function for handling mousedown event.
* @param coordinates - coordinates of the mouse click
* @category HelperFunctions
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L95-L98 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | handleMousedown | const handleMousedown = async (generator: WorkflowGenerator, page: Page, { x, y }: Coordinates) => {
await generator.onClick({ x, y }, page);
const previousUrl = page.url();
const tabsBeforeClick = page.context().pages().length;
await page.mouse.click(x, y);
// try if the click caused a navigation to a new url
try {
await page.waitForNavigation({ timeout: 2000 });
const currentUrl = page.url();
if (currentUrl !== previousUrl) {
generator.notifyUrlChange(currentUrl);
}
} catch (e) {
const { message } = e as Error;
} //ignore possible timeouts
// check if any new page was opened by the click
const tabsAfterClick = page.context().pages().length;
const numOfNewPages = tabsAfterClick - tabsBeforeClick;
if (numOfNewPages > 0) {
for (let i = 1; i <= numOfNewPages; i++) {
const newPage = page.context().pages()[tabsAfterClick - i];
if (newPage) {
generator.notifyOnNewTab(newPage, tabsAfterClick - i);
}
}
}
logger.log('debug', `Clicked on position x:${x}, y:${y}`);
}; | /**
* A mousedown event handler.
* Reproduces the click on the remote browser instance
* and generates pair data for the recorded workflow.
* @param generator - the workflow generator {@link Generator}
* @param page - the active page of the remote browser
* @param x - the x coordinate of the mousedown event
* @param y - the y coordinate of the mousedown event
* @category BrowserManagement
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L110-L138 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | onWheel | const onWheel = async (scrollDeltas: ScrollDeltas) => {
logger.log('debug', 'Handling scroll event emitted from client');
await handleWrapper(handleWheel, scrollDeltas);
}; | /**
* A wrapper function for handling the wheel event.
* @param scrollDeltas - the scroll deltas of the wheel event
* @category HelperFunctions
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L145-L148 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | handleWheel | const handleWheel = async (generator: WorkflowGenerator, page: Page, { deltaX, deltaY }: ScrollDeltas) => {
await page.mouse.wheel(deltaX, deltaY);
logger.log('debug', `Scrolled horizontally ${deltaX} pixels and vertically ${deltaY} pixels`);
}; | /**
* A wheel event handler.
* Reproduces the wheel event on the remote browser instance.
* Scroll is not generated for the workflow pair. This is because
* Playwright scrolls elements into focus on any action.
* @param generator - the workflow generator {@link Generator}
* @param page - the active page of the remote browser
* @param deltaX - the delta x of the wheel event
* @param deltaY - the delta y of the wheel event
* @category BrowserManagement
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L161-L164 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | onMousemove | const onMousemove = async (coordinates: Coordinates) => {
logger.log('debug', 'Handling mousemove event emitted from client');
await handleWrapper(handleMousemove, coordinates);
} | /**
* A wrapper function for handling the mousemove event.
* @param coordinates - the coordinates of the mousemove event
* @category HelperFunctions
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L171-L174 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | handleMousemove | const handleMousemove = async (generator: WorkflowGenerator, page: Page, { x, y }: Coordinates) => {
try {
await page.mouse.move(x, y);
throttle(async () => {
await generator.generateDataForHighlighter(page, { x, y });
}, 100)();
logger.log('debug', `Moved over position x:${x}, y:${y}`);
} catch (e) {
const { message } = e as Error;
logger.log('error', message);
}
} | /**
* A mousemove event handler.
* Reproduces the mousemove event on the remote browser instance
* and generates data for the client's highlighter.
* Mousemove is also not reflected in the workflow.
* @param generator - the workflow generator {@link Generator}
* @param page - the active page of the remote browser
* @param x - the x coordinate of the mousemove event
* @param y - the y coordinate of the mousemove event
* @category BrowserManagement
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L187-L198 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | onKeydown | const onKeydown = async (keyboardInput: KeyboardInput) => {
logger.log('debug', 'Handling keydown event emitted from client');
await handleWrapper(handleKeydown, keyboardInput);
} | /**
* A wrapper function for handling the keydown event.
* @param keyboardInput - the keyboard input of the keydown event
* @category HelperFunctions
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L205-L208 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | handleKeydown | const handleKeydown = async (generator: WorkflowGenerator, page: Page, { key, coordinates }: KeyboardInput) => {
await page.keyboard.down(key);
await generator.onKeyboardInput(key, coordinates, page);
logger.log('debug', `Key ${key} pressed`);
}; | /**
* A keydown event handler.
* Reproduces the keydown event on the remote browser instance
* and generates the workflow pair data.
* @param generator - the workflow generator {@link Generator}
* @param page - the active page of the remote browser
* @param key - the pressed key
* @param coordinates - the coordinates, where the keydown event happened
* @category BrowserManagement
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L220-L224 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | handleDateSelection | const handleDateSelection = async (generator: WorkflowGenerator, page: Page, data: DatePickerEventData) => {
await generator.onDateSelection(page, data);
logger.log('debug', `Date ${data.value} selected`);
} | /**
* Handles the date selection event.
* @param generator - the workflow generator {@link Generator}
* @param page - the active page of the remote browser
* @param data - the data of the date selection event {@link DatePickerEventData}
* @category BrowserManagement
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L233-L236 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | onKeyup | const onKeyup = async (keyboardInput: KeyboardInput) => {
logger.log('debug', 'Handling keyup event emitted from client');
await handleWrapper(handleKeyup, keyboardInput);
} | /**
* A wrapper function for handling the keyup event.
* @param keyboardInput - the keyboard input of the keyup event
* @category HelperFunctions
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L278-L281 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | handleKeyup | const handleKeyup = async (generator: WorkflowGenerator, page: Page, key: string) => {
await page.keyboard.up(key);
logger.log('debug', `Key ${key} unpressed`);
}; | /**
* A keyup event handler.
* Reproduces the keyup event on the remote browser instance.
* Does not generate any data - keyup is not reflected in the workflow.
* @param generator - the workflow generator {@link Generator}
* @param page - the active page of the remote browser
* @param key - the released key
* @category BrowserManagement
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L292-L295 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | onChangeUrl | const onChangeUrl = async (url: string) => {
logger.log('debug', 'Handling change url event emitted from client');
await handleWrapper(handleChangeUrl, url);
} | /**
* A wrapper function for handling the url change event.
* @param url - the new url of the page
* @category HelperFunctions
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L302-L305 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | handleChangeUrl | const handleChangeUrl = async (generator: WorkflowGenerator, page: Page, url: string) => {
if (url) {
await generator.onChangeUrl(url, page);
try {
await page.goto(url);
logger.log('debug', `Went to ${url}`);
} catch (e) {
const { message } = e as Error;
logger.log('error', message);
}
} else {
logger.log('warn', `No url provided`);
}
}; | /**
* An url change event handler.
* Navigates the page to the given url and generates data for the workflow.
* @param generator - the workflow generator {@link Generator}
* @param page - the active page of the remote browser
* @param url - the new url of the page
* @category BrowserManagement
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L315-L328 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | onRefresh | const onRefresh = async () => {
logger.log('debug', 'Handling refresh event emitted from client');
await handleWrapper(handleRefresh);
} | /**
* A wrapper function for handling the refresh event.
* @category HelperFunctions
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L334-L337 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | handleRefresh | const handleRefresh = async (generator: WorkflowGenerator, page: Page) => {
await page.reload();
logger.log('debug', `Page refreshed.`);
}; | /**
* A refresh event handler.
* Refreshes the page. This is not reflected in the workflow.
* @param generator - the workflow generator {@link Generator}
* @param page - the active page of the remote browser
* @category BrowserManagement
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L346-L349 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | onGoBack | const onGoBack = async () => {
logger.log('debug', 'Handling refresh event emitted from client');
await handleWrapper(handleGoBack);
} | /**
* A wrapper function for handling the go back event.
* @category HelperFunctions
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L355-L358 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | handleGoBack | const handleGoBack = async (generator: WorkflowGenerator, page: Page) => {
await page.goBack({ waitUntil: 'commit' });
generator.onGoBack(page.url());
logger.log('debug', 'Page went back')
}; | /**
* A go back event handler.
* Navigates the page back and generates data for the workflow.
* @param generator - the workflow generator {@link Generator}
* @param page - the active page of the remote browser
* @category BrowserManagement
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L367-L371 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | onGoForward | const onGoForward = async () => {
logger.log('debug', 'Handling refresh event emitted from client');
await handleWrapper(handleGoForward);
} | /**
* A wrapper function for handling the go forward event.
* @category HelperFunctions
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L377-L380 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | handleGoForward | const handleGoForward = async (generator: WorkflowGenerator, page: Page) => {
await page.goForward({ waitUntil: 'commit' });
generator.onGoForward(page.url());
logger.log('debug', 'Page went forward');
}; | /**
* A go forward event handler.
* Navigates the page forward and generates data for the workflow.
* @param generator - the workflow generator {@link Generator}
* @param page - the active page of the remote browser
* @category BrowserManagement
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L389-L393 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | registerInputHandlers | const registerInputHandlers = (socket: Socket) => {
socket.on("input:mousedown", onMousedown);
socket.on("input:wheel", onWheel);
socket.on("input:mousemove", onMousemove);
socket.on("input:keydown", onKeydown);
socket.on("input:keyup", onKeyup);
socket.on("input:url", onChangeUrl);
socket.on("input:refresh", onRefresh);
socket.on("input:back", onGoBack);
socket.on("input:forward", onGoForward);
socket.on("input:date", onDateSelection);
socket.on("input:dropdown", onDropdownSelection);
socket.on("input:time", onTimeSelection);
socket.on("input:datetime-local", onDateTimeLocalSelection);
socket.on("action", onGenerateAction);
}; | /**
* Helper function for registering the handlers onto established websocket connection.
* Registers:
* - mousedownHandler
* - wheelHandler
* - mousemoveHandler
* - keydownHandler
* - keyupHandler
* - changeUrlHandler
* - refreshHandler
* - goBackHandler
* - goForwardHandler
* - onGenerateAction
* input handlers.
*
* All these handlers first generates the workflow pair data
* and then calls the corresponding playwright's function to emulate the input.
* They also ignore any user input while interpretation is in progress.
*
* @param socket websocket with established connection
* @returns void
* @category BrowserManagement
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/inputHandlers.ts#L418-L433 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | BrowserPool.deleteRemoteBrowser | public addRemoteBrowser = (id: string, browser: RemoteBrowser, active: boolean = false): void => {
this.pool = {
...this.pool,
[id]: {
browser,
active,
},
}
logger.log('debug', `Remote browser with id: ${id} added to the pool`);
} | /**
* Returns the active browser's instance id from the pool.
* If there is no active browser, it returns undefined.
* If there are multiple active browsers, it returns the first one.
* @returns the first remote active browser instance's id from the pool
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/classes/BrowserPool.ts | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | RemoteBrowser.constructor | public constructor(socket: Socket) {
this.socket = socket;
this.interpreter = new WorkflowInterpreter(socket);
this.generator = new WorkflowGenerator(socket);
} | /**
* Initializes a new instances of the {@link Generator} and {@link WorkflowInterpreter} classes and
* assigns the socket instance everywhere.
* @param socket socket.io socket instance used to communicate with the client side
* @constructor
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/classes/RemoteBrowser.ts#L116-L120 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | RemoteBrowser.normalizeUrl | private normalizeUrl(url: string): string {
try {
const parsedUrl = new URL(url);
// Remove trailing slashes except for root path
parsedUrl.pathname = parsedUrl.pathname.replace(/\/+$/, '') || '/';
// Ensure consistent protocol handling
parsedUrl.protocol = parsedUrl.protocol.toLowerCase();
return parsedUrl.toString();
} catch {
return url;
}
} | /**
* Normalizes URLs to prevent navigation loops while maintaining consistent format
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/classes/RemoteBrowser.ts#L165-L176 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | RemoteBrowser.shouldEmitUrlChange | private shouldEmitUrlChange(newUrl: string): boolean {
if (!this.lastEmittedUrl) {
return true;
}
const normalizedNew = this.normalizeUrl(newUrl);
const normalizedLast = this.normalizeUrl(this.lastEmittedUrl);
return normalizedNew !== normalizedLast;
} | /**
* Determines if a URL change is significant enough to emit
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/classes/RemoteBrowser.ts#L181-L188 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | RemoteBrowser.interpretCurrentRecording | public initialize = async (userId: string): Promise<void> => {
this.browser = <Browser>(await chromium.launch({
headless: true,
args: [
"--disable-blink-features=AutomationControlled",
"--disable-web-security",
"--disable-features=IsolateOrigins,site-per-process",
"--disable-site-isolation-trials",
"--disable-extensions",
"--no-sandbox",
"--disable-dev-shm-usage",
],
}));
const proxyConfig = await getDecryptedProxyConfig(userId);
let proxyOptions: { server: string, username?: string, password?: string } = { server: '' };
if (proxyConfig.proxy_url) {
proxyOptions = {
server: proxyConfig.proxy_url,
...(proxyConfig.proxy_username && proxyConfig.proxy_password && {
username: proxyConfig.proxy_username,
password: proxyConfig.proxy_password,
}),
};
}
const contextOptions: any = {
viewport: { height: 400, width: 900 },
// recordVideo: { dir: 'videos/' }
// Force reduced motion to prevent animation issues
reducedMotion: 'reduce',
// Force JavaScript to be enabled
javaScriptEnabled: true,
// Set a reasonable timeout
timeout: 50000,
// Disable hardware acceleration
forcedColors: 'none',
isMobile: false,
hasTouch: false,
userAgent: this.getUserAgent(),
};
if (proxyOptions.server) {
contextOptions.proxy = {
server: proxyOptions.server,
username: proxyOptions.username ? proxyOptions.username : undefined,
password: proxyOptions.password ? proxyOptions.password : undefined,
};
}
this.context = await this.browser.newContext(contextOptions);
await this.context.addInitScript(
`const defaultGetter = Object.getOwnPropertyDescriptor(
Navigator.prototype,
"webdriver"
).get;
defaultGetter.apply(navigator);
defaultGetter.toString();
Object.defineProperty(Navigator.prototype, "webdriver", {
set: undefined,
enumerable: true,
configurable: true,
get: new Proxy(defaultGetter, {
apply: (target, thisArg, args) => {
Reflect.apply(target, thisArg, args);
return false;
},
}),
});
const patchedGetter = Object.getOwnPropertyDescriptor(
Navigator.prototype,
"webdriver"
).get;
patchedGetter.apply(navigator);
patchedGetter.toString();`
);
this.currentPage = await this.context.newPage();
await this.setupPageEventListeners(this.currentPage);
try {
const blocker = await PlaywrightBlocker.fromLists(fetch, ['https://easylist.to/easylist/easylist.txt']);
await blocker.enableBlockingInPage(this.currentPage);
this.client = await this.currentPage.context().newCDPSession(this.currentPage);
await blocker.disableBlockingInPage(this.currentPage);
console.log('Adblocker initialized');
} catch (error: any) {
console.warn('Failed to initialize adblocker, continuing without it:', error.message);
// Still need to set up the CDP session even if blocker fails
this.client = await this.currentPage.context().newCDPSession(this.currentPage);
}
} | /**
* Subscribes the remote browser for a screencast session
* on [CDP](https://chromedevtools.github.io/devtools-protocol/) level,
* where screenshot is being sent through the socket
* every time the browser's active page updates.
* @returns {Promise<void>}
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/classes/RemoteBrowser.ts | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | RemoteBrowser.registerEditorEvents | public registerEditorEvents = (): void => {
this.socket.on('rerender', async () => await this.makeAndEmitScreenshot());
this.socket.on('settings', (settings) => this.interpreterSettings = settings);
this.socket.on('changeTab', async (tabIndex) => await this.changeTab(tabIndex));
this.socket.on('addTab', async () => {
await this.currentPage?.context().newPage();
const lastTabIndex = this.currentPage ? this.currentPage.context().pages().length - 1 : 0;
await this.changeTab(lastTabIndex);
});
this.socket.on('closeTab', async (tabInfo) => {
const page = this.currentPage?.context().pages()[tabInfo.index];
if (page) {
if (tabInfo.isCurrent) {
if (this.currentPage?.context().pages()[tabInfo.index + 1]) {
// next tab
await this.changeTab(tabInfo.index + 1);
} else {
//previous tab
await this.changeTab(tabInfo.index - 1);
}
}
await page.close();
logger.log(
'debug',
`${tabInfo.index} page was closed, new length of pages: ${this.currentPage?.context().pages().length}`
)
} else {
logger.log('error', `${tabInfo.index} index out of range of pages`)
}
});
this.socket.on('setViewportSize', async (data: { width: number, height: number }) => {
const { width, height } = data;
logger.log('debug', `Received viewport size: width=${width}, height=${height}`);
// Update the browser context's viewport dynamically
if (this.context && this.browser) {
this.context = await this.browser.newContext({ viewport: { width, height } });
logger.log('debug', `Viewport size updated to width=${width}, height=${height} for the entire browser context`);
}
});
} | /**
* Registers all event listeners needed for the recording editor session.
* Should be called only once after the full initialization of the remote browser.
* @returns void
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/classes/RemoteBrowser.ts#L335-L375 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | RemoteBrowser.switchOff | public async switchOff(): Promise<void> {
try {
await this.interpreter.stopInterpretation();
if (this.screencastInterval) {
clearInterval(this.screencastInterval);
}
if (this.client) {
await this.stopScreencast();
}
if (this.browser) {
await this.browser.close();
}
this.screenshotQueue = [];
//this.performanceMonitor.reset();
} catch (error) {
logger.error('Error during browser shutdown:', error);
}
} | /**
* Terminates the screencast session and closes the remote browser.
* If an interpretation was running it will be stopped.
* @returns {Promise<void>}
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/classes/RemoteBrowser.ts#L411-L433 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | RemoteBrowser.changeTab | private changeTab = async (tabIndex: number): Promise<void> => {
const page = this.currentPage?.context().pages()[tabIndex];
if (page) {
await this.stopScreencast();
this.currentPage = page;
await this.setupPageEventListeners(this.currentPage);
//await this.currentPage.setViewportSize({ height: 400, width: 900 })
this.client = await this.currentPage.context().newCDPSession(this.currentPage);
this.socket.emit('urlChanged', this.currentPage.url());
await this.makeAndEmitScreenshot();
await this.subscribeToScreencast();
} else {
logger.log('error', `${tabIndex} index out of range of pages`)
}
} | /**
* Changes the active page to the page instance on the given index
* available in pages array on the {@link BrowserContext}.
* Automatically stops the screencast session on the previous page and starts the new one.
* @param tabIndex index of the page in the pages array on the {@link BrowserContext}
* @returns {Promise<void>}
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/classes/RemoteBrowser.ts#L546-L562 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | RemoteBrowser.startScreencast | private async startScreencast(): Promise<void> {
if (!this.client) {
logger.warn('Client is not initialized');
return;
}
try {
await this.client.send('Page.startScreencast', {
format: SCREENCAST_CONFIG.format,
});
// Set up screencast frame handler
this.client.on('Page.screencastFrame', async ({ data, sessionId }) => {
try {
const buffer = Buffer.from(data, 'base64');
await this.emitScreenshot(buffer);
await this.client?.send('Page.screencastFrameAck', { sessionId });
} catch (error) {
logger.error('Screencast frame processing failed:', error);
}
});
logger.info('Screencast started successfully');
} catch (error) {
logger.error('Failed to start screencast:', error);
}
} | /**
* Initiates screencast of the remote browser through socket,
* registers listener for rerender event and emits the loaded event.
* Should be called only once after the browser is fully initialized.
* @returns {Promise<void>}
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/browser-management/classes/RemoteBrowser.ts#L595-L621 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | BinaryOutputService.uploadAndStoreBinaryOutput | async uploadAndStoreBinaryOutput(run: Run, binaryOutput: Record<string, any>): Promise<Record<string, string>> {
const uploadedBinaryOutput: Record<string, string> = {};
const plainRun = run.toJSON();
for (const key of Object.keys(binaryOutput)) {
let binaryData = binaryOutput[key];
if (!plainRun.runId) {
console.error('Run ID is undefined. Cannot upload binary data.');
continue;
}
console.log(`Processing binary output key: ${key}`);
// Check if binaryData has a valid Buffer structure and parse it
if (binaryData && typeof binaryData.data === 'string') {
try {
const parsedData = JSON.parse(binaryData.data);
if (parsedData && parsedData.type === 'Buffer' && Array.isArray(parsedData.data)) {
binaryData = Buffer.from(parsedData.data);
} else {
console.error(`Invalid Buffer format for key: ${key}`);
continue;
}
} catch (error) {
console.error(`Failed to parse JSON for key: ${key}`, error);
continue;
}
}
// Handle cases where binaryData might not be a Buffer
if (!Buffer.isBuffer(binaryData)) {
console.error(`Binary data for key ${key} is not a valid Buffer.`);
continue;
}
try {
const minioKey = `${plainRun.runId}/${key}`;
await this.uploadBinaryOutputToMinioBucket(run, minioKey, binaryData);
// Construct the public URL for the uploaded object
// todo: use minio endpoint
const publicUrl = `http://localhost:${process.env.MINIO_PORT}/${this.bucketName}/${minioKey}`;
// Save the public URL in the result object
uploadedBinaryOutput[key] = publicUrl;
} catch (error) {
console.error(`Error uploading key ${key} to MinIO:`, error);
}
}
console.log('Uploaded Binary Output:', uploadedBinaryOutput);
try {
await run.update({ binaryOutput: uploadedBinaryOutput });
console.log('Run successfully updated with binary output');
} catch (updateError) {
console.error('Error updating run with binary output:', updateError);
}
return uploadedBinaryOutput;
} | /**
* Uploads binary data to Minio and stores references in PostgreSQL.
* @param run - The run object representing the current process.
* @param binaryOutput - The binary output object containing data to upload.
* @returns A map of Minio URLs pointing to the uploaded binary data.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/storage/mino.ts#L70-L132 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | traverseShadowDOM | const traverseShadowDOM = (element: HTMLElement): HTMLElement => {
let current = element;
let shadowRoot = current.shadowRoot;
let deepest = current;
while (shadowRoot) {
const shadowElement = shadowRoot.elementFromPoint(x, y) as HTMLElement;
if (!shadowElement || shadowElement === current) break;
deepest = shadowElement;
current = shadowElement;
shadowRoot = current.shadowRoot;
}
return deepest;
}; | // Function to traverse shadow DOM | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L35-L50 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | getDeepestElementFromPoint | const getDeepestElementFromPoint = (x: number, y: number): HTMLElement | null => {
// First, get the element at the clicked coordinates in the main document
let element = document.elementFromPoint(x, y) as HTMLElement;
if (!element) return null;
// Track the deepest element found
let deepestElement = element;
// Function to traverse shadow DOM
const traverseShadowDOM = (element: HTMLElement): HTMLElement => {
let current = element;
let shadowRoot = current.shadowRoot;
let deepest = current;
while (shadowRoot) {
const shadowElement = shadowRoot.elementFromPoint(x, y) as HTMLElement;
if (!shadowElement || shadowElement === current) break;
deepest = shadowElement;
current = shadowElement;
shadowRoot = current.shadowRoot;
}
return deepest;
};
// Handle iframe traversal
if (element.tagName === 'IFRAME') {
let currentIframe = element as HTMLIFrameElement;
while (currentIframe) {
try {
// Convert coordinates to iframe's local space
const iframeRect = currentIframe.getBoundingClientRect();
const iframeX = x - iframeRect.left;
const iframeY = y - iframeRect.top;
const iframeDocument = currentIframe.contentDocument || currentIframe.contentWindow?.document;
if (!iframeDocument) break;
const iframeElement = iframeDocument.elementFromPoint(iframeX, iframeY) as HTMLElement;
if (!iframeElement) break;
// Update deepest element and check for shadow DOM
deepestElement = traverseShadowDOM(iframeElement);
// Continue traversing if we found another iframe
if (iframeElement.tagName === 'IFRAME') {
currentIframe = iframeElement as HTMLIFrameElement;
} else {
break;
}
} catch (error) {
console.warn('Cannot access iframe content:', error);
break;
}
}
} else {
// If not an iframe, check for shadow DOM
deepestElement = traverseShadowDOM(element);
}
return deepestElement;
}; | // Enhanced helper function to get element from point including shadow DOM | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L26-L89 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | traverseShadowDOM | const traverseShadowDOM = (element: HTMLElement, depth: number = 0): HTMLElement => {
const MAX_SHADOW_DEPTH = 4;
let current = element;
let deepest = current;
while (current && depth < MAX_SHADOW_DEPTH) {
const shadowRoot = current.shadowRoot;
if (!shadowRoot) break;
const shadowElement = shadowRoot.elementFromPoint(x, y) as HTMLElement;
if (!shadowElement || shadowElement === current) break;
deepest = shadowElement;
current = shadowElement;
depth++;
}
return deepest;
}; | // Helper function to traverse shadow DOM | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L1205-L1223 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | getIframePath | const getIframePath = (el: HTMLElement) => {
const path = [];
let current = el;
let depth = 0;
const MAX_DEPTH = 4;
while (current && depth < MAX_DEPTH) {
// Get the owner document of the current element
const ownerDocument = current.ownerDocument;
// Check if this document belongs to an iframe
const frameElement = ownerDocument?.defaultView?.frameElement as HTMLIFrameElement;
if (frameElement) {
path.unshift({
frame: frameElement,
document: ownerDocument,
element: current
});
// Move up to the parent document's element (the iframe)
current = frameElement;
depth++;
} else {
break;
}
}
return path;
}; | // Helper function to get the complete iframe path up to document root | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L1279-L1306 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | genSelectorForShadowDOM | const genSelectorForShadowDOM = (element: HTMLElement) => {
// Get complete path up to document root
const getShadowPath = (el: HTMLElement) => {
const path = [];
let current = el;
let depth = 0;
const MAX_DEPTH = 4;
while (current && depth < MAX_DEPTH) {
const rootNode = current.getRootNode();
if (rootNode instanceof ShadowRoot) {
path.unshift({
host: rootNode.host as HTMLElement,
root: rootNode,
element: current
});
current = rootNode.host as HTMLElement;
depth++;
} else {
break;
}
}
return path;
};
const shadowPath = getShadowPath(element);
if (shadowPath.length === 0) return null;
try {
const selectorParts: string[] = [];
// Generate selector for each shadow DOM boundary
shadowPath.forEach((context, index) => {
// Get selector for the host element
const hostSelector = finder(context.host, {
root: index === 0 ? document.body : (shadowPath[index - 1].root as unknown as Element)
});
// For the last context, get selector for target element
if (index === shadowPath.length - 1) {
const elementSelector = finder(element, {
root: context.root as unknown as Element
});
selectorParts.push(`${hostSelector} >> ${elementSelector}`);
} else {
selectorParts.push(hostSelector);
}
});
return {
fullSelector: selectorParts.join(' >> '),
mode: shadowPath[shadowPath.length - 1].root.mode
};
} catch (e) {
console.warn('Error generating shadow DOM selector:', e);
return null;
}
}; | // Helper function to generate selectors for shadow DOM elements | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L1344-L1401 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.