import { BadRequestException } from '@nestjs/common'; export type Cursor = { scope: string; created_at: string; id: string; }; export function encodeCursor(cursor: Cursor): string { return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url'); } export function decodeCursor(value: string, expectedScope: string): Cursor { try { const parsed: unknown = JSON.parse( Buffer.from(value, 'base64url').toString('utf8'), ); if ( typeof parsed !== 'object' || parsed === null || !('scope' in parsed) || !('created_at' in parsed) || !('id' in parsed) || typeof parsed.scope !== 'string' || typeof parsed.created_at !== 'string' || typeof parsed.id !== 'string' || parsed.scope !== expectedScope || !/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test( parsed.id, ) || !/^(?:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)$/u.test( parsed.created_at, ) ) throw new Error('invalid cursor'); const timestamp = Date.parse(parsed.created_at); if (!Number.isFinite(timestamp)) throw new Error('invalid cursor'); return { scope: parsed.scope, created_at: parsed.created_at, id: parsed.id, }; } catch { throw new BadRequestException('Invalid cursor'); } } export function isAfter( createdAt: string, id: string, cursor: Cursor, ): boolean { return ( createdAt > cursor.created_at || (createdAt === cursor.created_at && id > cursor.id) ); }