import { Platform } from 'react-native'; import type { FeatureDataProvider } from '../types'; import { safeStringify } from './safeStringify'; const DEFAULT_MAX_PER_TYPE = 50; const DEFAULT_MAX_BODY_BYTES = 16 * 1024; const MAX_DEPTH = 8; export interface DebugDeviceReportOptions { maxPerType?: number; maxBodyBytes?: number; includeTypes?: string[]; } export interface DeviceInfo { platform: string; model: string; osVersion: string; appVersion: string; } export interface SessionInfo { id: string; startedAt: number; } export interface DebugDeviceReport { version: 2; device: DeviceInfo; session?: SessionInfo; logs: Record; } export function sanitizeDebugLogEntry(value: unknown, maxBodyBytes = DEFAULT_MAX_BODY_BYTES): unknown { return sanitizeValue(value, Math.max(256, Math.floor(maxBodyBytes))); } interface TruncatedValue { __debugToolkitTruncated: true; originalBytes: number; preview: string; } function utf8ByteLength(value: string): number { let bytes = 0; for (let index = 0; index < value.length; index += 1) { const code = value.charCodeAt(index); if (code <= 0x7f) { bytes += 1; } else if (code <= 0x7ff) { bytes += 2; } else if (code >= 0xd800 && code <= 0xdbff) { bytes += 4; index += 1; } else { bytes += 3; } } return bytes; } function truncateUtf8(value: string, maxBytes: number): string { if (utf8ByteLength(value) <= maxBytes) { return value; } let bytes = 0; let result = ''; for (let index = 0; index < value.length; index += 1) { const code = value.charCodeAt(index); const char = value[index]!; const charBytes = code <= 0x7f ? 1 : code <= 0x7ff ? 2 : code >= 0xd800 && code <= 0xdbff ? 4 : 3; if (bytes + charBytes > maxBytes) { break; } result += char; bytes += charBytes; if (charBytes === 4) { index += 1; result += value[index] ?? ''; } } return `${result}...[truncated]`; } function truncateLargeValue(value: unknown, maxBytes: number): unknown | TruncatedValue { const serialized = safeStringify(value); const originalBytes = utf8ByteLength(serialized); if (originalBytes <= maxBytes) { return value; } return { __debugToolkitTruncated: true, originalBytes, preview: truncateUtf8(serialized, maxBytes), }; } function sanitizeValue( value: unknown, maxBodyBytes: number, depth = 0, seen = new WeakSet(), key = '', ): unknown { try { return snapshotValue(value, maxBodyBytes, depth, seen, key); } catch { // Proxies and other hostile objects can throw during reflection. Logging // must never let that inspection failure escape into the business call. return '[Unserializable]'; } } function snapshotValue( value: unknown, maxBodyBytes: number, depth: number, seen: WeakSet, key: string, ): unknown { if (typeof value === 'string') { return truncateUtf8(value, maxBodyBytes); } if ( value === null || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'undefined' ) { return value; } if (typeof value === 'function') { return '[Function]'; } if (typeof value === 'symbol' || typeof value === 'bigint') { return String(value); } if (value instanceof Date) { return Date.prototype.toISOString.call(value); } if (typeof value !== 'object') { return value; } const normalizedKey = key.toLowerCase(); if (normalizedKey === 'body' || normalizedKey === 'data') { const normalized = sanitizeValue(value, maxBodyBytes, depth + 1, seen); return truncateLargeValue(normalized, maxBodyBytes); } if (seen.has(value)) { return '[Circular]'; } if (depth >= MAX_DEPTH) { return '[MaxDepth]'; } seen.add(value); const descriptors = Object.getOwnPropertyDescriptors(value); const result: Record | unknown[] = Array.isArray(value) ? [] : Object.create(null); for (const entryKey of Object.keys(descriptors)) { const descriptor = descriptors[entryKey]!; if (!descriptor.enumerable) { continue; } const entryValue = 'value' in descriptor ? sanitizeValue(descriptor.value, maxBodyBytes, depth + 1, seen, entryKey) : '[Accessor]'; // Defining a property also avoids special setters such as __proto__. Object.defineProperty(result, entryKey, { value: entryValue, enumerable: true, configurable: true, writable: true }); } return result; } export function createDebugDeviceReport( options: DebugDeviceReportOptions & { featureProvider?: FeatureDataProvider; session?: SessionInfo } = {}, ): DebugDeviceReport { const provider = options.featureProvider; const maxPerType = Math.max(1, Math.floor(options.maxPerType ?? DEFAULT_MAX_PER_TYPE)); const maxBodyBytes = Math.max(256, Math.floor(options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES)); const includeTypes = options.includeTypes?.length ? new Set(options.includeTypes) : null; const logs: DebugDeviceReport['logs'] = {}; provider?.features.forEach((feature) => { if (includeTypes && !includeTypes.has(feature.name)) { return; } let snapshot: unknown; try { snapshot = feature.getSnapshot(); } catch { return; } if (!Array.isArray(snapshot)) { return; } logs[feature.name] = snapshot .slice(-maxPerType) .map((entry) => sanitizeDebugLogEntry(entry, maxBodyBytes)); }); const constants = Platform.constants as Record | undefined; return { version: 2, device: { platform: Platform.OS, model: (constants?.model as string) || 'unknown', osVersion: Platform.Version == null ? 'unknown' : String(Platform.Version), appVersion: (constants?.appVersion as string) || 'unknown', }, session: options.session, logs, }; }