UNPKG

react-native-avo-inspector

Version:

[![npm version](https://badge.fury.io/js/react-native-avo-inspector.svg)](https://badge.fury.io/js/react-native-avo-inspector)

436 lines (435 loc) 22.2 kB
"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 AvoEventSpecCache_1 = require("./eventSpec/AvoEventSpecCache"); var AvoEventSpecFetcher_1 = require("./eventSpec/AvoEventSpecFetcher"); var EventValidator_1 = require("./eventSpec/EventValidator"); var utils_1 = require("./utils"); var libVersion = require("../package.json").version; var AvoInspector = /** @class */ (function () { function AvoInspector(options) { var _this = this; this.currentBranchId = 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 (options.publicEncryptionKey) { this.publicEncryptionKey = options.publicEncryptionKey; } if (this.environment === AvoInspectorEnv_1.AvoInspectorEnv.Dev) { AvoInspector._batchSize = 1; AvoInspector._shouldLog = true; } else { AvoInspector._batchSize = 30; AvoInspector._batchFlushSeconds = 30; AvoInspector._shouldLog = false; } try { AvoInspector.avoStorage = new AvoStorage_1.AvoStorage(AvoInspector._shouldLog); } catch (e) { console.error("[Avo Inspector] Failed to initialize storage. " + "If you are using React Native, make sure @react-native-async-storage/async-storage is installed.", e); } var avoNetworkCallsHandler = new AvoNetworkCallsHandler_1.AvoNetworkCallsHandler(this.apiKey, this.environment.toString(), options.appName || "", this.version, libVersion, this.publicEncryptionKey); this.avoBatcher = new AvoBatcher_1.AvoBatcher(avoNetworkCallsHandler); this.avoDeduplicator = new AvoDeduplicator_1.AvoDeduplicator(); // Initialize event spec validation infrastructure for dev/staging if (this.environment !== AvoInspectorEnv_1.AvoInspectorEnv.Prod) { try { this.eventSpecCache = new AvoEventSpecCache_1.EventSpecCache(AvoInspector._shouldLog); this.eventSpecFetcher = new AvoEventSpecFetcher_1.AvoEventSpecFetcher(5000, AvoInspector._shouldLog, this.environment); if (AvoInspector._shouldLog) { console.log("[Avo Inspector] Event spec fetching and validation enabled"); } } catch (e) { console.error("[Avo Inspector] Failed to initialize event spec validation.", e); } } // Fire-and-forget: eagerly initialize the anonymous ID and capture streamId AvoStreamId_1.AvoStreamId.initialize().then(function (id) { _this.streamId = id; }).catch(function (e) { console.error("Avo Inspector: failed to initialize anonymous ID.", e); }); } 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 () { var eventSchema, validationResult, schemaWithValidation, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 4, , 5]); if (!this.avoDeduplicator.shouldRegisterEvent(eventName, eventProperties, false)) return [3 /*break*/, 2]; if (AvoInspector.shouldLog) { console.log("Avo Inspector: supplied event " + eventName + " with params " + JSON.stringify(eventProperties)); } eventSchema = this.extractSchema(eventProperties, false); return [4 /*yield*/, this.fetchAndValidateEvent(eventName, eventProperties)]; case 1: validationResult = _a.sent(); if (validationResult) { schemaWithValidation = this.mergeValidationResults(eventSchema, validationResult); // Send validated events immediately, bypassing the batcher this.sendEventWithValidation(eventName, schemaWithValidation, null, null, validationResult, eventProperties); } else { this.trackSchemaInternal(eventName, eventSchema, null, null, eventProperties); } return [2 /*return*/, eventSchema]; case 2: if (AvoInspector.shouldLog) { console.log("Avo Inspector: Deduplicated event: " + eventName); } return [2 /*return*/, []]; case 3: return [3 /*break*/, 5]; case 4: e_1 = _a.sent(); console.error("Avo Inspector: something went wrong. Please report to support@avo.app.", e_1); return [2 /*return*/, []]; case 5: return [2 /*return*/]; } }); }); }; AvoInspector.prototype._avoFunctionTrackSchemaFromEvent = function (eventName, eventProperties, eventId, eventHash) { return __awaiter(this, void 0, void 0, function () { var eventSchema, validationResult, schemaWithValidation, e_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 4, , 5]); if (!this.avoDeduplicator.shouldRegisterEvent(eventName, eventProperties, true)) return [3 /*break*/, 2]; if (AvoInspector.shouldLog) { console.log("Avo Inspector: supplied event " + eventName + " with params " + JSON.stringify(eventProperties)); } eventSchema = this.extractSchema(eventProperties, false); return [4 /*yield*/, this.fetchAndValidateEvent(eventName, eventProperties)]; case 1: validationResult = _a.sent(); if (validationResult) { schemaWithValidation = this.mergeValidationResults(eventSchema, validationResult); // Send validated events immediately, bypassing the batcher this.sendEventWithValidation(eventName, schemaWithValidation, eventId, eventHash, validationResult, eventProperties); } else { this.trackSchemaInternal(eventName, eventSchema, eventId, eventHash, eventProperties); } return [2 /*return*/, eventSchema]; case 2: if (AvoInspector.shouldLog) { console.log("Avo Inspector: Deduplicated event: " + eventName); } return [2 /*return*/, []]; case 3: return [3 /*break*/, 5]; case 4: e_2 = _a.sent(); console.error("Avo Inspector: something went wrong. Please report to support@avo.app.", e_2); return [2 /*return*/, []]; case 5: 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) { try { this.avoBatcher.handleTrackSchema(eventName, eventSchema, eventId, eventHash, eventProperties); } catch (e) { console.error("Avo Inspector: something went wrong. Please report to support@avo.app.", e); } }; 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; }; /** * Handles branch change detection and cache storage for a fetched event spec. */ AvoInspector.prototype.handleBranchChangeAndCache = function (specResponse, eventName) { var _a; var newBranchId = specResponse.metadata.branchId; if (this.currentBranchId !== null && this.currentBranchId !== newBranchId) { if (AvoInspector.shouldLog) { console.log("[Avo Inspector] Branch changed from ".concat(this.currentBranchId, " to ").concat(newBranchId, ". Flushing cache.")); } (_a = this.eventSpecCache) === null || _a === void 0 ? void 0 : _a.clear(); } this.currentBranchId = newBranchId; if (this.eventSpecCache && this.streamId) { this.eventSpecCache.set(this.apiKey, this.streamId, eventName, specResponse); } }; /** * Fetches event spec and validates the event against it. * Returns ValidationResult if spec is available, null otherwise. * Only runs in dev/staging environments. */ AvoInspector.prototype.fetchAndValidateEvent = function (eventName, eventProperties) { return __awaiter(this, void 0, void 0, function () { var specResponse, fetched, validationResult, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: // Only fetch specs in dev/staging environments (NOT in production) if (this.environment === AvoInspectorEnv_1.AvoInspectorEnv.Prod) { return [2 /*return*/, null]; } // Only fetch if we have the required infrastructure if (!this.eventSpecCache || !this.eventSpecFetcher || !this.streamId) { return [2 /*return*/, null]; } _a.label = 1; case 1: _a.trys.push([1, 6, , 7]); specResponse = this.eventSpecCache.get(this.apiKey, this.streamId, eventName); if (!(specResponse === undefined)) return [3 /*break*/, 3]; return [4 /*yield*/, this.eventSpecFetcher.fetch({ apiKey: this.apiKey, streamId: this.streamId, eventName: eventName })]; case 2: fetched = _a.sent(); if (fetched) { this.handleBranchChangeAndCache(fetched, eventName); specResponse = fetched; } else { // Cache null response to prevent re-fetching this.eventSpecCache.set(this.apiKey, this.streamId, eventName, null); specResponse = null; } _a.label = 3; case 3: if (!specResponse) return [3 /*break*/, 5]; return [4 /*yield*/, (0, EventValidator_1.validateEvent)(eventProperties, specResponse)]; case 4: validationResult = _a.sent(); return [2 /*return*/, validationResult]; case 5: return [2 /*return*/, null]; case 6: error_1 = _a.sent(); if (AvoInspector.shouldLog) { console.error("[Avo Inspector] Error validating event ".concat(eventName, ":"), error_1); } return [2 /*return*/, null]; case 7: return [2 /*return*/]; } }); }); }; /** * Merges validation results into the event schema. * Adds failedEventIds or passedEventIds to each property based on validation. */ 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 }; // Recursively merge validation results into children if (prop.children && Array.isArray(prop.children)) { result.children = prop.children.map(function (child) { var _a; if (typeof child === 'string') { return child; } if (child && typeof child === 'object' && child.propertyName) { 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 a validated event immediately, bypassing the batcher. * Matches Android SDK's sendEventWithValidation behavior. */ AvoInspector.prototype.sendEventWithValidation = function (eventName, eventSchema, eventId, eventHash, validationResult, eventProperties) { var networkHandler = this.avoBatcher.networkCallsHandler; networkHandler.bodyForEventSchemaCall(eventName, eventSchema, eventId, eventHash, eventProperties, validationResult.metadata).then(function (eventBody) { networkHandler.reportValidatedEvent(eventBody); }).catch(function (e) { console.error("Avo Inspector: failed to send validated event.", e); }); }; AvoInspector._batchSize = 30; AvoInspector._batchFlushSeconds = 30; AvoInspector._shouldLog = false; return AvoInspector; }()); exports.AvoInspector = AvoInspector;