import { BadRequestException } from '@nestjs/common'; import { randomUUID } from 'node:crypto'; import { describe, expect, it } from 'vitest'; import { decodeCursor, encodeCursor } from './cursor.js'; const scope = 'messages:6f1c2a3e-1111-4222-8333-444455556666'; function encode(createdAt: string, cursorScope = scope): string { return encodeCursor({ scope: cursorScope, created_at: createdAt, id: randomUUID(), }); } describe('decodeCursor', () => { it('accepts valid instants and normalizes them to canonical milliseconds', () => { const accepted: Array<[string, string]> = [ ['2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'], ['2026-01-01T00:00:00Z', '2026-01-01T00:00:00.000Z'], ['2026-01-01T00:00:00.999999Z', '2026-01-01T00:00:00.999Z'], ['2024-02-29T23:59:59.000Z', '2024-02-29T23:59:59.000Z'], ['2026-12-31T23:59:59.999Z', '2026-12-31T23:59:59.999Z'], ]; for (const [createdAt, expected] of accepted) { const decoded = decodeCursor(encode(createdAt), scope); expect(decoded.created_at).toBe(expected); expect(decoded.scope).toBe(scope); } }); it('rejects calendar dates that the platform parser rolls over', () => { // 2026-02-31 would silently become 2026-03-03 and then fail inside SQL. for (const createdAt of [ '2026-02-31T00:00:00.000Z', '2025-02-29T00:00:00.000Z', '2026-04-31T00:00:00.000Z', '2026-06-31T12:00:00.000Z', ]) { expect(() => decodeCursor(encode(createdAt), scope)).toThrow( BadRequestException, ); } }); it('rejects out-of-range and malformed timestamps', () => { for (const createdAt of [ '2026-01-01T24:00:00.000Z', '2026-01-01T00:00:60.000Z', '2026-13-01T00:00:00.000Z', '2026-00-01T00:00:00.000Z', '2026-01-01T00:00:00', '2026-01-01T00:00:00+02:00', '2026-1-1T00:00:00.000Z', '2026-01-01', 'not-a-timestamp', ]) { expect(() => decodeCursor(encode(createdAt), scope)).toThrow( BadRequestException, ); } }); it('rejects a cursor from another scope, a malformed id, and non-cursor input', () => { expect(() => decodeCursor( encode('2026-01-01T00:00:00.000Z', 'messages:other'), scope, ), ).toThrow(BadRequestException); expect(() => decodeCursor( encodeCursor({ scope, created_at: '2026-01-01T00:00:00.000Z', id: 'not-a-uuid', }), scope, ), ).toThrow(BadRequestException); expect(() => decodeCursor('not-a-cursor', scope)).toThrow( BadRequestException, ); }); });