"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sessionReplayPlugin = exports.SessionReplayPlugin = exports.DEFAULT_SESSION_REPLAY_PROPERTY = exports.DEFAULT_EVENT_PROPERTY_PREFIX = void 0;
var tslib_1 = require("tslib");
var analytics_core_1 = require("@amplitude/analytics-core");
var session_replay_browser_1 = require("@amplitude/session-replay-browser");
var analytics_client_common_1 = require("@amplitude/analytics-client-common");
var helpers_1 = require("./helpers");
var version_1 = require("./version");
exports.DEFAULT_EVENT_PROPERTY_PREFIX = '[Amplitude]';
exports.DEFAULT_SESSION_REPLAY_PROPERTY = "".concat(exports.DEFAULT_EVENT_PROPERTY_PREFIX, " Session Replay ID");
var SessionReplayPlugin = /** @class */ (function () {
    function SessionReplayPlugin(options) {
        this.name = SessionReplayPlugin.pluginName;
        this.type = 'enrichment';
        // this.config is defined in setup() which will always be called first
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        this.config = null;
        this.sessionReplay = {
            flush: session_replay_browser_1.flush,
            getSessionId: session_replay_browser_1.getSessionId,
            getSessionReplayProperties: session_replay_browser_1.getSessionReplayProperties,
            init: session_replay_browser_1.init,
            setSessionId: session_replay_browser_1.setSessionId,
            shutdown: session_replay_browser_1.shutdown,
            evaluateTargetingAndCapture: session_replay_browser_1.evaluateTargetingAndCapture,
        };
        this.options = tslib_1.__assign({ forceSessionTracking: false }, options);
        this.srInitOptions = this.options;
    }
    SessionReplayPlugin.prototype.setup = function (config, _client) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var identityStore, userProperties, error_1;
            return tslib_1.__generator(this, function (_j) {
                switch (_j.label) {
                    case 0:
                        _j.trys.push([0, 2, , 3]);
                        /* istanbul ignore next */
                        config === null || config === void 0 ? void 0 : config.loggerProvider.log("Installing @amplitude/plugin-session-replay, version ".concat(version_1.VERSION, "."));
                        this.config = config;
                        if (this.options.forceSessionTracking) {
                            if (typeof config.defaultTracking === 'boolean') {
                                if (config.defaultTracking === false) {
                                    config.defaultTracking = {
                                        pageViews: false,
                                        formInteractions: false,
                                        fileDownloads: false,
                                        sessions: true,
                                    };
                                }
                            }
                            else {
                                config.defaultTracking = tslib_1.__assign(tslib_1.__assign({}, config.defaultTracking), { sessions: true });
                            }
                        }
                        identityStore = (0, analytics_client_common_1.getAnalyticsConnector)(this.config.instanceName).identityStore;
                        userProperties = identityStore.getIdentity().userProperties;
                        this.srInitOptions = {
                            instanceName: this.config.instanceName,
                            deviceId: (_a = this.options.deviceId) !== null && _a !== void 0 ? _a : this.config.deviceId,
                            optOut: this.config.optOut,
                            sessionId: this.options.customSessionId ? undefined : this.config.sessionId,
                            loggerProvider: this.config.loggerProvider,
                            logLevel: this.config.logLevel,
                            flushMaxRetries: this.config.flushMaxRetries,
                            serverZone: this.config.serverZone,
                            configServerUrl: this.options.configServerUrl || ((_b = this.config.remoteConfig) === null || _b === void 0 ? void 0 : _b.serverUrl),
                            trackServerUrl: this.options.trackServerUrl,
                            sampleRate: this.options.sampleRate,
                            privacyConfig: {
                                blockSelector: (_c = this.options.privacyConfig) === null || _c === void 0 ? void 0 : _c.blockSelector,
                                maskSelector: (_d = this.options.privacyConfig) === null || _d === void 0 ? void 0 : _d.maskSelector,
                                unmaskSelector: (_e = this.options.privacyConfig) === null || _e === void 0 ? void 0 : _e.unmaskSelector,
                                defaultMaskLevel: (_f = this.options.privacyConfig) === null || _f === void 0 ? void 0 : _f.defaultMaskLevel,
                            },
                            debugMode: this.options.debugMode,
                            shouldInlineStylesheet: this.options.shouldInlineStylesheet,
                            version: { type: 'plugin', version: version_1.VERSION },
                            performanceConfig: this.options.performanceConfig,
                            storeType: this.options.storeType,
                            useWebWorker: (_g = this.options.useWebWorker) !== null && _g !== void 0 ? _g : (_h = this.options.experimental) === null || _h === void 0 ? void 0 : _h.useWebWorker,
                            userProperties: userProperties,
                            applyBackgroundColorToBlockedElements: this.options.applyBackgroundColorToBlockedElements,
                            interactionConfig: this.options.interactionConfig,
                            captureDocumentTitle: this.options.captureDocumentTitle,
                            enableUrlChangePolling: this.options.enableUrlChangePolling,
                            urlChangePollingInterval: this.options.urlChangePollingInterval,
                            captureAdoptedStyleSheets: this.options.captureAdoptedStyleSheets,
                            crossOriginIframes: this.options.crossOriginIframes,
                            flushIntervalConfig: this.options.flushIntervalConfig,
                            eagerFullSnapshotSend: this.options.eagerFullSnapshotSend,
                            captureFullSnapshotOnFocus: this.options.captureFullSnapshotOnFocus,
                            maxPersistedEventsSizeBytes: this.options.maxPersistedEventsSizeBytes,
                            maxSingleEventSizeBytes: this.options.maxSingleEventSizeBytes,
                            sendTimeoutMs: this.options.sendTimeoutMs,
                        };
                        return [4 /*yield*/, this.sessionReplay.init(config.apiKey, this.srInitOptions).promise];
                    case 1:
                        _j.sent();
                        return [3 /*break*/, 3];
                    case 2:
                        error_1 = _j.sent();
                        /* istanbul ignore next */
                        config === null || config === void 0 ? void 0 : config.loggerProvider.error("Session Replay: Failed to initialize due to ".concat(error_1.message));
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    SessionReplayPlugin.prototype.onSessionIdChanged = function (sessionId) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            return tslib_1.__generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        (_a = this.config) === null || _a === void 0 ? void 0 : _a.loggerProvider.debug("Analytics session id is changed to ".concat(sessionId, ", SR session id is ").concat(String(this.sessionReplay.getSessionId()), "."));
                        return [4 /*yield*/, this.sessionReplay.setSessionId(sessionId).promise];
                    case 1:
                        _b.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    SessionReplayPlugin.prototype.onOptOutChanged = function (optOut) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var _b;
            return tslib_1.__generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        (_a = this.config) === null || _a === void 0 ? void 0 : _a.loggerProvider.debug("optOut is changed to ".concat(String(optOut), ", calling ").concat(optOut ? 'sessionReplay.shutdown()' : 'sessionReplay.init()', "."));
                        if (!optOut) return [3 /*break*/, 1];
                        this.sessionReplay.shutdown();
                        return [3 /*break*/, 4];
                    case 1:
                        _b = this.config != null;
                        if (!_b) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.sessionReplay.init(this.config.apiKey, this.srInitOptions).promise];
                    case 2:
                        _b = (_c.sent());
                        _c.label = 3;
                    case 3:
                        _b;
                        _c.label = 4;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    SessionReplayPlugin.prototype.execute = function (event) {
        var _a, _b, _c;
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var sessionId, sessionRecordingProperties, sessionId, userProperties, globalScope, sessionRecordingProperties, error_2;
            return tslib_1.__generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _d.trys.push([0, 9, , 10]);
                        if (!this.options.customSessionId) return [3 /*break*/, 4];
                        sessionId = this.options.customSessionId(event);
                        if (!sessionId) return [3 /*break*/, 3];
                        if (!(sessionId !== this.sessionReplay.getSessionId())) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.sessionReplay.setSessionId(sessionId).promise];
                    case 1:
                        _d.sent();
                        _d.label = 2;
                    case 2:
                        sessionRecordingProperties = this.sessionReplay.getSessionReplayProperties();
                        event.event_properties = tslib_1.__assign(tslib_1.__assign({}, event.event_properties), sessionRecordingProperties);
                        _d.label = 3;
                    case 3: return [3 /*break*/, 8];
                    case 4:
                        sessionId = (_a = this.config) === null || _a === void 0 ? void 0 : _a.sessionId;
                        if (!(sessionId && sessionId !== this.sessionReplay.getSessionId())) return [3 /*break*/, 6];
                        return [4 /*yield*/, this.sessionReplay.setSessionId(sessionId).promise];
                    case 5:
                        _d.sent();
                        _d.label = 6;
                    case 6:
                        if (!(sessionId && sessionId === event.session_id)) return [3 /*break*/, 8];
                        userProperties = void 0;
                        if (event.event_type === analytics_core_1.SpecialEventType.IDENTIFY) {
                            userProperties = (0, helpers_1.parseUserProperties)(event);
                        }
                        globalScope = (0, analytics_core_1.getGlobalScope)();
                        return [4 /*yield*/, this.sessionReplay.evaluateTargetingAndCapture({
                                event: event,
                                userProperties: userProperties,
                                page: ((_b = globalScope === null || globalScope === void 0 ? void 0 : globalScope.location) === null || _b === void 0 ? void 0 : _b.href) != null ? { url: globalScope.location.href } : undefined,
                            })];
                    case 7:
                        _d.sent();
                        sessionRecordingProperties = this.sessionReplay.getSessionReplayProperties();
                        event.event_properties = tslib_1.__assign(tslib_1.__assign({}, event.event_properties), sessionRecordingProperties);
                        _d.label = 8;
                    case 8:
                        if (event.event_type === analytics_core_1.SpecialEventType.IDENTIFY && event.event_properties) {
                            delete event.event_properties[exports.DEFAULT_SESSION_REPLAY_PROPERTY];
                        }
                        return [2 /*return*/, Promise.resolve(event)];
                    case 9:
                        error_2 = _d.sent();
                        /* istanbul ignore next */
                        (_c = this.config) === null || _c === void 0 ? void 0 : _c.loggerProvider.error("Session Replay: Failed to enrich event due to ".concat(error_2.message));
                        return [2 /*return*/, Promise.resolve(event)];
                    case 10: return [2 /*return*/];
                }
            });
        });
    };
    SessionReplayPlugin.prototype.teardown = function () {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            return tslib_1.__generator(this, function (_b) {
                try {
                    this.sessionReplay.shutdown();
                    // the following are initialized in setup() which will always be called first
                    // here we reset them to null to prevent memory leaks
                    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                    // @ts-ignore
                    this.config = null;
                }
                catch (error) {
                    /* istanbul ignore next */
                    (_a = this.config) === null || _a === void 0 ? void 0 : _a.loggerProvider.error("Session Replay: teardown failed due to ".concat(error.message));
                }
                return [2 /*return*/];
            });
        });
    };
    SessionReplayPlugin.prototype.getSessionReplayProperties = function () {
        return this.sessionReplay.getSessionReplayProperties();
    };
    SessionReplayPlugin.pluginName = '@amplitude/plugin-session-replay-browser';
    return SessionReplayPlugin;
}());
exports.SessionReplayPlugin = SessionReplayPlugin;
var sessionReplayPlugin = function (options) {
    return new SessionReplayPlugin(options);
};
exports.sessionReplayPlugin = sessionReplayPlugin;
//# sourceMappingURL=session-replay.js.map