import NativeAppticsApiTrackerModuleSpec, { type Spec } from '../NativeAppticsApiTrackerModule'; import { NativeModules, Platform } from 'react-native'; const LINKING_ERROR = `The package '@zoho_apptics/apptics-react-native' doesn't seem to be linked. Make sure: \n\n` + Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo managed workflow\n'; // eslint-disable-next-line @typescript-eslint/no-explicit-any const makeProxy = (): any => new Proxy( {}, { get() { throw new Error(LINKING_ERROR); }, } ); const NativeAppticsApiTrackerModule = (NativeAppticsApiTrackerModuleSpec ?? NativeModules.AppticsApiTrackerModule ?? makeProxy()) as Spec; // ─── Types ──────────────────────────────────────────────────────────────────── export interface StartApiTrackingParams { url: string; method: string; } export interface EndApiTrackingParams { trackId: string; statusCode?: number; errorMessage?: string; } // ─── State ──────────────────────────────────────────────────────────────────── /** URLs containing any of these strings will be silently skipped. */ export const excludedUrlPatterns = new Set(); let _autoTrackingEnabled = false; let _originalFetch: typeof fetch | null = null; // ─── Core bridge ────────────────────────────────────────────────────────────── async function startApiTracking( params: StartApiTrackingParams ): Promise { if (_shouldExclude(params.url)) return null; const id = await NativeAppticsApiTrackerModule.startApiTracking(params.url, params.method); return id.length > 0 ? id : null; } async function endApiTracking(params: EndApiTrackingParams): Promise { if (!params.trackId) return; await NativeAppticsApiTrackerModule.endApiTracking( params.trackId, params.statusCode ?? 0, params.errorMessage ?? '' ); } // ─── Auto tracking ──────────────────────────────────────────────────────────── function enableAutoTracking(): void { if (_autoTrackingEnabled) return; _originalFetch = globalThis.fetch; globalThis.fetch = _buildTrackedFetch(globalThis.fetch); _autoTrackingEnabled = true; } function disableAutoTracking(): void { if (!_autoTrackingEnabled || !_originalFetch) return; globalThis.fetch = _originalFetch; _originalFetch = null; _autoTrackingEnabled = false; } function isAutoTrackingEnabled(): boolean { return _autoTrackingEnabled; } // ─── Fetch wrapper ──────────────────────────────────────────────────────────── async function trackedFetch( input: RequestInfo | URL, init?: RequestInit ): Promise { return _buildTrackedFetch(globalThis.fetch)(input as Parameters[0], init); } // ─── HTTP client wrapper ────────────────────────────────────────────────────── function createAppticsHttpClient( baseFetch: typeof fetch = globalThis.fetch ): typeof fetch { return _buildTrackedFetch(baseFetch); } // ─── Internal helpers ───────────────────────────────────────────────────────── function _shouldExclude(url: string): boolean { for (const pattern of excludedUrlPatterns) { if (url.includes(pattern)) return true; } return false; } function _resolveUrl(input: RequestInfo | URL): string { if (typeof input === 'string') return input; if (input instanceof URL) return input.toString(); return (input as Request).url; } function _buildTrackedFetch(baseFetch: typeof fetch): typeof fetch { return async function ( input: RequestInfo | URL, init?: RequestInit ): Promise { const fetchInput = input as Parameters[0]; const url = _resolveUrl(input); const method = (init?.method ?? 'GET').toUpperCase(); if (_shouldExclude(url)) { return baseFetch(fetchInput, init); } let trackId: string | null = null; try { const id = await NativeAppticsApiTrackerModule.startApiTracking(url, method); trackId = id.length > 0 ? id : null; } catch (_) {} try { const response = await baseFetch(fetchInput, init); if (trackId) { NativeAppticsApiTrackerModule.endApiTracking(trackId, response.status, '').catch(() => {}); } return response; } catch (e: any) { if (trackId) { NativeAppticsApiTrackerModule.endApiTracking(trackId, 0, e?.message ?? String(e)).catch(() => {}); } throw e; } }; } // ─── Public API ─────────────────────────────────────────────────────────────── export const AppticsApiTracker = { startApiTracking, endApiTracking, enableAutoTracking, disableAutoTracking, isAutoTrackingEnabled, trackedFetch, createAppticsHttpClient, excludedUrlPatterns, };