All files / core/src/components error-boundary.js

67.64% Statements 92/136
62.59% Branches 82/131
74.19% Functions 23/31
70.76% Lines 92/130

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494                                      8x                   9x   9x 2x     7x 2x 2x 3x 3x 1x   2x     5x 5x 5x   5x 5x 5x 2x 2x           3x               18x 18x 18x 18x 18x                   6x 6x 6x 6x 6x                                                                     10x   10x 10x 10x         10x 10x 8x 8x   8x   8x             8x         8x                                                 8x       8x       6x           6x     6x 3x 3x             6x                     6x                                                                                         2x   2x 1x                 1x 1x               1x                 1x                   1x                 1x                                                             1x 1x   1x 2x     1x                             6x   6x 5x   5x     5x 5x       5x             3x   2x       2x       5x                     8x 8x 8x 8x 8x             7x   7x             7x     7x 1x       7x                                       1x             1x                     1x             1x               2x                            
/**
 * Coherent.js Error Boundary
 * 
 * Catches rendering errors and provides fallback UI.
 * Similar to React's Error Boundaries but for Coherent.js.
 * 
 * @module components/error-boundary
 */
 
import { isTrustedContent } from '../core/html-utils.js';
 
/**
 * Whether error state may persist between calls. In a browser a boundary
 * wraps one live UI, so "stay on the fallback until reset" makes sense. On
 * the server every call is a different request: shared state switched every
 * later request to the fallback after one failure, and kept that request's
 * props (possibly personal data) in memory.
 */
function isBrowser() {
  return typeof window !== 'undefined' && typeof document !== 'undefined';
}
 
/**
 * Evaluate function components nested in a tree (called without arguments,
 * as the renderer does), so that errors they throw happen inside the
 * boundary's try block. Otherwise the renderer calls them after the boundary
 * has returned and nested errors escape it.
 */
function resolveNestedComponents(node, depth = 0) {
  Iif (depth > 1000) return node;
 
  if (typeof node === 'function') {
    return resolveNestedComponents(node(), depth + 1);
  }
 
  if (Array.isArray(node)) {
    let changed = false;
    const resolved = node.map((child) => {
      const result = resolveNestedComponents(child, depth + 1);
      Iif (result !== child) changed = true;
      return result;
    });
    return changed ? resolved : node;
  }
 
  Eif (node && typeof node === 'object' && !isTrustedContent(node)) {
    const keys = Object.keys(node);
    Iif (keys.length !== 1) return node;
 
    const tag = keys[0];
    const props = node[tag];
    if (props && typeof props === 'object' && !Array.isArray(props) && props.children !== undefined) {
      const children = resolveNestedComponents(props.children, depth + 1);
      Iif (children !== props.children) {
        return { [tag]: { ...props, children } };
      }
    }
  }
 
  return node;
}
 
/**
 * Error boundary state
 */
class ErrorBoundaryState {
  constructor() {
    this.hasError = false;
    this.error = null;
    this.errorInfo = null;
    this.errorCount = 0;
    this.lastError = null;
  }
 
  reset() {
    this.hasError = false;
    this.error = null;
    this.errorInfo = null;
  }
 
  setError(error, errorInfo = {}) {
    this.hasError = true;
    this.error = error;
    this.errorInfo = errorInfo;
    this.errorCount++;
    this.lastError = Date.now();
  }
}
 
/**
 * Create an error boundary
 * 
 * @param {Object} options - Error boundary options
 * @param {Object|Function} options.fallback - Fallback component or function
 * @param {Function} [options.onError] - Error callback
 * @param {Function} [options.onReset] - Reset callback
 * @param {Array<string>} [options.resetKeys] - Keys that trigger reset
 * @param {boolean} [options.resetOnPropsChange] - Reset on props change
 * @param {number} [options.maxErrors] - Maximum errors before permanent fallback
 * @param {number} [options.resetTimeout] - Auto-reset timeout in ms
 * @returns {Function} Error boundary wrapper function
 * 
 * @example
 * const boundary = createErrorBoundary({
 *   fallback: { div: { text: 'Something went wrong' } },
 *   onError: (error, errorInfo) => console.error(error),
 *   resetKeys: ['userId']
 * });
 * 
 * const SafeComponent = boundary(MyComponent);
 */
export function createErrorBoundary(options = {}) {
  const {
    fallback = { div: { className: 'error-boundary', text: 'An error occurred' } },
    onError = null,
    onReset = null,
    resetKeys = [],
    resetOnPropsChange = false,
    maxErrors = Infinity,
    resetTimeout = null
  } = options;
 
  const sharedState = new ErrorBoundaryState();
  let previousProps = {};
  let resetTimer = null;
 
  /**
   * Wrap a component with error boundary
   */
  return function errorBoundaryWrapper(component) {
    return function wrappedComponent(props = {}) {
      const persistent = isBrowser();
      const state = persistent ? sharedState : new ErrorBoundaryState();
 
      try {
        // Check if we should reset based on props
        Iif (persistent && resetOnPropsChange && shouldReset(props, previousProps, resetKeys)) {
          state.reset();
          if (onReset) {
            onReset();
          }
        }
 
        Iif (persistent) {
          previousProps = { ...props };
        }
 
        // If we have an error and haven't exceeded max errors
        Iif (state.hasError) {
          if (state.errorCount >= maxErrors) {
            // Permanent fallback
            return typeof fallback === 'function'
              ? fallback(state.error, state.errorInfo, { permanent: true })
              : fallback;
          }
 
          // Return fallback with reset option
          const fallbackComponent = typeof fallback === 'function'
            ? fallback(state.error, state.errorInfo, {
                reset: () => {
                  state.reset();
                  if (onReset) {
                    onReset();
                  }
                },
                errorCount: state.errorCount
              })
            : fallback;
 
          return fallbackComponent;
        }
 
        // Try to render the component, nested function components included
        const result = typeof component === 'function'
          ? component(props)
          : component;
 
        return resolveNestedComponents(result);
 
      } catch (error) {
        // Capture error
        const errorInfo = {
          componentStack: error.stack,
          props,
          timestamp: Date.now()
        };
 
        state.setError(error, errorInfo);
 
        // Call error callback
        if (onError) {
          try {
            onError(error, errorInfo);
          } catch (callbackError) {
            console.error('Error in onError callback:', callbackError);
          }
        }
 
        // Set auto-reset timer if configured
        Iif (persistent && resetTimeout && !resetTimer) {
          resetTimer = setTimeout(() => {
            state.reset();
            resetTimer = null;
            if (onReset) {
              onReset();
            }
          }, resetTimeout);
        }
 
        // Return fallback
        return typeof fallback === 'function'
          ? fallback(error, errorInfo, {
              reset: () => {
                state.reset();
                if (resetTimer) {
                  clearTimeout(resetTimer);
                  resetTimer = null;
                }
                if (onReset) {
                  onReset();
                }
              },
              errorCount: state.errorCount
            })
          : fallback;
      }
    };
  };
}
 
/**
 * Check if error boundary should reset based on props
 */
function shouldReset(newProps, oldProps, resetKeys) {
  if (resetKeys.length === 0) {
    return false;
  }
 
  return resetKeys.some(key => newProps[key] !== oldProps[key]);
}
 
/**
 * Create a default error fallback component
 * 
 * @param {Object} options - Fallback options
 * @returns {Function} Fallback component function
 */
export function createErrorFallback(options = {}) {
  const {
    title = 'Something went wrong',
    showError = true,
    showStack = false,
    showReset = true,
    className = 'error-boundary-fallback',
    style = {}
  } = options;
 
  return function errorFallback(error, errorInfo, context = {}) {
    const children = [
      {
        h2: {
          className: 'error-title',
          text: title
        }
      }
    ];
 
    Eif (showError && error) {
      children.push({
        p: {
          className: 'error-message',
          text: error.message || 'Unknown error'
        }
      });
    }
 
    Iif (showStack && error && error.stack) {
      children.push({
        pre: {
          className: 'error-stack',
          text: error.stack
        }
      });
    }
 
    Iif (showReset && context.reset && !context.permanent) {
      children.push({
        button: {
          className: 'error-reset-button',
          text: 'Try Again',
          onclick: context.reset
        }
      });
    }
 
    Iif (context.errorCount > 1) {
      children.push({
        p: {
          className: 'error-count',
          text: `Error occurred ${context.errorCount} times`
        }
      });
    }
 
    return {
      div: {
        className,
        style: {
          padding: '20px',
          border: '1px solid #f44336',
          borderRadius: '4px',
          backgroundColor: '#ffebee',
          color: '#c62828',
          ...style
        },
        children
      }
    };
  };
}
 
/**
 * Wrap multiple components with the same error boundary
 * 
 * @param {Object} options - Error boundary options
 * @param {Object} components - Components to wrap
 * @returns {Object} Wrapped components
 * 
 * @example
 * const safeComponents = withErrorBoundary(
 *   { fallback: ErrorFallback },
 *   { Header, Footer, Content }
 * );
 */
export function withErrorBoundary(options, components) {
  const boundary = createErrorBoundary(options);
  const wrapped = {};
 
  Object.entries(components).forEach(([name, component]) => {
    wrapped[name] = boundary(component);
  });
 
  return wrapped;
}
 
/**
 * Error boundary for async components
 * 
 * @param {Object} options - Error boundary options
 * @returns {Function} Async error boundary wrapper
 */
export function createAsyncErrorBoundary(options = {}) {
  const {
    fallback = { div: { text: 'Loading...' } },
    errorFallback = { div: { text: 'Failed to load' } },
    onError = null,
    timeout = 10000
  } = options;
 
  return function asyncBoundaryWrapper(asyncComponent) {
    return async function wrappedAsyncComponent(props = {}) {
      let timer;
      try {
        // Set timeout (cleared below: a pending timer per call kept the
        // process alive for `timeout` ms after every render)
        const timeoutPromise = new Promise((_, reject) => {
          timer = setTimeout(() => reject(new Error('Component load timeout')), timeout);
        });
 
        // Race between component load and timeout
        const result = await Promise.race([
          typeof asyncComponent === 'function'
            ? asyncComponent(props)
            : asyncComponent,
          timeoutPromise
        ]);
 
        return result ?? fallback;
      } catch (error) {
        Iif (onError) {
          onError(error, { props, async: true });
        }
 
        return typeof errorFallback === 'function'
          ? errorFallback(error, { props })
          : errorFallback;
      } finally {
        clearTimeout(timer);
      }
    };
  };
}
 
/**
 * Global error handler for uncaught errors
 */
export class GlobalErrorHandler {
  constructor(options = {}) {
    this.options = options;
    this.errors = [];
    this.maxErrors = options.maxErrors || 100;
    this.onError = options.onError || null;
    this.enabled = options.enabled !== false;
  }
 
  /**
   * Capture an error
   */
  captureError(error, context = {}) {
    Iif (!this.enabled) return;
 
    const errorEntry = {
      error,
      context,
      timestamp: Date.now(),
      stack: error.stack
    };
 
    this.errors.push(errorEntry);
 
    // Limit stored errors
    if (this.errors.length > this.maxErrors) {
      this.errors.shift();
    }
 
    // Call error callback
    Iif (this.onError) {
      try {
        this.onError(error, context);
      } catch (callbackError) {
        console.error('Error in global error handler callback:', callbackError);
      }
    }
  }
 
  /**
   * Get all captured errors
   */
  getErrors() {
    return [...this.errors];
  }
 
  /**
   * Clear all errors
   */
  clearErrors() {
    this.errors = [];
  }
 
  /**
   * Get error statistics
   */
  getStats() {
    return {
      totalErrors: this.errors.length,
      enabled: this.enabled,
      maxErrors: this.maxErrors
    };
  }
 
  /**
   * Enable error handler
   */
  enable() {
    this.enabled = true;
  }
 
  /**
   * Disable error handler
   */
  disable() {
    this.enabled = false;
  }
}
 
/**
 * Create a global error handler
 */
export function createGlobalErrorHandler(options = {}) {
  return new GlobalErrorHandler(options);
}
 
/**
 * Export all error boundary utilities
 */
export default {
  createErrorBoundary,
  createErrorFallback,
  withErrorBoundary,
  createAsyncErrorBoundary,
  GlobalErrorHandler,
  createGlobalErrorHandler
};