ssr-web-avo-inspector
Version:
Avo Inspector for web with SSR and web workers support
482 lines (481 loc) • 26.1 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AvoInspector = void 0;
var AvoInspectorEnv_1 = require("./AvoInspectorEnv");
var AvoSchemaParser_1 = require("./AvoSchemaParser");
var AvoBatcher_1 = require("./AvoBatcher");
var AvoNetworkCallsHandler_1 = require("./AvoNetworkCallsHandler");
var AvoStorage_1 = require("./AvoStorage");
var AvoDeduplicator_1 = require("./AvoDeduplicator");
var AvoStreamId_1 = require("./AvoStreamId");
var AvoEventSpecFetcher_1 = require("./eventSpec/AvoEventSpecFetcher");
var AvoEventSpecCache_1 = require("./eventSpec/AvoEventSpecCache");
var EventValidator_1 = require("./eventSpec/EventValidator");
var utils_1 = require("./utils");
var libVersion = require("../package.json").version;
var AvoInspector = /** @class */ (function () {
// constructor(apiKey: string, env: AvoInspectorEnv, version: string) {
function AvoInspector(options) {
/** Last seen branchId from event spec responses, used for cache flush on branch change */
this.lastSeenBranchId = null;
// the constructor does aggressive null/undefined checking because same code paths will be accessible from JS
if ((0, utils_1.isValueEmpty)(options.env)) {
this.environment = AvoInspectorEnv_1.AvoInspectorEnv.Dev;
console.warn("[Avo Inspector] No environment provided. Defaulting to dev.");
}
else if (Object.values(AvoInspectorEnv_1.AvoInspectorEnv).indexOf(options.env) === -1) {
this.environment = AvoInspectorEnv_1.AvoInspectorEnv.Dev;
console.warn("[Avo Inspector] Unsupported environment provided. Defaulting to dev. Supported environments - Dev, Staging, Prod.");
}
else {
this.environment = options.env;
}
if ((0, utils_1.isValueEmpty)(options.apiKey)) {
throw new Error("[Avo Inspector] No API key provided. Inspector can't operate without API key.");
}
else {
this.apiKey = options.apiKey;
}
if ((0, utils_1.isValueEmpty)(options.version)) {
throw new Error("[Avo Inspector] No version provided. Many features of Inspector rely on versioning. Please provide comparable string version, i.e. integer or semantic.");
}
else {
this.version = options.version;
}
if (this.environment === AvoInspectorEnv_1.AvoInspectorEnv.Dev) {
AvoInspector._batchSize = 1;
AvoInspector._shouldLog = true;
}
else {
AvoInspector._batchSize = 30;
AvoInspector._batchFlushSeconds = 30;
AvoInspector._shouldLog = false;
}
AvoInspector.avoStorage = new AvoStorage_1.AvoStorage(AvoInspector._shouldLog, options.suffix != null ? options.suffix : "");
this.avoNetworkCallsHandler = new AvoNetworkCallsHandler_1.AvoNetworkCallsHandler(this.apiKey, this.environment.toString(), options.appName || "", this.version, libVersion, options.publicEncryptionKey);
this.avoBatcher = new AvoBatcher_1.AvoBatcher(this.avoNetworkCallsHandler);
this.avoDeduplicator = new AvoDeduplicator_1.AvoDeduplicator();
// Initialize event spec validation (active in dev/staging only)
this.eventSpecCache = new AvoEventSpecCache_1.EventSpecCache(AvoInspector._shouldLog);
this.eventSpecFetcher = new AvoEventSpecFetcher_1.AvoEventSpecFetcher(5000, AvoInspector._shouldLog, this.environment.toString());
}
Object.defineProperty(AvoInspector, "batchSize", {
get: function () {
return this._batchSize;
},
set: function (newSize) {
if (newSize < 1) {
this._batchSize = 1;
}
else {
this._batchSize = newSize;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(AvoInspector, "batchFlushSeconds", {
get: function () {
return this._batchFlushSeconds;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AvoInspector, "shouldLog", {
get: function () {
return this._shouldLog;
},
set: function (enable) {
this._shouldLog = enable;
},
enumerable: false,
configurable: true
});
AvoInspector.prototype.trackSchemaFromEvent = function (eventName, eventProperties) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.trackSchemaFromEventInternal(eventName, eventProperties, false, null, null)];
});
});
};
AvoInspector.prototype._avoFunctionTrackSchemaFromEvent = function (eventName, eventProperties, eventId, eventHash) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.trackSchemaFromEventInternal(eventName, eventProperties, true, eventId, eventHash)];
});
});
};
/**
* Shared implementation for trackSchemaFromEvent and _avoFunctionTrackSchemaFromEvent.
*/
AvoInspector.prototype.trackSchemaFromEventInternal = function (eventName, eventProperties, fromAvoFunction, eventId, eventHash) {
return __awaiter(this, void 0, void 0, function () {
var eventSchema, validationResult, schemaWithValidation, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 8, , 9]);
if (!this.avoDeduplicator.shouldRegisterEvent(eventName, eventProperties, fromAvoFunction)) return [3 /*break*/, 6];
if (AvoInspector.shouldLog) {
console.log("Avo Inspector: supplied event " +
eventName +
" with params " +
JSON.stringify(eventProperties));
}
eventSchema = this.extractSchema(eventProperties, false);
return [4 /*yield*/, this.validateEvent(eventName, eventProperties)];
case 1:
validationResult = _a.sent();
if (!validationResult) return [3 /*break*/, 3];
schemaWithValidation = this.mergeValidationResults(eventSchema, validationResult);
return [4 /*yield*/, this.sendEventWithValidation(eventName, schemaWithValidation, eventId, eventHash, validationResult, eventProperties)];
case 2:
_a.sent();
return [3 /*break*/, 5];
case 3:
// No spec: fall back to batched flow (still encrypt if possible)
return [4 /*yield*/, this.trackSchemaInternal(eventName, eventSchema, eventId, eventHash, eventProperties)];
case 4:
// No spec: fall back to batched flow (still encrypt if possible)
_a.sent();
_a.label = 5;
case 5: return [2 /*return*/, eventSchema];
case 6:
if (AvoInspector.shouldLog) {
console.log("Avo Inspector: Deduplicated event: " + eventName);
}
return [2 /*return*/, []];
case 7: return [3 /*break*/, 9];
case 8:
e_1 = _a.sent();
console.error("Avo Inspector: something went wrong. Please report to support@avo.app.", e_1);
return [2 /*return*/, []];
case 9: return [2 /*return*/];
}
});
});
};
AvoInspector.prototype.trackSchema = function (eventName, eventSchema) {
try {
if (this.avoDeduplicator.shouldRegisterSchemaFromManually(eventName, eventSchema)) {
if (AvoInspector.shouldLog) {
console.log("Avo Inspector: supplied event " +
eventName +
" with schema " +
JSON.stringify(eventSchema));
}
this.trackSchemaInternal(eventName, eventSchema, null, null);
}
else {
if (AvoInspector.shouldLog) {
console.log("Avo Inspector: Deduplicated event: " + eventName);
}
}
}
catch (e) {
console.error("Avo Inspector: something went wrong. Please report to support@avo.app.", e);
}
};
AvoInspector.prototype.trackSchemaInternal = function (eventName, eventSchema, eventId, eventHash, eventProperties) {
return __awaiter(this, void 0, void 0, function () {
var isDevOrStaging, eventBody, e_2;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 3, , 4]);
isDevOrStaging = this.environment === AvoInspectorEnv_1.AvoInspectorEnv.Dev ||
this.environment === AvoInspectorEnv_1.AvoInspectorEnv.Staging;
if (!(isDevOrStaging && eventProperties)) return [3 /*break*/, 2];
return [4 /*yield*/, this.avoNetworkCallsHandler.bodyForValidatedEventSchemaCall(eventName, eventSchema, eventId, eventHash, eventProperties)];
case 1:
eventBody = _a.sent();
this.avoNetworkCallsHandler.callInspectorImmediately(eventBody, function (error) {
if (error) {
// Fallback to batch on failure
_this.avoBatcher.handleTrackSchema(eventName, eventSchema, eventId, eventHash);
}
});
return [2 /*return*/];
case 2:
// Production or no event properties: use normal batched flow (respects sampling)
this.avoBatcher.handleTrackSchema(eventName, eventSchema, eventId, eventHash);
return [3 /*break*/, 4];
case 3:
e_2 = _a.sent();
console.error("Avo Inspector: something went wrong. Please report to support@avo.app.", e_2);
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
});
};
AvoInspector.prototype.enableLogging = function (enable) {
AvoInspector._shouldLog = enable;
};
AvoInspector.prototype.extractSchema = function (eventProperties, shouldLogIfEnabled) {
if (shouldLogIfEnabled === void 0) { shouldLogIfEnabled = true; }
try {
if (this.avoDeduplicator.hasSeenEventParams(eventProperties, true)) {
if (shouldLogIfEnabled && AvoInspector.shouldLog) {
console.warn("Avo Inspector: WARNING! You are trying to extract schema shape that was just reported by your Avo functions. " +
"This is an indicator of duplicate inspector reporting. " +
"Please reach out to support@avo.app for advice if you are not sure how to handle this.");
}
}
if (AvoInspector.shouldLog) {
console.log("Avo Inspector: extracting schema from " +
JSON.stringify(eventProperties));
}
return AvoSchemaParser_1.AvoSchemaParser.extractSchema(eventProperties);
}
catch (e) {
console.error("Avo Inspector: something went wrong. Please report to support@avo.app.", e);
return [];
}
};
AvoInspector.prototype.setBatchSize = function (newBatchSize) {
AvoInspector._batchSize = newBatchSize;
};
AvoInspector.prototype.setBatchFlushSeconds = function (newBatchFlushSeconds) {
AvoInspector._batchFlushSeconds = newBatchFlushSeconds;
};
/**
* Validates event properties against the Avo tracking plan spec.
*
* Active only in dev/staging environments. In prod, returns null immediately.
* Null spec responses are cached to avoid re-fetching.
* Cache is flushed when branchId changes between responses.
*
* @param eventName - The name of the event to validate
* @param eventProperties - The properties to validate
* @returns ValidationResult with property validation results, or null if spec unavailable
*/
AvoInspector.prototype.validateEvent = function (eventName, eventProperties) {
return __awaiter(this, void 0, void 0, function () {
var streamId, cachedSpec, spec, responseBranchId, e_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Only validate in dev/staging
if (this.environment !== AvoInspectorEnv_1.AvoInspectorEnv.Dev &&
this.environment !== AvoInspectorEnv_1.AvoInspectorEnv.Staging) {
return [2 /*return*/, null];
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
streamId = AvoStreamId_1.AvoStreamId.getAnonymousId();
// No stream ID (storage not ready) — skip validation, send as wild event
if (streamId === null) {
return [2 /*return*/, null];
}
cachedSpec = this.eventSpecCache.get(this.apiKey, streamId, eventName);
if (cachedSpec !== undefined) {
// Cache hit - cachedSpec is either EventSpecResponse or null (known absent)
if (cachedSpec === null) {
if (AvoInspector.shouldLog) {
console.log("[Avo Inspector] Cache hit (empty) for event: ".concat(eventName, ". Sending without validation."));
}
return [2 /*return*/, null];
}
if (AvoInspector.shouldLog) {
console.log("[Avo Inspector] Cache hit for event: ".concat(eventName));
}
return [2 /*return*/, (0, EventValidator_1.validateEvent)(eventProperties, cachedSpec)];
}
return [4 /*yield*/, this.eventSpecFetcher.fetch({
apiKey: this.apiKey,
streamId: streamId,
eventName: eventName,
})];
case 2:
spec = _a.sent();
// Transient error (network, timeout, parse failure) — don't cache, retry next time
if (spec === "transient_error") {
if (AvoInspector.shouldLog) {
console.log("[Avo Inspector] Transient error fetching event spec for: ".concat(eventName, ". Will retry next time."));
}
return [2 /*return*/, null];
}
if (spec) {
responseBranchId = spec.metadata.branchId;
if (this.lastSeenBranchId !== null && this.lastSeenBranchId !== responseBranchId) {
if (AvoInspector.shouldLog) {
console.log("[Avo Inspector] Branch ID changed from ".concat(this.lastSeenBranchId, " to ").concat(responseBranchId, ". Flushing event spec cache."));
}
this.eventSpecCache.clear();
}
this.lastSeenBranchId = responseBranchId;
// Cache the result after branch check (so flush doesn't lose it)
this.eventSpecCache.set(this.apiKey, streamId, eventName, spec);
return [2 /*return*/, (0, EventValidator_1.validateEvent)(eventProperties, spec)];
}
else {
// Event definitively not found — cache so we don't re-fetch
this.eventSpecCache.set(this.apiKey, streamId, eventName, null);
if (AvoInspector.shouldLog) {
console.log("[Avo Inspector] Event not found in tracking plan: ".concat(eventName, ". Cached empty response."));
}
return [2 /*return*/, null];
}
return [3 /*break*/, 4];
case 3:
e_3 = _a.sent();
if (AvoInspector.shouldLog) {
console.error("[Avo Inspector] Error during event spec validation:", e_3);
}
return [2 /*return*/, null];
case 4: return [2 /*return*/];
}
});
});
};
/**
* Merges validation results into the event schema.
* Adds failedEventIds or passedEventIds to each property based on validation.
* Recursively merges validation results for nested children.
*/
AvoInspector.prototype.mergeValidationResults = function (eventSchema, validationResult) {
var _this = this;
return eventSchema.map(function (prop) {
var propValidation = validationResult.propertyResults[prop.propertyName];
return _this.mergePropertyValidation(prop, propValidation);
});
};
/**
* Merges validation result into a single property, recursively handling children.
*/
AvoInspector.prototype.mergePropertyValidation = function (prop, propValidation) {
var _this = this;
var result = {
propertyName: prop.propertyName,
propertyType: prop.propertyType,
};
if (prop.encryptedPropertyValue) {
result.encryptedPropertyValue = prop.encryptedPropertyValue;
}
// Recursively merge validation results into children
if (prop.children && Array.isArray(prop.children)) {
result.children = prop.children.map(function (child) {
var _a;
// Children can be strings (for array types) or objects (for nested properties)
if (typeof child === "string") {
return child;
}
if (child && typeof child === "object" && child.propertyName) {
// Get nested validation result for this child
var childValidation = (_a = propValidation === null || propValidation === void 0 ? void 0 : propValidation.children) === null || _a === void 0 ? void 0 : _a[child.propertyName];
return _this.mergePropertyValidation(child, childValidation);
}
return child;
});
}
// Add validation result for this property
if (propValidation) {
if (propValidation.failedEventIds) {
result.failedEventIds = propValidation.failedEventIds;
}
if (propValidation.passedEventIds) {
result.passedEventIds = propValidation.passedEventIds;
}
}
return result;
};
/**
* Sends an event immediately with validation data (bypasses batching).
* Encrypts property values if publicEncryptionKey is configured.
* Logs validation info if shouldLog is true.
*/
AvoInspector.prototype.sendEventWithValidation = function (eventName, eventSchema, eventId, eventHash, validationResult, eventProperties) {
return __awaiter(this, void 0, void 0, function () {
var hasFailures, eventBody;
var _this = this;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
// Log validation info if shouldLog is enabled
if (AvoInspector.shouldLog) {
hasFailures = eventSchema.some(function (p) { return p.failedEventIds && p.failedEventIds.length > 0; });
if (hasFailures) {
console.log("[Avo Inspector] Validation failures for event \"".concat(eventName, "\":"), eventSchema
.filter(function (p) { return p.failedEventIds && p.failedEventIds.length > 0; })
.map(function (p) { return ({
property: p.propertyName,
failedEventIds: p.failedEventIds,
}); }));
}
}
return [4 /*yield*/, this.avoNetworkCallsHandler.bodyForValidatedEventSchemaCall(eventName, eventSchema, eventId, eventHash, eventProperties)];
case 1:
eventBody = _b.sent();
// Add metadata
if (validationResult.metadata) {
eventBody.eventSpecMetadata = validationResult.metadata;
}
if ((_a = validationResult.metadata) === null || _a === void 0 ? void 0 : _a.branchId) {
eventBody.validatedBranchId = validationResult.metadata.branchId;
}
// Send immediately (bypass batching)
this.avoNetworkCallsHandler.callInspectorImmediately(eventBody, function (error) {
if (error) {
if (AvoInspector.shouldLog) {
console.error("[Avo Inspector] Failed to send event \"".concat(eventName, "\" with validation:"), error);
}
// Fallback: add to batch on failure (without validation data)
_this.avoBatcher.handleTrackSchema(eventName, eventSchema, eventId, eventHash);
}
else {
if (AvoInspector.shouldLog) {
console.log("[Avo Inspector] Event \"".concat(eventName, "\" sent successfully with validation"));
}
}
});
return [2 /*return*/];
}
});
});
};
AvoInspector._batchSize = 30;
AvoInspector._batchFlushSeconds = 30;
AvoInspector._shouldLog = false;
return AvoInspector;
}());
exports.AvoInspector = AvoInspector;