CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-intlify--shared

Shared utility package for intlify project providing performance tools, string formatting, event emitters, and type checking utilities.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

warning-system.mddocs/

Warning System

Consistent warning and debugging message display system for development and production environments.

Capabilities

Basic Warning

Display warning messages with consistent formatting.

/**
 * Display a warning message with intlify prefix
 * @param msg - Warning message to display
 * @param err - Optional error object to display stack trace
 */
function warn(msg: string, err?: Error): void;

Usage Examples:

import { warn } from "@intlify/shared";

// Basic warning message
warn("Translation key not found");

// Warning with error details
try {
  riskyOperation();
} catch (error) {
  warn("Operation failed", error);
}

// Conditional warnings
function validateInput(input: any) {
  if (!input) {
    warn("Input validation failed: empty input provided");
    return false;
  }
  return true;
}

Warning Once

Display warning messages only once per unique message to avoid spam.

/**
 * Display a warning message only once per unique message
 * @param msg - Warning message to display once
 */
function warnOnce(msg: string): void;

Usage Examples:

import { warnOnce } from "@intlify/shared";

// This warning will only appear once, even if called multiple times
function deprecatedFunction() {
  warnOnce("deprecatedFunction is deprecated, use newFunction instead");
  // Function implementation...
}

// Called multiple times, but warning shows only once
deprecatedFunction(); // Warning appears
deprecatedFunction(); // No warning
deprecatedFunction(); // No warning

// Different messages are tracked separately
function anotherDeprecatedFunction() {
  warnOnce("anotherDeprecatedFunction is deprecated");
  // This will show because it's a different message
}

Warning System Behavior

Console Output Format

All warnings are prefixed with [intlify] for consistent identification:

[intlify] Translation key not found
[intlify] Operation failed
Error: Something went wrong
    at Object.<anonymous> (/path/to/file.js:10:15)
    ...

Environment Detection

The warning system automatically detects if console is available:

  • Browser environments: Uses console.warn()
  • Node.js environments: Uses console.warn()
  • Environments without console: Silent (no errors thrown)

Error Stack Traces

When an Error object is provided to warn(), the stack trace is displayed using console.warn(err.stack).

Advanced Usage Patterns

Conditional Warnings

import { warn, warnOnce } from "@intlify/shared";

// Development-only warnings
const isDevelopment = process.env.NODE_ENV === 'development';

function devWarn(message: string) {
  if (isDevelopment) {
    warn(message);
  }
}

// Usage
devWarn("This warning only appears in development");

Warning Categories

import { warn } from "@intlify/shared";

// Create category-specific warning functions
function createCategoryWarner(category: string) {
  return (message: string, error?: Error) => {
    warn(`[${category}] ${message}`, error);
  };
}

const i18nWarn = createCategoryWarner("i18n");
const routerWarn = createCategoryWarner("router");

// Usage
i18nWarn("Missing translation for key: user.name");
routerWarn("Route not found: /invalid-path");

// Output:
// [intlify] [i18n] Missing translation for key: user.name
// [intlify] [router] Route not found: /invalid-path

Performance-Conscious Warnings

import { warnOnce } from "@intlify/shared";

class PerformanceMonitor {
  private warningThresholds = {
    slow: 100,
    verySlow: 1000
  };

  measureOperation(name: string, operation: () => void) {
    const start = Date.now();
    operation();
    const duration = Date.now() - start;
    
    if (duration > this.warningThresholds.verySlow) {
      warnOnce(`Operation "${name}" is very slow (${duration}ms)`);
    } else if (duration > this.warningThresholds.slow) {
      warnOnce(`Operation "${name}" is slow (${duration}ms)`);
    }
  }
}

Error Context Enhancement

import { warn } from "@intlify/shared";

function enhancedWarn(message: string, context?: Record<string, any>, error?: Error) {
  let fullMessage = message;
  
  if (context) {
    const contextStr = Object.entries(context)
      .map(([key, value]) => `${key}: ${JSON.stringify(value)}`)
      .join(", ");
    fullMessage += ` (Context: ${contextStr})`;
  }
  
  warn(fullMessage, error);
}

// Usage
enhancedWarn("API request failed", {
  url: "/api/users",
  method: "GET",
  status: 404
});

// Output: [intlify] API request failed (Context: url: "/api/users", method: "GET", status: 404)

Integration with Intlify Ecosystem

Translation Warnings

import { warn, warnOnce } from "@intlify/shared";

function handleTranslationIssues() {
  // One-time warnings for missing configurations
  warnOnce("Fallback locale not configured");
  
  // Per-occurrence warnings for runtime issues
  warn("Translation key 'user.welcome' not found in locale 'fr'");
}

Development vs Production

import { warn, warnOnce } from "@intlify/shared";

// The warning system works in both development and production
// Use conditional logic for development-only warnings
function createI18nInstance(options: any) {
  if (process.env.NODE_ENV === 'development') {
    if (!options.locale) {
      warn("No default locale specified, using 'en'");
    }
    
    if (options.legacy === undefined) {
      warnOnce("Consider setting legacy mode explicitly for better performance");
    }
  }
  
  // Production warnings for critical issues
  if (!options.messages) {
    warn("No translation messages provided");
  }
}

Memory Management

The warnOnce function maintains an internal record of displayed messages:

  • Memory usage: Grows with unique warning messages
  • Cleanup: No automatic cleanup (messages persist for application lifetime)
  • Best practice: Use warnOnce for finite set of deprecation warnings, not dynamic content
// ✅ Good: Finite set of deprecation warnings
warnOnce("Method X is deprecated, use Y instead");

// ❌ Avoid: Dynamic content that could cause memory leaks
warnOnce(`User ${userId} has invalid data`); // Could create many unique messages

docs

environment-performance.md

event-system.md

index.md

object-utilities.md

string-processing.md

type-checking.md

warning-system.md

tile.json