/** * Platform detection utilities * * Provides functions to detect the current platform and environment */ // Declare global objects for TypeScript declare const wx: unknown; declare const my: unknown; declare const swan: unknown; declare const tt: unknown; declare const qq: unknown; declare const window: unknown; /** * Supported platform types */ export enum PlatformType { /** WeChat Mini Program */ WECHAT = 'wechat', /** Alipay Mini Program */ ALIPAY = 'alipay', /** Baidu Smart Program */ BAIDU = 'baidu', /** ByteDance Mini Program (Douyin, Toutiao) */ BYTEDANCE = 'bytedance', /** QQ Mini Program */ QQ = 'qq', /** Web platform */ WEB = 'web', /** Unknown platform */ UNKNOWN = 'unknown', } /** * Type guard for objects with request method */ function hasRequestMethod(obj: unknown): obj is { request: unknown } { return typeof obj === 'object' && obj !== null && 'request' in obj; } /** * Type guard for window objects with navigator */ function isWindowWithNavigator(obj: unknown): obj is { navigator: unknown } { return typeof obj === 'object' && obj !== null && 'navigator' in obj; } /** * Detects the current platform * * @returns The detected platform type */ export function detectPlatform(): PlatformType { if (typeof wx !== 'undefined' && hasRequestMethod(wx)) { return PlatformType.WECHAT; } if (typeof my !== 'undefined' && hasRequestMethod(my)) { return PlatformType.ALIPAY; } if (typeof swan !== 'undefined' && hasRequestMethod(swan)) { return PlatformType.BAIDU; } if (typeof tt !== 'undefined' && hasRequestMethod(tt)) { return PlatformType.BYTEDANCE; } if (typeof qq !== 'undefined' && hasRequestMethod(qq)) { return PlatformType.QQ; } if (typeof window !== 'undefined' && isWindowWithNavigator(window)) { return PlatformType.WEB; } return PlatformType.UNKNOWN; } /** * Gets the platform-specific global object * * @returns The platform-specific global object or null if unknown */ export function getPlatformGlobal(): unknown { switch (detectPlatform()) { case PlatformType.WECHAT: return wx; case PlatformType.ALIPAY: return my; case PlatformType.BAIDU: return swan; case PlatformType.BYTEDANCE: return tt; case PlatformType.QQ: return qq; case PlatformType.WEB: return window; default: return null; } } /** * Checks if the current platform is supported * * @returns True if the platform is supported, false otherwise */ export function isPlatformSupported(): boolean { const platform = detectPlatform(); return platform !== PlatformType.UNKNOWN && platform !== PlatformType.WEB; } /** * Gets the platform name as a human-readable string * * @returns The platform name */ export function getPlatformName(): string { switch (detectPlatform()) { case PlatformType.WECHAT: return '微信小程序'; case PlatformType.ALIPAY: return '支付宝小程序'; case PlatformType.BAIDU: return '百度小程序'; case PlatformType.BYTEDANCE: return '字节跳动小程序'; case PlatformType.QQ: return 'QQ小程序'; case PlatformType.WEB: return 'Web平台'; default: return '未知平台'; } }