@nimpl/ab-tests
Version:
A package for conducting A/B tests on a website using middleware
57 lines (56 loc) • 2.22 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.findTest = void 0;
const roll_test_1 = require("./utils/roll-test");
const test_rule_1 = require("./utils/test-rule");
const findTest = (tests, request, prevTest) => {
const targetPathname = request.nextUrl.pathname;
let testData = null;
for (const test of tests) {
const isPrevTest = test.id === prevTest?.id;
const match = targetPathname.match(`^${test.source}$`);
if (!match)
continue;
const groups = match.groups || {};
if (test.has) {
for (const rule of test.has) {
if (isPrevTest && rule.ignoreOnNextRequests)
continue;
const { match, groups: ruleGroups } = (0, test_rule_1.testRule)(request.nextUrl, rule);
if (!match)
break;
Object.assign(groups, ruleGroups);
}
}
if (test.missing) {
for (const rule of test.missing) {
if (isPrevTest && rule.ignoreOnNextRequests)
continue;
const { match, groups: ruleGroups } = (0, test_rule_1.testRule)(request.nextUrl, rule);
if (match)
break;
Object.assign(groups, ruleGroups);
}
}
testData = { test, groups: match.groups || {}, isPrevTest };
if (isPrevTest || !prevTest) {
break;
}
}
if (testData) {
const { test, groups, isPrevTest } = testData;
const variantIndex = prevTest && isPrevTest ? prevTest.variantIndex : (0, roll_test_1.rollTest)(test.variants);
if (typeof variantIndex !== "undefined") {
const variant = test.variants[variantIndex];
const formattedDestination = Object.entries(groups).reduce((acc, [key, value]) => acc.replace(`:${key}`, value), variant.destination);
return {
id: test.id,
variantIndex,
destination: formattedDestination,
type: variant.type,
status: variant.status,
};
}
}
};
exports.findTest = findTest;
;