41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
declare const plus: any
|
||
|
||
const DEVICE_SN_STORAGE_KEY = 'wallace:screen:sn'
|
||
const DEVICE_SN_PREFIX = 'WLS-'
|
||
|
||
const normalizeNativeId = (value: unknown) => String(value || '')
|
||
.toUpperCase()
|
||
.replace(/[^A-Z0-9]/g, '')
|
||
.slice(0, 32)
|
||
|
||
const createFallbackId = () => {
|
||
const timestamp = Date.now().toString(36).toUpperCase()
|
||
const random = Math.random().toString(36).slice(2, 12).toUpperCase()
|
||
return `${timestamp}${random}`
|
||
}
|
||
|
||
/**
|
||
* APP 端优先使用 DCloud 提供的设备唯一标识 `plus.device.uuid`。
|
||
* H5、模拟器或标识不可用时,生成应用级标识并持久化,保证同一次安装期间稳定。
|
||
*/
|
||
const getNativeDeviceId = () => {
|
||
// #ifdef APP-PLUS
|
||
try {
|
||
return normalizeNativeId(plus?.device?.uuid)
|
||
} catch {
|
||
return ''
|
||
}
|
||
// #endif
|
||
return ''
|
||
}
|
||
|
||
export const getOrCreateDeviceSn = () => {
|
||
const saved = String(uni.getStorageSync(DEVICE_SN_STORAGE_KEY) || '')
|
||
if (saved) return saved
|
||
|
||
const sourceId = getNativeDeviceId() || createFallbackId()
|
||
const sn = `${DEVICE_SN_PREFIX}${sourceId}`
|
||
uni.setStorageSync(DEVICE_SN_STORAGE_KEY, sn)
|
||
return sn
|
||
}
|