@dash0/sdk-web
Version:
Dash0's Web SDK to collect telemetry from end-users' web browsers
63 lines (62 loc) • 1.97 kB
JavaScript
import { win, debug, warn, INIT_MESSAGE } from "../utils";
import { reportError } from "../api/report-error";
import { identify } from "../api/identify";
import { debug as debugApi } from "../api/debug";
import { init as initApi } from "../api/init";
import { terminateSession } from "../api/session";
import { addSignalAttribute, removeSignalAttribute } from "../api/attributes";
import { sendEvent } from "../api/events";
import { setActiveLogLevel } from "../api/log-level";
/**
* All the APIs exposed through the script tag via `dash0('{{api name}}')`
*/
const scriptApis = {
init: initApi,
debug: debugApi,
identify,
terminateSession,
reportError,
addSignalAttribute,
removeSignalAttribute,
setActiveLogLevel,
sendEvent,
};
init();
function init() {
debug(`${INIT_MESSAGE} (via Script)`);
const globalObject = win["dash0"];
if (!globalObject) {
warn("global 'dash0' not found. Did you use the correct Dash0 Web SDK initializer?");
return;
}
if (!globalObject["_q"]) {
warn("Dash0 Web SDK command queue not defined. Did you add the script tag multiple times to your website?");
return;
}
processQueuedApiCalls(globalObject["_q"]);
addApiCallAfterInitializationSupport();
}
function processQueuedApiCalls(apiCalls) {
for (let i = 0, len = apiCalls.length; i < len; i++) {
processQueuedApiCall(apiCalls[i]);
}
}
function processQueuedApiCall(apiCall) {
const apiName = apiCall[0];
// @ts-expect-error the APIs are dynamic
const apiFn = scriptApis[apiName];
if (!apiFn) {
warn("Unsupported Dash0 Web SDK api: ", apiCall[0]);
return;
}
const args = [];
for (let i = 1; i < apiCall.length; i++) {
args.push(apiCall[i]);
}
apiFn.apply(null, args);
}
function addApiCallAfterInitializationSupport() {
win["dash0"] = function () {
return processQueuedApiCall(arguments);
};
}