"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function newSessionId() {
    return now();
}
function now() {
    return new Date().getTime();
}
const THIRTY_MINUTES = 30 * 60000;
function stale(id, updated, length = THIRTY_MINUTES) {
    if (id === null || updated === null) {
        return true;
    }
    const accessedAt = updated;
    if (now() - accessedAt >= length) {
        return true;
    }
    return false;
}
const action = {
    title: 'Session Plugin',
    description: 'Generates a Session ID and attaches it to every Amplitude browser based event.',
    platform: 'web',
    hidden: true,
    defaultSubscription: 'type = "track" or type = "identify" or type = "group" or type = "page" or type = "alias"',
    fields: {
        sessionLength: {
            label: 'Session Length',
            type: 'number',
            required: false,
            description: 'Time in milliseconds to be used before considering a session stale.'
        }
    },
    lifecycleHook: 'enrichment',
    perform: (_, { context, payload, analytics }) => {
        const storageFallback = {
            get: (key) => {
                const data = window.localStorage.getItem(key);
                return data === null ? null : parseInt(data, 10);
            },
            set: (key, value) => {
                return window.localStorage.setItem(key, value.toString());
            }
        };
        const newSession = newSessionId();
        const storage = analytics.storage
            ?
                analytics.storage
            : storageFallback;
        const raw = storage.get('analytics_session_id');
        const updated = storage.get('analytics_session_id.last_access');
        let id = raw;
        if (stale(raw, updated, payload.sessionLength)) {
            id = newSession;
            storage.set('analytics_session_id', id);
        }
        else {
            storage.set('analytics_session_id', id);
        }
        storage.set('analytics_session_id.last_access', newSession);
        if (context.event.integrations?.All !== false || context.event.integrations['Actions Amplitude']) {
            context.updateEvent('integrations.Actions Amplitude', {});
            context.updateEvent('integrations.Actions Amplitude.session_id', id);
        }
        return;
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map