@wauth/sdk
Version:
Web2 auth sdk for Arweave
188 lines • 7.98 kB
JavaScript
export var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
LogLevel[LogLevel["INFO"] = 1] = "INFO";
LogLevel[LogLevel["WARN"] = 2] = "WARN";
LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
LogLevel[LogLevel["OFF"] = 4] = "OFF";
})(LogLevel || (LogLevel = {}));
export class WAuthLogger {
static instance;
logLevel = LogLevel.INFO;
prefix = '[WAuth SDK]';
isFirstLog = true;
constructor() {
// Set log level from environment or default
const envLogLevel = (typeof process !== 'undefined' && process.env?.WAUTH_LOG_LEVEL) || 'INFO';
this.logLevel = LogLevel[envLogLevel.toUpperCase()] || LogLevel.INFO;
}
static getInstance() {
if (!WAuthLogger.instance) {
WAuthLogger.instance = new WAuthLogger();
}
return WAuthLogger.instance;
}
showWAuthHeader() {
if (this.isFirstLog) {
console.log('%c┌─────────────────────────────────────────────┐', 'color: #FF6B35;');
console.log('%c│ 🔐 WAUTH SDK LOGS 🔐 │', 'color: #FF6B35; font-weight: bold;');
console.log('%c└─────────────────────────────────────────────┘', 'color: #FF6B35;');
console.log('');
this.isFirstLog = false;
}
}
setLogLevel(level) {
this.logLevel = level;
}
shouldLog(level) {
return level >= this.logLevel;
}
formatMessage(level, component, message, data) {
const timestamp = new Date().toISOString();
const baseMessage = `${this.prefix} ${timestamp} [${level}] [${component}] ${message}`;
if (data) {
return `${baseMessage} ${JSON.stringify(data, null, 2)}`;
}
return baseMessage;
}
debug(component, message, data) {
if (this.shouldLog(LogLevel.DEBUG)) {
console.debug(this.formatMessage('DEBUG', component, message, data));
}
}
info(component, message, data) {
if (this.shouldLog(LogLevel.INFO)) {
console.info(this.formatMessage('INFO', component, message, data));
}
}
warn(component, message, data) {
if (this.shouldLog(LogLevel.WARN)) {
console.warn(this.formatMessage('WARN', component, message, data));
}
}
error(component, message, error) {
if (this.shouldLog(LogLevel.ERROR)) {
let errorData = error;
if (error instanceof Error) {
errorData = {
name: error.name,
message: error.message,
stack: error.stack
};
}
console.error(this.formatMessage('ERROR', component, message, errorData));
}
}
// WAuth-specific beautified logging methods
authStart(operation, provider, input) {
this.showWAuthHeader();
const providerText = provider ? ` via ${provider}` : '';
console.groupCollapsed(`%c🔐 ${operation}${providerText}`, 'color: #FF6B35; font-weight: bold; font-size: 12px;');
if (input && Object.keys(input).length > 0) {
console.log('%cInput:', 'color: #4CAF50; font-weight: bold;', input);
}
}
authSuccess(operation, result, duration) {
const durationText = duration ? ` (${duration}ms)` : '';
console.log('%cResult:', 'color: #2196F3; font-weight: bold;', result);
console.groupEnd();
// Show a success summary
console.log(`%c✅ ${operation} completed successfully${durationText}`, 'color: #4CAF50; font-weight: bold; font-size: 11px;');
}
authError(operation, error, duration) {
const errorStr = error instanceof Error ? error.message : String(error);
const durationText = duration ? ` (${duration}ms)` : '';
console.log('%cError:', 'color: #F44336; font-weight: bold;', errorStr);
if (error instanceof Error && error.stack) {
console.log('%cStack Trace:', 'color: #FF9800; font-weight: bold;');
console.log(error.stack);
}
console.groupEnd();
// Show an error summary
console.log(`%c❌ ${operation} failed${durationText}`, 'color: #F44336; font-weight: bold; font-size: 11px;');
}
// Wallet operations
walletOperation(operation, details) {
console.groupCollapsed(`%c💳 Wallet ${operation}`, 'color: #9C27B0; font-weight: bold; font-size: 12px;');
if (details) {
console.log('%cDetails:', 'color: #2196F3; font-weight: bold;', details);
}
console.groupEnd();
}
// Session management
sessionUpdate(action, details) {
console.groupCollapsed(`%c🔑 Session ${action}`, 'color: #607D8B; font-weight: bold; font-size: 12px;');
if (details) {
console.log('%cSession Info:', 'color: #2196F3; font-weight: bold;', details);
}
console.groupEnd();
}
// Password operations
passwordOperation(operation, success = true, attempt) {
const icon = success ? '🔓' : '🔒';
const color = success ? '#4CAF50' : '#FF9800';
const attemptText = attempt ? ` (attempt ${attempt})` : '';
console.log(`%c${icon} Password ${operation}${attemptText}`, `color: ${color}; font-weight: bold; font-size: 11px;`);
}
// Backend operations
backendRequest(method, endpoint, status) {
const statusIcon = status && status < 400 ? '📡' : '⚠️';
const statusColor = status && status < 400 ? '#2196F3' : '#FF9800';
const statusText = status ? ` [${status}]` : '';
console.log(`%c${statusIcon} ${method} ${endpoint}${statusText}`, `color: ${statusColor}; font-weight: bold; font-size: 11px;`);
}
// Construction and initialization
initialization(message, data) {
console.groupCollapsed(`%c⚡ WAuth ${message}`, 'color: #FF6B35; font-weight: bold; font-size: 12px;');
if (data) {
console.log('%cConfig:', 'color: #2196F3; font-weight: bold;', data);
}
console.groupEnd();
}
// Simple styled logging for common operations
simple(level, message, data) {
const styles = {
info: { icon: 'ℹ️', color: '#2196F3' },
warn: { icon: '⚠️', color: '#FF9800' },
error: { icon: '❌', color: '#F44336' }
};
const { icon, color } = styles[level];
if (data) {
console.groupCollapsed(`%c${icon} ${message}`, `color: ${color}; font-weight: bold; font-size: 11px;`);
console.log('%cData:', 'color: #666; font-weight: bold;', data);
console.groupEnd();
}
else {
console.log(`%c${icon} ${message}`, `color: ${color}; font-weight: bold; font-size: 11px;`);
}
}
}
// Export singleton instance
export const wauthLogger = WAuthLogger.getInstance();
// Helper function to measure execution time for WAuth operations
export function measureWAuthTime(fn) {
const start = Date.now();
return fn().then(result => ({
result,
duration: Date.now() - start
}));
}
// Helper function to wrap WAuth operations with logging
export async function loggedWAuthOperation(operation, input, fn, provider) {
const logger = WAuthLogger.getInstance();
const startTime = Date.now();
// Show operation start
logger.authStart(operation, provider, input);
try {
const result = await fn();
const duration = Date.now() - startTime;
logger.authSuccess(operation, result, duration);
return result;
}
catch (error) {
const duration = Date.now() - startTime;
logger.authError(operation, error, duration);
throw error;
}
}
//# sourceMappingURL=logger.js.map