"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.hosts = void 0;
exports.formatPayload = formatPayload;
exports.sanitiseEventName = sanitiseEventName;
exports.formatAttributes = formatAttributes;
exports.generateUUIDFor = generateUUIDFor;
const crypto = __importStar(require("crypto"));
const VWO_NAMESPACE = '11e13cd7-6c48-53ec-8679-7e9c752273c5';
exports.hosts = {
    US: 'https://dev.visualwebsiteoptimizer.com',
    EU: 'https://dev.visualwebsiteoptimizer.com/eu01',
    AS: 'https://dev.visualwebsiteoptimizer.com/as01'
};
function uuidv5(name, namespace) {
    const namespaceBuffer = Buffer.from(namespace.replace(/-/g, ''), 'hex');
    const nameBuffer = Buffer.from(name);
    const hashBuffer = crypto.createHash('sha1').update(namespaceBuffer).update(nameBuffer).digest();
    hashBuffer[6] &= 0x0f;
    hashBuffer[6] |= 0x50;
    hashBuffer[8] &= 0x3f;
    hashBuffer[8] |= 0x80;
    const uuidSegments = [
        hashBuffer.subarray(0, 4).toString('hex'),
        hashBuffer.subarray(4, 6).toString('hex'),
        hashBuffer.subarray(6, 8).toString('hex'),
        hashBuffer.subarray(8, 10).toString('hex'),
        hashBuffer.subarray(10, 16).toString('hex')
    ];
    return uuidSegments.join('-');
}
function generate(name, namespace) {
    if (!name || !namespace) {
        return '';
    }
    return uuidv5(name, namespace);
}
function formatPayload(name, payload, isCustomEvent, isTrack = false, apiKey = '', accountId = 0) {
    let formattedProperties = {};
    const vwoUuid = apiKey.trim().length ? generateUUIDFor(payload.vwoUuid, accountId) : payload.vwoUuid;
    if (isTrack) {
        formattedProperties = { ...payload.properties };
        delete formattedProperties['vwo_uuid'];
    }
    const epochTime = new Date().valueOf();
    const time = Math.floor(epochTime);
    const sessionId = Math.floor(epochTime / 1000);
    const page = payload.page
        ? {
            ...payload.page,
            referrerUrl: payload.page['referrer']
        }
        : {};
    const structuredPayload = {
        d: {
            msgId: `${vwoUuid}-${sessionId}`,
            visId: vwoUuid,
            event: {
                props: {
                    ...formattedProperties,
                    page,
                    isCustomEvent,
                    vwoMeta: {
                        source: 'segment.cloud',
                        metric: {}
                    }
                },
                name,
                time
            },
            sessionId
        }
    };
    const headers = payload.userAgent
        ? {
            'User-Agent': payload.userAgent
        }
        : {};
    if (apiKey.trim().length) {
        const visitorObj = {
            props: {
                vwo_fs_environment: apiKey
            }
        };
        structuredPayload.d.event.props.$visitor = visitorObj;
        structuredPayload.d.visitor = visitorObj;
    }
    if (payload.ip) {
        headers['X-Forwarded-For'] = payload.ip;
    }
    return { headers, structuredPayload };
}
function sanitiseEventName(name) {
    return 'segment.' + name;
}
function formatAttributes(attributes) {
    const formattedAttributes = {};
    for (const key in attributes) {
        formattedAttributes[`segment.${key}`] = attributes[key];
    }
    return formattedAttributes;
}
function generateUUIDFor(userId, accountId) {
    userId = `${userId}`;
    const hash = `${accountId}`;
    const userIdNamespace = generate(hash, VWO_NAMESPACE);
    const uuidForUserIdAccountId = generate(userId, userIdNamespace);
    const desiredUuid = uuidForUserIdAccountId.replace(/-/gi, '').toUpperCase();
    return desiredUuid;
}
//# sourceMappingURL=utility.js.map