29 lines
890 B
TypeScript
29 lines
890 B
TypeScript
/** Device-side ids (moved from src/lib/field/client-ops.ts, which re-exports them). */
|
|
|
|
/** RFC 4122 v4 id; falls back to getRandomValues outside secure contexts. */
|
|
export function newClientId(): string {
|
|
const c = globalThis.crypto;
|
|
if (typeof c?.randomUUID === "function") return c.randomUUID();
|
|
const b = new Uint8Array(16);
|
|
c.getRandomValues(b);
|
|
b[6] = (b[6] & 0x0f) | 0x40;
|
|
b[8] = (b[8] & 0x3f) | 0x80;
|
|
const h = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
}
|
|
|
|
const DEVICE_KEY = "craftvia.field.deviceId";
|
|
|
|
export function deviceId(): string {
|
|
try {
|
|
let id = localStorage.getItem(DEVICE_KEY);
|
|
if (!id) {
|
|
id = newClientId();
|
|
localStorage.setItem(DEVICE_KEY, id);
|
|
}
|
|
return id;
|
|
} catch {
|
|
return "unknown-device";
|
|
}
|
|
}
|