Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions apps/acf-extension/src/content_scripts/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import ActionProcessor from './action';
import AddonProcessor from './addon';
import Common from './common';
import { I18N_COMMON, I18N_ERROR } from './i18n';
import { logger } from './logger';
import Statement from './statement';
import { statusBar } from './status-bar';
import UserScriptProcessor from './userscript';
Expand Down Expand Up @@ -41,7 +42,7 @@ const Actions = (() => {
const action = actions[i];
window.ext.__currentActionName = action.name ?? ACTION_I18N.NO_NAME;
if (action.disabled) {
console.debug(`${ACTION_I18N.TITLE} #${i + 1}`, `[${window.ext.__currentActionName}]`, `🚫 ${I18N_COMMON.DISABLED} `);
logger.debug(['ACTION', `#${i + 1}`, window.ext.__currentActionName], `🚫 ${I18N_COMMON.DISABLED}`);
i += 1;
continue;
}
Expand All @@ -59,14 +60,14 @@ const Actions = (() => {
notify(action);
} catch (error) {
if (error === EActionStatus.SKIPPED || error === EActionRunning.SKIP) {
console.debug(`${ACTION_I18N.TITLE} #${window.ext.__currentAction}`, `[${window.ext.__currentActionName}]`, window.ext.__actionError, `⏭️ ${EActionStatus.SKIPPED}`);
logger.debug(['ACTION', `#${window.ext.__currentAction}`, window.ext.__currentActionName], `⏭️ ${EActionStatus.SKIPPED}`, { error: window.ext.__actionError });
action.status = EActionStatus.SKIPPED;
} else if (typeof error === 'number' || (typeof error === 'string' && isValidUUID(error))) {
const index = typeof error === 'number' ? error : actions.findIndex((a) => a.id === error);
if (index === -1) {
throw new ConfigError(I18N_ERROR.ACTION_NOT_FOUND_FOR_GOTO, ACTION_I18N.TITLE);
}
console.debug(`${ACTION_I18N.TITLE} #${window.ext.__currentAction}`, `[${window.ext.__currentActionName}]`, window.ext.__actionError, `${I18N_COMMON.GOTO} Action ➡️ ${index + 1}`);
logger.debug(['ACTION', `#${window.ext.__currentAction}`, window.ext.__currentActionName], `${I18N_COMMON.GOTO} Action ➡️ ${index + 1}`, { error: window.ext.__actionError });
i = index - 1;
} else {
throw error;
Expand Down
11 changes: 6 additions & 5 deletions apps/acf-extension/src/content_scripts/batch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { STATUS_BAR_TYPE } from '@dhruv-techapps/shared-status-bar';
import Actions from './actions';
import Common from './common';
import { I18N_COMMON } from './i18n';
import { logger } from './logger';
import { statusBar } from './status-bar';

const BATCH_I18N = {
Expand All @@ -27,7 +28,7 @@ const BatchProcessor = (() => {
if (batch.repeat > 0) {
for (let i = 0; i < batch.repeat; i += 1) {
statusBar.batchUpdate(i + 2);
console.groupCollapsed(`${BATCH_I18N.TITLE} #${i + 2} [${I18N_COMMON.REPEAT}]`);
logger.debug(['BATCH', `#${i + 2}`, I18N_COMMON.REPEAT], 'Starting repeat batch');
if (batch?.repeatInterval) {
await statusBar.wait(batch?.repeatInterval, STATUS_BAR_TYPE.BATCH_REPEAT, i + 2);
}
Expand All @@ -42,7 +43,7 @@ const BatchProcessor = (() => {
iconUrl: Common.getNotificationIcon()
});
}
console.groupEnd();
logger.debug(['BATCH', `#${i + 2}`, I18N_COMMON.REPEAT], 'Completed repeat batch');
}
} else if (batch.repeat < -1) {
let i = 1;
Expand All @@ -62,9 +63,9 @@ const BatchProcessor = (() => {
const start = async (actions: Array<IAction | IUserScript>, batch?: IBatch) => {
try {
statusBar.batchUpdate(1);
console.groupCollapsed(`${BATCH_I18N.TITLE} #1 (${I18N_COMMON.DEFAULT})`);
logger.debug(['BATCH', '#1', I18N_COMMON.DEFAULT], 'Starting default batch');
await Actions.start(actions, 1);
console.groupEnd();
logger.debug(['BATCH', '#1', I18N_COMMON.DEFAULT], 'Completed default batch');
if (batch) {
if (batch.refresh) {
refresh();
Expand All @@ -73,7 +74,7 @@ const BatchProcessor = (() => {
}
}
} catch (error) {
console.groupEnd();
logger.error(['BATCH'], 'Batch execution failed', error);
throw error;
}
};
Expand Down
3 changes: 2 additions & 1 deletion apps/acf-extension/src/content_scripts/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import BatchProcessor from './batch';
import Common from './common';
import { Hotkey } from './hotkey';
import { I18N_COMMON } from './i18n';
import { logger } from './logger';
import { statusBar } from './status-bar';
import DomWatchManager from './util/dom-watch-manager';
import GoogleSheets from './util/google-sheets';
Expand Down Expand Up @@ -52,7 +53,7 @@ const ConfigProcessor = (() => {
if (config.watch?.watchEnabled) {
// Set up the sequence restart callback for DOM watcher
DomWatchManager.setSequenceRestartCallback(async () => {
console.debug(`Actions: Restarting entire action sequence due to DOM changes`);
logger.debug(['ACTIONS', 'DOM-RESTART'], 'Restarting entire action sequence due to DOM changes');
await Actions.start(config.actions, window.ext.__batchRepeat + 1);
});

Expand Down
21 changes: 15 additions & 6 deletions apps/acf-extension/src/content_scripts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { IExtension, Logger, LoggerColor } from '@dhruv-techapps/core-common';
import { scope } from '../common/instrument';
import ConfigProcessor from './config';
import { logger } from './logger';
import { statusBar } from './status-bar';

scope.setTag('page', 'content-script');
Expand All @@ -16,11 +17,19 @@
window.ext = window.ext || {};

let reloadOnError = false;
new SettingsStorage().getSettings().then((settings) => {
if (settings.reloadOnError !== undefined) {
reloadOnError = settings.reloadOnError;

// Initialize logger and settings
(async () => {

Check warning on line 22 in apps/acf-extension/src/content_scripts/index.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/index.ts#L22

ES2017 async function declarations are forbidden.
try {
await logger.initialize();
const settings = await new SettingsStorage().getSettings();
if (settings.reloadOnError !== undefined) {
reloadOnError = settings.reloadOnError;

Check warning on line 27 in apps/acf-extension/src/content_scripts/index.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/index.ts#L27

Unsafe assignment of an `any` value.
}
} catch (error) {
console.warn('Failed to initialize logger/settings:', error);
}
});
})();

async function loadConfig(loadType: ELoadTypes) {
try {
Expand Down Expand Up @@ -70,9 +79,9 @@
if (action === RUNTIME_MESSAGE_ACF.RUN_CONFIG) {
try {
new ConfigStorage().getConfigById(configId).then(async (config) => {
Logger.color(chrome.runtime.getManifest().name, LoggerColor.PRIMARY, 'debug', config?.url, 'START');
logger.info(['CONFIG', 'RUNTIME'], `Starting config: ${config?.url}`);
await ConfigProcessor.checkStartType([], config);
Logger.color(chrome.runtime.getManifest().name, LoggerColor.PRIMARY, 'debug', config?.url, 'END');
logger.info(['CONFIG', 'RUNTIME'], `Completed config: ${config?.url}`);
});
} catch (e) {
if (e instanceof Error) {
Expand Down
96 changes: 96 additions & 0 deletions apps/acf-extension/src/content_scripts/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { SettingsStorage } from '@dhruv-techapps/acf-store';

Check warning on line 1 in apps/acf-extension/src/content_scripts/logger.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/logger.ts#L1

Can't resolve '@dhruv-techapps/acf-store' in '/src/apps/acf-extension/src/content_scripts'
import { EnhancedLogger, ELoggingLevel } from '@dhruv-techapps/core-common';

Check warning on line 2 in apps/acf-extension/src/content_scripts/logger.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/logger.ts#L2

Can't resolve '@dhruv-techapps/core-common' in '/src/apps/acf-extension/src/content_scripts'

Check warning on line 2 in apps/acf-extension/src/content_scripts/logger.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/logger.ts#L2

Unable to resolve path to module '@dhruv-techapps/core-common'.

export class ContentScriptLogger {
private static instance: ContentScriptLogger;
private logger: EnhancedLogger;
private initialized = false;

private constructor() {
this.logger = EnhancedLogger.getInstance();
}

public static getInstance(): ContentScriptLogger {
if (!ContentScriptLogger.instance) {
ContentScriptLogger.instance = new ContentScriptLogger();
}
return ContentScriptLogger.instance;
}

public async initialize(): Promise<void> {

Check warning on line 20 in apps/acf-extension/src/content_scripts/logger.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/logger.ts#L20

Method initialize has a cyclomatic complexity of 9 (limit is 8)
if (this.initialized) {
return;
}

try {
const settings = await new SettingsStorage().getSettings();

Check warning on line 26 in apps/acf-extension/src/content_scripts/logger.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/logger.ts#L26

Unsafe call of an `error` type typed value.

Check warning on line 26 in apps/acf-extension/src/content_scripts/logger.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/logger.ts#L26

Unsafe member access .getSettings on an `error` typed value.
const logging = settings.logging;

Check warning on line 27 in apps/acf-extension/src/content_scripts/logger.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/logger.ts#L27

ES2015 block-scoped variables are forbidden.

Check warning on line 27 in apps/acf-extension/src/content_scripts/logger.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/logger.ts#L27

Unsafe member access .logging on an `error` typed value.

if (logging) {
// Convert string enum to number enum
let level = ELoggingLevel.WARN;
switch (logging.level) {
case 'error':
level = ELoggingLevel.ERROR;

Check warning on line 34 in apps/acf-extension/src/content_scripts/logger.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/logger.ts#L34

Unsafe assignment of an error typed value.
break;
case 'warn':
level = ELoggingLevel.WARN;
break;
case 'info':
level = ELoggingLevel.INFO;
break;
case 'debug':
level = ELoggingLevel.DEBUG;
break;
case 'trace':
level = ELoggingLevel.TRACE;
break;
}
Comment on lines +31 to +48
Copy link

Copilot AI Aug 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The manual string-to-enum conversion could be simplified using a mapping object or by ensuring both enum definitions use the same value types to avoid this conversion logic entirely.

Suggested change
let level = ELoggingLevel.WARN;
switch (logging.level) {
case 'error':
level = ELoggingLevel.ERROR;
break;
case 'warn':
level = ELoggingLevel.WARN;
break;
case 'info':
level = ELoggingLevel.INFO;
break;
case 'debug':
level = ELoggingLevel.DEBUG;
break;
case 'trace':
level = ELoggingLevel.TRACE;
break;
}
const levelMap: Record<string, ELoggingLevel> = {
error: ELoggingLevel.ERROR,
warn: ELoggingLevel.WARN,
info: ELoggingLevel.INFO,
debug: ELoggingLevel.DEBUG,
trace: ELoggingLevel.TRACE,
};
const level = levelMap[logging.level] ?? ELoggingLevel.WARN;

Copilot uses AI. Check for mistakes.


this.logger.configure({
level,
enableVerbose: logging.enableVerbose,
useRingBuffer: logging.useRingBuffer,
ringBufferSize: logging.ringBufferSize
});
}

this.initialized = true;
} catch (error) {
// Fallback to default configuration
console.warn('Failed to load logging settings, using defaults:', error);
this.initialized = true;
}
}

public error(scopes: string[], message: string, meta?: unknown): void {
this.logger.error(scopes, message, meta);
}

public warn(scopes: string[], message: string, meta?: unknown): void {
this.logger.warn(scopes, message, meta);
}

public info(scopes: string[], message: string, meta?: unknown): void {
this.logger.info(scopes, message, meta);
}

public debug(scopes: string[], message: string, meta?: unknown): void {
this.logger.debug(scopes, message, meta);
}

public trace(scopes: string[], message: string, meta?: unknown): void {
this.logger.trace(scopes, message, meta);
}

public getRingBuffer() {
return this.logger.getRingBuffer();
}

public clearRingBuffer(): void {
this.logger.clearRingBuffer();
}
}

// Global logger instance
export const logger = ContentScriptLogger.getInstance();
78 changes: 76 additions & 2 deletions apps/acf-extension/src/content_scripts/status-bar.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,77 @@
import { StatusBar } from '@dhruv-techapps/shared-status-bar';
import { SettingsStorage } from '@dhruv-techapps/acf-store';
import { EnhancedStatusBar, StatusBar, EStatusBarMode } from '@dhruv-techapps/shared-status-bar';

export const statusBar = new StatusBar();
class StatusBarFactory {
private static instance: StatusBarFactory;
private statusBar?: EnhancedStatusBar | StatusBar;
private initialized = false;

Check warning on line 7 in apps/acf-extension/src/content_scripts/status-bar.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/status-bar.ts#L7

ES2022 field 'initialized' is forbidden.

private constructor() {}

public static getInstance(): StatusBarFactory {
if (!StatusBarFactory.instance) {
StatusBarFactory.instance = new StatusBarFactory();
}
return StatusBarFactory.instance;
}

public async getStatusBar(): Promise<EnhancedStatusBar | StatusBar> {
if (!this.initialized) {
await this.initialize();
}
return this.statusBar!;
}

private async initialize(): Promise<void> {

Check warning on line 25 in apps/acf-extension/src/content_scripts/status-bar.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/status-bar.ts#L25

Method initialize has a cyclomatic complexity of 11 (limit is 8)
if (this.initialized) {
return;
}

try {
const settings = await new SettingsStorage().getSettings();

Check warning on line 31 in apps/acf-extension/src/content_scripts/status-bar.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/status-bar.ts#L31

Unsafe assignment of an error typed value.

// Use enhanced status bar with settings integration
const enhancedStatusBar = new EnhancedStatusBar();

// Configure based on settings
const statusBarMode = settings.statusBarMode ?? EStatusBarMode.FULL;

Check warning on line 37 in apps/acf-extension/src/content_scripts/status-bar.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/status-bar.ts#L37

ES2020 nullish coalescing operators are forbidden.
const enableStatusBar = settings.enableStatusBar ?? true;

Check warning on line 38 in apps/acf-extension/src/content_scripts/status-bar.ts

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

apps/acf-extension/src/content_scripts/status-bar.ts#L38

Unsafe member access .enableStatusBar on an `error` typed value.
const location = settings.statusBar === 'hide' ? 'hide' : settings.statusBar;

enhancedStatusBar.configure({
enabled: enableStatusBar && location !== 'hide',
mode: statusBarMode,
location
});

// Set location for backward compatibility
if (enableStatusBar && location !== 'hide') {
await enhancedStatusBar.setLocation(location);
}

this.statusBar = enhancedStatusBar;
this.initialized = true;
} catch (error) {
// Fallback to legacy status bar
console.warn('Failed to load status bar settings, using legacy:', error);
this.statusBar = new StatusBar();
this.initialized = true;
}
}
}

// Create proxy to maintain existing API
const factory = StatusBarFactory.getInstance();

export const statusBar = new Proxy({} as EnhancedStatusBar | StatusBar, {
get(target, prop) {
return async (...args: any[]) => {
const instance = await factory.getStatusBar();
const method = (instance as any)[prop];
if (typeof method === 'function') {
return method.apply(instance, args);
}
return method;
};
}
});
15 changes: 8 additions & 7 deletions apps/acf-extension/src/content_scripts/util/dom-watch-manager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { IWatchSettings, defaultWatchSettings } from '@dhruv-techapps/acf-common';
import { logger } from '../logger';

interface DomWatchState {
isActive: boolean;
Expand Down Expand Up @@ -27,7 +28,7 @@ const DomWatchManager = (() => {
return;
}

console.debug('DomWatchManager: Restarting action sequence due to DOM changes');
logger.debug(['DOM-WATCHER'], 'Restarting action sequence due to DOM changes');
await state.sequenceRestartCallback();
};

Expand All @@ -43,7 +44,7 @@ const DomWatchManager = (() => {
try {
await processingFn();
} catch (error) {
console.error('DomWatchManager: Error in debounced processing:', error);
logger.error(['DOM-WATCHER'], 'Error in debounced processing', error);
}
state.debounceTimeout = null;
}, delay);
Expand All @@ -60,14 +61,14 @@ const DomWatchManager = (() => {
const elapsed = Date.now() - state.startTime;
if (elapsed >= lifecycleStopConditions.timeout * 60 * 1000) {
// Convert mins to milliseconds
console.debug('DomWatchManager: Stopping due to timeout');
logger.debug(['DOM-WATCHER'], 'Stopping due to timeout');
return true;
}
}

// Check URL change
if (lifecycleStopConditions.urlChange && state.currentUrl !== window.location.href) {
console.debug('DomWatchManager: Stopping due to URL change');
logger.debug(['DOM-WATCHER'], 'Stopping due to URL change');
return true;
}

Expand Down Expand Up @@ -116,7 +117,7 @@ const DomWatchManager = (() => {
});
});

console.debug(`DomWatchManager: Initialized observer on ${watchRoot}`);
logger.debug(['DOM-WATCHER'], `Initialized observer on ${watchRoot}`);
};

// Register configuration-level DOM watching
Expand All @@ -136,7 +137,7 @@ const DomWatchManager = (() => {
start();
}

console.debug(`DomWatchManager: Registered configuration-level DOM watching`);
logger.debug(['DOM-WATCHER'], 'Registered configuration-level DOM watching');
};

// Start DOM watching
Expand All @@ -149,7 +150,7 @@ const DomWatchManager = (() => {
state.currentUrl = window.location.href;
initializeObserver();

console.debug('DomWatchManager: Started configuration-level DOM watching');
logger.debug(['DOM-WATCHER'], 'Started configuration-level DOM watching');
};

// Get current watch status
Expand Down
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading