UNPKG

@dash0/sdk-web

Version:

Dash0's Web SDK to collect telemetry from end-users' web browsers

66 lines (65 loc) 1.77 kB
const ANY_VALUE_KEYS = [ "stringValue", "boolValue", "intValue", "doubleValue", "arrayValue", "kvlistValue", "bytesValue", ]; function isAnyValue(value) { if (value == null || typeof value !== "object") return false; const keys = Object.keys(value); return keys.length === 1 && ANY_VALUE_KEYS.includes(keys[0]); } export function toAnyValue(value) { if (value == null) { return undefined; } let anyValue = {}; if (Array.isArray(value)) { anyValue["arrayValue"] = { values: value.map((e) => toAnyValue(e)) }; } else if (typeof value === "string") { anyValue["stringValue"] = value; } else if (typeof value === "number") { anyValue["doubleValue"] = value; } else if (typeof value === "boolean") { anyValue["boolValue"] = value; } else if (isAnyValue(value)) { anyValue = value; } else if (typeof value === "object") { anyValue["kvlistValue"] = { values: Object.entries(value).map(([key, value]) => toKeyValue(key, value)) }; } return anyValue; } export function toKeyValue(key, value) { return { key: key, value: toAnyValue(value), }; } export function addAttribute(attributes, key, value) { if (!key) return; attributes.push(toKeyValue(key, value)); } export function removeAttribute(attributes, key) { const index = attributes.findIndex((attr) => attr["key"] === key); if (index !== -1) { attributes.splice(index, 1); } } export function withPrefix(prefix) { if (!prefix) return (attr) => attr; if (Array.isArray(prefix)) { return (attr) => [...prefix, attr].join("."); } return (attr) => `${prefix}.${attr}`; }