{"_id":"@codeimplants/app-core","_rev":"2-7470ea2ced5f31bf7299cf1d59a9e4d8","name":"@codeimplants/app-core","dist-tags":{"latest":"1.0.1"},"versions":{"1.0.0":{"name":"@codeimplants/app-core","version":"1.0.0","keywords":["app-core","error-handling","retry-logic","state-management","platform-agnostic","typescript","react","react-native","ionic","capacitor","error-recovery","circuit-breaker","exponential-backoff","health-monitoring","version-management","zero-dependencies"],"author":{"name":"Code Implants"},"license":"MIT","_id":"@codeimplants/app-core@1.0.0","maintainers":[{"name":"codeimplants","email":"codeimplants@gmail.com"}],"homepage":"https://github.com/codeimplants/digital-libraries/tree/main/packages/core/app-core#readme","bugs":{"url":"https://github.com/codeimplants/digital-libraries/issues"},"dist":{"shasum":"e1ff35540935b7397426534f893f250fe96a7c3f","tarball":"https://registry.npmjs.org/@codeimplants/app-core/-/app-core-1.0.0.tgz","fileCount":191,"integrity":"sha512-EK3rp+6ZSzbAt6GhY48k1rUYnvPg59DMJdXaiQscEJTdJP3SValxJcdL59jjgej3Zygfkn94ajHawY5mbu8xlA==","signatures":[{"sig":"MEQCIDXuPCSBkCfcslfeZ5L5dSChQPaumiTrgqGeTNdrL0LXAiBX72kH68By5rI9xlhNWu4X/0yJvLsUY9G+KmC+foaZqw==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":255481},"main":"dist/index.js","types":"dist/index.d.ts","engines":{"npm":">=8.0.0","node":">=16.0.0"},"gitHead":"d2d9201914a7632aca41f8289c06a59304b16c1d","scripts":{"test":"jest","build":"tsc -p tsconfig.build.json","clean":"rimraf dist","prebuild":"npm run clean","preversion":"npm run test","test:watch":"jest --watch","type-check":"tsc --noEmit","build:watch":"tsc -p tsconfig.build.json --watch","postversion":"git push && git push --tags","test:coverage":"jest --coverage","prepublishOnly":" npm run type-check && npm run build"},"_npmUser":{"name":"codeimplants","email":"codeimplants@gmail.com"},"repository":{"url":"git+https://github.com/codeimplants/digital-libraries.git","type":"git","directory":"packages/core/app-core"},"_npmVersion":"11.6.2","description":"Platform-agnostic foundational package for building robust applications across Web, React Native, Ionic, and Capacitor","directories":{},"sideEffects":false,"_nodeVersion":"22.12.0","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^30.2.0","rimraf":"^6.1.2","ts-jest":"^29.4.6","typescript":"^5.9.3","@types/jest":"^30.0.0","@types/node":"^25.2.3","jest-fetch-mock":"^3.0.3"},"_npmOperationalInternal":{"tmp":"tmp/app-core_1.0.0_1771087753640_0.8043890513280942","host":"s3://npm-registry-packages-npm-production"}},"1.0.1":{"name":"@codeimplants/app-core","version":"1.0.1","description":"Platform-agnostic foundational package for building robust applications across Web, React Native, Ionic, and Capacitor","main":"dist/index.js","types":"dist/index.d.ts","sideEffects":false,"scripts":{"build":"tsc -p tsconfig.build.json","build:watch":"tsc -p tsconfig.build.json --watch","test":"jest","test:watch":"jest --watch","test:coverage":"jest --coverage","type-check":"tsc --noEmit","clean":"rimraf dist","prebuild":"npm run clean","prepublishOnly":" npm run type-check && npm run build","preversion":"npm run test","postversion":"git push && git push --tags"},"keywords":["app-core","error-handling","retry-logic","state-management","platform-agnostic","typescript","react","react-native","ionic","capacitor","error-recovery","circuit-breaker","exponential-backoff","health-monitoring","version-management","zero-dependencies"],"author":{"name":"Code Implants"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/codeimplants/digital-libraries.git","directory":"packages/core/app-core"},"bugs":{"url":"https://github.com/codeimplants/digital-libraries/issues"},"homepage":"https://github.com/codeimplants/digital-libraries/tree/main/packages/core/app-core#readme","publishConfig":{"access":"public"},"devDependencies":{"@types/jest":"^30.0.0","@types/node":"^25.2.3","jest":"^30.2.0","jest-fetch-mock":"^3.0.3","rimraf":"^6.1.2","ts-jest":"^29.4.6","typescript":"^5.9.3"},"engines":{"node":">=16.0.0","npm":">=8.0.0"},"gitHead":"2f8b6605bf2a9697c19749338e31bf6446e44446","_id":"@codeimplants/app-core@1.0.1","_nodeVersion":"22.12.0","_npmVersion":"11.6.2","dist":{"integrity":"sha512-9h8rBF/T16Q0l4XqpCYDtvl1U5wy5j6Rzc9mFvCRGeglsOgDuqQ5njfdfA1JA3tmu7+tZTJx5zCZ1rTiOJPgdw==","shasum":"1a9645d6df8b653d1f511653ad82b5b591278200","tarball":"https://registry.npmjs.org/@codeimplants/app-core/-/app-core-1.0.1.tgz","fileCount":187,"unpackedSize":271237,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIBUWHZhZNaT3qPyg0/Iyo1bOdPeGDbApz8F5k71PlcoqAiAIqLAm8Gjd1zaqtJBnPa2F8iXz8gi18Cl96oslU5tZFw=="}]},"_npmUser":{"name":"codeimplants","email":"codeimplants@gmail.com"},"directories":{},"maintainers":[{"name":"codeimplants","email":"codeimplants@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/app-core_1.0.1_1771446553464_0.9394183610348723"},"_hasShrinkwrap":false}},"time":{"created":"2026-02-14T16:49:13.583Z","modified":"2026-02-18T20:29:13.764Z","1.0.0":"2026-02-14T16:49:13.781Z","1.0.1":"2026-02-18T20:29:13.641Z"},"bugs":{"url":"https://github.com/codeimplants/digital-libraries/issues"},"author":{"name":"Code Implants"},"license":"MIT","homepage":"https://github.com/codeimplants/digital-libraries/tree/main/packages/core/app-core#readme","keywords":["app-core","error-handling","retry-logic","state-management","platform-agnostic","typescript","react","react-native","ionic","capacitor","error-recovery","circuit-breaker","exponential-backoff","health-monitoring","version-management","zero-dependencies"],"repository":{"type":"git","url":"git+https://github.com/codeimplants/digital-libraries.git","directory":"packages/core/app-core"},"description":"Platform-agnostic foundational package for building robust applications across Web, React Native, Ionic, and Capacitor","maintainers":[{"name":"codeimplants","email":"codeimplants@gmail.com"}],"readme":"# @codeimplants/app-core\r\n\r\n> Platform-agnostic App Foundation / Core SDK for building robust, production-ready applications across Web (React), React Native, Ionic, and Capacitor. **Single shared package—imported by every app. No app overrides core behavior.**\r\n\r\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\r\n\r\n## 📋 Table of Contents\r\n\r\n- [Overview](#overview)\r\n- [App Foundation Checklist](#app-foundation-checklist)\r\n- [Features](#features)\r\n- [Installation](#installation)\r\n- [Copy-Paste Setup](#copy-paste-setup)\r\n- [Quick Start](#quick-start)\r\n- [Core Concepts](#core-concepts)\r\n- [API Reference](#api-reference)\r\n- [Platform Integration](#platform-integration)\r\n- [Integration with Related Packages](#integration-with-related-packages)\r\n- [Global Error Boundary Integration](#global-error-boundary-integration)\r\n- [Best Practices](#best-practices)\r\n- [Full Application Integration](#full-application-integration)\r\n- [Examples](#examples)\r\n- [Contributing](#contributing)\r\n- [License](#license)\r\n\r\n## 🎯 Overview\r\n\r\n`@codeimplants/app-core` is the platform-agnostic **App Foundation / Core SDK** that provides shared business logic and infrastructure independent of UI and platform. It acts as the single shared foundation for all applications—every app imports it, and core behavior is not overridden by apps.\r\n\r\n### What it Does\r\n\r\n- **Global Error Boundary** - Unified error handling, retry & circuit breaker, central support\r\n- **Environment and configuration management** - Centralized config with feature flags\r\n- **API layer abstraction** - HTTP client, interceptors, error normalization\r\n- **Authentication logic** - Login, logout, token refresh, session handling\r\n- **Storage abstraction** - Unified interface for web and native storage\r\n- **App lifecycle hooks** - init, pause, resume, destroy\r\n- **Logging system** - Dev and production support with configurable levels\r\n- **Integration layer** - Offline/network status monitoring\r\n- **Shared constants, types, and utilities** - Type-safe interfaces\r\n\r\n### What it Doesn't Do\r\n\r\n- ❌ No UI components or styling (use `@codeimplants/ui-kit` for screens)\r\n- ❌ No platform-specific code (no direct localStorage, AsyncStorage, DOM usage)\r\n- ❌ No framework-specific dependencies\r\n\r\n---\r\n\r\n## ✅ App Foundation Checklist\r\n\r\n| Requirement | API / Feature |\r\n|-------------|---------------|\r\n| **Global Error Boundary** | `handleError(error, context)`, `reportCrash(context)` + Error Boundary integration |\r\n| **Unified fallback UI** | `showFallback(type)` returns fallback config; emit `fallback_requested` |\r\n| **Retry & circuit breaker** | `executeWithRetry()`, `RetryManager`, `CircuitBreaker` |\r\n| **Support** | Use `@codeimplants/support` with ui-kit for WhatsApp/Email/Phone buttons |\r\n| **App lifecycle hooks** | `onInit()`, `onPause()`, `onResume()`, `destroy()` |\r\n| **Config & feature flags** | `getConfig()`, `updateConfig()`, `getFeatureFlag(key)` |\r\n\r\n### Required APIs (Must Provide)\r\n\r\n```typescript\r\nappCore.handleError(error, context)   // Error classification + decision\r\nappCore.showFallback(type)            // Unified fallback config\r\nappCore.reportCrash(context)          // Crash reporting\r\n// Support: use @codeimplants/support + ui-kit for WhatsApp/Email/Phone buttons\r\n```\r\n\r\n## ✨ Features\r\n\r\n- **🔐 Authentication Manager** - Complete token management, auto-refresh, session handling\r\n- **💾 Storage Abstraction** - Unified interface for Web, React Native, and Ionic storage\r\n- **🌐 Robust API Client** - Http client with interceptors, error normalization, and types\r\n- **🔄 Intelligent Retry Logic** - Exponential backoff, circuit breakers, configurable strategies\r\n- **🛡️ Robust Error Handling** - Error classification, automatic recovery, support escalation\r\n- **📊 App State Management** - Health monitoring, connectivity tracking, degraded state handling\r\n- **🎯 Support Integration** - Contextual support, frustration detection, multi-channel\r\n- **🔧 Recovery Strategies** - Clear cache, reset state, reload app, safe mode\r\n- **📝 Comprehensive Logging** - Configurable levels, namespace support, production-ready\r\n- **🎪 Event System** - Type-safe event emitter for cross-module communication\r\n- **✅ Full TypeScript Support** - Complete type definitions and inference\r\n- **🧪 Testable** - Dependency injection, mockable interfaces\r\n- **📦 Zero Dependencies** - No runtime dependencies, minimal bundle size\r\n\r\n## 📦 Installation\r\n\r\n```bash\r\nnpm install @codeimplants/app-core\r\n```\r\n\r\nor\r\n\r\n```bash\r\nyarn add @codeimplants/app-core\r\n```\r\n\r\n---\r\n\r\n## 📋 Copy-Paste Setup\r\n\r\nCopy these blocks into your app to enable core features.\r\n\r\n### 1. AppCore init (`src/init.ts` or `appCore.ts`)\r\n\r\n```typescript\r\nimport {\r\n  AppCore,\r\n  MemoryStorage,\r\n  Logger,\r\n} from '@codeimplants/app-core'\r\n\r\nconst appCore = new AppCore({\r\n  errorConfig: {\r\n    maxRetries: 3,\r\n    supportThreshold: 2,\r\n    recoveryThreshold: 5,\r\n  },\r\n  featureFlags: {\r\n    // your flags\r\n  },\r\n})\r\n\r\n// Optional: global uncaught error handler (call early in bootstrap)\r\nif (typeof window !== 'undefined') {\r\n  window.onerror = (message, source, lineno, colno, error) => {\r\n    appCore.reportCrash({\r\n      message: String(message),\r\n      stack: error?.stack,\r\n      metadata: { source, lineno, colno },\r\n    })\r\n  }\r\n}\r\n\r\nexport { appCore }\r\n```\r\n\r\n### 2. React – root wrap (`App.tsx`)\r\n\r\n```tsx\r\nimport React, { Component, ErrorInfo, ReactNode } from 'react'\r\nimport { appCore } from './init'\r\n\r\ninterface Props { children: ReactNode }\r\n\r\nclass AppErrorBoundary extends Component<Props, { hasError: boolean }> {\r\n  state = { hasError: false }\r\n\r\n  static getDerivedStateFromError() {\r\n    return { hasError: true }\r\n  }\r\n\r\n  componentDidCatch(error: Error, errorInfo: ErrorInfo) {\r\n    appCore.reportCrash({\r\n      message: error.message,\r\n      stack: error.stack,\r\n      component: errorInfo.componentStack,\r\n    })\r\n  }\r\n\r\n  render() {\r\n    if (this.state.hasError) {\r\n      const fallback = appCore.showFallback('generic_error')\r\n      return (\r\n        <div>\r\n          <h1>{fallback.title}</h1>\r\n          <p>{fallback.message}</p>\r\n          <button onClick={() => { appCore.resetErrorState(); this.setState({ hasError: false }) }}>\r\n            Try Again\r\n          </button>\r\n          <button>Contact Support</button> {/* Wire to @codeimplants/support */}\r\n        </div>\r\n      )\r\n    }\r\n    return this.props.children\r\n  }\r\n}\r\n\r\nfunction App() {\r\n  return (\r\n    <AppErrorBoundary>\r\n      {/* Your app */}\r\n    </AppErrorBoundary>\r\n  )\r\n}\r\n```\r\n\r\n### 3. React Native – root wrap + lifecycle\r\n\r\n```tsx\r\nimport React, { Component, ErrorInfo, ReactNode } from 'react'\r\nimport { View, Text, Button, AppState, AppStateStatus } from 'react-native'\r\nimport { appCore } from './init'\r\n\r\n// Error boundary\r\ninterface Props { children: ReactNode }\r\nclass AppErrorBoundary extends Component<Props, { hasError: boolean }> {\r\n  state = { hasError: false }\r\n\r\n  static getDerivedStateFromError() {\r\n    return { hasError: true }\r\n  }\r\n\r\n  componentDidCatch(error: Error, errorInfo: ErrorInfo) {\r\n    appCore.reportCrash({\r\n      message: error.message,\r\n      stack: error.stack,\r\n      component: errorInfo.componentStack,\r\n    })\r\n  }\r\n\r\n  render() {\r\n    if (this.state.hasError) {\r\n      const fallback = appCore.showFallback('generic_error')\r\n      return (\r\n        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 }}>\r\n          <Text>{fallback.title}</Text>\r\n          <Text>{fallback.message}</Text>\r\n          <Button title=\"Try Again\" onPress={() => { appCore.resetErrorState(); this.setState({ hasError: false }) }} />\r\n          <Button title=\"Contact Support\" /> {/* Wire to @codeimplants/support */}\r\n        </View>\r\n      )\r\n    }\r\n    return this.props.children\r\n  }\r\n}\r\n\r\n// Lifecycle sync (use in root component)\r\nexport function useAppLifecycle() {\r\n  React.useEffect(() => {\r\n    const sub = AppState.addEventListener('change', (state: AppStateStatus) => {\r\n      if (state === 'active') appCore.onResume()\r\n      else if (state === 'background') appCore.onPause()\r\n    })\r\n    return () => sub.remove()\r\n  }, [])\r\n}\r\n\r\n// Usage in App.tsx\r\nexport default function App() {\r\n  useAppLifecycle()\r\n  return (\r\n    <AppErrorBoundary>\r\n      {/* Your app */}\r\n    </AppErrorBoundary>\r\n  )\r\n}\r\n```\r\n\r\n### 4. Error handling in async code\r\n\r\n```typescript\r\nimport { appCore } from './init'\r\n\r\nasync function fetchData() {\r\n  try {\r\n    const data = await appCore.executeWithRetry(() => fetch('/api/data').then(r => r.json()), {\r\n      maxAttempts: 3,\r\n      onRetry: (attempt) => console.log(`Retry ${attempt}`),\r\n    })\r\n    return data\r\n  } catch (error) {\r\n    const decision = appCore.handleError(error as Error, { action: 'fetch_data', component: 'DataScreen' })\r\n    if (decision.action === 'show_support') { /* Show ui-kit screen with support buttons */ }\r\n    else if (decision.screenData) appCore.showFallback(decision.screen ?? 'generic_error', decision.screenData)\r\n    throw error\r\n  }\r\n}\r\n```\r\n\r\n### 5. Connectivity sync (with `@codeimplants/app-network`)\r\n\r\n```tsx\r\nimport { useEffect } from 'react'\r\nimport { OfflineProvider, OfflineBanner, useOffline } from '@codeimplants/app-network'\r\nimport { appCore } from './init'\r\n\r\nfunction ConnectivitySync() {\r\n  const { isOnline } = useOffline()\r\n  useEffect(() => { appCore.updateConnectivity(isOnline) }, [isOnline])\r\n  return null\r\n}\r\n\r\nexport function App() {\r\n  return (\r\n    <OfflineProvider>\r\n      <ConnectivitySync />\r\n      <OfflineBanner />\r\n      {/* Your app */}\r\n    </OfflineProvider>\r\n  )\r\n}\r\n```\r\n\r\n### 6. Version check before render (with `@codeimplants/version-control`)\r\n\r\n```typescript\r\nimport { VersionSDK } from '@codeimplants/version-control'\r\nimport { appCore } from './init'\r\n\r\nexport async function bootstrap() {\r\n  const decision = await VersionSDK.check('https://api.yourapp.com', 'your-api-key')\r\n  if (['FORCE_UPDATE', 'KILL_SWITCH', 'MAINTENANCE'].includes(decision.action)) {\r\n    appCore.showFallback('maintenance', { message: decision.message })\r\n    return false\r\n  }\r\n  appCore.onInit()\r\n  return true\r\n}\r\n```\r\n\r\n---\r\n\r\n## 🚀 Quick Start\r\n\r\n### Basic Setup\r\n\r\n```typescript\r\nimport {\r\n  AppCore,\r\n  AuthManager,\r\n  ApiClient,\r\n  MemoryStorage,\r\n  Logger,\r\n  AppCoreEventEmitter,\r\n} from '@codeimplants/app-core'\r\n\r\n// 1. Initialize dependencies\r\nconst logger = new Logger('App')\r\nconst eventEmitter = new AppCoreEventEmitter()\r\nconst storage = new MemoryStorage() // Use platform-specific adapter in production\r\n\r\n// 2. Initialize AppCore\r\nconst appCore = new AppCore({\r\n  errorConfig: {\r\n    maxRetries: 3,\r\n  },\r\n  // ... other config\r\n})\r\n\r\n// 3. Initialize AuthManager\r\nconst authManager = new AuthManager(\r\n  storage,\r\n  eventEmitter,\r\n  {\r\n    tokenKey: 'app_token',\r\n    autoRefresh: true,\r\n  },\r\n  logger\r\n)\r\n\r\n// 4. Initialize ApiClient\r\nconst apiClient = new ApiClient(\r\n  {\r\n    baseURL: 'https://api.yourapp.com',\r\n    timeout: 30000,\r\n  },\r\n  logger\r\n)\r\n\r\nexport { appCore, authManager, apiClient }\r\n```\r\n\r\n### Making Authenticated Requests\r\n\r\n```typescript\r\nimport { AuthInterceptor } from '@codeimplants/app-core'\r\nimport { apiClient, authManager } from './init'\r\n\r\n// Add auth interceptor to automatically inject token\r\napiClient.addInterceptor(\r\n  new AuthInterceptor(async () => {\r\n    return await authManager.getToken()\r\n  })\r\n)\r\n\r\nasync function fetchUserProfile() {\r\n  try {\r\n    // Typed response\r\n    const response = await apiClient.get<UserProfile>('/api/me')\r\n    return response.data\r\n  } catch (error) {\r\n    // Error is automatically normalized\r\n    throw error\r\n  }\r\n}\r\n```\r\n\r\n### Error Handling\r\n\r\n```typescript\r\nimport { appCore } from './init'\r\n\r\nasync function safeFetch() {\r\n  try {\r\n    // ... operation\r\n  } catch (error) {\r\n    // Get intelligent decision on how to handle the error\r\n    const decision = appCore.handleError(error as Error, {\r\n      action: 'fetch_data',\r\n      component: 'UserProfile',\r\n    })\r\n\r\n    switch (decision.action) {\r\n      case 'retry':\r\n        // ...\r\n        break\r\n      // ... handle other actions\r\n    }\r\n  }\r\n}\r\n```\r\n\r\n### Retry with Automatic Backoff\r\n\r\n```typescript\r\nimport appCore from './appCore'\r\n\r\nasync function fetchWithRetry() {\r\n  try {\r\n    const data = await appCore.executeWithRetry(\r\n      async () => {\r\n        const response = await fetch('/api/data')\r\n        if (!response.ok) throw new Error('API Error')\r\n        return response.json()\r\n      },\r\n      {\r\n        maxAttempts: 3,\r\n        exponentialBackoff: true,\r\n        timeout: 5000,\r\n        onRetry: (attempt, delay) => {\r\n          console.log(`Retry attempt ${attempt}, waiting ${delay}ms`)\r\n        },\r\n      }\r\n    )\r\n\r\n    return data\r\n  } catch (error) {\r\n    console.error('All retries exhausted', error)\r\n    throw error\r\n  }\r\n}\r\n```\r\n\r\n### App State Monitoring\r\n\r\n```typescript\r\nimport appCore from './appCore'\r\n\r\n// Get current app state\r\nconst state = appCore.getAppState()\r\n\r\nconsole.log('Current state:', state.state) // 'healthy' | 'degraded' | 'critical' | 'offline' | 'maintenance'\r\nconsole.log('Can make API calls:', state.allowedActions.canMakeApiCalls)\r\nconsole.log('Can use cache:', state.allowedActions.canUseCache)\r\n\r\n// Listen to state changes\r\nappCore.on('state_changed', (event) => {\r\n  console.log('State changed:', event.payload.previousState, '->', event.payload.newState)\r\n\r\n  // Update UI based on new state\r\n  if (event.payload.newState === 'offline') {\r\n    showOfflineBanner()\r\n  }\r\n})\r\n\r\n// Update connectivity manually\r\nwindow.addEventListener('online', () => appCore.updateConnectivity(true))\r\nwindow.addEventListener('offline', () => appCore.updateConnectivity(false))\r\n```\r\n\r\n## 🧩 Core Concepts\r\n\r\n### Managers\r\n\r\nThe package is organized into specialized managers:\r\n\r\n- **ErrorManager** - Classifies errors, tracks error history, determines recovery strategies\r\n- **RetryManager** - Handles retry logic with backoff strategies and circuit breakers\r\n- **AppStateManager** - Monitors app health, connectivity, and determines allowed actions\r\n\r\n- **RecoveryManager** - Executes recovery strategies when errors persist\r\n\r\n### Event System\r\n\r\nAll managers emit events through a centralized event emitter:\r\n\r\n```typescript\r\n// Listen to all events\r\nappCore.on('*', (event) => {\r\n  console.log('Event:', event.type, event.payload)\r\n})\r\n\r\n// Listen to specific events\r\nappCore.on('error_occurred', (event) => {\r\n  // Send to analytics\r\n  analytics.track('error', event.payload)\r\n})\r\n\r\nappCore.on('retry_attempted', (event) => {\r\n  console.log(`Retry ${event.payload.attemptNumber}/${event.payload.maxAttempts}`)\r\n})\r\n```\r\n\r\n### Error Classification\r\n\r\nErrors are automatically classified into types:\r\n\r\n- `network` - Network connectivity issues\r\n- `timeout` - Request timeouts\r\n- `server` - 5xx server errors\r\n- `client` - 4xx client errors\r\n- `auth` - Authentication/authorization errors\r\n- `not_found` - 404 errors\r\n- `rate_limit` - Rate limiting errors\r\n- `validation` - Input validation errors\r\n- `critical` - Critical system errors\r\n- `unknown` - Unclassified errors\r\n\r\n### Retry Strategies\r\n\r\nBuilt-in retry strategies:\r\n\r\n- **ExponentialBackoff** - Delay doubles with each retry (1s, 2s, 4s, 8s...)\r\n- **LinearBackoff** - Fixed delay between retries\r\n- **CircuitBreaker** - Prevents cascading failures by opening circuit after threshold\r\n\r\n## 📚 API Reference\r\n\r\n### AppCore\r\n\r\n#### Constructor\r\n\r\n```typescript\r\nnew AppCore(config: AppCoreConfig)\r\n```\r\n\r\n#### Methods\r\n\r\n| Method | Description |\r\n|--------|-------------|\r\n| `handleError(error, context?)` | Handle error, return `ErrorDecision` (retry, show_error, show_support, recover) |\r\n| `showFallback(type, overrides?)` | Return unified fallback config; emit `fallback_requested` |\r\n| `reportCrash(context)` | Report crash; emit `crash_reported`; track in ErrorManager |\r\n| `executeWithRetry(operation, options?)` | Execute with retry & circuit breaker |\r\n| `getAppState()` | Current app state (healthy, degraded, critical, offline, maintenance) |\r\n| `updateConnectivity(isOnline)` | Update network status |\r\n| `resetErrorState()` | Reset consecutive error count |\r\n| `getFeatureFlag(key)` | Get feature flag value |\r\n| `onInit(metadata?)` | App lifecycle: init |\r\n| `onPause(metadata?)` | App lifecycle: pause (background) |\r\n| `onResume(metadata?)` | App lifecycle: resume (foreground) |\r\n| `on(eventType, callback)` | Subscribe to events |\r\n| `getConfig()` / `updateConfig()` | Config access |\r\n| `destroy()` | Cleanup |\r\n\r\n### Fallback Types\r\n\r\n`showFallback(type)` accepts: `offline`, `api_error`, `maintenance`, `slow_connection`, `permission`, `rate_limit`, `generic_error`, `loading`, `empty_state`, `session_expired`.\r\n\r\n### Event Types\r\n\r\n- `error_occurred` - When an error is handled\r\n- `fallback_requested` - When `showFallback()` is called\r\n- `crash_reported` - When `reportCrash()` is called\r\n- `retry_attempted`, `state_changed`, `recovery_started`\r\n- `app_init`, `app_pause`, `app_resume`, `app_destroy` - Lifecycle\r\n- `circuit_breaker_opened`, `circuit_breaker_closed`\r\n\r\n## 🔌 Platform Integration\r\n\r\n### React\r\n\r\n```typescript\r\n// hooks/useAppCore.ts\r\nimport { useEffect, useState } from 'react';\r\nimport appCore from '../appCore';\r\n\r\nexport function useAppState() {\r\n  const [state, setState] = useState(appCore.getAppState());\r\n\r\n  useEffect(() => {\r\n    const unsubscribe = appCore.on('state_changed', () => {\r\n      setState(appCore.getAppState());\r\n    });\r\n\r\n    return unsubscribe;\r\n  }, []);\r\n\r\n  return state;\r\n}\r\n\r\n// Component usage\r\nfunction App() {\r\n  const appState = useAppState();\r\n\r\n  if (appState.state === 'offline') {\r\n    return <OfflineBanner />;\r\n  }\r\n\r\n  return <YourApp />;\r\n}\r\n```\r\n\r\n### React Native\r\n\r\n```typescript\r\nimport NetInfo from '@react-native-community/netinfo'\r\nimport appCore from './appCore'\r\n\r\n// Monitor network connectivity\r\nNetInfo.addEventListener((state) => {\r\n  appCore.updateConnectivity(state.isConnected ?? false)\r\n})\r\n```\r\n\r\n### Ionic/Capacitor\r\n\r\n```typescript\r\nimport { Network } from '@capacitor/network'\r\nimport appCore from './appCore'\r\n\r\n// Monitor network status\r\nNetwork.addListener('networkStatusChange', (status) => {\r\n  appCore.updateConnectivity(status.connected)\r\n})\r\n```\r\n\r\n---\r\n\r\n## 🔗 Integration with Related Packages\r\n\r\nApp-core is the **foundation**; integrate with these packages for full-stack resilience:\r\n\r\n### @codeimplants/version-control\r\n\r\nVersion checks (soft/force updates, maintenance, kill switch). Call **before** rendering the app.\r\n\r\n```typescript\r\nimport { VersionSDK } from '@codeimplants/version-control'\r\nimport { appCore } from './init'\r\n\r\nasync function bootstrap() {\r\n  const decision = await VersionSDK.check('https://api.yourapp.com', 'your-api-key')\r\n\r\n  switch (decision.action) {\r\n    case 'FORCE_UPDATE':\r\n    case 'KILL_SWITCH':\r\n      appCore.showFallback('maintenance', { message: decision.message })\r\n      return\r\n    case 'MAINTENANCE':\r\n      appCore.showFallback('maintenance', { message: decision.message })\r\n      return\r\n  }\r\n\r\n  appCore.onInit()\r\n  // Render app\r\n}\r\n```\r\n\r\n### @codeimplants/app-network\r\n\r\nConnectivity monitoring + OfflineBanner. Feed status into app-core.\r\n\r\n```typescript\r\nimport { OfflineProvider, OfflineBanner, useOffline } from '@codeimplants/app-network'\r\nimport { useEffect } from 'react'\r\nimport { appCore } from './init'\r\n\r\n// Sync connectivity to app-core (must be inside OfflineProvider)\r\nfunction ConnectivitySync() {\r\n  const { isOnline } = useOffline()\r\n  useEffect(() => {\r\n    appCore.updateConnectivity(isOnline)\r\n  }, [isOnline])\r\n  return null\r\n}\r\n\r\nfunction App() {\r\n  return (\r\n    <OfflineProvider>\r\n      <ConnectivitySync />\r\n      <OfflineBanner />\r\n      <YourApp />\r\n    </OfflineProvider>\r\n  )\r\n}\r\n```\r\n\r\n**React Native:** Use `@react-native-community/netinfo`; `app-network` detects RN and uses it. Add the same `ConnectivitySync` component.\r\n\r\n### @codeimplants/ui-kit\r\n\r\nError screens (ApiErrorScreen, NetworkOfflineScreen, etc.) map to `showFallback` / `handleError` results.\r\n\r\n```typescript\r\nimport {\r\n  ApiErrorScreen,\r\n  NetworkOfflineScreen,\r\n  ErrorBoundaryScreen,\r\n} from '@codeimplants/ui-kit'\r\nimport { appCore, type FallbackData } from '@codeimplants/app-core'\r\n\r\n// Map fallback type to ui-kit screens\r\nfunction FallbackRenderer({ fallback }: { fallback: FallbackData }) {\r\n  switch (fallback.type) {\r\n    case 'offline':\r\n      return <NetworkOfflineScreen onRetry={() => appCore.resetErrorState()} />\r\n    case 'api_error':\r\n    case 'generic_error':\r\n      return (\r\n        <ApiErrorScreen\r\n          onRetry={() => appCore.resetErrorState()}\r\n          support={{ whatsapp: { number: '...' }, email: { address: '...' } }}\r\n        />\r\n      )\r\n    default:\r\n      return <ErrorBoundaryScreen message={fallback.message} />\r\n  }\r\n}\r\n```\r\n\r\n### @codeimplants/support\r\n\r\nSupport logic (WhatsApp, Email, Phone). Use with ui-kit error screens—ui-kit shows support buttons; on click, use `useSupport().openWhatsApp()` etc.\r\n\r\n```typescript\r\nimport { SupportProvider } from '@codeimplants/support'\r\n\r\n// Wrap app; ui-kit screens use useSupport for button actions\r\n<SupportProvider config={{ whatsapp: { number: '...' }, email: { address: '...' } }}>\r\n  <YourApp />\r\n</SupportProvider>\r\n```\r\n\r\n---\r\n\r\n## 🛡️ Global Error Boundary Integration\r\n\r\nApp-core provides **logic**; your app provides the **UI** error boundary. Wire them together:\r\n\r\n### React\r\n\r\n```tsx\r\nimport React, { Component, ErrorInfo, ReactNode } from 'react'\r\nimport { appCore } from './init'\r\n\r\ninterface Props {\r\n  children: ReactNode\r\n  fallback?: ReactNode\r\n}\r\n\r\nexport class AppErrorBoundary extends Component<Props, { hasError: boolean; error?: Error }> {\r\n  state = { hasError: false, error: undefined as Error | undefined }\r\n\r\n  static getDerivedStateFromError(error: Error) {\r\n    return { hasError: true, error }\r\n  }\r\n\r\n  componentDidCatch(error: Error, errorInfo: ErrorInfo) {\r\n    appCore.reportCrash({\r\n      message: error.message,\r\n      stack: error.stack,\r\n      component: errorInfo.componentStack,\r\n      metadata: { errorInfo },\r\n    })\r\n    appCore.showFallback('generic_error', { message: error.message })\r\n  }\r\n\r\n  render() {\r\n    if (this.state.hasError) {\r\n      return this.props.fallback ?? <div>Something went wrong.</div>\r\n    }\r\n    return this.props.children\r\n  }\r\n}\r\n```\r\n\r\n### React Native\r\n\r\n```tsx\r\nimport React, { Component, ErrorInfo, ReactNode } from 'react'\r\nimport { View, Text, Button } from 'react-native'\r\nimport { appCore } from './init'\r\n// Optional: use @codeimplants/ui-kit ErrorBoundaryScreen\r\n// import { ErrorBoundaryScreen } from '@codeimplants/ui-kit'\r\n\r\ninterface Props {\r\n  children: ReactNode\r\n}\r\n\r\nexport class AppErrorBoundary extends Component<Props, { hasError: boolean; error?: Error }> {\r\n  state = { hasError: false, error: undefined as Error | undefined }\r\n\r\n  static getDerivedStateFromError(error: Error) {\r\n    return { hasError: true, error }\r\n  }\r\n\r\n  componentDidCatch(error: Error, errorInfo: ErrorInfo) {\r\n    appCore.reportCrash({\r\n      message: error.message,\r\n      stack: error.stack,\r\n      component: errorInfo.componentStack,\r\n    })\r\n    appCore.showFallback('generic_error', { message: error.message })\r\n  }\r\n\r\n  handleRetry = () => {\r\n    appCore.resetErrorState()\r\n    this.setState({ hasError: false, error: undefined })\r\n  }\r\n\r\n  render() {\r\n    if (this.state.hasError) {\r\n      return (\r\n        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 }}>\r\n          <Text>Something went wrong.</Text>\r\n          <Button title=\"Try Again\" onPress={this.handleRetry} />\r\n          <Button title=\"Contact Support\" /> {/* Wire to @codeimplants/support */}\r\n        </View>\r\n      )\r\n    }\r\n    return this.props.children\r\n  }\r\n}\r\n```\r\n\r\n### Wire global uncaught errors\r\n\r\n```typescript\r\n// index.tsx or App.tsx (early in bootstrap)\r\nwindow.onerror = (message, source, lineno, colno, error) => {\r\n  appCore.reportCrash({\r\n    message: String(message),\r\n    stack: error?.stack,\r\n    metadata: { source, lineno, colno },\r\n  })\r\n}\r\n\r\n// React Native: use ErrorUtils\r\nif (typeof ErrorUtils !== 'undefined') {\r\n  const originalHandler = ErrorUtils.getGlobalHandler()\r\n  ErrorUtils.setGlobalHandler((error, isFatal) => {\r\n    appCore.reportCrash({\r\n      message: error.message,\r\n      stack: error.stack,\r\n      metadata: { isFatal },\r\n    })\r\n    originalHandler?.(error, isFatal)\r\n  })\r\n}\r\n```\r\n\r\n---\r\n\r\n## 💡 Best Practices\r\n\r\n### 1. Initialize Early\r\n\r\nInitialize AppCore as early as possible in your application lifecycle:\r\n\r\n```typescript\r\n// index.ts or App.tsx\r\nimport appCore from './appCore'\r\n\r\n// Configure logger for development\r\nif (process.env.NODE_ENV === 'development') {\r\n  Logger.configure({ minLevel: 'debug' })\r\n}\r\n```\r\n\r\n### 2. Centralize Error Handling\r\n\r\nUse the core APIs—never bypass app-core:\r\n\r\n```typescript\r\n// errorHandler.ts\r\nimport { appCore } from './init'\r\n\r\nexport function globalErrorHandler(error: Error, context?: ErrorContext) {\r\n  const decision = appCore.handleError(error, context)\r\n\r\n  switch (decision.action) {\r\n    case 'retry':\r\n      return appCore.executeWithRetry(() => /* retry logic */)\r\n    case 'show_error':\r\n      return appCore.showFallback(decision.screen ?? 'generic_error', decision.screenData)\r\n    case 'show_support':\r\n      return appCore.showFallback(decision.screen ?? 'generic_error', {\r\n        ...decision.screenData,\r\n        supportAvailable: true,\r\n      }) // ui-kit screen shows support buttons; use @codeimplants/support for actions\r\n    case 'recover':\r\n      return /* trigger recovery via RecoveryManager */\r\n  }\r\n}\r\n```\r\n\r\n### 3. Use Type Guards\r\n\r\nLeverage TypeScript for type safety:\r\n\r\n```typescript\r\nimport { NetworkError, APIError } from '@codeimplants/app-core'\r\n\r\nfunction handleError(error: Error) {\r\n  if (error instanceof NetworkError) {\r\n    // Handle network error\r\n  } else if (error instanceof APIError) {\r\n    // Handle API error\r\n  }\r\n}\r\n```\r\n\r\n### 4. Monitor Events\r\n\r\nSet up analytics tracking:\r\n\r\n```typescript\r\nappCore.on('*', (event) => {\r\n  // Send to analytics service\r\n  analytics.track(`app_core_${event.type}`, event.payload)\r\n})\r\n```\r\n\r\n### 5. Clean Up\r\n\r\nAlways clean up when unmounting:\r\n\r\n```typescript\r\nuseEffect(() => {\r\n  const unsubscribe = appCore.on('error_occurred', handleError)\r\n\r\n  return () => {\r\n    unsubscribe()\r\n  }\r\n}, [])\r\n```\r\n\r\n## 📖 Full Application Integration\r\n\r\n**Recommended bootstrap order:**\r\n\r\n1. Initialize `AppCore` (single instance)\r\n2. Run `VersionSDK.check()` → show maintenance/update fallback if needed\r\n3. Wrap app with `OfflineProvider` + `ConnectivitySync` (app-network)\r\n4. Wrap app with `AppErrorBoundary` (calls `reportCrash`, `showFallback`)\r\n5. Set global `window.onerror` / `ErrorUtils.setGlobalHandler`\r\n6. Wrap with `SupportProvider` (@codeimplants/support) if using support\r\n7. Call `appCore.onInit()` when app is ready\r\n8. Use `appCore.onPause()` / `appCore.onResume()` on app state changes (React Native: AppState)\r\n\r\n**React Native lifecycle example:**\r\n\r\n```typescript\r\nimport { AppState, AppStateStatus } from 'react-native'\r\n\r\nuseEffect(() => {\r\n  const sub = AppState.addEventListener('change', (state: AppStateStatus) => {\r\n    if (state === 'active') appCore.onResume()\r\n    else if (state === 'background') appCore.onPause()\r\n  })\r\n  return () => sub.remove()\r\n}, [])\r\n```\r\n\r\n## 📖 Examples\r\n\r\nSee the [examples](./examples) directory for complete examples:\r\n\r\n- React SPA integration\r\n- React Native app integration\r\n- Ionic/Capacitor integration\r\n- API client wrapper\r\n- Custom error handling\r\n\r\n## 📄 License\r\n\r\nMIT © [Code Implants Software Technologies Pvt. Ltd.](LICENSE)\r\n\r\n## 🔗 Related Packages\r\n\r\n| Package | Purpose |\r\n|---------|---------|\r\n| `@codeimplants/version-control` | Version checks, force/soft updates, maintenance, kill switch |\r\n| `@codeimplants/app-network` | Connectivity monitoring, OfflineBanner, resilient API client |\r\n| `@codeimplants/ui-kit` | Error screens (ApiErrorScreen, NetworkOfflineScreen, etc.) |\r\n| `@codeimplants/support` | Support logic (WhatsApp, Email, Phone); use with ui-kit error screens |\r\n","readmeFilename":"README.md"}