Files
wzdj/lib/analytics/journey-session.ts
卡若 ea3a589f0b
Some checks failed
CI / notice (push) Has been cancelled
chore: sync docs, gitea wiki assets, templates
Made-with: Cursor
2026-04-14 18:44:44 +08:00

44 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** 浏览器会话内稳定的旅程 sessionIdWM-O1-KR1-02 */
const SESSION_KEY = "wz_journey_sid"
/** 跨会话匿名设备 ID未登录也可上报旅程 */
const ANON_KEY = "wz_anon_id"
export function getOrCreateJourneySessionId(): string {
if (typeof window === "undefined") return "ssr"
try {
let sid = sessionStorage.getItem(SESSION_KEY)
if (!sid) {
sid =
typeof crypto !== "undefined" && "randomUUID" in crypto
? crypto.randomUUID()
: `wz_${Date.now()}_${Math.random().toString(36).slice(2, 12)}`
sessionStorage.setItem(SESSION_KEY, sid)
}
return sid
} catch {
return `wz_fallback_${Date.now()}`
}
}
export function newJourneyClientEventId(): string {
if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID()
return `evt_${Date.now()}_${Math.random().toString(36).slice(2, 12)}`
}
export function getOrCreateAnonymousId(): string {
if (typeof window === "undefined") return "ssr"
try {
let id = localStorage.getItem(ANON_KEY)
if (!id) {
id =
typeof crypto !== "undefined" && "randomUUID" in crypto
? `anon_${crypto.randomUUID()}`
: `anon_${Date.now()}_${Math.random().toString(36).slice(2, 12)}`
localStorage.setItem(ANON_KEY, id)
}
return id.slice(0, 128)
} catch {
return `anon_fallback_${Date.now()}`
}
}