Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.
TypeScript analyticsaudience-segmentationchartscohort-analysisgoogle-analyticsproduct-analyticsstatisticsuser-journeyweb-analytics
Add coverage for core utility behavior
Mike Cao65e810ec7927
diff --git a/src/lib/boardComponentCompatibility.test.ts b/src/lib/boardComponentCompatibility.test.tsnew file mode 100644index 000000000..3bad01875--- /dev/null+++ b/src/lib/boardComponentCompatibility.test.ts@@ -0,0 +1,33 @@+import { describe, expect, test } from 'vitest';+import {+ getSupportedBoardComponentEntityTypes,+ isBoardComponentSupportedByEntityType,+} from './boardComponentCompatibility';++describe('getSupportedBoardComponentEntityTypes', () => {+ test('returns the supported entity types for a known component', () => {+ expect(getSupportedBoardComponentEntityTypes('Funnel')).toEqual(['website']);+ });++ test('returns undefined for an unknown component', () => {+ expect(getSupportedBoardComponentEntityTypes('Unknown')).toBeUndefined();+ });+});++describe('isBoardComponentSupportedByEntityType', () => {+ test('returns true when the entity type is supported', () => {+ expect(isBoardComponentSupportedByEntityType('Funnel', 'website')).toBe(true);+ });++ test('returns false when the entity type is not supported', () => {+ expect(isBoardComponentSupportedByEntityType('Funnel', 'segment' as any)).toBe(false);+ });++ test('returns true when no entity type is provided', () => {+ expect(isBoardComponentSupportedByEntityType('Funnel')).toBe(true);+ });++ test('returns true for components without a compatibility entry', () => {+ expect(isBoardComponentSupportedByEntityType('Unknown', 'website')).toBe(true);+ });+});diff --git a/src/lib/boards.test.ts b/src/lib/boards.test.tsindex f80e7c79e..897d95d7e 100644--- a/src/lib/boards.test.ts+++ b/src/lib/boards.test.ts@@ -32,25 +32,17 @@ test('board component compatibility matrix defines website-only components expliexpect(BOARD_COMPONENT_COMPATIBILITY_MATRIX.RealtimeActiveUsers).toEqual([BOARD_ENTITY_TYPES.website,]);- expect(BOARD_COMPONENT_COMPATIBILITY_MATRIX.RealtimeHeader).toEqual([- BOARD_ENTITY_TYPES.website,- ]);- expect(BOARD_COMPONENT_COMPATIBILITY_MATRIX.RealtimeChart).toEqual([- BOARD_ENTITY_TYPES.website,- ]);+ expect(BOARD_COMPONENT_COMPATIBILITY_MATRIX.RealtimeHeader).toEqual([BOARD_ENTITY_TYPES.website]);+ expect(BOARD_COMPONENT_COMPATIBILITY_MATRIX.RealtimeChart).toEqual([BOARD_ENTITY_TYPES.website]);expect(BOARD_COMPONENT_COMPATIBILITY_MATRIX.RevenueMetricsBar).toEqual([BOARD_ENTITY_TYPES.website,]);- expect(BOARD_COMPONENT_COMPATIBILITY_MATRIX.RevenueChart).toEqual([- BOARD_ENTITY_TYPES.website,- ]);+ expect(BOARD_COMPONENT_COMPATIBILITY_MATRIX.RevenueChart).toEqual([BOARD_ENTITY_TYPES.website]);expect(BOARD_COMPONENT_COMPATIBILITY_MATRIX.RevenueMetricsTable).toEqual([BOARD_ENTITY_TYPES.website,]);expect(BOARD_COMPONENT_COMPATIBILITY_MATRIX.UTM).toEqual([BOARD_ENTITY_TYPES.website]);- expect(BOARD_COMPONENT_COMPATIBILITY_MATRIX.WeeklyTraffic).toEqual([- BOARD_ENTITY_TYPES.website,- ]);+ expect(BOARD_COMPONENT_COMPATIBILITY_MATRIX.WeeklyTraffic).toEqual([BOARD_ENTITY_TYPES.website]);expect(getSupportedBoardComponentEntityTypes('EventsMetricsBar')).toEqual([BOARD_ENTITY_TYPES.website,]);@@ -90,7 +82,9 @@ test('isBoardComponentSupported leaves other components available for all boardtest('metrics table limits pixel and link boards to overview-page metric types', () => {const definition = getComponentDefinition('MetricsTable');- const options = definition?.configFields?.find(field => field.name === 'type')?.optionsByEntityType;+ const options = definition?.configFields?.find(+ field => field.name === 'type',+ )?.optionsByEntityType;expect(options?.pixel?.map(option => option.value)).toEqual(['referrer',diff --git a/src/lib/colors.test.ts b/src/lib/colors.test.tsnew file mode 100644index 000000000..1a41f6525--- /dev/null+++ b/src/lib/colors.test.ts@@ -0,0 +1,69 @@+import { describe, expect, test } from 'vitest';+import { getColor, getThemeColors, hex2RGB, hex6, rgb2Hex } from './colors';++describe('hex6', () => {+ test('is deterministic for the same input', () => {+ expect(hex6('umami')).toBe(hex6('umami'));+ });++ test('returns a 6-character hex string', () => {+ expect(hex6('anything')).toMatch(/^[0-9a-f]{6}$/);+ });++ test('produces different hashes for different inputs', () => {+ expect(hex6('a')).not.toBe(hex6('b'));+ });+});++describe('hex2RGB', () => {+ test('converts a hex color to RGB channels', () => {+ expect(hex2RGB('#2680eb')).toEqual({ r: 0x26, g: 0x80, b: 0xeb });+ });++ test('works without a leading hash', () => {+ expect(hex2RGB('ffffff')).toEqual({ r: 255, g: 255, b: 255 });+ expect(hex2RGB('000000')).toEqual({ r: 0, g: 0, b: 0 });+ });+});++describe('rgb2Hex', () => {+ test('joins channels into a hex string', () => {+ expect(rgb2Hex(0x26, 0x80, 0xeb)).toBe('2680eb');+ });++ test('applies the given prefix', () => {+ expect(rgb2Hex(0xff, 0xff, 0xff, '#')).toBe('#ffffff');+ });++ test('round-trips with hex2RGB for full-byte channels', () => {+ const hex = '2680eb';+ const { r, g, b } = hex2RGB(hex);+ expect(rgb2Hex(r, g, b)).toBe(hex);+ });+});++describe('getColor', () => {+ test('is deterministic for the same seed', () => {+ expect(getColor('umami')).toBe(getColor('umami'));+ });++ test('produces different colors for different seeds', () => {+ expect(getColor('a')).not.toBe(getColor('b'));+ });+});++describe('getThemeColors', () => {+ test('builds a color structure for the light theme', () => {+ const result = getThemeColors('light');++ expect(result.colors.theme).toMatchObject({ primary: '#2680eb' });+ expect(result.colors.map.baseColor).toBe('#2680eb');+ expect(result.colors.chart.views.backgroundColor).toContain('rgba');+ expect(result.colors.chart.text).toBeDefined();+ });++ test('builds a color structure for the dark theme', () => {+ const result = getThemeColors('dark');+ expect(result.colors.theme).toMatchObject({ fill: '#191919' });+ });+});diff --git a/src/lib/crypto.test.ts b/src/lib/crypto.test.tsnew file mode 100644index 000000000..70b8cf692--- /dev/null+++ b/src/lib/crypto.test.ts@@ -0,0 +1,89 @@+import { describe, expect, test, vi } from 'vitest';+import { decrypt, encrypt, hash, md5, uuid } from './crypto';++describe('encrypt/decrypt', () => {+ test('round-trips a value with the same secret', () => {+ const secret = 'my-secret';+ const value = 'hello world';++ const encrypted = encrypt(value, secret);++ expect(encrypted).not.toBe(value);+ expect(decrypt(encrypted, secret)).toBe(value);+ });++ test('produces different ciphertext on each call (random iv/salt)', () => {+ const secret = 'my-secret';++ expect(encrypt('same', secret)).not.toBe(encrypt('same', secret));+ });++ test('fails to decrypt with the wrong secret', () => {+ const encrypted = encrypt('secret data', 'right-secret');++ expect(() => decrypt(encrypted, 'wrong-secret')).toThrow();+ });++ test('fails to decrypt tampered ciphertext', () => {+ const secret = 'my-secret';+ const encrypted = encrypt('secret data', secret);++ const buf = Buffer.from(encrypted, 'base64');+ buf[buf.length - 1] ^= 0xff;+ const tampered = buf.toString('base64');++ expect(() => decrypt(tampered, secret)).toThrow();+ });+});++describe('hash', () => {+ test('is deterministic for the same input', () => {+ expect(hash('a', 'b', 'c')).toBe(hash('a', 'b', 'c'));+ });++ test('returns a 128-char sha512 hex string', () => {+ expect(hash('umami')).toMatch(/^[0-9a-f]{128}$/);+ });++ test('changes when input changes', () => {+ expect(hash('a')).not.toBe(hash('b'));+ });+});++describe('md5', () => {+ test('is deterministic for the same input', () => {+ expect(md5('a', 'b')).toBe(md5('a', 'b'));+ });++ test('returns a 32-char hex string', () => {+ expect(md5('umami')).toMatch(/^[0-9a-f]{32}$/);+ });+});++describe('uuid', () => {+ test('returns a v4 uuid with no args', () => {+ vi.stubEnv('USE_UUIDV7', '');++ expect(uuid()).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,+ );++ vi.unstubAllEnvs();+ });++ test('is deterministic (v5) for the same args', () => {+ vi.stubEnv('APP_SECRET', 'test-secret');++ expect(uuid('a', 'b')).toBe(uuid('a', 'b'));++ vi.unstubAllEnvs();+ });++ test('differs for different args', () => {+ vi.stubEnv('APP_SECRET', 'test-secret');++ expect(uuid('a')).not.toBe(uuid('b'));++ vi.unstubAllEnvs();+ });+});diff --git a/src/lib/data.test.ts b/src/lib/data.test.tsindex c2000d774..6a3c47733 100644--- a/src/lib/data.test.ts+++ b/src/lib/data.test.ts@@ -4,9 +4,9 @@ import { getStoredStringValue } from './data';describe('getStoredStringValue', () => {test('truncates oversized string values to the storage limit', () => {- expect(getStoredStringValue('x'.repeat(FIELD_LENGTH.stringValue + 25), DATA_TYPE.string)).toHaveLength(- FIELD_LENGTH.stringValue,- );+ expect(+ getStoredStringValue('x'.repeat(FIELD_LENGTH.stringValue + 25), DATA_TYPE.string),+ ).toHaveLength(FIELD_LENGTH.stringValue);});test('drops oversized array payloads instead of storing invalid truncated JSON', () => {diff --git a/src/lib/date.test.ts b/src/lib/date.test.tsnew file mode 100644index 000000000..0fa818d20--- /dev/null+++ b/src/lib/date.test.ts@@ -0,0 +1,471 @@+import {+ addDays,+ addMonths,+ endOfDay,+ endOfHour,+ endOfMonth,+ endOfWeek,+ endOfYear,+ startOfDay,+ startOfHour,+ startOfMonth,+ startOfWeek,+ startOfYear,+ subDays,+ subHours,+ subMinutes,+ subMonths,+ subWeeks,+ subYears,+} from 'date-fns';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import {+ formatDate,+ generateTimeSeries,+ getAllowedUnits,+ getCompareDate,+ getDateRangeValue,+ getDayOfWeekAsDate,+ getMaxSelectableDate,+ getMinimumUnit,+ getMonthDateRangeValue,+ getOffsetDateRange,+ getTimezone,+ isInvalidDate,+ isValidTimezone,+ maxDate,+ minDate,+ normalizeTimezone,+ parseDateRange,+ parseDateValue,+} from './date';++// A fixed instant used across timezone-sensitive tests. All expected date+// values are recomputed with the same date-fns helpers the implementation+// uses, so assertions stay robust regardless of the host timezone.+const NOW = new Date('2026-07-24T12:00:00');++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(NOW);+});++afterEach(() => {+ vi.useRealTimers();+});++describe('parseDateValue', () => {+ test.each([+ ['1hour', { num: 1, unit: 'hour' }],+ ['24hour', { num: 24, unit: 'hour' }],+ ['1day', { num: 1, unit: 'day' }],+ ['7day', { num: 7, unit: 'day' }],+ ['1week', { num: 1, unit: 'week' }],+ ['1month', { num: 1, unit: 'month' }],+ ['12month', { num: 12, unit: 'month' }],+ ['1year', { num: 1, unit: 'year' }],+ ['0day', { num: 0, unit: 'day' }],+ ])('parses %s', (input, expected) => {+ expect(parseDateValue(input)).toEqual(expected);+ });++ test('returns null for unsupported units', () => {+ expect(parseDateValue('1minute')).toBeNull();+ expect(parseDateValue('1decade')).toBeNull();+ expect(parseDateValue('range:1:2')).toBeNull();+ expect(parseDateValue('')).toBeNull();+ expect(parseDateValue('day')).toBeNull();+ });++ test('returns null when value lacks a matching pattern (has match method)', () => {+ // Non-string values that still expose (an absent) `.match` are guarded by+ // optional chaining and yield null.+ expect(parseDateValue(123 as any)).toBeNull();+ expect(parseDateValue({} as any)).toBeNull();+ });+});++describe('parseDateRange', () => {+ test('returns null for non-string input', () => {+ expect(parseDateRange(null as any)).toBeNull();+ expect(parseDateRange(123 as any)).toBeNull();+ expect(parseDateRange(undefined as any)).toBeNull();+ });++ test('parses hour ranges', () => {+ const result = parseDateRange('24hour');+ expect(result).toMatchObject({+ unit: 'hour',+ num: 24,+ offset: 0,+ value: '24hour',+ });+ expect(result.startDate).toEqual(subHours(startOfHour(NOW), 24));+ expect(result.endDate).toEqual(endOfHour(NOW));+ });++ test('parses day ranges', () => {+ const result = parseDateRange('7day');+ expect(result).toMatchObject({+ unit: 'day',+ num: 7,+ offset: 0,+ value: '7day',+ });+ expect(result.startDate).toEqual(subDays(startOfDay(NOW), 7));+ expect(result.endDate).toEqual(endOfDay(NOW));+ });++ test('parses week ranges', () => {+ const result = parseDateRange('4week');+ expect(result).toMatchObject({+ unit: 'day',+ num: 4,+ offset: 0,+ value: '4week',+ });+ expect(result.startDate).toEqual(subWeeks(startOfWeek(NOW), 4));+ expect(result.endDate).toEqual(endOfWeek(NOW));+ });++ test('parses month ranges', () => {+ const result = parseDateRange('6month');+ expect(result).toMatchObject({+ unit: 'month',+ num: 6,+ offset: 0,+ value: '6month',+ });+ expect(result.startDate).toEqual(subMonths(startOfMonth(NOW), 6));+ expect(result.endDate).toEqual(endOfMonth(NOW));+ });++ test('parses year ranges', () => {+ const result = parseDateRange('1year');+ expect(result).toMatchObject({+ unit: 'month',+ num: 1,+ offset: 0,+ value: '1year',+ });+ expect(result.startDate).toEqual(subYears(startOfYear(NOW), 1));+ expect(result.endDate).toEqual(endOfYear(NOW));+ });++ test('handles zero-num keyword variants ("this period")', () => {+ // 0day => the current day only, unit collapses to hour+ const day = parseDateRange('0day');+ expect(day).toMatchObject({ unit: 'hour', num: 1, offset: 0 });+ expect(day.startDate).toEqual(startOfDay(NOW));+ expect(day.endDate).toEqual(endOfDay(NOW));++ // 0month => the current month only, unit collapses to day+ const month = parseDateRange('0month');+ expect(month).toMatchObject({ unit: 'day', num: 1 });+ expect(month.startDate).toEqual(startOfMonth(NOW));++ // 0hour => still one hour, unit stays hour+ const hour = parseDateRange('0hour');+ expect(hour).toMatchObject({ unit: 'hour', num: 1 });+ expect(hour.startDate).toEqual(startOfHour(NOW));+ });++ test('honors the unitValue override', () => {+ const result = parseDateRange('7day', 'week');+ expect(result.unit).toBe('week');+ expect(result.num).toBe(7);+ });++ test('parses explicit range values', () => {+ const start = new Date('2026-01-01T00:00:00Z');+ const end = new Date('2026-01-11T00:00:00Z'); // 10 days -> day unit+ const value = `range:${start.getTime()}:${end.getTime()}`;++ const result = parseDateRange(value);+ expect(result.startDate).toEqual(start);+ expect(result.endDate).toEqual(end);+ expect(result.value).toBe(value);+ expect(result.unit).toBe('day');+ });++ test('range unit reflects minimum unit of the span', () => {+ const start = new Date('2026-01-01T00:00:00Z');+ const end = new Date('2026-01-01T00:30:00Z'); // 30 minutes+ const value = getDateRangeValue(start, end);+ expect(parseDateRange(value).unit).toBe('minute');+ });++ test('applies timezone conversion without throwing and preserves metadata', () => {+ const result = parseDateRange('1day', undefined, 'en-US', 'America/New_York');+ expect(result.startDate).toBeInstanceOf(Date);+ expect(result.endDate).toBeInstanceOf(Date);+ expect(result).toMatchObject({ unit: 'day', num: 1, value: '1day' });+ });+});++describe('getOffsetDateRange', () => {+ test('returns the same range when offset is 0', () => {+ const range = parseDateRange('7day');+ expect(getOffsetDateRange(range, 0)).toBe(range);+ });++ test('shifts day ranges backward', () => {+ const range = parseDateRange('7day');+ const shifted = getOffsetDateRange(range, -1);+ expect(shifted.offset).toBe(-1);+ // change = num * offset = 7 * -1+ expect(shifted.startDate).toEqual(addDays(range.startDate, -7));+ expect(shifted.endDate).toEqual(addDays(range.endDate, -7));+ });++ test('shifts month ranges and handles month boundaries', () => {+ const range = parseDateRange('1month');+ const shifted = getOffsetDateRange(range, -1);+ expect(shifted.offset).toBe(-1);+ expect(shifted.startDate).toEqual(addMonths(range.startDate, -1));+ expect(shifted.endDate).toEqual(addMonths(range.endDate, -1));+ });++ test('shifts year ranges (year rollover)', () => {+ const range = parseDateRange('1year');+ const shifted = getOffsetDateRange(range, 1);+ expect(shifted.startDate.getFullYear()).toBe(range.startDate.getFullYear() + 1);+ });++ test('falls back to unit add function for explicit ranges', () => {+ const start = new Date('2026-01-01T00:00:00Z');+ const end = new Date('2026-01-11T00:00:00Z');+ const range = parseDateRange(getDateRangeValue(start, end));+ // originalUnit from parseDateValue('range:...') is undefined -> default branch+ const shifted = getOffsetDateRange(range, 1);+ expect(shifted.offset).toBe(1);+ expect(shifted.startDate).toBeInstanceOf(Date);+ expect(shifted.endDate).toBeInstanceOf(Date);+ });+});++describe('getMinimumUnit', () => {+ const base = new Date('2026-01-01T00:00:00Z');++ test('returns minute for spans up to 60 minutes', () => {+ expect(getMinimumUnit(base, new Date('2026-01-01T00:59:00Z'))).toBe('minute');+ expect(getMinimumUnit(base, new Date('2026-01-01T01:00:00Z'))).toBe('minute');+ });++ test('returns hour for spans up to 30 days (non date-range)', () => {+ expect(getMinimumUnit(base, new Date('2026-01-15T00:00:00Z'))).toBe('hour');+ });++ test('date-range mode caps hour at 48 hours', () => {+ const within = new Date('2026-01-02T23:00:00Z'); // ~47h+ const beyond = new Date('2026-01-05T00:00:00Z'); // >48h+ expect(getMinimumUnit(base, within, true)).toBe('hour');+ expect(getMinimumUnit(base, beyond, true)).toBe('day');+ });++ test('returns day for spans up to 7 calendar months', () => {+ expect(getMinimumUnit(base, new Date('2026-06-01T00:00:00Z'))).toBe('day');+ });++ test('returns month for spans up to 24 calendar months', () => {+ expect(getMinimumUnit(base, new Date('2027-06-01T00:00:00Z'))).toBe('month');+ });++ test('returns year for spans beyond 24 calendar months', () => {+ expect(getMinimumUnit(base, new Date('2029-01-01T00:00:00Z'))).toBe('year');+ });+});++describe('getAllowedUnits', () => {+ const base = new Date('2026-01-01T00:00:00Z');++ test('includes all units for minute-level spans', () => {+ expect(getAllowedUnits(base, new Date('2026-01-01T00:30:00Z'))).toEqual([+ 'minute',+ 'hour',+ 'day',+ 'month',+ 'year',+ ]);+ });++ test('drops finer units for day-level spans', () => {+ // ~4 months -> minimum unit day+ expect(getAllowedUnits(base, new Date('2026-05-01T00:00:00Z'))).toEqual([+ 'day',+ 'month',+ 'year',+ ]);+ });++ test('maps year minimum down to month as the finest allowed unit', () => {+ expect(getAllowedUnits(base, new Date('2030-01-01T00:00:00Z'))).toEqual(['month', 'year']);+ });+});++describe('getCompareDate', () => {+ const startDate = new Date('2026-07-01T00:00:00Z');+ const endDate = new Date('2026-07-08T00:00:00Z');++ test('year over year shifts both bounds back one year', () => {+ expect(getCompareDate('yoy', startDate, endDate)).toEqual({+ compare: 'yoy',+ startDate: subYears(startDate, 1),+ endDate: subYears(endDate, 1),+ });+ });++ test('previous period shifts back by the span length', () => {+ const result = getCompareDate('prev', startDate, endDate);+ expect(result.compare).toBe('prev');+ // 7 days = 10080 minutes+ expect(result.startDate).toEqual(subMinutes(startDate, 10080));+ expect(result.endDate).toEqual(subMinutes(endDate, 10080));+ expect(result.endDate).toEqual(startDate);+ });++ test('returns empty object for unknown compare modes', () => {+ expect(getCompareDate('unknown', startDate, endDate)).toEqual({});+ });+});++describe('maxDate / minDate', () => {+ const a = new Date('2026-01-01T00:00:00Z');+ const b = new Date('2026-06-01T00:00:00Z');+ const c = new Date('2026-12-01T00:00:00Z');++ test('maxDate returns the latest valid date, ignoring non-dates', () => {+ expect(maxDate(a, b, c)).toEqual(c);+ expect(maxDate(a, null as any, c, undefined as any)).toEqual(c);+ });++ test('minDate returns the earliest valid date, ignoring non-dates', () => {+ expect(minDate(a, b, c)).toEqual(a);+ expect(minDate(null, a, 'nope', c)).toEqual(a);+ });+});++describe('getDayOfWeekAsDate', () => {+ test('returns a future date, never today', () => {+ const result = getDayOfWeekAsDate(0);+ // Same weekday as start of current week would collide with today -> pushed +7+ expect(result.getTime()).toBeGreaterThan(NOW.getTime());+ });++ test('later weekdays fall within the current week window', () => {+ const start = startOfWeek(NOW);+ const result = getDayOfWeekAsDate(6);+ expect(result).toEqual(addDays(start, 6));+ });+});++describe('formatDate', () => {+ test('formats a Date with a custom pattern', () => {+ const date = new Date('2026-07-24T00:00:00');+ expect(formatDate(date, 'yyyy-MM-dd')).toBe('2026-07-24');+ });++ test('accepts string input', () => {+ expect(formatDate('2026-07-24T00:00:00', 'yyyy-MM-dd')).toBe('2026-07-24');+ });++ test('accepts numeric timestamp input', () => {+ const date = new Date('2026-07-24T00:00:00');+ expect(formatDate(date.getTime(), 'yyyy')).toBe('2026');+ });+});++describe('generateTimeSeries', () => {+ test('fills gaps between min and max with null values (day unit)', () => {+ const min = new Date('2026-07-01T00:00:00');+ const max = new Date('2026-07-05T00:00:00');+ const data = [+ { x: '2026-07-02T00:00:00', y: 10 },+ { x: '2026-07-04T00:00:00', y: 20 },+ ];++ const series = generateTimeSeries(data, min, max, 'day', 'en-US');++ // Inclusive of both ends: Jul 1..5 => 5 buckets+ expect(series).toHaveLength(5);+ expect(series.map(s => s.x)).toEqual([+ '2026-07-01',+ '2026-07-02',+ '2026-07-03',+ '2026-07-04',+ '2026-07-05',+ ]);+ expect(series[0].y).toBeNull();+ expect(series[1].y).toBe(10);+ expect(series[3].y).toBe(20);+ expect(series[4].y).toBeNull();+ });++ test('single bucket when min and max share a period', () => {+ const min = new Date('2026-07-01T03:00:00');+ const max = new Date('2026-07-01T21:00:00');+ const series = generateTimeSeries([], min, max, 'day', 'en-US');+ expect(series).toHaveLength(1);+ expect(series[0].y).toBeNull();+ });+});++describe('getDateRangeValue / getMonthDateRangeValue', () => {+ test('builds a range token from two dates', () => {+ const start = new Date('2026-01-01T00:00:00Z');+ const end = new Date('2026-02-01T00:00:00Z');+ expect(getDateRangeValue(start, end)).toBe(`range:${start.getTime()}:${end.getTime()}`);+ });++ test('builds a month range token spanning the whole month', () => {+ const date = new Date('2026-07-15T12:00:00');+ const value = getMonthDateRangeValue(date);+ const [, startTime, endTime] = value.split(':');+ expect(new Date(+startTime)).toEqual(startOfMonth(date));+ expect(new Date(+endTime)).toEqual(endOfMonth(date));+ });+});++describe('getMaxSelectableDate', () => {+ test('returns the later of end-of-year or six months out', () => {+ // For July, +6 months (late Jan next year) is later than end of the year.+ expect(getMaxSelectableDate(NOW)).toEqual(addMonths(NOW, 6));+ });++ test('picks end of year when it is later than +6 months', () => {+ // Early January: end of this year is far beyond +6 months.+ const january = new Date('2026-01-02T00:00:00');+ expect(getMaxSelectableDate(january)).toEqual(endOfYear(january));+ });+});++describe('timezone helpers', () => {+ test('normalizeTimezone maps deprecated aliases', () => {+ expect(normalizeTimezone('Asia/Calcutta')).toBe('Asia/Kolkata');+ expect(normalizeTimezone('America/New_York')).toBe('America/New_York');+ });++ test('isValidTimezone accepts real and aliased zones', () => {+ expect(isValidTimezone('America/New_York')).toBe(true);+ expect(isValidTimezone('Asia/Calcutta')).toBe(true);+ expect(isValidTimezone('Not/AZone')).toBe(false);+ });++ test('getTimezone returns a non-empty string', () => {+ expect(typeof getTimezone()).toBe('string');+ expect(getTimezone().length).toBeGreaterThan(0);+ });+});++describe('isInvalidDate', () => {+ test('detects invalid Date instances', () => {+ expect(isInvalidDate(new Date('not a date'))).toBe(true);+ });++ test('valid dates and non-dates are not flagged', () => {+ expect(isInvalidDate(new Date('2026-07-24'))).toBe(false);+ expect(isInvalidDate('2026-07-24')).toBe(false);+ expect(isInvalidDate(null)).toBe(false);+ expect(isInvalidDate(undefined)).toBe(false);+ });+});diff --git a/src/lib/db.test.ts b/src/lib/db.test.tsnew file mode 100644index 000000000..06503f6db--- /dev/null+++ b/src/lib/db.test.ts@@ -0,0 +1,95 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';++// db.ts imports none of these directly, but the mocks keep the test isolated+// from real database clients if that ever changes.+vi.mock('@/lib/prisma', () => ({}));+vi.mock('@/lib/clickhouse', () => ({}));+vi.mock('@/lib/kafka', () => ({}));++let db!: typeof import('./db');++beforeEach(async () => {+ vi.resetModules();+ db = await import('./db');+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('getDatabaseType', () => {+ test('maps a postgres:// url to postgresql', () => {+ expect(db.getDatabaseType('postgres://user:pass@localhost:5432/umami')).toBe('postgresql');+ });++ test('returns postgresql for a postgresql:// url', () => {+ expect(db.getDatabaseType('postgresql://user:pass@localhost:5432/umami')).toBe('postgresql');+ });++ test('returns the raw scheme for other databases', () => {+ expect(db.getDatabaseType('mysql://user:pass@localhost:3306/umami')).toBe('mysql');+ });++ test('reads process.env.DATABASE_URL by default', () => {+ vi.stubEnv('DATABASE_URL', 'postgres://user:pass@localhost:5432/umami');+ expect(db.getDatabaseType()).toBe('postgresql');+ });++ test('falls back to the DATABASE_URL default when called with undefined', () => {+ vi.stubEnv('DATABASE_URL', 'postgres://user:pass@localhost:5432/umami');+ expect(db.getDatabaseType(undefined)).toBe('postgresql');+ });+});++describe('runQuery', () => {+ test('runs the clickhouse query when CLICKHOUSE_URL is set', async () => {+ vi.stubEnv('CLICKHOUSE_URL', 'http://localhost:8123');+ const clickhouse = vi.fn().mockResolvedValue('clickhouse-result');+ const prisma = vi.fn();++ await expect(db.runQuery({ clickhouse, prisma })).resolves.toBe('clickhouse-result');+ expect(clickhouse).toHaveBeenCalledTimes(1);+ expect(prisma).not.toHaveBeenCalled();+ });++ test('prefers the kafka query over clickhouse when both are provided', async () => {+ vi.stubEnv('CLICKHOUSE_URL', 'http://localhost:8123');+ const kafka = vi.fn().mockResolvedValue('kafka-result');+ const clickhouse = vi.fn();++ await expect(db.runQuery({ kafka, clickhouse })).resolves.toBe('kafka-result');+ expect(kafka).toHaveBeenCalledTimes(1);+ expect(clickhouse).not.toHaveBeenCalled();+ });++ test('runs the prisma query for a postgresql database', async () => {+ vi.stubEnv('CLICKHOUSE_URL', '');+ vi.stubEnv('DATABASE_URL', 'postgresql://user:pass@localhost:5432/umami');+ const prisma = vi.fn().mockResolvedValue('prisma-result');++ await expect(db.runQuery({ prisma })).resolves.toBe('prisma-result');+ expect(prisma).toHaveBeenCalledTimes(1);+ });++ test('returns undefined for an unsupported database with no clickhouse', async () => {+ vi.stubEnv('CLICKHOUSE_URL', '');+ vi.stubEnv('DATABASE_URL', 'mysql://user:pass@localhost:3306/umami');+ const prisma = vi.fn();++ await expect(db.runQuery({ prisma })).resolves.toBeUndefined();+ expect(prisma).not.toHaveBeenCalled();+ });+});++describe('BigInt.prototype.toJSON', () => {+ test('serializes bigint values as numbers', () => {+ expect((BigInt(123) as any).toJSON()).toBe(123);+ expect(JSON.stringify({ count: BigInt(42) })).toBe('{"count":42}');+ });+});++describe('notImplemented', () => {+ test('throws a Not implemented error', () => {+ expect(() => db.notImplemented()).toThrow('Not implemented.');+ });+});diff --git a/src/lib/detect.test.ts b/src/lib/detect.test.tsindex 8b66e06f7..b40347998 100644--- a/src/lib/detect.test.ts+++ b/src/lib/detect.test.ts@@ -27,9 +27,7 @@ test('getIpAddress: Custom header', () => {test('getIpAddress: Custom header set to x-forwarded-for uses leftmost IP in chain', () => {process.env.CLIENT_IP_HEADER = 'x-forwarded-for';- expect(- getIpAddress(new Headers({ 'x-forwarded-for': `${IP}, 10.0.0.1, 10.0.0.2` })),- ).toEqual(IP);+ expect(getIpAddress(new Headers({ 'x-forwarded-for': `${IP}, 10.0.0.1, 10.0.0.2` }))).toEqual(IP);});test('getIpAddress: CloudFlare header', () => {diff --git a/src/lib/filters.test.ts b/src/lib/filters.test.tsnew file mode 100644index 000000000..0945acd2c--- /dev/null+++ b/src/lib/filters.test.ts@@ -0,0 +1,72 @@+import { describe, expect, test } from 'vitest';+import { paramFilter, percentFilter } from './filters';++describe('percentFilter', () => {+ test('computes each row percentage of the total', () => {+ const result = percentFilter([+ { x: 'a', y: 25 },+ { x: 'b', y: 75 },+ ]);++ expect(result).toEqual([+ { x: 'a', y: 25, z: 25 },+ { x: 'b', y: 75, z: 75 },+ ]);+ });++ test('preserves extra props', () => {+ const result = percentFilter([{ x: 'a', y: 10, label: 'foo' }]);+ expect(result[0]).toMatchObject({ x: 'a', y: 10, z: 100, label: 'foo' });+ });++ test('uses zero percentage when total is zero', () => {+ const result = percentFilter([+ { x: 'a', y: 0 },+ { x: 'b', y: 0 },+ ]);++ expect(result).toEqual([+ { x: 'a', y: 0, z: 0 },+ { x: 'b', y: 0, z: 0 },+ ]);+ });++ test('returns an empty array for non-array input', () => {+ expect(percentFilter(undefined as any)).toEqual([]);+ expect(percentFilter(null as any)).toEqual([]);+ });+});++describe('paramFilter', () => {+ test('splits query string keys into rows', () => {+ const result = paramFilter([{ x: 'a=1&b=2', y: 5 }]);++ expect(result).toEqual(+ expect.arrayContaining([+ { x: 'a=1', p: 'a', v: '1', y: 5 },+ { x: 'b=2', p: 'b', v: '2', y: 5 },+ ]),+ );+ expect(result).toHaveLength(2);+ });++ test('aggregates counts across matching key/value pairs', () => {+ const result = paramFilter([+ { x: 'a=1', y: 5 },+ { x: 'a=1', y: 3 },+ { x: 'a=2', y: 1 },+ ]);++ expect(result).toEqual(+ expect.arrayContaining([+ { x: 'a=1', p: 'a', v: '1', y: 8 },+ { x: 'a=2', p: 'a', v: '2', y: 1 },+ ]),+ );+ expect(result).toHaveLength(2);+ });++ test('returns an empty array when there are no params', () => {+ expect(paramFilter([{ x: '', y: 1 }])).toEqual([]);+ });+});diff --git a/src/lib/generate.test.ts b/src/lib/generate.test.tsnew file mode 100644index 000000000..6864c3e5d--- /dev/null+++ b/src/lib/generate.test.ts@@ -0,0 +1,36 @@+import { describe, expect, test } from 'vitest';+import { getRandomChars, random } from './generate';++describe('random', () => {+ test('returns a value within the inclusive range', () => {+ for (let i = 0; i < 1000; i++) {+ const n = random(1, 6);+ expect(n).toBeGreaterThanOrEqual(1);+ expect(n).toBeLessThanOrEqual(6);+ }+ });++ test('returns the single value when min equals max', () => {+ expect(random(5, 5)).toBe(5);+ });+});++describe('getRandomChars', () => {+ test('returns a string of the requested length', () => {+ expect(getRandomChars(16)).toHaveLength(16);+ expect(getRandomChars(0)).toBe('');+ });++ test('only uses characters from the default alphabet', () => {+ expect(getRandomChars(200)).toMatch(/^[0-9a-zA-Z]+$/);+ });++ test('respects a custom character set', () => {+ expect(getRandomChars(50, 'ab')).toMatch(/^[ab]+$/);+ });++ test('produces reasonably unique values', () => {+ const values = new Set(Array.from({ length: 100 }, () => getRandomChars(16)));+ expect(values.size).toBe(100);+ });+});diff --git a/src/lib/ip.test.ts b/src/lib/ip.test.tsnew file mode 100644index 000000000..968b1efa9--- /dev/null+++ b/src/lib/ip.test.ts@@ -0,0 +1,114 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { getIpAddress, stripPort } from './ip';++function headers(init: Record<string, string>) {+ return new Headers(init);+}++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('getIpAddress', () => {+ test('returns undefined when no known headers are present', () => {+ expect(getIpAddress(headers({}))).toBeUndefined();+ });++ test('extracts the first address from an x-forwarded-for chain', () => {+ expect(getIpAddress(headers({ 'x-forwarded-for': '1.2.3.4, 5.6.7.8, 9.10.11.12' }))).toBe(+ '1.2.3.4',+ );+ });++ test('trims whitespace around the x-forwarded-for client address', () => {+ expect(getIpAddress(headers({ 'x-forwarded-for': ' 1.2.3.4 , 5.6.7.8' }))).toBe('1.2.3.4');+ });++ test('reads the Cloudflare cf-connecting-ip header', () => {+ expect(getIpAddress(headers({ 'cf-connecting-ip': '203.0.113.5' }))).toBe('203.0.113.5');+ });++ test('reads the Fastly fastly-client-ip header', () => {+ expect(getIpAddress(headers({ 'fastly-client-ip': '198.51.100.7' }))).toBe('198.51.100.7');+ });++ test('reads the x-real-ip reverse proxy header', () => {+ expect(getIpAddress(headers({ 'x-real-ip': '192.0.2.9' }))).toBe('192.0.2.9');+ });++ test('parses the RFC 7239 forwarded header', () => {+ expect(getIpAddress(headers({ forwarded: 'for=192.0.2.60;proto=http;by=203.0.113.43' }))).toBe(+ '192.0.2.60',+ );+ });++ test('prefers higher-priority vendor headers over x-forwarded-for', () => {+ expect(+ getIpAddress(+ headers({+ 'cf-connecting-ip': '203.0.113.5',+ 'x-forwarded-for': '1.2.3.4',+ }),+ ),+ ).toBe('203.0.113.5');+ });++ test('normalizes a full IPv6 address to compressed form', () => {+ expect(getIpAddress(headers({ 'x-real-ip': '2001:0db8:0000:0000:0000:0000:0000:0001' }))).toBe(+ '2001:db8::1',+ );+ });++ test('converts an IPv4-mapped IPv6 address to IPv4', () => {+ expect(getIpAddress(headers({ 'x-real-ip': '::ffff:1.2.3.4' }))).toBe('1.2.3.4');+ });++ test('strips the port from an IPv4 address with a port', () => {+ expect(getIpAddress(headers({ 'x-real-ip': '1.2.3.4:8080' }))).toBe('1.2.3.4');+ });++ test('returns garbage input unchanged as a fallback', () => {+ expect(getIpAddress(headers({ 'x-real-ip': 'not-an-ip' }))).toBe('not-an-ip');+ });++ test('uses a custom CLIENT_IP_HEADER when configured', () => {+ vi.stubEnv('CLIENT_IP_HEADER', 'x-custom-ip');+ expect(+ getIpAddress(+ headers({+ 'x-custom-ip': '10.0.0.1',+ 'x-forwarded-for': '1.2.3.4',+ }),+ ),+ ).toBe('10.0.0.1');+ });++ test('falls back to standard headers when CLIENT_IP_HEADER is absent from the request', () => {+ vi.stubEnv('CLIENT_IP_HEADER', 'x-custom-ip');+ expect(getIpAddress(headers({ 'x-real-ip': '192.0.2.9' }))).toBe('192.0.2.9');+ });+});++describe('stripPort', () => {+ test('returns nullish input unchanged', () => {+ expect(stripPort(undefined)).toBeUndefined();+ expect(stripPort(null)).toBeNull();+ expect(stripPort('')).toBe('');+ });++ test('removes the port from an IPv4 address', () => {+ expect(stripPort('1.2.3.4:8080')).toBe('1.2.3.4');+ });++ test('leaves a plain IPv4 address unchanged', () => {+ expect(stripPort('1.2.3.4')).toBe('1.2.3.4');+ });++ test('keeps only the bracketed portion of a bracketed IPv6 address', () => {+ expect(stripPort('[::1]:8080')).toBe('[::1]');+ });++ test('leaves an unbracketed IPv6 address unchanged', () => {+ expect(stripPort('::1')).toBe('::1');+ });+});diff --git a/src/lib/jwt.test.ts b/src/lib/jwt.test.tsnew file mode 100644index 000000000..f124aed47--- /dev/null+++ b/src/lib/jwt.test.ts@@ -0,0 +1,49 @@+import { describe, expect, test } from 'vitest';+import { createSecureToken, createToken, parseSecureToken, parseToken } from './jwt';++const SECRET = 'test-secret';++describe('createToken/parseToken', () => {+ test('round-trips a payload with the correct secret', () => {+ const token = createToken({ userId: '123' }, SECRET);+ const parsed = parseToken(token, SECRET) as any;++ expect(parsed.userId).toBe('123');+ });++ test('returns null for an invalid token', () => {+ expect(parseToken('not-a-jwt', SECRET)).toBeNull();+ });++ test('returns null when verified with the wrong secret', () => {+ const token = createToken({ userId: '123' }, SECRET);++ expect(parseToken(token, 'wrong-secret')).toBeNull();+ });+});++describe('createSecureToken/parseSecureToken', () => {+ test('round-trips an encrypted token with the correct secret', () => {+ const token = createSecureToken({ userId: '456' }, SECRET);+ const parsed = parseSecureToken(token, SECRET) as any;++ expect(parsed.userId).toBe('456');+ });++ test('produces an opaque (encrypted) token, not a raw jwt', () => {+ const token = createSecureToken({ userId: '456' }, SECRET);++ // Raw jwts have exactly two dots; the encrypted wrapper is base64.+ expect(token.split('.').length).not.toBe(3);+ });++ test('returns null when parsed with the wrong secret', () => {+ const token = createSecureToken({ userId: '456' }, SECRET);++ expect(parseSecureToken(token, 'wrong-secret')).toBeNull();+ });++ test('returns null for a malformed secure token', () => {+ expect(parseSecureToken('garbage', SECRET)).toBeNull();+ });+});diff --git a/src/lib/lang.test.ts b/src/lib/lang.test.tsnew file mode 100644index 000000000..e4c01a7a4--- /dev/null+++ b/src/lib/lang.test.ts@@ -0,0 +1,42 @@+import { enUS, fr } from 'date-fns/locale';+import { describe, expect, test } from 'vitest';+import { getDateLocale, getTextDirection } from './lang';++describe('getDateLocale', () => {+ test('returns the configured date-fns locale', () => {+ expect(getDateLocale('fr-FR')).toBe(fr);+ });++ test('falls back to en-US for unknown locales', () => {+ expect(getDateLocale('xx-XX')).toBe(enUS);+ });++ test('falls back to en-US when a language has no dateLocale', () => {+ expect(getDateLocale('fo-FO')).toBe(enUS);+ });+});++describe('getTextDirection', () => {+ test('returns rtl for right-to-left languages', () => {+ expect(getTextDirection('ar-SA')).toBe('rtl');+ expect(getTextDirection('fa-IR')).toBe('rtl');+ expect(getTextDirection('ur-PK')).toBe('rtl');+ });++ // NOTE: Hebrew (he-IL) is a right-to-left language but is NOT marked with+ // `dir: 'rtl'` in `languages`, so getTextDirection returns 'ltr'. This asserts+ // the current (suspected buggy) behavior. If the source is fixed to add+ // `dir: 'rtl'` for he-IL, update this expectation to 'rtl'.+ test('does not mark Hebrew as rtl (suspected source bug)', () => {+ expect(getTextDirection('he-IL')).toBe('ltr');+ });++ test('returns ltr for left-to-right languages', () => {+ expect(getTextDirection('en-US')).toBe('ltr');+ expect(getTextDirection('fr-FR')).toBe('ltr');+ });++ test('falls back to ltr for unknown locales', () => {+ expect(getTextDirection('xx-XX')).toBe('ltr');+ });+});diff --git a/src/lib/password.test.ts b/src/lib/password.test.tsnew file mode 100644index 000000000..12763c53d--- /dev/null+++ b/src/lib/password.test.ts@@ -0,0 +1,29 @@+import { describe, expect, test } from 'vitest';+import { checkPassword, hashPassword } from './password';++describe('hashPassword', () => {+ test('returns a bcrypt hash distinct from the plaintext', () => {+ const hash = hashPassword('correct horse');++ expect(hash).not.toBe('correct horse');+ expect(hash).toMatch(/^\$2[aby]\$/);+ });++ test('produces different hashes for the same password (random salt)', () => {+ expect(hashPassword('same')).not.toBe(hashPassword('same'));+ });+});++describe('checkPassword', () => {+ test('accepts the correct password', () => {+ const hash = hashPassword('correct horse');++ expect(checkPassword('correct horse', hash)).toBe(true);+ });++ test('rejects the wrong password', () => {+ const hash = hashPassword('correct horse');++ expect(checkPassword('wrong horse', hash)).toBe(false);+ });+});diff --git a/src/lib/recorder.test.ts b/src/lib/recorder.test.tsnew file mode 100644index 000000000..142832660--- /dev/null+++ b/src/lib/recorder.test.ts@@ -0,0 +1,56 @@+import { describe, expect, test } from 'vitest';+import { getRecorderConfig, getRecorderEnabled } from './recorder';++describe('getRecorderConfig', () => {+ test('returns an empty object for non-object values', () => {+ expect(getRecorderConfig(null)).toEqual({});+ expect(getRecorderConfig(undefined)).toEqual({});+ expect(getRecorderConfig('x')).toEqual({});+ expect(getRecorderConfig([1, 2])).toEqual({});+ });++ test('only keeps boolean enabled flags that are strictly true', () => {+ expect(getRecorderConfig({ replayEnabled: true, heatmapEnabled: false })).toEqual({+ replayEnabled: true,+ });+ expect(getRecorderConfig({ replayEnabled: 'true' })).toEqual({});+ });++ test('keeps numeric sample rates', () => {+ expect(getRecorderConfig({ sampleRate: 0.5, heatmapSampleRate: 1 })).toEqual({+ sampleRate: 0.5,+ heatmapSampleRate: 1,+ });+ expect(getRecorderConfig({ sampleRate: '0.5' })).toEqual({});+ });++ test('only accepts known mask levels', () => {+ expect(getRecorderConfig({ maskLevel: 'strict' })).toEqual({ maskLevel: 'strict' });+ expect(getRecorderConfig({ maskLevel: 'moderate' })).toEqual({ maskLevel: 'moderate' });+ expect(getRecorderConfig({ maskLevel: 'loose' })).toEqual({});+ });++ test('rounds finite maxDuration and rejects non-finite values', () => {+ expect(getRecorderConfig({ maxDuration: 12.6 })).toEqual({ maxDuration: 13 });+ expect(getRecorderConfig({ maxDuration: Infinity })).toEqual({});+ expect(getRecorderConfig({ maxDuration: NaN })).toEqual({});+ });++ test('keeps a string blockSelector', () => {+ expect(getRecorderConfig({ blockSelector: '.hidden' })).toEqual({ blockSelector: '.hidden' });+ expect(getRecorderConfig({ blockSelector: 5 })).toEqual({});+ });+});++describe('getRecorderEnabled', () => {+ test('is true when replay or heatmap is enabled', () => {+ expect(getRecorderEnabled({ replayEnabled: true })).toBe(true);+ expect(getRecorderEnabled({ heatmapEnabled: true })).toBe(true);+ });++ test('is false otherwise', () => {+ expect(getRecorderEnabled({})).toBe(false);+ expect(getRecorderEnabled(null)).toBe(false);+ expect(getRecorderEnabled({ sampleRate: 1 })).toBe(false);+ });+});diff --git a/src/lib/schema.test.ts b/src/lib/schema.test.tsnew file mode 100644index 000000000..67c644635--- /dev/null+++ b/src/lib/schema.test.ts@@ -0,0 +1,291 @@+import { describe, expect, test } from 'vitest';+import { z } from 'zod';+import {+ attributionReportSchema,+ filterParams,+ funnelReportSchema,+ goalReportSchema,+ pagingParams,+ reportBaseSchema,+ reportTypeSchema,+ segmentTypeParam,+ sortingParams,+ teamRoleParam,+ timezoneParam,+ unitParam,+ urlOrPathParam,+ userRoleParam,+ withDateRange,+} from './schema';++const UUID = '11111111-1111-4111-8111-111111111111';++describe('timezoneParam', () => {+ test('accepts a valid timezone', () => {+ expect(timezoneParam.parse('America/New_York')).toBe('America/New_York');+ });++ test('rejects an invalid timezone', () => {+ expect(() => timezoneParam.parse('Not/AZone')).toThrow();+ });+});++describe('unitParam', () => {+ test.each(['year', 'month', 'hour', 'day', 'minute'])('accepts the %s unit', unit => {+ expect(unitParam.parse(unit)).toBe(unit);+ });++ test('rejects an unknown unit', () => {+ expect(() => unitParam.parse('week')).toThrow();+ });+});++describe('withDateRange', () => {+ const schema = withDateRange();++ test('accepts a numeric startAt/endAt range and coerces strings', () => {+ const result = schema.parse({ startAt: '5', endAt: '10' });+ expect(result.startAt).toBe(5);+ expect(result.endAt).toBe(10);+ });++ test('accepts a startDate/endDate range and coerces to dates', () => {+ const result = schema.parse({ startDate: '2024-01-01', endDate: '2024-01-31' });+ expect(result.startDate).toBeInstanceOf(Date);+ expect(result.endDate).toBeInstanceOf(Date);+ });++ test('rejects when neither range is fully provided', () => {+ expect(() => schema.parse({})).toThrow();+ expect(() => schema.parse({ startAt: 5 })).toThrow();+ });++ test('merges an additional shape into the schema', () => {+ const extended = withDateRange({ websiteId: z.uuid() });+ const result = extended.parse({ startAt: 1, endAt: 2, websiteId: UUID });+ expect(result.websiteId).toBe(UUID);+ });+});++describe('filterParams', () => {+ const schema = z.object({ ...filterParams });++ test('coerces eventType to a positive integer', () => {+ expect(schema.parse({ eventType: '3' }).eventType).toBe(3);+ });++ test('rejects a non-positive eventType', () => {+ expect(() => schema.parse({ eventType: '0' })).toThrow();+ });++ test('validates segment as a uuid', () => {+ expect(schema.parse({ segment: UUID }).segment).toBe(UUID);+ expect(() => schema.parse({ segment: 'not-a-uuid' })).toThrow();+ });++ test('restricts match to all or any', () => {+ expect(schema.parse({ match: 'all' }).match).toBe('all');+ expect(() => schema.parse({ match: 'some' })).toThrow();+ });++ test('allows an empty object since all fields are optional', () => {+ expect(schema.parse({})).toEqual({});+ });+});++describe('pagingParams', () => {+ const schema = z.object({ ...pagingParams });++ test('coerces page and pageSize to numbers', () => {+ const result = schema.parse({ page: '2', pageSize: '25' });+ expect(result.page).toBe(2);+ expect(result.pageSize).toBe(25);+ });++ test('rejects a non-positive page', () => {+ expect(() => schema.parse({ page: '0' })).toThrow();+ });+});++describe('sortingParams', () => {+ const schema = z.object({ ...sortingParams });++ test('transforms sortDescending "true" to boolean true', () => {+ expect(schema.parse({ sortDescending: 'true' }).sortDescending).toBe(true);+ });++ test('transforms sortDescending "false" to boolean false', () => {+ expect(schema.parse({ sortDescending: 'false' }).sortDescending).toBe(false);+ });++ test('leaves sortDescending undefined when omitted', () => {+ expect(schema.parse({}).sortDescending).toBeUndefined();+ });++ test('rejects an invalid sortDescending value', () => {+ expect(() => schema.parse({ sortDescending: 'yes' })).toThrow();+ });+});++describe('userRoleParam', () => {+ test('accepts known user roles', () => {+ expect(userRoleParam.parse('admin')).toBe('admin');+ expect(userRoleParam.parse('view-only')).toBe('view-only');+ });++ test('rejects an unknown role', () => {+ expect(() => userRoleParam.parse('superuser')).toThrow();+ });+});++describe('teamRoleParam', () => {+ test('accepts a known team role', () => {+ expect(teamRoleParam.parse('team-manager')).toBe('team-manager');+ });++ test('rejects an unknown team role', () => {+ expect(() => teamRoleParam.parse('team-owner')).toThrow();+ });+});++describe('segmentTypeParam', () => {+ test('accepts segment and cohort', () => {+ expect(segmentTypeParam.parse('segment')).toBe('segment');+ expect(segmentTypeParam.parse('cohort')).toBe('cohort');+ });++ test('rejects an unknown segment type', () => {+ expect(() => segmentTypeParam.parse('group')).toThrow();+ });+});++describe('urlOrPathParam', () => {+ test('accepts a relative path', () => {+ expect(urlOrPathParam.parse('/settings/websites')).toBe('/settings/websites');+ });++ test('accepts an absolute url', () => {+ expect(urlOrPathParam.parse('https://umami.is/docs')).toBe('https://umami.is/docs');+ });+});++describe('goalReportSchema', () => {+ test('parses a valid goal report and coerces dates', () => {+ const result = goalReportSchema.parse({+ type: 'goal',+ parameters: {+ startDate: '2024-01-01',+ endDate: '2024-01-31',+ type: 'event',+ value: 'signup',+ },+ });+ expect(result.parameters.startDate).toBeInstanceOf(Date);+ expect(result.parameters.value).toBe('signup');+ });++ test('rejects a mismatched literal type', () => {+ expect(() =>+ goalReportSchema.parse({+ type: 'funnel',+ parameters: { startDate: '2024-01-01', endDate: '2024-01-31', type: 'event', value: 'x' },+ }),+ ).toThrow();+ });+});++describe('funnelReportSchema', () => {+ const valid = {+ type: 'funnel' as const,+ parameters: {+ startDate: '2024-01-01',+ endDate: '2024-01-31',+ window: '30',+ steps: [+ { type: 'path', value: '/home' },+ { type: 'event', value: 'purchase' },+ ],+ },+ };++ test('parses a valid funnel report and coerces window', () => {+ const result = funnelReportSchema.parse(valid);+ expect(result.parameters.window).toBe(30);+ expect(result.parameters.steps).toHaveLength(2);+ });++ test('requires at least two steps', () => {+ expect(() =>+ funnelReportSchema.parse({+ ...valid,+ parameters: { ...valid.parameters, steps: [{ type: 'path', value: '/home' }] },+ }),+ ).toThrow();+ });+});++describe('reportTypeSchema', () => {+ test('discriminates on the type field', () => {+ const result = reportTypeSchema.parse({+ type: 'attribution',+ parameters: {+ startDate: '2024-01-01',+ endDate: '2024-01-31',+ model: 'first-click',+ type: 'event',+ step: 'purchase',+ },+ });+ expect(result.type).toBe('attribution');+ });++ test('rejects an unknown report type', () => {+ expect(() => reportTypeSchema.parse({ type: 'nonsense', parameters: {} })).toThrow();+ });+});++describe('attributionReportSchema', () => {+ test('rejects an invalid attribution model', () => {+ expect(() =>+ attributionReportSchema.parse({+ type: 'attribution',+ parameters: {+ startDate: '2024-01-01',+ endDate: '2024-01-31',+ model: 'middle-click',+ type: 'event',+ step: 'purchase',+ },+ }),+ ).toThrow();+ });+});++describe('reportBaseSchema', () => {+ test('parses a valid report with a uuid website', () => {+ const result = reportBaseSchema.parse({+ websiteId: UUID,+ type: 'goal',+ name: 'My Report',+ parameters: { foo: 'bar' },+ });+ expect(result.name).toBe('My Report');+ });++ test('rejects a name longer than 200 characters', () => {+ expect(() =>+ reportBaseSchema.parse({+ websiteId: UUID,+ type: 'goal',+ name: 'x'.repeat(201),+ parameters: {},+ }),+ ).toThrow();+ });++ test('rejects a non-uuid website id', () => {+ expect(() =>+ reportBaseSchema.parse({ websiteId: 'nope', type: 'goal', name: 'r', parameters: {} }),+ ).toThrow();+ });+});diff --git a/src/lib/share.test.ts b/src/lib/share.test.tsnew file mode 100644index 000000000..4f8caa9ac--- /dev/null+++ b/src/lib/share.test.ts@@ -0,0 +1,50 @@+import { describe, expect, test } from 'vitest';+import { allowShareFilter, excludeShareFilterParam, getShareTheme } from './share';++describe('allowShareFilter', () => {+ test('returns true when parameters are missing', () => {+ expect(allowShareFilter()).toBe(true);+ expect(allowShareFilter(null)).toBe(true);+ });++ test('returns true unless allowFilter is explicitly false', () => {+ expect(allowShareFilter({ allowFilter: true } as any)).toBe(true);+ expect(allowShareFilter({} as any)).toBe(true);+ expect(allowShareFilter({ allowFilter: false } as any)).toBe(false);+ });+});++describe('getShareTheme', () => {+ test('returns light or dark when valid', () => {+ expect(getShareTheme({ theme: 'light' } as any)).toBe('light');+ expect(getShareTheme({ theme: 'dark' } as any)).toBe('dark');+ });++ test('returns undefined for missing or invalid themes', () => {+ expect(getShareTheme()).toBeUndefined();+ expect(getShareTheme(null)).toBeUndefined();+ expect(getShareTheme({ theme: 'blue' } as any)).toBeUndefined();+ });+});++describe('excludeShareFilterParam', () => {+ test('returns true for known filter columns', () => {+ expect(excludeShareFilterParam('path')).toBe(true);+ expect(excludeShareFilterParam('country')).toBe(true);+ });++ test('strips trailing digits before matching filter columns', () => {+ expect(excludeShareFilterParam('path2')).toBe(true);+ });++ test('returns true for reserved query params', () => {+ expect(excludeShareFilterParam('segment')).toBe(true);+ expect(excludeShareFilterParam('cohort')).toBe(true);+ expect(excludeShareFilterParam('match')).toBe(true);+ expect(excludeShareFilterParam('excludeBounce')).toBe(true);+ });++ test('returns false for unrelated keys', () => {+ expect(excludeShareFilterParam('foo')).toBe(false);+ });+});diff --git a/src/lib/sort.test.ts b/src/lib/sort.test.tsnew file mode 100644index 000000000..d16f07358--- /dev/null+++ b/src/lib/sort.test.ts@@ -0,0 +1,35 @@+import { describe, expect, test } from 'vitest';+import { sanitizeSortFilters } from './sort';++describe('sanitizeSortFilters', () => {+ const allowed = ['name', 'createdAt'] as const;++ test('keeps orderBy and sortDescending when the field is allowed', () => {+ const result = sanitizeSortFilters({ orderBy: 'name', sortDescending: true }, allowed);+ expect(result).toEqual({ orderBy: 'name', sortDescending: true });+ });++ test('drops orderBy when the field is not allowed', () => {+ const result = sanitizeSortFilters({ orderBy: 'secret', sortDescending: true }, allowed);+ expect(result).toEqual({});+ });++ test('falls back to defaults when the field is not allowed', () => {+ const result = sanitizeSortFilters({ orderBy: 'secret' }, allowed, {+ orderBy: 'createdAt',+ sortDescending: false,+ });+ expect(result).toEqual({ orderBy: 'createdAt', sortDescending: false });+ });++ test('applies defaults when orderBy is missing', () => {+ const result = sanitizeSortFilters({}, allowed, { orderBy: 'name' });+ expect(result).toEqual({ orderBy: 'name' });+ });++ test('preserves other filter fields', () => {+ const result = sanitizeSortFilters({ orderBy: 'bad', startDate: new Date(0) } as any, allowed);+ expect(result).toMatchObject({ startDate: new Date(0) });+ expect(result).not.toHaveProperty('orderBy');+ });+});diff --git a/src/lib/subscription.test.ts b/src/lib/subscription.test.tsindex ea9de44e6..52361aa84 100644--- a/src/lib/subscription.test.ts+++ b/src/lib/subscription.test.ts@@ -41,9 +41,9 @@ describe('getCloudWebsiteLimit', () => {});test('still limits teams whose owner has no subscription even if unlimited websites is set', () => {- expect(- getCloudWebsiteLimit({ hasSubscription: false, unlimitedWebsites: true }),- ).toBe(CLOUD_FREE_WEBSITE_LIMIT);+ expect(getCloudWebsiteLimit({ hasSubscription: false, unlimitedWebsites: true })).toBe(+ CLOUD_FREE_WEBSITE_LIMIT,+ );});});diff --git a/src/lib/two-factor/backup-codes.test.ts b/src/lib/two-factor/backup-codes.test.tsnew file mode 100644index 000000000..89e998c18--- /dev/null+++ b/src/lib/two-factor/backup-codes.test.ts@@ -0,0 +1,54 @@+import { describe, expect, test } from 'vitest';+import { generateBackupCodes, verifyBackupCode } from './backup-codes';++describe('generateBackupCodes', () => {+ test('generates 10 plaintext codes and 10 hashes', async () => {+ const { plaintext, hashed } = await generateBackupCodes();++ expect(plaintext).toHaveLength(10);+ expect(hashed).toHaveLength(10);+ });++ test('formats codes as two uppercase 16-hex groups separated by a dash', async () => {+ const { plaintext } = await generateBackupCodes();++ for (const code of plaintext) {+ expect(code).toMatch(/^[0-9A-F]{16}-[0-9A-F]{16}$/);+ }+ });++ test('hashes are bcrypt hashes distinct from the plaintext', async () => {+ const { plaintext, hashed } = await generateBackupCodes();++ for (let i = 0; i < plaintext.length; i++) {+ expect(hashed[i]).toMatch(/^\$2[aby]\$/);+ expect(hashed[i]).not.toBe(plaintext[i]);+ }+ });++ test('generates unique codes', async () => {+ const { plaintext } = await generateBackupCodes();++ expect(new Set(plaintext).size).toBe(plaintext.length);+ });+});++describe('verifyBackupCode', () => {+ test('returns the matching index for a valid code', async () => {+ const { plaintext, hashed } = await generateBackupCodes();++ expect(await verifyBackupCode(plaintext[3], hashed)).toBe(3);+ });++ test('is case-insensitive on input', async () => {+ const { plaintext, hashed } = await generateBackupCodes();++ expect(await verifyBackupCode(plaintext[0].toLowerCase(), hashed)).toBe(0);+ });++ test('returns null for an unknown code', async () => {+ const { hashed } = await generateBackupCodes();++ expect(await verifyBackupCode('DEADBEEFDEADBEEF-DEADBEEFDEADBEEF', hashed)).toBeNull();+ });+});diff --git a/src/lib/two-factor/crypto.test.ts b/src/lib/two-factor/crypto.test.tsnew file mode 100644index 000000000..94f74ba7c--- /dev/null+++ b/src/lib/two-factor/crypto.test.ts@@ -0,0 +1,53 @@+import { describe, expect, test, vi } from 'vitest';++const KEY = 'a'.repeat(64);++describe('encryptSecret/decryptSecret', () => {+ test('round-trips a secret with a valid key', async () => {+ vi.stubEnv('TWO_FACTOR_ENCRYPTION_KEY', KEY);+ vi.resetModules();+ const { encryptSecret, decryptSecret } = await import('./crypto');++ const plaintext = 'JBSWY3DPEHPK3PXP';+ const stored = encryptSecret(plaintext);++ expect(stored).not.toContain(plaintext);+ expect(stored.split(':')).toHaveLength(3);+ expect(decryptSecret(stored)).toBe(plaintext);++ vi.unstubAllEnvs();+ });++ test('produces different ciphertext each call (random iv)', async () => {+ vi.stubEnv('TWO_FACTOR_ENCRYPTION_KEY', KEY);+ vi.resetModules();+ const { encryptSecret } = await import('./crypto');++ expect(encryptSecret('same')).not.toBe(encryptSecret('same'));++ vi.unstubAllEnvs();+ });++ test('fails to decrypt tampered ciphertext', async () => {+ vi.stubEnv('TWO_FACTOR_ENCRYPTION_KEY', KEY);+ vi.resetModules();+ const { encryptSecret, decryptSecret } = await import('./crypto');++ const [ciphertext, iv, tag] = encryptSecret('secret').split(':');+ const flipped = (ciphertext[0] === 'f' ? '0' : 'f') + ciphertext.slice(1);++ expect(() => decryptSecret(`${flipped}:${iv}:${tag}`)).toThrow();++ vi.unstubAllEnvs();+ });++ test('throws when the encryption key is missing or invalid', async () => {+ vi.stubEnv('TWO_FACTOR_ENCRYPTION_KEY', 'too-short');+ vi.resetModules();+ const { encryptSecret } = await import('./crypto');++ expect(() => encryptSecret('secret')).toThrow(/missing or invalid/);++ vi.unstubAllEnvs();+ });+});diff --git a/src/lib/two-factor/totp.test.ts b/src/lib/two-factor/totp.test.tsnew file mode 100644index 000000000..233fdeb66--- /dev/null+++ b/src/lib/two-factor/totp.test.ts@@ -0,0 +1,49 @@+import { generateSecret, generateSync } from 'otplib';+import { describe, expect, test } from 'vitest';+import { generateOtpAuthUri, generateTotpSecret, verifyTotp } from './totp';++describe('generateTotpSecret', () => {+ test('returns a base32 secret string', () => {+ const secret = generateTotpSecret();++ expect(typeof secret).toBe('string');+ expect(secret).toMatch(/^[A-Z2-7]+$/);+ });++ test('returns a different secret each call', () => {+ expect(generateTotpSecret()).not.toBe(generateTotpSecret());+ });+});++describe('generateOtpAuthUri', () => {+ test('builds an otpauth uri containing issuer, label and secret', () => {+ const secret = generateTotpSecret();+ const uri = generateOtpAuthUri(secret, 'alice');++ expect(uri).toContain('otpauth://totp/');+ expect(uri).toContain('issuer=Umami');+ expect(uri).toContain('alice');+ expect(uri).toContain(`secret=${secret}`);+ });+});++describe('verifyTotp', () => {+ test('verifies a token generated for the current time step', async () => {+ const secret = generateSecret();+ const token = generateSync({ secret });++ expect(await verifyTotp(token, secret)).toBe(true);+ });++ test('rejects an incorrect token', async () => {+ const secret = generateSecret();++ expect(await verifyTotp('000000', secret)).toBe(false);+ });++ test('rejects a valid token verified against a different secret', async () => {+ const token = generateSync({ secret: generateSecret() });++ expect(await verifyTotp(token, generateSecret())).toBe(false);+ });+});diff --git a/src/lib/url.test.ts b/src/lib/url.test.tsnew file mode 100644index 000000000..834f9f272--- /dev/null+++ b/src/lib/url.test.ts@@ -0,0 +1,83 @@+import { describe, expect, test } from 'vitest';+import {+ buildPath,+ getQueryString,+ isValidUrl,+ safeDecodeURI,+ safeDecodeURIComponent,+} from './url';++describe('getQueryString', () => {+ test('returns an empty string for no params', () => {+ expect(getQueryString()).toBe('');+ expect(getQueryString({})).toBe('');+ });++ test('serializes params into a query string', () => {+ expect(getQueryString({ a: 1, b: 'two' })).toBe('a=1&b=two');+ });++ test('skips undefined, null and NaN values', () => {+ expect(getQueryString({ a: 1, b: undefined, c: null, d: NaN })).toBe('a=1');+ });++ test('encodes special characters', () => {+ expect(getQueryString({ q: 'a b&c' })).toBe('q=a+b%26c');+ });+});++describe('buildPath', () => {+ test('appends a query string when params are present', () => {+ expect(buildPath('/api', { a: 1 })).toBe('/api?a=1');+ });++ test('returns the path unchanged when there are no params', () => {+ expect(buildPath('/api')).toBe('/api');+ expect(buildPath('/api', {})).toBe('/api');+ });+});++describe('safeDecodeURI', () => {+ test('decodes a valid encoded URI', () => {+ expect(safeDecodeURI('a%20b')).toBe('a b');+ });++ test('returns the original string for malformed input', () => {+ expect(safeDecodeURI('%')).toBe('%');+ expect(safeDecodeURI('%E0%A4%A')).toBe('%E0%A4%A');+ });++ test('passes through null and undefined', () => {+ expect(safeDecodeURI(null)).toBeNull();+ expect(safeDecodeURI(undefined)).toBeUndefined();+ });+});++describe('safeDecodeURIComponent', () => {+ test('decodes a valid encoded component', () => {+ expect(safeDecodeURIComponent('a%26b')).toBe('a&b');+ });++ test('returns the original string for malformed input', () => {+ expect(safeDecodeURIComponent('%')).toBe('%');+ expect(safeDecodeURIComponent('%ZZ')).toBe('%ZZ');+ });++ test('passes through null and undefined', () => {+ expect(safeDecodeURIComponent(null)).toBeNull();+ expect(safeDecodeURIComponent(undefined)).toBeUndefined();+ });+});++describe('isValidUrl', () => {+ test('returns true for valid urls', () => {+ expect(isValidUrl('https://umami.is')).toBe(true);+ expect(isValidUrl('http://localhost:3000/path?q=1')).toBe(true);+ });++ test('returns false for invalid urls', () => {+ expect(isValidUrl('not a url')).toBe(false);+ expect(isValidUrl('/relative/path')).toBe(false);+ expect(isValidUrl('')).toBe(false);+ });+});diff --git a/src/lib/utils.test.ts b/src/lib/utils.test.tsnew file mode 100644index 000000000..966d9d404--- /dev/null+++ b/src/lib/utils.test.ts@@ -0,0 +1,98 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { chunkArray, ensureArray, hook, shuffleArray, sleep } from './utils';++describe('hook', () => {+ test('calls callback then original and returns original result', () => {+ const calls: string[] = [];+ const obj = {+ value: 5,+ method(this: any, n: number) {+ calls.push('orig');+ return this.value + n;+ },+ };++ const callback = vi.fn(function (this: any, _n: number) {+ calls.push('cb');+ });++ const wrapped = hook(obj, 'method', callback);+ const result = wrapped(10);++ expect(result).toBe(15);+ expect(callback).toHaveBeenCalledWith(10);+ expect(calls).toEqual(['cb', 'orig']);+ });+});++describe('chunkArray', () => {+ test('splits an array into chunks of the given size', () => {+ expect(chunkArray([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]);+ });++ test('returns a single chunk when size exceeds length', () => {+ expect(chunkArray([1, 2, 3], 10)).toEqual([[1, 2, 3]]);+ });++ test('returns an empty array for an empty input', () => {+ expect(chunkArray([], 3)).toEqual([]);+ });+});++describe('ensureArray', () => {+ test('returns empty array for undefined', () => {+ expect(ensureArray(undefined)).toEqual([]);+ });++ test('returns empty array for null', () => {+ expect(ensureArray(null)).toEqual([]);+ });++ test('returns the same array when given an array', () => {+ const arr = [1, 2, 3];+ expect(ensureArray(arr)).toBe(arr);+ });++ test('wraps a non-array value in an array', () => {+ expect(ensureArray('a')).toEqual(['a']);+ expect(ensureArray(0)).toEqual([0]);+ });+});++describe('shuffleArray', () => {+ test('does not mutate the original array', () => {+ const arr = [1, 2, 3, 4, 5];+ const copy = [...arr];+ shuffleArray(arr);+ expect(arr).toEqual(copy);+ });++ test('returns an array with the same length and members', () => {+ const arr = [1, 2, 3, 4, 5];+ const result = shuffleArray(arr);+ expect(result).toHaveLength(arr.length);+ expect([...result].sort()).toEqual([...arr].sort());+ });+});++describe('sleep', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ test('resolves after the given delay', async () => {+ const resolved = vi.fn();+ const promise = sleep(1000).then(resolved);++ expect(resolved).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(1000);+ await promise;++ expect(resolved).toHaveBeenCalled();+ });+});