import { vi } from "vitest"; import type { CalendarEvent } from "../src/agenda.js"; import { createApp } from "../src/app.js"; import type { GoogleClient } from "../src/google/types.js"; export const ALMATY = "Asia/Almaty"; /** Понедельник 16 ноября 2026, 10:00 по Алматы. */ export const MONDAY_10 = new Date("2026-11-16T10:00:00+05:00"); export function timed(title: string | null, start: string, end?: string): CalendarEvent { const startDate = new Date(`${start}:00+05:00`); const endDate = end ? new Date(`${end}:00+05:00`) : new Date(startDate.getTime() + 3_600_000); return { id: `${title}-${start}`, title, allDay: false, start: startDate, end: endDate }; } export function allDay(title: string | null, startDate: string, endDate: string): CalendarEvent { return { id: `${title}-${startDate}`, title, allDay: true, startDate, endDate }; } /** Подставной календарь Google с заданными событиями; вызовы можно проверять. */ export function stubGoogle(initial: CalendarEvent[] = [], timeZone = ALMATY) { const state = { events: initial }; const client = { isMock: false, authUrl: vi.fn( ({ state: s, redirectUri }: { state: string; redirectUri: string }) => `https://accounts.google.test/consent?state=${s}&redirect_uri=${encodeURIComponent(redirectUri)}`, ), exchangeCode: vi.fn(async () => ({ refreshToken: "stub-refresh-token" })), refreshAccessToken: vi.fn(async () => "stub-access-token"), listEvents: vi.fn(async () => ({ timeZone, events: state.events })), } satisfies GoogleClient; return { client, state }; } /** Браузер для тестов: хранит cookie между запросами. */ export function browser(app: ReturnType, headers: Record = {}) { const jar = new Map(); return { jar, async get(path: string, method = "GET") { const cookie = [...jar].map(([k, v]) => `${k}=${v}`).join("; "); const res = await app.request(`http://ea.test${path}`, { method, headers: { "accept-language": "ru-RU", ...headers, ...(cookie ? { cookie } : {}) }, }); for (const line of res.headers.getSetCookie()) { const [pair = "", ...attrs] = line.split(";"); const eq = pair.indexOf("="); const name = pair.slice(0, eq); const value = pair.slice(eq + 1); const expired = attrs.some((a) => /^\s*max-age=0$/i.test(a)); if (expired || value === "") jar.delete(name); else jar.set(name, value); } return res; }, /** Проходит подключение: кнопка → страница согласия → возврат в EA. */ async connect(answer: "allow" | "deny" = "allow") { const start = await this.get("/connect"); const consent = new URL(start.headers.get("location") ?? ""); const state = consent.searchParams.get("state") ?? ""; const query = answer === "allow" ? `code=stub-code&state=${state}` : `error=access_denied&state=${state}`; const back = await this.get(`/auth/google/callback?${query}`); return this.get(back.headers.get("location") ?? "/"); }, }; } export function appWith(google: GoogleClient, now: Date = MONDAY_10) { return createApp({ google, sessionSecret: "test-secret", now: () => now }); } /** Видимый текст страницы без разметки и стилей. */ export function visibleText(html: string): string { return html .replace(//g, " ") .replace(//g, " ") .replace(/<[^>]+>/g, " ") .replace(/"/g, '"') .replace(/&/g, "&") .replace(/\s+/g, " ") .trim(); }