systemInfo.js 3.09 KB
/**
 * @file 系统信息兼容层:合并微信新 API,替代已废弃的 wx.getSystemInfoSync / wx.getSystemInfo。
 * 纯函数模块,不调 setData、不访问页面实例。
 * 与 usedcar 的 utils/systemInfo.js 保持一致的实现。
 */

/** 测试专用:重置 legacy environment 缓存 */
export function __resetLegacyEnvironmentCacheForTest() {
	legacyEnvironmentResolved = false
	legacyEnvironmentCache = LEGACY_ENV_UNSET
}

/** @type {string|undefined|symbol} */
let legacyEnvironmentCache
/** 是否已解析过 legacy environment(含「无需 sync」的结论) */
let legacyEnvironmentResolved = false
const LEGACY_ENV_UNSET = Symbol('legacyEnvironmentUnset')

/**
 * 旧版企微判断:优先新 API,仅在必要时调用一次原生 wx.getSystemInfoSync().environment
 * @returns {string|undefined}
 */
function getLegacyEnvironment() {
	if (legacyEnvironmentResolved) {
		return legacyEnvironmentCache === LEGACY_ENV_UNSET ? undefined : legacyEnvironmentCache
	}
	legacyEnvironmentResolved = true

	try {
		const appBase = wx.getAppBaseInfo?.()
		const host = appBase?.host
		const hostEnv = typeof host === 'string' ? host : host?.env
		if (hostEnv === 'wxwork') {
			legacyEnvironmentCache = 'wxwork'
			return legacyEnvironmentCache
		}
		if (typeof wx.qy !== 'undefined') {
			legacyEnvironmentCache = 'wxwork'
			return legacyEnvironmentCache
		}

		const legacyEnv = wx.getSystemInfoSync?.()?.environment
		legacyEnvironmentCache = legacyEnv || LEGACY_ENV_UNSET
		return legacyEnv
	} catch (_) {
		legacyEnvironmentCache = LEGACY_ENV_UNSET
		return undefined
	}
}

/**
 * 解析企微运行环境,对齐旧版 getSystemInfoSync().environment
 * 优先 legacy / host.env、wx.qy 兜底
 * @param {string|{ env?: string }} [host]
 * @returns {string}
 */
function resolveEnvironment(host) {
	const legacyEnv = getLegacyEnvironment()
	if (legacyEnv) return legacyEnv

	const hostEnv = typeof host === 'string' ? host : host?.env
	if (hostEnv === 'wxwork') return 'wxwork'

	if (typeof wx.qy !== 'undefined') return 'wxwork'

	return ''
}

/**
 * 同步获取与旧版 getSystemInfoSync 兼容的系统信息对象
 * @returns {WechatMiniprogram.SystemInfo}
 */
export function getSystemInfoSync() {
	const deviceInfo = wx.getDeviceInfo()
	const windowInfo = wx.getWindowInfo()
	const appBaseInfo = wx.getAppBaseInfo()

	return {
		...deviceInfo,
		...windowInfo,
		...appBaseInfo,
		environment: resolveEnvironment(appBaseInfo.host),
	}
}

/**
 * 登录端标识,对齐 loginControlList 后端约定:1 企微,0 微信
 * 与旧版 accountItems / wxLogin 一致:优先读原生 wx.getSystemInfoSync().environment
 * @returns {0|1}
 */
export function getLoginEnvName() {
	const legacyEnv = getLegacyEnvironment()
	if (legacyEnv) return 1

	return getSystemInfoSync().environment ? 1 : 0
}

/**
 * 异步获取系统信息,行为对齐旧版 wx.getSystemInfo
 * @param {WechatMiniprogram.GetSystemInfoOption} [options]
 */
export function getSystemInfo(options = {}) {
	try {
		const res = getSystemInfoSync()
		options.success?.(res)
	} catch (err) {
		options.fail?.(err)
	} finally {
		options.complete?.()
	}
}