Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions src/lib/api/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ vi.mock('../auth/session', () => ({
}));

import { API } from './index';
import type { AcademicProfile } from '../calendar/academicProfile';

const fetchMock = vi.fn<(url: string, init?: RequestInit) => Promise<Response>>();

Expand All @@ -34,6 +35,107 @@ beforeEach(() => {
vi.stubGlobal('fetch', fetchMock);
});

describe('academic data endpoints', () => {
it('reads and completes the independent server-side backfill flags', async () => {
const initial = {
past_terms: { completed: false, completed_at: null },
academic_data: { completed: false, completed_at: null }
};
const done = {
...initial,
academic_data: { completed: true, completed_at: '2026-10-23T12:00:00Z' }
};
fetchMock.mockResolvedValueOnce(json(initial)).mockResolvedValueOnce(json(done));
expect(await API.getBackfills()).toEqual(initial);
expect(await API.completeBackfill('academic_data')).toEqual(done);
expect(fetchMock.mock.calls.map(([url, init]) => [url, init?.method])).toEqual([
['https://calendar.example.test/api/user/backfills', 'GET'],
['https://calendar.example.test/api/user/backfills/academic_data', 'PUT']
]);
});
it('rejects malformed or unconfirmed backfill state', async () => {
fetchMock.mockResolvedValueOnce(json({}));
await expect(API.getBackfills()).rejects.toThrow('Invalid backfill state');
fetchMock.mockResolvedValueOnce(
json({
past_terms: { completed: false, completed_at: null },
academic_data: { completed: false, completed_at: null }
})
);
await expect(API.completeBackfill('academic_data')).rejects.toThrow('not recorded');
});
const profile: AcademicProfile = {
source: 'leopardweb',
level: 'Undergraduate',
class_standing: null,
admit_type: null,
admit_term: null,
programs: []
};
it('sends the academic profile with normal extension authentication', async () => {
fetchMock.mockResolvedValue(json({ ...profile, programs: [] }));
await API.saveAcademicProfile(profile);
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('https://calendar.example.test/api/user/academic_profile');
expect(init?.method).toBe('PUT');
expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer header.payload.signature');
expect(JSON.parse(String(init?.body))).toEqual(profile);
});
it('sends complete per-term outcome lists in batches of at most thirty terms', async () => {
const terms = Array.from({ length: 31 }, (_, index) => ({
term: `${2000 + index}10`,
courses: [{ crn: '1', outcome: 'c_or_better' as const }]
}));
fetchMock.mockImplementation(async (_url, init) =>
json({
terms: JSON.parse(String(init?.body)).terms.map((term: { term: string }) => ({
term: term.term,
updated: 1,
unknown_crns: []
}))
})
);
expect((await API.saveCourseOutcomes({ terms })).terms).toHaveLength(31);
expect(
fetchMock.mock.calls.map(([, init]) => JSON.parse(String(init?.body)).terms.length)
).toEqual([30, 1]);
expect(fetchMock.mock.calls[0][0]).toBe(
'https://calendar.example.test/api/user/course_outcomes'
);
expect(fetchMock.mock.calls[0][1]?.method).toBe('PUT');
});
it('skips an empty outcomes payload and rejects oversized terms before sending', async () => {
expect(await API.saveCourseOutcomes({ terms: [] })).toEqual({ terms: [] });
await expect(
API.saveCourseOutcomes({
terms: [
{
term: '202610',
courses: Array.from({ length: 31 }, (_, index) => ({
crn: String(index),
outcome: 'failed'
}))
}
]
})
).rejects.toThrow('30 course outcomes');
expect(fetchMock).not.toHaveBeenCalled();
});
it('preserves invalid_term errors for display and rejects malformed outcome responses', async () => {
fetchMock.mockResolvedValueOnce(
json({ error: 'Invalid catalog term', code: 'invalid_term' }, 422)
);
await expect(API.saveAcademicProfile(profile)).rejects.toMatchObject({
status: 422,
code: 'invalid_term'
});
fetchMock.mockResolvedValueOnce(json({ terms: [] }));
await expect(
API.saveCourseOutcomes({ terms: [{ term: '202610', courses: [] }] })
).rejects.toThrow('Invalid course outcomes response');
});
});

describe('API.requestOAuthForEmail', () => {
it('starts OAuth for an existing linked email', async () => {
const email = 'linked@example.test';
Expand Down
93 changes: 93 additions & 0 deletions src/lib/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type {
CatalogTerm,
BackfillName,
BackfillState,
ConnectedAccount,
CurrentTerm,
ProcessingTerm,
Expand Down Expand Up @@ -57,12 +59,103 @@ import {
type SavedMeetingInput
} from '../friends/savedMeetings';
import { getBaseUrl, getJwtToken, readJson, request, requestJson } from './client';
import type { AcademicProfile, StoredAcademicProfile } from '../calendar/academicProfile';
import type { CourseOutcomes, CourseOutcomesResult } from '../calendar/courseOutcomes';

export { ApiError } from './client';

const PREFERENCE_VERSION = /^[a-f0-9]{64}$/;

export class API {
public static async getBackfills(): Promise<BackfillState> {
return this.readBackfills(
await requestJson('/user/backfills', 'Failed to read backfill state')
);
}

public static async completeBackfill(name: BackfillName): Promise<BackfillState> {
const state = this.readBackfills(
await requestJson(`/user/backfills/${name}`, 'Failed to record completed backfill', {
method: 'PUT'
})
);
if (!state[name].completed) throw new Error('The backfill was not recorded as complete');
return state;
}

private static readBackfills(value: unknown): BackfillState {
if (!value || typeof value !== 'object') throw new Error('Invalid backfill state');
for (const name of ['past_terms', 'academic_data']) {
const entry = (value as Record<string, unknown>)[name];
if (!entry || typeof entry !== 'object') throw new Error('Invalid backfill state');
const fields = entry as Record<string, unknown>;
if (
typeof fields.completed !== 'boolean' ||
(fields.completed_at !== null && typeof fields.completed_at !== 'string') ||
(fields.completed && !fields.completed_at)
)
throw new Error('Invalid backfill state');
}
return value as BackfillState;
}

public static async saveAcademicProfile(
profile: AcademicProfile
): Promise<StoredAcademicProfile> {
const data = await requestJson<StoredAcademicProfile>(
'/user/academic_profile',
'Failed to save academic profile',
{ method: 'PUT', body: profile }
);
if (
!Array.isArray(data?.programs) ||
data.programs.some(
(program) =>
!program ||
typeof program.name !== 'string' ||
![true, false, null].includes(program.matched)
)
)
throw new Error('Invalid academic profile response');
return data;
}

public static async saveCourseOutcomes(
outcomes: CourseOutcomes,
active: () => boolean = () => true
): Promise<CourseOutcomesResult> {
if (outcomes.terms.some((term) => term.courses.length > 30))
throw new Error(
'The backend supports at most 30 course outcomes per term. No outcomes were sent.'
);
const terms: CourseOutcomesResult['terms'] = [];
for (let index = 0; index < outcomes.terms.length; index += 30) {
if (!active()) throw new Error('The academic data session ended. Try again.');
const batch = outcomes.terms.slice(index, index + 30);
const data = await requestJson<CourseOutcomesResult>(
'/user/course_outcomes',
'Failed to save course outcomes',
{ method: 'PUT', body: { terms: batch } }
);
if (
!Array.isArray(data?.terms) ||
data.terms.length !== batch.length ||
data.terms.some(
(result, position) =>
!result ||
result.term !== batch[position].term ||
!Number.isSafeInteger(result.updated) ||
result.updated < 0 ||
!Array.isArray(result.unknown_crns) ||
result.unknown_crns.some((crn) => typeof crn !== 'string')
)
)
throw new Error('Invalid course outcomes response');
terms.push(...data.terms);
}
return { terms };
}

public static get baseUrl(): Promise<string> {
return getBaseUrl();
}
Expand Down
5 changes: 3 additions & 2 deletions src/lib/browser/tabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,15 @@ async function witContainerId(): Promise<string | undefined> {
}
}

export async function createWitTab(url: string): Promise<chrome.tabs.Tab> {
export async function createWitTab(url: string, active = true): Promise<chrome.tabs.Tab> {
const cookieStoreId = await witContainerId();
try {
return await chrome.tabs.create({
url,
active,
...(cookieStoreId ? { cookieStoreId } : {})
} as chrome.tabs.CreateProperties);
} catch {
return await chrome.tabs.create({ url });
return await chrome.tabs.create({ url, active });
}
}
113 changes: 113 additions & 0 deletions src/lib/calendar/academicProfile.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import {
fetchAcademicProfile,
lookupAcademicProfile,
STUDENT_PROFILE_URL
} from './academicProfile';

vi.mock('../browser/tabs', () => ({ createWitTab: vi.fn() }));
import { createWitTab } from '../browser/tabs';

function setup(url = STUDENT_PROFILE_URL, status = 'complete') {
const listeners = () => ({ addListener: vi.fn(), removeListener: vi.fn() });
const browser = {
tabs: {
query: vi.fn(async (): Promise<chrome.tabs.Tab[]> => []),
get: vi.fn(async () => ({ id: 7, url, status })),
remove: vi.fn(async () => {}),
onUpdated: listeners(),
onRemoved: listeners()
},
scripting: {
executeScript: vi.fn(
async (): Promise<unknown[]> => [{ result: { profile: { program: 'Computer Science' } } }]
)
}
};
vi.mocked(createWitTab).mockResolvedValue({ id: 7 } as chrome.tabs.Tab);
vi.stubGlobal('chrome', browser);
return browser;
}

beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.unstubAllGlobals();
vi.useRealTimers();
});

it('opens Student Profile and reads HTML in the loaded page', async () => {
const browser = setup();
expect(await fetchAcademicProfile()).toEqual({ program: 'Computer Science' });
expect(createWitTab).toHaveBeenCalledWith(STUDENT_PROFILE_URL, false);
expect(browser.scripting.executeScript).toHaveBeenCalledWith({
target: { tabId: 7 },
world: 'MAIN',
func: lookupAcademicProfile
});
expect(browser.tabs.remove).toHaveBeenCalledWith(7);
});

it('reuses an existing profile tab without closing it', async () => {
const browser = setup();
browser.tabs.query.mockResolvedValue([
{ id: 7, url: STUDENT_PROFILE_URL.replace(/#$/, ''), active: false } as chrome.tabs.Tab
]);
await fetchAcademicProfile();
expect(browser.tabs.query).toHaveBeenCalledWith({ url: STUDENT_PROFILE_URL.replace(/#$/, '') });
expect(createWitTab).not.toHaveBeenCalled();
expect(browser.tabs.remove).not.toHaveBeenCalled();
});

it('closes a background login redirect and returns an actionable sign-in URL without injecting', async () => {
const browser = setup('https://selfservice.wit.edu/StudentSelfService/login');
await expect(fetchAcademicProfile()).rejects.toMatchObject({
name: 'StudentPageAuthError',
url: STUDENT_PROFILE_URL
});
expect(browser.scripting.executeScript).not.toHaveBeenCalled();
expect(browser.tabs.remove).toHaveBeenCalledWith(7);
});

it('times out a stalled tab and removes listeners and the owned tab', async () => {
vi.useFakeTimers();
const browser = setup(undefined, 'loading');
const result = expect(fetchAcademicProfile()).rejects.toThrow('did not finish loading');
await vi.advanceTimersByTimeAsync(30_000);
await result;
expect(browser.tabs.onUpdated.removeListener).toHaveBeenCalled();
expect(browser.tabs.onRemoved.removeListener).toHaveBeenCalled();
expect(browser.tabs.remove).toHaveBeenCalledWith(7);
});

it('handles a closed tab while loading', async () => {
const browser = setup(undefined, 'loading');
browser.tabs.onRemoved.addListener.mockImplementation((listener: (id: number) => void) => {
queueMicrotask(() => listener(7));
});
await expect(fetchAcademicProfile()).rejects.toThrow('was closed');
expect(browser.scripting.executeScript).not.toHaveBeenCalled();
expect(browser.tabs.onUpdated.removeListener).toHaveBeenCalled();
});

it.each([{ results: [] }, { results: [{ result: { error: 'The profile did not load' } }] }])(
'rejects missing or failed extraction results',
async ({ results }) => {
const browser = setup();
browser.scripting.executeScript.mockResolvedValue(results);
await expect(fetchAcademicProfile()).rejects.toThrow();
expect(browser.tabs.remove).toHaveBeenCalledWith(7);
}
);

it('discards a late result after its session ends', async () => {
const browser = setup();
let active = true;
browser.scripting.executeScript.mockImplementation(async () => {
active = false;
return [{ result: { profile: { program: 'Old account' } } }];
});
expect(await fetchAcademicProfile(() => active)).toBeUndefined();
expect(browser.tabs.remove).toHaveBeenCalledWith(7);
});
Loading
Loading