Compare commits

...

7 Commits

62 changed files with 1785 additions and 2641 deletions

View File

@@ -1,36 +0,0 @@
name: Deploy
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
name: Deploy
steps:
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.1.27
- name: Install dependencies
run: bun install
- name: Install libsql server
run: curl --proto '=https' --tlsv1.2 -LsSf https://github.com/tursodatabase/libsql/releases/download/libsql-server-v0.24.14/libsql-server-installer.sh | sh
- name: Test
run: bun run test --dbCommand \"~/.cargo/bin/sqld --http-listen-addr=127.0.0.1:3001\"
# TODO: uncomment this when https://github.com/cloudflare/workers-sdk/issues/5082 is fixed
# - name: Verify env
# run: bun env:verify
# env:
# CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
# IS_CI: true
- name: Run DB migration
run: bun run db:migrate
env:
TURSO_URL: ${{ vars.TURSO_URL }}
TURSO_AUTH_TOKEN: ${{ secrets.TURSO_AUTH_TOKEN }}
- name: Deploy
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}

3
.gitignore vendored
View File

@@ -7,3 +7,6 @@ dist
*.db-*
.env
.idea/ChatHistory_schema_v3.xml
# Vitest coverage reports
coverage/

View File

@@ -1,7 +0,0 @@
[test]
preload = [
"./testSetup.ts",
"./src/mocks/consumet.ts",
"./src/mocks/getGoogleAuthToken.ts",
"./src/mocks/cloudflare.ts",
]

View File

@@ -5,21 +5,17 @@
"main": "src/index.ts",
"type": "module",
"scripts": {
"dev:cloudflare": "wrangler dev src/index.ts --port 8080",
"dev:server": "TURSO_URL=http://127.0.0.1:3000 TURSO_AUTH_TOKEN=123 bun run --watch src/index.ts",
"prod:server": "bun run src/index.ts",
"dev": "wrangler dev src/index.ts --port 8080",
"deploy": "wrangler deploy --minify src/index.ts",
"env:generate": "bun src/scripts/generateEnv.ts",
"env:verify": "bun src/scripts/verifyEnv.ts",
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate",
"test": "bun src/testRunner.ts",
"prepare": "husky",
"tsx": "tsx"
"test": "vitest",
"test:ui": "vitest --ui",
"coverage": "vitest --coverage",
"prepare": "husky"
},
"dependencies": {
"@consumet/extensions": "github:consumet/consumet.ts#3dd0ccb",
"@haverstack/axios-fetch-adapter": "^0.12.0",
"@hono/swagger-ui": "^0.5.1",
"@hono/zod-openapi": "^0.19.5",
"@hono/zod-validator": "^0.2.2",
@@ -41,17 +37,16 @@
"devDependencies": {
"@0no-co/graphqlsp": "^1.12.16",
"@cloudflare/vitest-pool-workers": "^0.10.7",
"@cloudflare/workers-types": "^4.20250423.0",
"@trivago/prettier-plugin-sort-imports": "^4.3.0",
"@types/bun": "^1.2.10",
"@types/lodash.isequal": "^4.5.8",
"@types/lodash.mapkeys": "^4.6.9",
"@types/luxon": "^3.6.2",
"@types/node": "^24.10.1",
"@types/node": "^22.10.1",
"@types/pngjs": "^6.0.5",
"@vitest/coverage-v8": "^3.2.4",
"@vitest/coverage-istanbul": "3.2.4",
"@vitest/runner": "^3.2.4",
"@vitest/snapshot": "^3.2.4",
"@vitest/ui": "^3.2.4",
"cloudflare": "^5.2.0",
"dotenv": "^17.2.3",
"drizzle-kit": "^0.31.7",
@@ -60,13 +55,13 @@
"husky": "^9.1.7",
"lint-staged": "^15.5.1",
"miniflare": "^4.20251109.1",
"msw": "2.4.3",
"prettier": "^3.5.3",
"prettier-plugin-toml": "^2.0.4",
"ts-morph": "^22.0.0",
"tsx": "^4.20.6",
"tsx": "^4.19.2",
"typescript": "^5.8.3",
"util": "^0.12.5",
"vite-tsconfig-paths": "^5.1.4",
"vitest": "^3.2.4",
"wrangler": "^4.51.0",
"zx": "8.1.5"

1038
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +0,0 @@
import { ANIME, META } from "@consumet/extensions";
import fetchAdapter from "@haverstack/axios-fetch-adapter";
const gogoAnime = new ANIME.Gogoanime(undefined, undefined, fetchAdapter);
export const aniList = new META.Anilist(gogoAnime, undefined, fetchAdapter);

View File

@@ -6,7 +6,7 @@ import { maybeUpdateLastConnectedAt } from "~/middleware/maybeUpdateLastConnecte
import type { QueueBody } from "./libs/tasks/queueTask";
const app = new Hono<Cloudflare.Env>();
export const app = new Hono<Cloudflare.Env>();
app.use(maybeUpdateLastConnectedAt);

View File

@@ -0,0 +1,92 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import * as getAdminSdkCredentials from "~/libs/gcloud/getAdminSdkCredentials";
import * as sendFcmMessage from "~/libs/gcloud/sendFcmMessage";
import * as maybeScheduleNextAiringEpisode from "~/libs/maybeScheduleNextAiringEpisode";
import * as token from "~/models/token";
import * as watchStatus from "~/models/watchStatus";
import * as aniwatch from "~/services/episodes/getByAniListId/aniwatch";
import * as getEpisodeUrl from "~/services/episodes/getEpisodeUrl";
import { onNewEpisode } from "./new-episode";
describe("onNewEpisode", () => {
beforeEach(() => {
vi.restoreAllMocks();
// Default mocks
vi.spyOn(getAdminSdkCredentials, "getAdminSdkCredentials").mockReturnValue(
{} as any,
);
vi.spyOn(watchStatus, "isWatchingTitle").mockResolvedValue(true);
vi.spyOn(aniwatch, "getEpisodesFromAniwatch").mockResolvedValue({
providerId: "test",
episodes: [],
} as any);
vi.spyOn(token, "getTokensSubscribedToTitle").mockResolvedValue([]);
vi.spyOn(
maybeScheduleNextAiringEpisode,
"maybeScheduleNextAiringEpisode",
).mockResolvedValue();
vi.spyOn(sendFcmMessage, "sendFcmMessage").mockResolvedValue({} as any);
// Mock Successful fetchUrlResult
vi.spyOn(getEpisodeUrl, "fetchEpisodeUrl").mockResolvedValue({
url: "http://example.com/stream",
headers: {},
} as any);
});
it("should return isNoLongerWatching if title is not being watched", async () => {
vi.spyOn(watchStatus, "isWatchingTitle").mockResolvedValue(false);
const result = await onNewEpisode(123, 10);
expect(result).toEqual({
success: true,
result: { isNoLongerWatching: true },
});
});
it("should return failure if fetching episode URL fails", async () => {
vi.spyOn(getEpisodeUrl, "fetchEpisodeUrl").mockResolvedValue(null);
const result = await onNewEpisode(123, 10);
expect(result).toEqual({
success: false,
message: "Failed to fetch episode URL",
});
});
it("should send FCM messages to subscribed tokens", async () => {
const tokens = ["token1", "token2"];
vi.spyOn(token, "getTokensSubscribedToTitle").mockResolvedValue(tokens);
const sendSpy = vi.spyOn(sendFcmMessage, "sendFcmMessage");
await onNewEpisode(123, 10);
expect(sendSpy).toHaveBeenCalledTimes(2);
// Verify arguments for one call
expect(sendSpy).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
token: "token1",
data: expect.objectContaining({
type: "new_episode",
aniListId: "123",
episodeNumber: "10",
}),
}),
);
});
it("should schedule next airing episode", async () => {
const scheduleSpy = vi.spyOn(
maybeScheduleNextAiringEpisode,
"maybeScheduleNextAiringEpisode",
);
await onNewEpisode(123, 10);
expect(scheduleSpy).toHaveBeenCalledWith(123);
});
});

View File

@@ -1,11 +1,17 @@
import { env } from "cloudflare:workers";
import { useMockData } from "~/libs/useMockData";
import type { Title } from "~/types/title";
export async function fetchTitleFromAnilist(
id: number,
token?: string | undefined,
): Promise<Title | undefined> {
if (useMockData()) {
const { mockTitleDetails } = await import("~/mocks");
return mockTitleDetails();
}
const durableObjectId = env.ANILIST_DO.idFromName(
id.toString() + (token == null ? "" : "_" + token),
);

View File

@@ -1,4 +1,4 @@
import { describe, expect, it } from "bun:test";
import { describe, expect, it } from "vitest";
import { Case, changeStringCase } from "./changeStringCase";

View File

@@ -1,10 +1,10 @@
import { describe, expect, it } from "bun:test";
import { describe, expect, it } from "vitest";
import { fetchFromMultipleSources } from "./fetchFromMultipleSources";
describe("fetchFromMultipleSources", () => {
it("no promises, throws exception", () => {
expect(() => fetchFromMultipleSources([])).toThrow(
it("no promises, throws exception", async () => {
await expect(fetchFromMultipleSources([])).rejects.toThrow(
"fetchPromises cannot be empty",
);
});
@@ -30,7 +30,7 @@ describe("fetchFromMultipleSources", () => {
() => Promise.resolve(3),
]);
expect(errorOccurred).toBeFalse();
expect(errorOccurred).toBe(false);
});
it("has promises that all throw, returns null", async () => {
@@ -48,7 +48,7 @@ describe("fetchFromMultipleSources", () => {
() => Promise.reject(new Error("error")),
]);
expect(errorOccurred).toBeTrue();
expect(errorOccurred).toBe(true);
});
it("has promises but cache has value, returns cached value", async () => {
@@ -80,7 +80,7 @@ describe("fetchFromMultipleSources", () => {
},
);
expect(errorOccurred).toBeFalse();
expect(errorOccurred).toBe(false);
});
it("has promises, no cached value, no valid response, should not save in cache", async () => {

View File

@@ -0,0 +1,122 @@
import { describe, expect, it } from "vitest";
import { findBestMatchingTitle } from "./findBestMatchingTitle";
describe("findBestMatchingTitle", () => {
it("should return the exact match for userPreferred title", () => {
const title = {
userPreferred: "One Piece",
english: "One Piece",
};
const titlesToSearch = [
{ userPreferred: "Naruto", english: "Naruto" },
{ userPreferred: "One Piece", english: "One Piece" },
{ userPreferred: "Bleach", english: "Bleach" },
];
const result = findBestMatchingTitle(title, titlesToSearch);
expect(result.title).toBe("one piece");
expect(result.score).toBeGreaterThan(0.8);
});
it("should return the exact match for english title if userPreferred is missing", () => {
const title = {
english: "Attack on Titan",
};
const titlesToSearch = [
{ userPreferred: "Shingeki no Kyojin", english: "Attack on Titan" },
{ userPreferred: "Naruto", english: "Naruto" },
];
const result = findBestMatchingTitle(title, titlesToSearch);
expect(result.title).toBe("attack on titan");
expect(result.score).toBeGreaterThan(0.8);
});
it("should favor userPreferred match over english match if score is higher", () => {
const title = {
userPreferred: "Fullmetal Alchemist: Brotherhood",
english: "Fullmetal Alchemist Brotherhood",
};
const titlesToSearch = [
{
userPreferred: "Fullmetal Alchemist: Brotherhood",
english: "Fullmetal Alchemist",
},
];
const result = findBestMatchingTitle(title, titlesToSearch);
expect(result.title).toBe("fullmetal alchemist: brotherhood");
});
it("should handle partial matches with high scores", () => {
const title = {
userPreferred: "My Hero Academia 2",
};
const titlesToSearch = [
{ userPreferred: "My Hero Academia" },
{ userPreferred: "My Hero Academia 2" },
{ userPreferred: "My Hero Academia 3" },
];
const result = findBestMatchingTitle(title, titlesToSearch);
expect(result.title).toBe("my hero academia 2");
});
it("should filter by suffix for 'My Hero Academia' logic", () => {
const title = {
english: "My Hero Academia 3",
};
// Expected suffix is "3"
const titlesToSearch = [
{ userPreferred: "Boku no Hero Academia", english: "My Hero Academia" },
{
userPreferred: "Boku no Hero Academia 2",
english: "My Hero Academia 2",
},
{
userPreferred: "Boku no Hero Academia 3",
english: "My Hero Academia 3",
},
];
const result = findBestMatchingTitle(title, titlesToSearch);
// It should match the one ending with 3
expect(result.title).toBe("my hero academia 3");
});
it("should return null/low score if no good match is found", () => {
const title = {
userPreferred: "Random Unknown Anime",
};
const titlesToSearch = [
{ userPreferred: "Naruto" },
{ userPreferred: "Bleach" },
];
const result = findBestMatchingTitle(title, titlesToSearch);
// It will return *some* match because valid targets > 0, but score should be low.
// However, the implementation always returns the "best" match from the list.
// If the list is not empty, it returns something.
expect(result.title).toBeTruthy();
expect(result.score).toBeLessThan(0.5);
});
it("should return null if titlesToSearch is empty", () => {
const title = {
userPreferred: "One Piece",
};
const titlesToSearch: any[] = [];
const result = findBestMatchingTitle(title, titlesToSearch);
expect(result.title).toBeNull();
expect(result.score).toBe(0);
});
});

View File

@@ -1,12 +1,8 @@
import { describe, expect, it } from "bun:test";
import { server } from "~/mocks";
import { describe, expect, it } from "vitest";
import type { AdminSdkCredentials } from "./getAdminSdkCredentials";
import { verifyFcmToken } from "./verifyFcmToken";
server.listen();
const FAKE_ADMIN_SDK_JSON: AdminSdkCredentials = {
type: "service_account",
projectId: "test-26g38",
@@ -28,14 +24,14 @@ describe("verifyFcmToken", () => {
// "7v8sy43aq0re4r8xe7rmr0cn1fsmh6phehnfla2pa73z899zmhyarivmkt4sj6pyv0py43u6p2sim6wz2vg9ypjp9rug1keoth7f6ll3gdvas4q020u3ah51r6bjgn51j6bd92ztmtof3ljpcm8q31njvndy65enm68";
// const res = await verifyFcmToken(token, FAKE_ADMIN_SDK_JSON);
// expect(res).toBeTrue();
// expect(res).toBe(true);
// });
it("invalid token, returns false", async () => {
const token = "abc123";
const res = await verifyFcmToken(token, FAKE_ADMIN_SDK_JSON);
expect(res).toBeFalse();
expect(res).toBe(false);
});
it("invalid ADMIN_SDK_JSON, returns false", async () => {
@@ -46,6 +42,6 @@ describe("verifyFcmToken", () => {
clientEmail: "",
});
expect(res).toBeFalse();
expect(res).toBe(false);
});
});

View File

@@ -1,6 +1,5 @@
import { DateTime } from "luxon";
import { describe, expect, it } from "bun:test";
import { describe, expect, it } from "vitest";
import { getCurrentAndNextSeason } from "./getCurrentAndNextSeason";

View File

@@ -1,30 +0,0 @@
import type { HonoRequest } from "hono";
export function getCurrentDomain(req: HonoRequest): string | undefined;
export function getCurrentDomain(
req: HonoRequest,
avoidLocalhost: false,
): string;
export function getCurrentDomain(
req: HonoRequest,
avoidLocalhost: true,
): string | undefined;
export function getCurrentDomain(req: HonoRequest, avoidLocalhost = true) {
let domain = req.url.replace(req.path, "");
if (domain.includes("?")) {
domain = domain.split("?")[0];
}
if (avoidLocalhost) {
if (
domain.includes("localhost") ||
domain.includes("127.0.0.1") ||
domain.includes("192.168.1")
) {
console.log("Domain is localhost, returning undefined");
return;
}
}
return domain;
}

View File

@@ -1,4 +1,4 @@
import { describe, expect, it } from "bun:test";
import { describe, expect, it } from "vitest";
import { lazy } from "./lazy";
@@ -16,7 +16,7 @@ describe("lazy", () => {
return "value";
});
expect(setValue).toBeFalse();
expect(setValue).toBe(false);
});
it("lazy function called if get is called", () => {
@@ -26,7 +26,7 @@ describe("lazy", () => {
return "value";
}).get();
expect(setValue).toBeTrue();
expect(setValue).toBe(true);
});
it("lazy function called only once if get is called multiple times", () => {

View File

@@ -1,23 +0,0 @@
export async function logStep<T = void>(
inProgressText: string,
step: () => Promise<T> | T,
): Promise<T>;
export async function logStep<T = void>(
inProgressText: string,
step: () => Promise<T> | T,
doneText: string,
): Promise<T>;
export async function logStep<T = void>(
inProgressText: string,
step: () => Promise<T> | T,
doneText: string = `Completed step "${inProgressText}"`,
) {
console.time(doneText);
console.log(`${inProgressText}...`);
return Promise.resolve(step()).then((value) => {
console.timeEnd(doneText);
return value;
});
}

View File

@@ -0,0 +1,72 @@
import { DateTime } from "luxon";
import { describe, expect, it, vi } from "vitest";
import * as unreleasedTitles from "~/models/unreleasedTitles";
import * as getNextEpisodeAiringAt from "./anilist/getNextEpisodeAiringAt";
import { maybeScheduleNextAiringEpisode } from "./maybeScheduleNextAiringEpisode";
import * as queueTask from "./tasks/queueTask";
describe("maybeScheduleNextAiringEpisode", () => {
it("should add to unreleased titles if status is NOT_YET_RELEASED and no airing time", async () => {
vi.spyOn(
getNextEpisodeAiringAt,
"getNextEpisodeTimeUntilAiring",
).mockResolvedValue({
status: "NOT_YET_RELEASED",
} as any);
const addSpy = vi
.spyOn(unreleasedTitles, "addUnreleasedTitle")
.mockResolvedValue();
const queueSpy = vi.spyOn(queueTask, "queueTask");
await maybeScheduleNextAiringEpisode(12345);
expect(addSpy).toHaveBeenCalledWith(12345);
expect(queueSpy).not.toHaveBeenCalled();
});
it("should return early if airing time is too far in the future (> 720 hours)", async () => {
const futureTime = DateTime.now().plus({ hours: 721 }).toSeconds();
vi.spyOn(
getNextEpisodeAiringAt,
"getNextEpisodeTimeUntilAiring",
).mockResolvedValue({
nextAiring: { airingAt: futureTime },
status: "RELEASING",
} as any);
const addSpy = vi.spyOn(unreleasedTitles, "addUnreleasedTitle");
const queueSpy = vi.spyOn(queueTask, "queueTask");
await maybeScheduleNextAiringEpisode(12345);
expect(addSpy).not.toHaveBeenCalled();
expect(queueSpy).not.toHaveBeenCalled();
});
it("should queue task and remove unreleased title if airing soon", async () => {
const nearFutureTime = DateTime.now().plus({ hours: 24 }).toSeconds();
vi.spyOn(
getNextEpisodeAiringAt,
"getNextEpisodeTimeUntilAiring",
).mockResolvedValue({
nextAiring: { airingAt: nearFutureTime, episode: 12 },
status: "RELEASING",
} as any);
const removeSpy = vi
.spyOn(unreleasedTitles, "removeUnreleasedTitle")
.mockResolvedValue();
const queueSpy = vi
.spyOn(queueTask, "queueTask")
.mockResolvedValue({} as any);
await maybeScheduleNextAiringEpisode(12345);
expect(queueSpy).toHaveBeenCalledWith(
"NEW_EPISODE",
{ aniListId: 12345, episodeNumber: 12 },
{ scheduleConfig: { epochTime: nearFutureTime } },
);
expect(removeSpy).toHaveBeenCalledWith(12345);
});
});

View File

@@ -1,4 +1,4 @@
import { describe, expect, it } from "bun:test";
import { describe, expect, it } from "vitest";
import { PromiseTimedOutError, promiseTimeout } from "./promiseTimeout";

View File

@@ -1,4 +1,4 @@
import { describe, expect, it } from "bun:test";
import { describe, expect, it } from "vitest";
import { readEnvVariable } from "./readEnvVariable";
@@ -30,6 +30,6 @@ describe("readEnvVariable", () => {
});
it("env not defined, returns default value", () => {
expect(readEnvVariable<boolean>("ENABLE_ANIFY", undefined)).toBe(true);
expect(readEnvVariable<boolean>("ENABLE_ANIFY", {})).toBe(true);
});
});

View File

@@ -1,4 +1,4 @@
import { describe, expect, it } from "bun:test";
import { describe, expect, it } from "vitest";
import { sortByProperty } from "./sortByProperty";

View File

@@ -1,6 +1,5 @@
import { DateTime } from "luxon";
import { beforeEach, describe, expect, it, mock } from "bun:test";
import { beforeEach, describe, expect, it, mock } from "vitest";
import type { DelayedTaskMetadata } from "./delayedTask";
import {

View File

@@ -1,28 +1,28 @@
import { beforeEach, describe, expect, it, mock } from "bun:test";
import { type Mock, beforeEach, describe, expect, it, vi } from "vitest";
import { processDelayedTasks } from "./processDelayedTasks";
describe("processDelayedTasks", () => {
let mockEnv: Cloudflare.Env;
let mockCtx: ExecutionContext;
let kvGetSpy: ReturnType<typeof mock>;
let kvDeleteSpy: ReturnType<typeof mock>;
let kvPutSpy: ReturnType<typeof mock>;
let queueSendSpy: ReturnType<typeof mock>;
let kvGetSpy: ReturnType<typeof vi.fn>;
let kvDeleteSpy: ReturnType<typeof vi.fn>;
let kvPutSpy: ReturnType<typeof vi.fn>;
let queueSendSpy: ReturnType<typeof vi.fn>;
beforeEach(() => {
kvGetSpy = mock(() => Promise.resolve(null));
kvDeleteSpy = mock(() => Promise.resolve());
kvPutSpy = mock(() => Promise.resolve());
queueSendSpy = mock(() => Promise.resolve());
kvGetSpy = vi.fn(() => Promise.resolve(null));
kvDeleteSpy = vi.fn(() => Promise.resolve());
kvPutSpy = vi.fn(() => Promise.resolve());
queueSendSpy = vi.fn(() => Promise.resolve());
mockEnv = {
DELAYED_TASKS: {
get: kvGetSpy,
delete: kvDeleteSpy,
put: kvPutSpy,
list: mock(() => Promise.resolve({ keys: [], list_complete: true })),
getWithMetadata: mock(() =>
list: vi.fn(() => Promise.resolve({ keys: [], list_complete: true })),
getWithMetadata: vi.fn(() =>
Promise.resolve({ value: null, metadata: null }),
),
} as any,
@@ -30,13 +30,13 @@ describe("processDelayedTasks", () => {
send: queueSendSpy,
} as any,
ANILIST_UPDATES: {
send: mock(() => Promise.resolve()),
send: vi.fn(() => Promise.resolve()),
} as any,
} as any;
mockCtx = {
waitUntil: mock(() => {}),
passThroughOnException: mock(() => {}),
waitUntil: vi.fn(() => {}),
passThroughOnException: vi.fn(() => {}),
} as any;
});
@@ -61,7 +61,7 @@ describe("processDelayedTasks", () => {
retryCount: 0,
};
mockEnv.DELAYED_TASKS.list = mock(() =>
mockEnv.DELAYED_TASKS.list = vi.fn(() =>
Promise.resolve({
keys: [{ name: `delayed-task:${scheduledTime}:task-1` }],
list_complete: true,
@@ -93,7 +93,7 @@ describe("processDelayedTasks", () => {
retryCount: 0,
};
mockEnv.DELAYED_TASKS.list = mock(() =>
mockEnv.DELAYED_TASKS.list = vi.fn(() =>
Promise.resolve({
keys: [{ name: `delayed-task:${scheduledTime}:task-2` }],
list_complete: true,
@@ -122,7 +122,7 @@ describe("processDelayedTasks", () => {
retryCount: 0,
};
mockEnv.DELAYED_TASKS.list = mock(() =>
mockEnv.DELAYED_TASKS.list = vi.fn(() =>
Promise.resolve({
keys: [{ name: `delayed-task:${scheduledTime}:task-3` }],
list_complete: true,
@@ -141,7 +141,7 @@ describe("processDelayedTasks", () => {
});
it("logs alert after 3 failed attempts", async () => {
const consoleErrorSpy = mock(() => {});
const consoleErrorSpy = vi.fn(() => {});
const originalConsoleError = console.error;
console.error = consoleErrorSpy as any;
@@ -158,7 +158,7 @@ describe("processDelayedTasks", () => {
retryCount: 2, // Will become 3 after this failure
};
mockEnv.DELAYED_TASKS.list = mock(() =>
mockEnv.DELAYED_TASKS.list = vi.fn(() =>
Promise.resolve({
keys: [{ name: `delayed-task:${scheduledTime}:task-4` }],
list_complete: true,
@@ -202,7 +202,7 @@ describe("processDelayedTasks", () => {
retryCount: 0,
};
mockEnv.DELAYED_TASKS.list = mock(() =>
mockEnv.DELAYED_TASKS.list = vi.fn(() =>
Promise.resolve({
keys: [
{ name: `delayed-task:${task1Metadata.scheduledEpochTime}:task-1` },
@@ -223,7 +223,7 @@ describe("processDelayedTasks", () => {
});
it("skips tasks with null values in KV", async () => {
mockEnv.DELAYED_TASKS.list = mock(() =>
mockEnv.DELAYED_TASKS.list = vi.fn(() =>
Promise.resolve({
keys: [{ name: "delayed-task:123:invalid" }],
list_complete: true,

View File

@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it, mock, spyOn } from "bun:test";
import { type Mock, beforeEach, describe, expect, it, spyOn, vi } from "vitest";
import { queueTask } from "./queueTask";
@@ -6,20 +6,20 @@ describe("queueTask - delayed task handling", () => {
const MAX_DELAY_SECONDS = 12 * 60 * 60; // 43,200 seconds
let mockEnv: Cloudflare.Env;
let kvPutSpy: ReturnType<typeof mock>;
let queueSendSpy: ReturnType<typeof mock>;
let kvPutSpy: ReturnType<typeof vi.fn>;
let queueSendSpy: ReturnType<typeof vi.fn>;
beforeEach(() => {
kvPutSpy = mock(() => Promise.resolve());
queueSendSpy = mock(() => Promise.resolve());
kvPutSpy = vi.fn(() => Promise.resolve());
queueSendSpy = vi.fn(() => Promise.resolve());
mockEnv = {
DELAYED_TASKS: {
put: kvPutSpy,
get: mock(() => Promise.resolve(null)),
delete: mock(() => Promise.resolve()),
list: mock(() => Promise.resolve({ keys: [], list_complete: true })),
getWithMetadata: mock(() =>
get: vi.fn(() => Promise.resolve(null)),
delete: vi.fn(() => Promise.resolve()),
list: vi.fn(() => Promise.resolve({ keys: [], list_complete: true })),
getWithMetadata: vi.fn(() =>
Promise.resolve({ value: null, metadata: null }),
),
} as any,
@@ -27,12 +27,12 @@ describe("queueTask - delayed task handling", () => {
send: queueSendSpy,
} as any,
ANILIST_UPDATES: {
send: mock(() => Promise.resolve()),
send: vi.fn(() => Promise.resolve()),
} as any,
} as any;
// Mock crypto.randomUUID
globalThis.crypto.randomUUID = mock(() => "test-uuid-123");
globalThis.crypto.randomUUID = vi.fn(() => "test-uuid-123");
});
describe("tasks with delay <= 12 hours", () => {

View File

@@ -1,15 +0,0 @@
import { HttpResponse, graphql } from "msw";
export function deleteAnilistMediaListEntry() {
return graphql.mutation(
"DeleteMediaListEntry",
({ variables: { entryId } }) =>
HttpResponse.json({
data: {
DeleteMediaListEntry: {
deleted: entryId > 0,
},
},
}),
);
}

View File

@@ -1,35 +0,0 @@
import { HttpResponse, graphql } from "msw";
export function getAnilistMediaListEntry() {
return graphql.query("GetMediaListEntry", ({ variables: { titleId } }) => {
if (titleId === 10) {
return HttpResponse.json({
data: {
Media: {
mediaListEntry: {
id: 123456,
},
},
},
});
} else if (titleId === 139518) {
return HttpResponse.json({
data: {
Media: {
mediaListEntry: {
id: 123457,
},
},
},
});
}
return HttpResponse.json({
data: {
Media: {
mediaListEntry: null,
},
},
});
});
}

View File

@@ -1,16 +0,0 @@
import { HttpResponse, graphql } from "msw";
export function getAnilistNextAiringEpisode() {
return graphql.query(
"GetNextEpisodeAiringAt",
({ variables: { titleId } }) => {
return HttpResponse.json({
data: {
Media: {
nextAiringEpisode: null,
},
},
});
},
);
}

View File

@@ -1,575 +0,0 @@
import { HttpResponse, graphql } from "msw";
export function getAnilistSearchResults() {
return graphql.query("Search", ({ variables: { query, page } }) => {
console.log(`Intercepting Search query with ${query} and page ${page}`);
if (!query || query === "a" || query === "aniwatch") {
return HttpResponse.json({
data: {
Page: {
media: [],
pageInfo: {
hasNextPage: false,
},
},
},
});
}
return HttpResponse.json({
data: {
Page: {
media: [
{
id: 151807,
title: {
userPreferred: "Ore dake Level Up na Ken",
english: "Solo Leveling",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx151807-yxY3olrjZH4k.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx151807-yxY3olrjZH4k.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx151807-yxY3olrjZH4k.png",
},
},
{
id: 2759,
title: {
userPreferred: "Evangelion Shin Movie: Jo",
english: "Evangelion: 1.0 You Are (Not) Alone",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx2759-z07kq8Pnw5B1.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx2759-z07kq8Pnw5B1.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx2759-z07kq8Pnw5B1.jpg",
},
},
{
id: 139589,
title: {
userPreferred: "Kotarou wa Hitorigurashi",
english: "Kotaro Lives Alone",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx139589-oFz7JwpwRkQV.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx139589-oFz7JwpwRkQV.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx139589-oFz7JwpwRkQV.png",
},
},
{
id: 145815,
title: {
userPreferred:
"Noumin Kanren no Skill Bakka Agetetara Naze ka Tsuyoku Natta.",
english:
"I've Somehow Gotten Stronger When I Improved My Farm-Related Skills",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx145815-XsgcXy7WzgtK.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx145815-XsgcXy7WzgtK.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx145815-XsgcXy7WzgtK.png",
},
},
{
id: 176496,
title: {
userPreferred:
"Ore dake Level Up na Ken: Season 2 - Arise from the Shadow",
english: "Solo Leveling Season 2 -Arise from the Shadow-",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx176496-r6oXxEqdZL0n.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx176496-r6oXxEqdZL0n.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx176496-r6oXxEqdZL0n.jpg",
},
},
{
id: 1965,
title: {
userPreferred: "sola",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx1965-lWBpcTni9PS9.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx1965-lWBpcTni9PS9.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx1965-lWBpcTni9PS9.png",
},
},
{
id: 118123,
title: {
userPreferred: "Holo no Graffiti",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx118123-xqn5fYsjKXJU.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx118123-xqn5fYsjKXJU.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx118123-xqn5fYsjKXJU.png",
},
},
{
id: 2582,
title: {
userPreferred: "Soukou Kihei Votoms",
english: "Armored Trooper Votoms",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx2582-aB1Vh1jDobQ3.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx2582-aB1Vh1jDobQ3.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx2582-aB1Vh1jDobQ3.jpg",
},
},
{
id: 116384,
title: {
userPreferred: "Sol Levante",
english: "Sol Levante",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx116384-xn0nQAKGFSd7.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx116384-xn0nQAKGFSd7.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx116384-xn0nQAKGFSd7.png",
},
},
{
id: 104073,
title: {
userPreferred: "Sono Toki, Kanojo wa.",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/nx104073-OQ8YBTy7zmKf.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/nx104073-OQ8YBTy7zmKf.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/nx104073-OQ8YBTy7zmKf.jpg",
},
},
{
id: 15313,
title: {
userPreferred: "Wooser no Sono Higurashi",
english: "Wooser's Hand-to-Mouth Life",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/15313.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/15313.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/15313.jpg",
},
},
{
id: 8068,
title: {
userPreferred: "Kuroshitsuji Picture Drama",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/8068.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/8068.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/8068.jpg",
},
},
{
id: 3174,
title: {
userPreferred: "sola Specials",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/3174.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/3174.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/3174.jpg",
},
},
{
id: 1443,
title: {
userPreferred: "SOL BIANCA",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/1443.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/1443.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/1443.jpg",
},
},
{
id: 153431,
title: {
userPreferred: "Onna no Sono no Hoshi",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx153431-DMBYQxagH3Uu.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx153431-DMBYQxagH3Uu.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx153431-DMBYQxagH3Uu.jpg",
},
},
{
id: 1444,
title: {
userPreferred: "Sol Bianca: Taiyou no Fune",
english: "Sol Bianca: The Legacy",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx1444-7Yn6hmQ2bk9D.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx1444-7Yn6hmQ2bk9D.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx1444-7Yn6hmQ2bk9D.png",
},
},
{
id: 4138,
title: {
userPreferred: "Chiisana Pengin: Lolo no Bouken",
english: "The Adventures of Scamper the Penguin",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/4138.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/4138.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/4138.jpg",
},
},
{
id: 164192,
title: {
userPreferred: "Planetarium",
english: "Planetarium",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx164192-KQ8sYXbaAl6i.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx164192-KQ8sYXbaAl6i.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx164192-KQ8sYXbaAl6i.png",
},
},
{
id: 5838,
title: {
userPreferred: "Furudera no Obake-soudou",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/b5838-QTe07RRZylUm.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/b5838-QTe07RRZylUm.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/b5838-QTe07RRZylUm.jpg",
},
},
{
id: 162882,
title: {
userPreferred: "P.E.T.",
english: "P.E.T.",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx162882-OQENM5pXn7QQ.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx162882-OQENM5pXn7QQ.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx162882-OQENM5pXn7QQ.jpg",
},
},
{
id: 102710,
title: {
userPreferred: "Kairaku no Sono",
english: "The Garden of Pleasure",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/102710-dVayaOkzATwa.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/102710-dVayaOkzATwa.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/102710-dVayaOkzATwa.png",
},
},
{
id: 162881,
title: {
userPreferred: "Mosh Race",
english: "Mosh Race",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx162881-c7xmNA6DlHFZ.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx162881-c7xmNA6DlHFZ.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx162881-c7xmNA6DlHFZ.jpg",
},
},
{
id: 5935,
title: {
userPreferred: "Marco Polo no Boken",
english: "Marco Polo's Adventures",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/5935.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/5935.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/5935.jpg",
},
},
{
id: 103449,
title: {
userPreferred: "SOL",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/103449-FxDK8eJuMAKg.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/103449-FxDK8eJuMAKg.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/103449-FxDK8eJuMAKg.jpg",
},
},
{
id: 12993,
title: {
userPreferred: "Sono Mukou no Mukougawa",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/12993.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/12993.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/12993.jpg",
},
},
{
id: 20459,
title: {
userPreferred: "Ganbare! Lulu Lolo",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/20459.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/20459.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/20459.jpg",
},
},
{
id: 137760,
title: {
userPreferred: "Soko ni wa Mata Meikyuu",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/b137760-CleNdfmuKRy7.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/b137760-CleNdfmuKRy7.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/b137760-CleNdfmuKRy7.png",
},
},
{
id: 7473,
title: {
userPreferred: "Rennyo to Sono Haha",
english: "Rennyo and His Mother",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/7473.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/7473.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/7473.jpg",
},
},
{
id: 21418,
title: {
userPreferred: "Ganbare! Lulu Lolo 3rd Season",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/21418-TZYwdItidowx.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/21418-TZYwdItidowx.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/21418-TZYwdItidowx.jpg",
},
},
{
id: 103517,
title: {
userPreferred: "Toute wa Sono Kotae",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/103517-XgOUryeFaPDW.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/103517-XgOUryeFaPDW.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/103517-XgOUryeFaPDW.jpg",
},
},
{
id: 113572,
title: {
userPreferred: "Sono Saki no Taniji",
english: "Journey to the beyond",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/b113572-hP9x1SkRJXvA.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/b113572-hP9x1SkRJXvA.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/b113572-hP9x1SkRJXvA.jpg",
},
},
{
id: 20864,
title: {
userPreferred: "Ganbare! Lulu Lolo 2nd Season",
english: null,
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/20864.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/20864.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/20864.jpg",
},
},
{
id: 15129,
title: {
userPreferred: "Tanpen Animation Junpei Fujita",
english: "Short Animations of Junpei Fujita",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/15129.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/15129.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/15129.jpg",
},
},
{
id: 106557,
title: {
userPreferred: "Sono Ie no Namae",
english: "A Place to Name",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/nx106557-TPLmwa2EccB9.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/nx106557-TPLmwa2EccB9.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/nx106557-TPLmwa2EccB9.jpg",
},
},
{
id: 118133,
title: {
userPreferred: "Guzu no Soko",
english: "In Inertia",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/b118133-y7RvDFmr30hZ.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/b118133-y7RvDFmr30hZ.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/b118133-y7RvDFmr30hZ.jpg",
},
},
{
id: 169686,
title: {
userPreferred: "Soto ni Denai hi",
english: "Indoor Days",
},
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx169686-exScHzB5UX2D.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx169686-exScHzB5UX2D.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx169686-exScHzB5UX2D.jpg",
},
},
],
pageInfo: {
hasNextPage: false,
},
},
},
});
});
}

View File

@@ -1,70 +0,0 @@
import { HttpResponse, graphql } from "msw";
export function getAnilistTitle() {
return graphql.query(
"GetTitle",
({ variables: { id }, request: { headers } }) => {
console.log(
`Intercepting GetTitle query with ID ${id} and Authorization header ${headers.get("authorization")}`,
);
if (id === -1 || id === 50) {
return HttpResponse.json({
errors: [
{
message: "Not Found.",
status: 404,
locations: [
{
line: 2,
column: 2,
},
],
},
],
data: {
Media: null,
},
});
}
return HttpResponse.json({
data: {
Media: {
id: 135643,
idMal: 49210,
title: {
english: "The Grimm Variations",
userPreferred: "The Grimm Variations",
},
description:
'Once upon a time, brothers Jacob and Wilhelm collected fairy tales from across the land and made them into a book. They also had a much younger sister, the innocent and curious Charlotte, who they loved very much. One day, while the brothers were telling Charlotte a fairy tale like usual, they saw that she had a somewhat melancholy look on her face. She asked them, "Do you suppose they really lived happily ever after?"\n<br><br>\nThe pages of Grimms\' Fairy Tales, written by Jacob and Wilhelm, are now presented from the unique perspective of Charlotte, who sees the stories quite differently from her brothers.\n<br><br>\n(Source: Netflix Anime)',
episodes: 6,
genres: ["Fantasy", "Thriller"],
status: "FINISHED",
bannerImage:
"https://s4.anilist.co/file/anilistcdn/media/anime/banner/135643-cmQZCR3z9dB5.jpg",
averageScore: 66,
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx135643-2kJt86K9Db9P.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx135643-2kJt86K9Db9P.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx135643-2kJt86K9Db9P.jpg",
},
countryOfOrigin: "JP",
mediaListEntry: headers.has("authorization")
? {
id: 402665918,
progress: 1,
status: "CURRENT",
}
: null,
nextAiringEpisode: null,
},
},
});
},
);
}

View File

@@ -1,37 +0,0 @@
import { HttpResponse, graphql } from "msw";
export function updateAnilistWatchStatus() {
return graphql.mutation(
"UpdateWatchStatus",
({ variables: { titleId, watchStatus }, request: { headers } }) => {
console.log(
`Intercepting UpdateWatchStatus mutation with ID ${titleId}, watch status ${watchStatus} and Authorization header ${headers.get("authorization")}`,
);
if (titleId === -1) {
return HttpResponse.json({
errors: [
{
message: "validation",
status: 400,
locations: [
{
line: 2,
column: 2,
},
],
validation: {
mediaId: ["The selected media id is invalid."],
},
},
],
data: {
SaveMediaListEntry: null,
},
});
}
return HttpResponse.json({ data: { id: titleId } });
},
);
}

View File

@@ -1,31 +0,0 @@
import { HttpResponse, http } from "msw";
export function getAniwatchEpisodes() {
return http.get(
"https://aniwatch.up.railway.app/api/v2/hianime/anime/:aniListId/episodes",
({ params }) => {
const aniListId = Number(params["aniListId"]);
if (aniListId === 4) {
return HttpResponse.json({
code: 200,
message: "success",
episodes: [
{
id: "aniwatch-1",
episode: 1,
title: "EP 1",
isFiller: false,
isDub: false,
image: null,
},
],
});
}
return HttpResponse.json(
{ code: 500, message: "Server error", episodes: [] },
{ status: 500 },
);
},
);
}

View File

@@ -1,512 +0,0 @@
import { HttpResponse, http } from "msw";
export function getAniwatchSearchResults() {
return http.get(
"https://aniwatch.up.railway.app/api/v2/hianime/search",
({ request }) => {
const query = new URL(request.url).searchParams.get("query");
return HttpResponse.json({
animes: [
{
id: "naruto-shippuden-355",
name: "Naruto: Shippuden",
jname: "Naruto: Shippuuden",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/9cbcf87f54194742e7686119089478f8.jpg",
duration: "23m",
type: "TV",
rating: null,
episodes: {
sub: 500,
dub: 500,
},
},
{
id: "naruto-shippuden-the-movie-2306",
name: "Naruto: Shippuden the Movie",
jname: "Naruto: Shippuuden Movie 1",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/071ca93201eccc34a9e088013bc27807.jpg",
duration: "94m",
type: "Movie",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "naruto-shippuden-the-movie-2-bonds-2346",
name: "Naruto: Shippuden the Movie 2 -Bonds-",
jname: "Naruto: Shippuuden Movie 2 - Kizuna",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/74a112674ab92212933e41cb532689a5.jpg",
duration: "92m",
type: "Movie",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "naruto-x-ut-1840",
name: "Naruto x UT",
jname: "Naruto x UT",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/be66602efedb73c4688e302303b0a422.jpg",
duration: "6m",
type: "OVA",
rating: null,
episodes: {
sub: 1,
dub: null,
},
},
{
id: "naruto-677",
name: "Naruto",
jname: "Naruto",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/5db400c33f7494bc8ae96f9e634958d0.jpg",
duration: "23m",
type: "TV",
rating: null,
episodes: {
sub: 220,
dub: 220,
},
},
{
id: "naruto-the-movie-2-legend-of-the-stone-of-gelel-4004",
name: "Naruto the Movie 2: Legend of the Stone of Gelel",
jname:
"Naruto Movie 2: Dai Gekitotsu! Maboroshi no Chiteiiseki Dattebayo!",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/111f06edfffba5f46f5cac05db2a6bce.jpg",
duration: "97m",
type: "Movie",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "road-of-naruto-18220",
name: "Road of Naruto",
jname: "Road of Naruto",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/fd414879634ea83ad2c4fc1c33e8ac43.jpg",
duration: "9m",
type: "ONA",
rating: null,
episodes: {
sub: 1,
dub: null,
},
},
{
id: "naruto-shippuuden-movie-5-blood-prison-1642",
name: "Naruto: Shippuuden Movie 5 - Blood Prison",
jname: "Naruto: Shippuuden Movie 5 - Blood Prison",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/23a436a4ae640fa191a587b5e417bf7d.jpg",
duration: "102m",
type: "Movie",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "boruto-naruto-next-generations-8143",
name: "Boruto: Naruto Next Generations",
jname: "Boruto: Naruto Next Generations",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/32c83e2ad4a43229996356840db3982c.jpg",
duration: "23m",
type: "TV",
rating: null,
episodes: {
sub: 293,
dub: 273,
},
},
{
id: "boruto-naruto-the-movie-1391",
name: "Boruto: Naruto the Movie",
jname: "Boruto: Naruto the Movie",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/f0ad5b3ee01703cc817638973b535aa2.jpg",
duration: "95m",
type: "Movie",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "naruto-shippuuden-movie-6-road-to-ninja-1066",
name: "Naruto: Shippuuden Movie 6: Road to Ninja",
jname: "Naruto: Shippuuden Movie 6 - Road to Ninja",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/dde4a8a8ddd19648711845448d02d6d8.jpg",
duration: "109m",
type: "Movie",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "the-last-naruto-the-movie-882",
name: "The Last: Naruto the Movie",
jname: "The Last: Naruto the Movie",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/8d42031c8f566e744d84de02d42466bc.jpg",
duration: "112m",
type: "Movie",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "naruto-shippuuden-movie-3-inheritors-of-will-of-fire-2044",
name: "Naruto Shippuuden Movie 3: Inheritors of Will of Fire",
jname: "Naruto: Shippuuden Movie 3 - Hi no Ishi wo Tsugu Mono",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/1b9aad793b15265876f479c53ca7bfe1.jpg",
duration: "95m",
type: "Movie",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "naruto-shippuuden-movie-4-the-lost-tower-1821",
name: "Naruto: Shippuuden Movie 4 - The Lost Tower",
jname: "Naruto: Shippuuden Movie 4 - The Lost Tower",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/68c5ae4e5b496eb0474920659a9a85e2.jpg",
duration: "85m",
type: "Movie",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "boruto-naruto-the-movie-the-day-naruto-became-the-hokage-1805",
name: "Boruto: Naruto the Movie - The Day Naruto Became the Hokage",
jname: "Boruto: Naruto the Movie - Naruto ga Hokage ni Natta Hi",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/b19c06fae70eab67b1f390ed3cd905d8.jpg",
duration: "10m",
type: "Special",
rating: null,
episodes: {
sub: 1,
dub: null,
},
},
{
id: "naruto-the-movie-3-guardians-of-the-crescent-moon-kingdom-4005",
name: "Naruto the Movie 3: Guardians of the Crescent Moon Kingdom",
jname:
"Naruto Movie 3: Dai Koufun! Mikazuki Jima no Animaru Panikku Dattebayo!",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/73d003618cd260df44e93a5baf9acb56.jpg",
duration: "94m",
type: "Movie",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "naruto-find-the-crimson-four-leaf-clover-5694",
name: "Naruto: Find the Crimson Four-leaf Clover!",
jname: "Naruto: Akaki Yotsuba no Clover wo Sagase",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/da3a3d57e29aa0dba87cd6e1596b78e9.jpg",
duration: "17m",
type: "Special",
rating: null,
episodes: {
sub: 1,
dub: null,
},
},
{
id: "naruto-ova5-naruto-the-genie-and-the-three-wishes-3657",
name: "Naruto OVA5: Naruto, The Genie, and The Three Wishes!!",
jname:
"Naruto Soyokazeden Movie: Naruto to Mashin to Mitsu no Onegai Dattebayo!!",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/57935a347fb4328e0132c76afdd85822.jpg",
duration: "14m",
type: "OVA",
rating: null,
episodes: {
sub: 1,
dub: null,
},
},
{
id: "naruto-narutimate-hero-3-tsuini-gekitotsu-jounin-vs-genin-musabetsu-dairansen-taikai-kaisai-4485",
name: "Naruto Narutimate Hero 3: Tsuini Gekitotsu! Jounin vs. Genin!! Musabetsu Dairansen Taikai Kaisai!!",
jname:
"Naruto Narutimate Hero 3: Tsuini Gekitotsu! Jounin vs. Genin!! Musabetsu Dairansen Taikai Kaisai!!",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/939f107dc40ca24056b90c0b215bd475.jpg",
duration: "26m",
type: "OVA",
rating: null,
episodes: {
sub: 1,
dub: null,
},
},
{
id: "naruto-ova7-chunin-exam-on-fire-and-naruto-vs-konohamaru-2928",
name: "Naruto OVA7: Chunin Exam on Fire! and Naruto vs. Konohamaru!",
jname: "Naruto: Honoo no Chuunin Shiken! Naruto vs. Konohamaru!!",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/44246cdf24c85468599ff2b9496c27cb.jpg",
duration: "14m",
type: "Movie",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "naruto-the-movie-ninja-clash-in-the-land-of-snow-3162",
name: "Naruto Movie 1: Ninja Clash in the Land of Snow",
jname:
"Naruto Movie 1: Dai Katsugeki!! Yuki Hime Shinobu Houjou Dattebayo!",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/a1ab85f1eb75ec0a986e4c9d5fe04b49.jpg",
duration: "82m",
type: "Movie",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "naruto-ova9-sunny-side-battle-1916",
name: "Naruto OVA9: Sunny Side Battle",
jname: "Naruto: Shippuuden - Sunny Side Battle",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/94c836b7aff106f515b53f8eb440ccdf.jpg",
duration: "11m",
type: "Special",
rating: null,
episodes: {
sub: 1,
dub: null,
},
},
{
id: "naruto-the-cross-roads-4291",
name: "Naruto: The Cross Roads",
jname: "Naruto: The Cross Roads",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/99d7c753d9535c0d91858e4dd2a8d939.jpg",
duration: "27m",
type: "Special",
rating: null,
episodes: {
sub: 1,
dub: null,
},
},
{
id: "naruto-ova2-the-lost-story-mission-protect-the-waterfall-village-4538",
name: "Naruto OVA2: The Lost Story - Mission: Protect the Waterfall Village",
jname: "Naruto: Takigakure no Shitou - Ore ga Eiyuu Dattebayo!",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/ed2ca489d8c438c880056ea507efc93c.jpg",
duration: "40m",
type: "Special",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "naruto-ova3-hidden-leaf-village-grand-sports-festival-4136",
name: "Naruto OVA3: Hidden Leaf Village Grand Sports Festival",
jname:
"Naruto: Dai Katsugeki!! Yuki Hime Shinobu Houjou Dattebayo! - Konoha no Sato no Dai Undoukai",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/b4bb0d2caaa9591fdb3c442738d7f87a.jpg",
duration: "11m",
type: "Special",
rating: null,
episodes: {
sub: 1,
dub: 1,
},
},
{
id: "naruto-spin-off-rock-lee-his-ninja-pals-2992",
name: "NARUTO Spin-Off: Rock Lee & His Ninja Pals",
jname: "Naruto SD: Rock Lee no Seishun Full-Power Ninden",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/37f8b16b0f693e433207117abe5daf44.jpg",
duration: "24m",
type: "TV",
rating: null,
episodes: {
sub: 51,
dub: 51,
},
},
],
mostPopularAnimes: [
{
id: "one-piece-100",
name: "One Piece",
jname: "One Piece",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/bcd84731a3eda4f4a306250769675065.jpg",
episodes: {
sub: 1116,
dub: 1085,
},
type: "TV",
},
{
id: "naruto-shippuden-355",
name: "Naruto: Shippuden",
jname: "Naruto: Shippuuden",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/9cbcf87f54194742e7686119089478f8.jpg",
episodes: {
sub: 500,
dub: 500,
},
type: "TV",
},
{
id: "jujutsu-kaisen-2nd-season-18413",
name: "Jujutsu Kaisen 2nd Season",
jname: "Jujutsu Kaisen 2nd Season",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/b51f863b05f30576cf9d85fa9b911bb5.png",
episodes: {
sub: 23,
dub: 23,
},
type: "TV",
},
{
id: "bleach-806",
name: "Bleach",
jname: "Bleach",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/bd5ae1d387a59c5abcf5e1a6a616728c.jpg",
episodes: {
sub: 366,
dub: 366,
},
type: "TV",
},
{
id: "black-clover-2404",
name: "Black Clover",
jname: "Black Clover",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/f58b0204c20ae3310f65ae7b8cb9987e.jpg",
episodes: {
sub: 170,
dub: 170,
},
type: "TV",
},
{
id: "demon-slayer-kimetsu-no-yaiba-swordsmith-village-arc-18056",
name: "Demon Slayer: Kimetsu no Yaiba Swordsmith Village Arc",
jname: "Kimetsu no Yaiba: Katanakaji no Sato-hen",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/db2f3ce7b9cab7fdc160b005bffb899a.png",
episodes: {
sub: 11,
dub: 11,
},
type: "TV",
},
{
id: "boruto-naruto-next-generations-8143",
name: "Boruto: Naruto Next Generations",
jname: "Boruto: Naruto Next Generations",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/32c83e2ad4a43229996356840db3982c.jpg",
episodes: {
sub: 293,
dub: 273,
},
type: "TV",
},
{
id: "naruto-677",
name: "Naruto",
jname: "Naruto",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/5db400c33f7494bc8ae96f9e634958d0.jpg",
episodes: {
sub: 220,
dub: 220,
},
type: "TV",
},
{
id: "jujutsu-kaisen-tv-534",
name: "Jujutsu Kaisen (TV)",
jname: "Jujutsu Kaisen (TV)",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/82402f796b7d84d7071ab1e03ff7747a.jpg",
episodes: {
sub: 24,
dub: 24,
},
type: "TV",
},
{
id: "spy-x-family-17977",
name: "Spy x Family",
jname: "Spy x Family",
poster:
"https://cdn.noitatnemucod.net/thumbnail/300x400/100/88bd17534dc4884f23027035d23d74e5.jpg",
episodes: {
sub: 12,
dub: 12,
},
type: "TV",
},
],
currentPage: 1,
hasNextPage: false,
totalPages: 1,
searchQuery: "naruto-shippuden-355",
searchFilters: {},
});
},
);
}

View File

@@ -1,53 +0,0 @@
import { HttpResponse, http } from "msw";
export function getAniwatchSources() {
return http.get(
"https://aniwatch.up.railway.app/api/v2/hianime/episode/sources",
({ request }) => {
const url = new URL(request.url);
const id = url.searchParams.get("id");
if (id === "unknown") {
return HttpResponse.json(
{
code: 404,
message:
"The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.",
},
{ status: 404 },
);
}
return HttpResponse.json({
tracks: [
{
file: "https://s.megastatics.com/subtitle/4ea42fb35b93b7a2d8e69ca8fe55c0e5/eng-2.vtt",
label: "English",
kind: "captions",
default: true,
},
{
file: "https://s.megastatics.com/thumbnails/be7d997958cdf9b9444d910c2c28645e/thumbnails.vtt",
kind: "thumbnails",
},
],
intro: {
start: 258,
end: 347,
},
outro: {
start: 1335,
end: 1424,
},
sources: [
{
url: "https://vd2.biananset.net/_v7/26c0c3f5b635f5b9153fca5d43037bb06875d79b3f1528ca69ac83f8e14c90a48cce237316cbf6fa12de243f1dca5118b8dbb767aff155b79ad687a75905004314bee838cdbd8bea083910d6f660f3e29ebb5bb3e48dd9b30816c31737fc8fdf9dd123a7ea937c5594fb9daf540e6a4e6aecef840e23f0fe9cfe20638e3467a2/master.m3u8",
type: "hls",
},
],
anilistID: 153406,
malID: 52635,
});
},
);
}

View File

@@ -1,24 +0,0 @@
import { mock } from "bun:test";
mock.module("cloudflare:workers", () => ({
env: {
ADMIN_SDK_JSON: JSON.stringify({
type: "service_account",
projectId: "test-26g38",
privateKeyId: "privateKeyId",
privateKey: "privateKey",
clientEmail: "test@test.com",
clientID: "clientId",
authURI: "https://accounts.google.com/o/oauth2/auth",
tokenURI: "https://oauth2.googleapis.com/token",
authProviderX509CertUrl: "https://www.googleapis.com/oauth2/v1/certs",
clientX509CertUrl:
"https://www.googleapis.com/robot/v1/metadata/x509/test%40test.com",
universeDomain: "aniplay.com",
}),
ANIWATCH_URL: "https://aniwatch.to",
CONSUMET_URL: "https://api.consumet.org",
ANILIST_URL: "https://graphql.anilist.co",
GOOGLE_AUTH_URL: "https://www.googleapis.com/oauth2/v4/token",
},
}));

View File

@@ -1,35 +0,0 @@
import type { IAnimeEpisode, ISource } from "@consumet/extensions";
import { mock } from "bun:test";
mock.module("src/consumet", () => ({
aniList: {
fetchEpisodesListById(
id: string,
dub?: boolean | undefined,
fetchFiller?: boolean | undefined,
): Promise<IAnimeEpisode[]> {
if (id === "3") {
return Promise.resolve([
{
id: "consumet-1",
number: 1,
title: "Consumet 1",
},
]);
}
return Promise.resolve([]);
},
fetchEpisodeSources(episodeId: string, ...args: any): Promise<ISource> {
if (episodeId === "unknown") {
return Promise.resolve({ sources: [] });
}
return Promise.resolve({
sources: [{ url: "https://consumet.com" }],
subtitles: [],
});
},
},
}));

View File

@@ -1,76 +0,0 @@
import { HttpResponse, http } from "msw";
import type { FcmMessagePayload } from "~/libs/gcloud/sendFcmMessage";
export function mockFcmMessageResponse() {
return http.post<{}, { message: FcmMessagePayload; validate_only: boolean }>(
"https://fcm.googleapis.com/v1/projects/test-26g38/messages:send",
async ({ request }) => {
const { message } = await request.json();
const { name, token } = message;
if (name === "token_verification") {
if (token?.length === 163) {
return HttpResponse.json({ name });
}
return HttpResponse.json({
error: {
code: 400,
message:
"The registration token is not a valid FCM registration token",
status: "INVALID_ARGUMENT",
details: [
{
"@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
errorCode: "INVALID_ARGUMENT",
},
],
},
});
}
return HttpResponse.json(message);
},
);
}
export function mockCreateGcloudTask() {
return http.post<{}, { task: { name: string } }>(
"https://content-cloudtasks.googleapis.com/v2/projects/test-26g38/locations/northamerica-northeast1/queues/new-episode/tasks",
async ({ request }) => {
const {
task: { name },
} = await request.json();
return HttpResponse.json({ name });
},
);
}
export function mockDeleteGcloudTask() {
return http.delete<{ taskId: string }>(
"https://content-cloudtasks.googleapis.com/v2/projects/test-26g38/locations/northamerica-northeast1/queues/new-episode/tasks/:taskId",
async ({ params }) => {
const { taskId } = params;
if (taskId === "123") {
return HttpResponse.json({
error: {
code: 404,
message: "Task not found",
status: "NOT_FOUND",
details: [
{
"@type": "type.googleapis.com/google.rpc.Status",
code: 5,
message: "Task not found",
},
],
},
});
}
return HttpResponse.json({ messageId: "123" });
},
);
}

View File

@@ -1,41 +0,0 @@
import type { TokenOptions } from "gtoken";
import { mock } from "bun:test";
import type { AdminSdkCredentials } from "~/libs/gcloud/getAdminSdkCredentials";
const emailRegex =
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
class MockGoogleToken {
private email: string | undefined;
constructor(options: TokenOptions) {
this.email = options.email;
}
getToken() {
console.log("getToken", this.email);
if (!this.email) {
return Promise.reject("No email provided");
}
if (!emailRegex.test(this.email)) {
return Promise.reject("Invalid email");
}
return Promise.resolve({
access_token: "asd",
});
}
}
mock.module("src/libs/gcloud/getGoogleAuthToken", () => {
return {
getGoogleAuthToken: (adminSdkJson: AdminSdkCredentials) => {
return new MockGoogleToken({
email: adminSdkJson.clientEmail,
}).getToken();
},
};
});

View File

@@ -1,29 +0,0 @@
import { deleteAnilistMediaListEntry } from "./anilist/deleteMediaListEntry";
import { getAnilistMediaListEntry } from "./anilist/mediaListEntry";
import { getAnilistNextAiringEpisode } from "./anilist/nextAiringEpisode";
import { getAnilistSearchResults } from "./anilist/search";
import { getAnilistTitle } from "./anilist/title";
import { updateAnilistWatchStatus } from "./anilist/updateWatchStatus";
import { getAniwatchEpisodes } from "./aniwatch/episodes";
import { getAniwatchSearchResults } from "./aniwatch/search";
import { getAniwatchSources } from "./aniwatch/sources";
import {
mockCreateGcloudTask,
mockDeleteGcloudTask,
mockFcmMessageResponse,
} from "./gcloud";
export const handlers = [
deleteAnilistMediaListEntry(),
getAnilistMediaListEntry(),
getAnilistNextAiringEpisode(),
getAnilistSearchResults(),
getAnilistTitle(),
updateAnilistWatchStatus(),
getAniwatchEpisodes(),
getAniwatchSearchResults(),
getAniwatchSources(),
mockCreateGcloudTask(),
mockDeleteGcloudTask(),
mockFcmMessageResponse(),
];

View File

@@ -1,5 +1,105 @@
import { setupServer } from "msw/node";
import type { Episode } from "~/types/episode";
import type { FetchUrlResponseSchema } from "~/types/episode/fetch-url-response";
import type { Title } from "~/types/title";
import type { HomeTitle } from "~/types/title/homeTitle";
import { handlers } from "./handlers";
/**
* Mock data for search results
*/
export const mockSearchResults: HomeTitle[] = [
{
id: 151807,
title: "Solo Leveling",
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx151807-yxY3olrjZH4k.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx151807-yxY3olrjZH4k.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx151807-yxY3olrjZH4k.png",
},
},
{
id: 139589,
title: "Kotaro Lives Alone",
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx139589-oFz7JwpwRkQV.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx139589-oFz7JwpwRkQV.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx139589-oFz7JwpwRkQV.png",
},
},
{
id: 176496,
title: "Solo Leveling Season 2 -Arise from the Shadow-",
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx176496-r6oXxEqdZL0n.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx176496-r6oXxEqdZL0n.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx176496-r6oXxEqdZL0n.jpg",
},
},
];
export const server = setupServer(...handlers);
/**
* Mock data for title details
*/
export const mockTitleDetails: () => Title = () => ({
id: Math.floor(Math.random() * 1000000),
idMal: Math.floor(Math.random() * 1000000),
title: {
userPreferred: "The Grimm Variations",
english: "The Grimm Variations",
},
description:
'Once upon a time, brothers Jacob and Wilhelm collected fairy tales from across the land and made them into a book. They also had a much younger sister, the innocent and curious Charlotte, who they loved very much. One day, while the brothers were telling Charlotte a fairy tale like usual, they saw that she had a somewhat melancholy look on her face. She asked them, "Do you suppose they really lived happily ever after?"<br><br>\nThe pages of Grimms\' Fairy Tales, written by Jacob and Wilhelm, are now presented from the unique perspective of Charlotte, who sees the stories quite differently from her brothers.<br><br>\n(Source: Netflix Anime)',
episodes: 6,
genres: ["Fantasy", "Thriller"],
status: "FINISHED",
bannerImage:
"https://s4.anilist.co/file/anilistcdn/media/anime/banner/135643-cmQZCR3z9dB5.jpg",
averageScore: 66,
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx135643-2kJt86K9Db9P.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx135643-2kJt86K9Db9P.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx135643-2kJt86K9Db9P.jpg",
},
countryOfOrigin: "JP",
mediaListEntry: null,
nextAiringEpisode: null,
});
/**
* Mock data for episode URL
* Using Big Buck Bunny test video
*/
export const mockEpisodeUrl: FetchUrlResponseSchema = {
source: "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8",
subtitles: [],
audio: [],
intro: null,
outro: null,
headers: {},
};
/**
* Mock data for episodes list
* Returns a sample list of 50 episodes for testing
*/
export const mockEpisodes: () => Episode[] = () => {
const randomId = Math.floor(Math.random() * 1000000);
return Array.from({ length: 50 }, (_, i) => ({
id: `${randomId}-episode-${i + 1}`,
number: i + 1,
title: `Episode ${i + 1}`,
isFiller: false,
updatedAt: 0,
}));
};

View File

@@ -1,105 +0,0 @@
import type { Episode } from "~/types/episode";
import type { FetchUrlResponseSchema } from "~/types/episode/fetch-url-response";
import type { Title } from "~/types/title";
import type { HomeTitle } from "~/types/title/homeTitle";
/**
* Mock data for search results
*/
export const mockSearchResults: HomeTitle[] = [
{
id: 151807,
title: "Solo Leveling",
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx151807-yxY3olrjZH4k.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx151807-yxY3olrjZH4k.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx151807-yxY3olrjZH4k.png",
},
},
{
id: 139589,
title: "Kotaro Lives Alone",
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx139589-oFz7JwpwRkQV.png",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx139589-oFz7JwpwRkQV.png",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx139589-oFz7JwpwRkQV.png",
},
},
{
id: 176496,
title: "Solo Leveling Season 2 -Arise from the Shadow-",
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx176496-r6oXxEqdZL0n.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx176496-r6oXxEqdZL0n.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx176496-r6oXxEqdZL0n.jpg",
},
},
];
/**
* Mock data for title details
*/
export const mockTitleDetails: () => Title = () => ({
id: Math.floor(Math.random() * 1000000),
idMal: Math.floor(Math.random() * 1000000),
title: {
userPreferred: "The Grimm Variations",
english: "The Grimm Variations",
},
description:
'Once upon a time, brothers Jacob and Wilhelm collected fairy tales from across the land and made them into a book. They also had a much younger sister, the innocent and curious Charlotte, who they loved very much. One day, while the brothers were telling Charlotte a fairy tale like usual, they saw that she had a somewhat melancholy look on her face. She asked them, "Do you suppose they really lived happily ever after?"<br><br>\nThe pages of Grimms\' Fairy Tales, written by Jacob and Wilhelm, are now presented from the unique perspective of Charlotte, who sees the stories quite differently from her brothers.<br><br>\n(Source: Netflix Anime)',
episodes: 6,
genres: ["Fantasy", "Thriller"],
status: "FINISHED",
bannerImage:
"https://s4.anilist.co/file/anilistcdn/media/anime/banner/135643-cmQZCR3z9dB5.jpg",
averageScore: 66,
coverImage: {
extraLarge:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx135643-2kJt86K9Db9P.jpg",
large:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx135643-2kJt86K9Db9P.jpg",
medium:
"https://s4.anilist.co/file/anilistcdn/media/anime/cover/small/bx135643-2kJt86K9Db9P.jpg",
},
countryOfOrigin: "JP",
mediaListEntry: null,
nextAiringEpisode: null,
});
/**
* Mock data for episode URL
* Using Big Buck Bunny test video
*/
export const mockEpisodeUrl: FetchUrlResponseSchema = {
source: "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8",
subtitles: [],
audio: [],
intro: null,
outro: null,
headers: {},
};
/**
* Mock data for episodes list
* Returns a sample list of 50 episodes for testing
*/
export const mockEpisodes: () => Episode[] = () => {
const randomId = Math.floor(Math.random() * 1000000);
return Array.from({ length: 50 }, (_, i) => ({
id: `${randomId}-episode-${i + 1}`,
number: i + 1,
title: `Episode ${i + 1}`,
isFiller: false,
updatedAt: 0,
}));
};

View File

@@ -1,15 +1,9 @@
// import { createClient } from "@libsql/client";
import { env as cloudflareEnv } from "cloudflare:workers";
import { drizzle } from "drizzle-orm/d1";
type Db = ReturnType<typeof drizzle>;
// let db: Db | null = null;
export function getDb(env: Cloudflare.Env = cloudflareEnv): Db {
// if (db) {
// return db;
// }
const db = drizzle(env.DB, { logger: true });
return db;
}

View File

@@ -0,0 +1,109 @@
import { GraphQLError } from "graphql";
import { describe, expect, it, vi } from "vitest";
import { markEpisodeAsWatched } from "~/services/episodes/markEpisodeAsWatched/anilist";
import { markEpisodeAsWatchedMutation } from "./markEpisodeAsWatched";
vi.mock("~/services/episodes/markEpisodeAsWatched/anilist", () => ({
markEpisodeAsWatched: vi.fn(),
}));
vi.mock("~/services/watch-status", () => ({
updateWatchStatus: vi.fn(),
}));
describe("markEpisodeAsWatched mutation", () => {
it("should throw GraphQLError if aniListToken is missing", async () => {
await expect(
markEpisodeAsWatchedMutation(
null,
{ input: { titleId: 1, episodeNumber: 1, isComplete: false } },
{ aniListToken: undefined } as any,
),
).rejects.toThrow(
new GraphQLError(
"AniList token is required. Please provide X-AniList-Token header.",
{
extensions: { code: "UNAUTHORIZED" },
},
),
);
});
it("should call markEpisodeAsWatched service", async () => {
vi.mocked(markEpisodeAsWatched).mockResolvedValue({} as any);
await markEpisodeAsWatchedMutation(
null,
{ input: { titleId: 1, episodeNumber: 1, isComplete: false } },
{ aniListToken: "token" } as any,
);
expect(markEpisodeAsWatched).toHaveBeenCalledWith("token", 1, 1, false);
});
it("should update watch status locally if isComplete is true and deviceId is present", async () => {
vi.mocked(markEpisodeAsWatched).mockResolvedValue({} as any);
const { updateWatchStatus } = await import("~/services/watch-status");
await markEpisodeAsWatchedMutation(
null,
{ input: { titleId: 1, episodeNumber: 1, isComplete: true } },
{ aniListToken: "token", deviceId: "device-id" } as any,
);
expect(updateWatchStatus).toHaveBeenCalledWith("device-id", 1, "COMPLETED");
});
it("should not update watch status locally if deviceId is missing", async () => {
vi.mocked(markEpisodeAsWatched).mockResolvedValue({} as any);
const { updateWatchStatus } = await import("~/services/watch-status");
vi.mocked(updateWatchStatus).mockClear();
const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
await markEpisodeAsWatchedMutation(
null,
{ input: { titleId: 1, episodeNumber: 1, isComplete: true } },
{ aniListToken: "token" } as any,
);
expect(updateWatchStatus).not.toHaveBeenCalled();
expect(consoleSpy).toHaveBeenCalledWith(
"Device ID not found in context, skipping watch status update",
);
});
it("should throw GraphQLError if service return null", async () => {
vi.mocked(markEpisodeAsWatched).mockResolvedValue(null as any);
await expect(
markEpisodeAsWatchedMutation(
null,
{ input: { titleId: 1, episodeNumber: 1, isComplete: false } },
{ aniListToken: "token" } as any,
),
).rejects.toThrow(
new GraphQLError("Failed to mark episode as watched", {
extensions: { code: "INTERNAL_SERVER_ERROR" },
}),
);
});
it("should catch errors and throw GraphQLError", async () => {
vi.mocked(markEpisodeAsWatched).mockRejectedValue(new Error("Foo"));
await expect(
markEpisodeAsWatchedMutation(
null,
{ input: { titleId: 1, episodeNumber: 1, isComplete: false } },
{ aniListToken: "token" } as any,
),
).rejects.toThrow(
new GraphQLError("Failed to mark episode as watched", {
extensions: { code: "INTERNAL_SERVER_ERROR" },
}),
);
});
});

View File

@@ -0,0 +1,55 @@
import { GraphQLError } from "graphql";
import { describe, expect, it, vi } from "vitest";
import { updateWatchStatus } from "~/services/watch-status";
import { updateWatchStatusMutation } from "./updateWatchStatus";
vi.mock("~/services/watch-status", () => ({
updateWatchStatus: vi.fn(),
}));
describe("updateWatchStatus mutation", () => {
it("should throw GraphQLError if deviceId is missing", async () => {
await expect(
updateWatchStatusMutation(
null,
{ input: { titleId: 1, watchStatus: "CURRENT" } },
{ deviceId: undefined } as any,
),
).rejects.toThrow(
new GraphQLError(
"Device ID is required. Please provide X-Device-ID header.",
{
extensions: { code: "BAD_REQUEST" },
},
),
);
});
it("should call updateWatchStatus service with correct parameters", async () => {
await updateWatchStatusMutation(
null,
{ input: { titleId: 1, watchStatus: "CURRENT" } },
{ deviceId: "device-id" } as any,
);
expect(updateWatchStatus).toHaveBeenCalledWith("device-id", 1, "CURRENT");
});
it("should catch service errors and throw GraphQLError", async () => {
vi.mocked(updateWatchStatus).mockRejectedValue(new Error("Service error"));
await expect(
updateWatchStatusMutation(
null,
{ input: { titleId: 1, watchStatus: "CURRENT" } },
{ deviceId: "device-id" } as any,
),
).rejects.toThrow(
new GraphQLError("Failed to update watch status", {
extensions: { code: "INTERNAL_SERVER_ERROR" },
}),
);
});
});

View File

@@ -0,0 +1,91 @@
import { env } from "cloudflare:workers";
import { GraphQLError } from "graphql";
import { describe, expect, it, vi } from "vitest";
import type { GraphQLContext } from "~/context";
import { home } from "./home";
enum HomeCategory {
WATCHING,
PLANNING,
}
describe("home resolver", () => {
const mockContext = {
user: { name: "testuser" },
aniListToken: "test-token",
} as GraphQLContext;
it("should fetch WATCHING titles using CURRENT status filter", async () => {
const mockResponse = { some: "data" };
const mockStub = {
getTitles: vi.fn().mockResolvedValue(mockResponse),
};
// @ts-expect-error - Partial mock
env.ANILIST_DO = {
getByName: vi.fn().mockResolvedValue(mockStub),
};
const result = await home(
null,
{ category: HomeCategory.WATCHING },
mockContext,
);
expect(result).toEqual(mockResponse);
expect(env.ANILIST_DO.getByName).toHaveBeenCalledWith("GLOBAL");
expect(mockStub.getTitles).toHaveBeenCalledWith(
"testuser",
1,
["CURRENT"],
"test-token",
);
});
it("should fetch PLANNING titles using PLANNING, PAUSED, REPEATING status filters", async () => {
const mockResponse = { some: "data" };
const mockStub = {
getTitles: vi.fn().mockResolvedValue(mockResponse),
};
// @ts-expect-error - Partial mock
env.ANILIST_DO = {
getByName: vi.fn().mockResolvedValue(mockStub),
};
const result = await home(
null,
{ category: HomeCategory.PLANNING, page: 2 },
mockContext,
);
expect(result).toEqual(mockResponse);
expect(mockStub.getTitles).toHaveBeenCalledWith(
"testuser",
2,
["PLANNING", "PAUSED", "REPEATING"],
"test-token",
);
});
it("should throw GraphQLError if Durable Object response is null", async () => {
const mockStub = {
getTitles: vi.fn().mockResolvedValue(null),
};
// @ts-expect-error - Partial mock
env.ANILIST_DO = {
getByName: vi.fn().mockResolvedValue(mockStub),
};
await expect(
home(null, { category: HomeCategory.WATCHING }, mockContext),
).rejects.toThrow(
new GraphQLError("Failed to fetch 0 titles", {
extensions: { code: "INTERNAL_SERVER_ERROR" },
}),
);
});
});

View File

@@ -0,0 +1,51 @@
import { GraphQLError } from "graphql";
import { describe, expect, it, vi } from "vitest";
import { fetchPopularTitlesFromAnilist } from "~/services/popular/browse/anilist";
import { popularBrowse } from "./popularBrowse";
vi.mock("~/services/popular/browse/anilist", () => ({
fetchPopularTitlesFromAnilist: vi.fn(),
}));
describe("popularBrowse resolver", () => {
it("should fetch titles with default limit", async () => {
const mockResponse = {
trending: ["trending"],
popular: ["popular"],
upcoming: ["upcoming"],
};
vi.mocked(fetchPopularTitlesFromAnilist).mockResolvedValue(mockResponse);
const result = await popularBrowse(null, {}, {} as any);
expect(result).toEqual(mockResponse);
expect(fetchPopularTitlesFromAnilist).toHaveBeenCalledWith(10);
});
it("should fetch titles with provided limit", async () => {
const mockResponse = {};
vi.mocked(fetchPopularTitlesFromAnilist).mockResolvedValue(mockResponse);
await popularBrowse(null, { limit: 20 }, {} as any);
expect(fetchPopularTitlesFromAnilist).toHaveBeenCalledWith(20);
});
it("should throw GraphQLError if service returns null", async () => {
vi.mocked(fetchPopularTitlesFromAnilist).mockResolvedValue(undefined);
await expect(popularBrowse(null, {}, {} as any)).rejects.toThrow(
new GraphQLError("Failed to fetch popular titles", {
extensions: { code: "INTERNAL_SERVER_ERROR" },
}),
);
});
it("should map response correctly to trending, popular, and upcoming", async () => {
vi.mocked(fetchPopularTitlesFromAnilist).mockResolvedValue({} as any);
const result = await popularBrowse(null, {}, {} as any);
expect(result).toEqual({ trending: [], popular: [], upcoming: [] });
});
});

View File

@@ -0,0 +1,59 @@
import { GraphQLError } from "graphql";
import { describe, expect, it, vi } from "vitest";
import { fetchPopularTitlesFromAnilist } from "~/services/popular/category/anilist";
import { popularByCategory } from "./popularByCategory";
vi.mock("~/services/popular/category/anilist", () => ({
fetchPopularTitlesFromAnilist: vi.fn(),
}));
describe("popularByCategory resolver", () => {
it("should fetch titles for a specific category with page and limit", async () => {
const mockResponse = { results: ["title"], hasNextPage: true };
vi.mocked(fetchPopularTitlesFromAnilist).mockResolvedValue(
mockResponse as any,
);
const result = await popularByCategory(
null,
{ category: "trending", page: 2, limit: 20 },
{} as any,
);
expect(result).toEqual(mockResponse);
expect(fetchPopularTitlesFromAnilist).toHaveBeenCalledWith(
"trending",
2,
20,
);
});
it("should use default page and limit", async () => {
const mockResponse = { results: [], hasNextPage: false };
vi.mocked(fetchPopularTitlesFromAnilist).mockResolvedValue(
mockResponse as any,
);
await popularByCategory(null, { category: "popular" }, {} as any);
expect(fetchPopularTitlesFromAnilist).toHaveBeenCalledWith(
"popular",
1,
10,
);
});
it("should throw GraphQLError if service returns null", async () => {
vi.mocked(fetchPopularTitlesFromAnilist).mockResolvedValue(undefined);
await expect(
popularByCategory(null, { category: "upcoming" }, {} as any),
).rejects.toThrow(
new GraphQLError("Failed to fetch upcoming titles", {
extensions: { code: "INTERNAL_SERVER_ERROR" },
}),
);
});
});

View File

@@ -0,0 +1,44 @@
import { GraphQLError } from "graphql";
import { describe, expect, it, vi } from "vitest";
import { getUser } from "~/services/auth/anilist/getUser";
import { user } from "./user";
vi.mock("~/services/auth/anilist/getUser", () => ({
getUser: vi.fn(),
}));
describe("user resolver", () => {
it("should throw GraphQLError (UNAUTHORIZED) if aniListToken is missing", async () => {
await expect(
user(null, {}, { aniListToken: undefined } as any),
).rejects.toThrow(
new GraphQLError("Unauthorized", {
extensions: { code: "UNAUTHORIZED" },
}),
);
});
it("should fetch user if token is present", async () => {
const mockUser = { id: 1, name: "test" };
vi.mocked(getUser).mockResolvedValue(mockUser as any);
const result = await user(null, {}, { aniListToken: "token" } as any);
expect(result).toEqual(mockUser);
expect(getUser).toHaveBeenCalledWith("token");
});
it("should throw GraphQLError if user service returns null", async () => {
vi.mocked(getUser).mockResolvedValue(null);
await expect(
user(null, {}, { aniListToken: "token" } as any),
).rejects.toThrow(
new GraphQLError("Failed to fetch user", {
extensions: { code: "INTERNAL_SERVER_ERROR" },
}),
);
});
});

View File

@@ -1,47 +0,0 @@
import { $ } from "bun";
import { Project } from "ts-morph";
import { logStep } from "~/libs/logStep";
await logStep(
'Re-generating "env.d.ts"',
() => $`bunx wrangler types src/types/env.d.ts`.quiet(),
"Generated env.d.ts",
);
const secretNames = await logStep(
"Fetching secrets from Cloudflare",
async (): Promise<string[]> => {
const { stdout } = await $`bunx wrangler secret list`.quiet();
return JSON.parse(stdout.toString()).map(
(secret: { name: string; type: "secret_text" }) => secret.name,
);
},
"Fetched secrets",
);
const project = new Project({});
const envSourceFile = project.addSourceFileAtPath("src/types/env.d.ts");
envSourceFile.insertImportDeclaration(2, {
isTypeOnly: true,
moduleSpecifier: "hono",
namedImports: ["Env as HonoEnv"],
});
envSourceFile
.getInterfaceOrThrow("Env")
.addExtends(["HonoEnv", "Record<string, unknown>"]);
envSourceFile.getInterfaceOrThrow("Env").addProperties(
secretNames.map((name) => ({
name,
type: `string`,
})),
);
await project.save();
await logStep(
"Formatting env.d.ts",
() => $`bunx prettier --write src/types/env.d.ts`.quiet(),
"Formatted env.d.ts",
);

View File

@@ -1,42 +0,0 @@
import { $, sleep, spawn } from "bun";
import { readFile } from "fs/promises";
import { logStep } from "~/libs/logStep";
await $`cp src/types/env.d.ts /tmp/env.d.ts`.quiet();
await logStep(
'Generating "env.d.ts"',
() => import("./generateEnv"),
"Generated env.d.ts",
);
await logStep("Comparing env.d.ts", async () => {
function filterComments(content: Buffer) {
return content
.toString()
.split("\n")
.filter((line) => !line.trim().startsWith("//"))
.join("\n");
}
const currentFileContent = filterComments(await readFile("/tmp/env.d.ts"));
const generatedFileContent = filterComments(
await readFile("src/types/env.d.ts"),
);
if (currentFileContent === generatedFileContent) {
console.log("env.d.ts is up to date");
return;
}
const isCI = process.env["IS_CI"] === "true";
const vcsCommand = isCI ? "git" : "sl";
spawn({
cmd: [vcsCommand, "diff", "src/types/env.d.ts"],
stdout: "inherit",
});
// add 1 second to make sure spawn completes
await sleep(1000);
throw new Error("env.d.ts is out of date");
});

View File

@@ -0,0 +1,54 @@
import { env } from "cloudflare:workers";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getUser } from "./getUser";
describe("getUser service", () => {
const mockStub = {
getUserProfile: vi.fn(),
};
beforeEach(() => {
vi.clearAllMocks();
// @ts-expect-error - Partial mock
env.ANILIST_DO = {
idFromName: vi.fn().mockReturnValue("global-id"),
get: vi.fn().mockReturnValue(mockStub),
};
});
it("should fetch user profile from Durable Object", async () => {
const mockUser = { id: 1, name: "User", statistics: { anime: {} } };
mockStub.getUserProfile.mockResolvedValue(mockUser);
const result = await getUser("token");
expect(result).toEqual({
...mockUser,
statistics: mockUser.statistics.anime,
});
expect(mockStub.getUserProfile).toHaveBeenCalledWith("token");
});
it("should return null if DO throws 401 error", async () => {
mockStub.getUserProfile.mockRejectedValue(new Error("401 Unauthorized"));
const result = await getUser("token");
expect(result).toBeNull();
});
it("should rethrow other DO errors", async () => {
mockStub.getUserProfile.mockRejectedValue(new Error("Other Error"));
await expect(getUser("token")).rejects.toThrow("Other Error");
});
it("should return null if DO returns null", async () => {
mockStub.getUserProfile.mockResolvedValue(null);
const result = await getUser("token");
expect(result).toBeNull();
});
});

View File

@@ -7,7 +7,7 @@ export async function fetchEpisodes(
// Check if we should use mock data
const { useMockData } = await import("~/libs/useMockData");
if (useMockData()) {
const { mockEpisodes } = await import("~/mocks/mockData");
const { mockEpisodes } = await import("~/mocks");
return mockEpisodes();
}

View File

@@ -1,47 +1,71 @@
import { describe, expect, it } from "bun:test";
import { beforeEach, describe, expect, it, vi } from "vitest";
import app from "~/index";
import { server } from "~/mocks";
import { fetchEpisodeUrl } from "./index";
server.listen();
describe("fetchEpisodeUrl", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('requests the "/episodes/:id/url" route', () => {
it("with sources from Aniwatch", async () => {
const response = await app.request(
"/episodes/4/url",
(global.fetch as any).mockResolvedValue({
ok: true,
json: async () => ({
status: 200,
data: {
tracks: [],
intro: { start: 258, end: 347 },
outro: { start: 1335, end: 1424 },
sources: [
{
method: "POST",
body: JSON.stringify({
episodeNumber: 1,
url: "https://www032.vipanicdn.net/streamhls/aa804a2400535d84dd59454b28d329fb/ep.1.1712504065.m3u8",
type: "hls",
},
],
anilistID: 153406,
malID: 52635,
},
}),
headers: { "Content-Type": "application/json" },
},
{
ENABLE_ANIFY: "true",
},
);
});
expect(response.json()).resolves.toEqual({
const result = await fetchEpisodeUrl({
id: "4",
aniListId: 153406,
episodeNumber: 1,
});
expect(result).toEqual({
success: true,
result: {
source:
"https://www032.vipanicdn.net/streamhls/aa804a2400535d84dd59454b28d329fb/ep.1.1712504065.m3u8",
subtitles: [],
audio: [],
intro: [258, 347],
outro: [1335, 1424],
headers: undefined,
},
});
});
it("with no URL from Aniwatch source", async () => {
const response = await app.request("/episodes/-1/url", {
method: "POST",
body: JSON.stringify({
episodeNumber: -1,
(global.fetch as any).mockResolvedValue({
ok: true,
json: async () => ({
status: 200,
data: {
sources: [],
sub: [],
},
}),
headers: { "Content-Type": "application/json" },
});
expect(response.json()).resolves.toEqual({ success: false });
expect(response.status).toBe(404);
const result = await fetchEpisodeUrl({
id: "4",
aniListId: 153406,
episodeNumber: 1,
});
expect(result).toEqual({ success: false });
});
});

View File

@@ -1,3 +1,4 @@
import { useMockData } from "~/libs/useMockData";
import { FetchUrlResponse } from "~/types/episode/fetch-url-response";
import { fetchEpisodes } from "../getByAniListId";
@@ -13,6 +14,11 @@ export async function fetchEpisodeUrl({
aniListId: number;
episodeNumber: number;
}): Promise<FetchUrlResponse | null> {
if (useMockData()) {
const { mockEpisodeUrl } = await import("~/mocks");
return { success: true, result: mockEpisodeUrl };
}
try {
let episodeId = id;
if (!id) {

View File

@@ -0,0 +1,64 @@
import { env } from "cloudflare:workers";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { markEpisodeAsWatched } from "./anilist";
describe("markEpisodeAsWatched service", () => {
const mockStub = {
markTitleAsWatched: vi.fn(),
markEpisodeAsWatched: vi.fn(),
};
beforeEach(() => {
vi.clearAllMocks();
// @ts-expect-error - Partial mock
env.ANILIST_DO = {
idFromName: vi.fn().mockReturnValue("global-id"),
get: vi.fn().mockReturnValue(mockStub),
};
});
it("should call markTitleAsWatched on DO if markTitleAsComplete is true", async () => {
mockStub.markTitleAsWatched.mockResolvedValue({
user: { id: 1, statistics: { anime: {} } },
});
const result = await markEpisodeAsWatched("token", 1, 12, true);
expect(result).toBeDefined();
expect(mockStub.markTitleAsWatched).toHaveBeenCalledWith(1, "token");
expect(mockStub.markEpisodeAsWatched).not.toHaveBeenCalled();
});
it("should call markEpisodeAsWatched on DO if markTitleAsComplete is false", async () => {
mockStub.markEpisodeAsWatched.mockResolvedValue({
user: { id: 1, statistics: { anime: {} } },
});
const result = await markEpisodeAsWatched("token", 1, 12, false);
expect(result).toBeDefined();
expect(mockStub.markEpisodeAsWatched).toHaveBeenCalledWith(1, 12, "token");
expect(mockStub.markTitleAsWatched).not.toHaveBeenCalled();
});
it("should throw error if DO returns null", async () => {
mockStub.markEpisodeAsWatched.mockResolvedValue(null);
await expect(markEpisodeAsWatched("token", 1, 12, false)).rejects.toThrow(
"Failed to mark episode as watched",
);
});
it("should return formatted user data", async () => {
const mockUser = { id: 1, statistics: { anime: { count: 10 } } };
mockStub.markEpisodeAsWatched.mockResolvedValue({ user: mockUser });
const result = await markEpisodeAsWatched("token", 1, 12, false);
expect(result).toEqual({
...mockUser,
statistics: { count: 10 },
});
});
});

View File

@@ -0,0 +1,84 @@
import { env } from "cloudflare:workers";
import { describe, expect, it, vi } from "vitest";
import { fetchPopularTitlesFromAnilist } from "./anilist";
// Mock getCurrentAndNextSeason
vi.mock("~/libs/getCurrentAndNextSeason", () => ({
getCurrentAndNextSeason: vi.fn(() => ({
current: { season: "WINTER", year: 2024 },
next: { season: "SPRING", year: 2024 },
})),
}));
vi.mock("../mapTitle", () => ({
mapTitle: vi.fn((title) => ({ id: title.id, title: title.title })),
}));
describe("fetchPopularTitlesFromAnilist (Browse)", () => {
it("should fetch popular titles from Durable Object with current/next season info", async () => {
const mockReponse = {
trending: { media: [{ id: 1, title: "Trending" }] },
season: { media: [{ id: 2, title: "Popular" }] },
nextSeason: {
media: [
{
id: 3,
title: "Upcoming",
nextAiringEpisode: { airingAt: 123 },
},
],
},
};
const mockNextSeasonResponse = {
Page: { media: [{ id: 4, title: "Next Season Popular" }] },
};
const mockStub = {
browsePopular: vi.fn().mockResolvedValue(mockReponse),
nextSeasonPopular: vi.fn().mockResolvedValue(mockNextSeasonResponse),
};
// @ts-expect-error - Partial mock
env.ANILIST_DO = {
getByName: vi.fn().mockReturnValue(mockStub),
};
const result = await fetchPopularTitlesFromAnilist(10);
expect(result.trending).toHaveLength(1);
expect(result.popular).toHaveLength(1);
expect(result.upcoming).toHaveLength(1);
expect(mockStub.browsePopular).toHaveBeenCalledWith(
"WINTER",
2024,
"SPRING",
2024,
10,
);
expect(mockStub.nextSeasonPopular).toHaveBeenCalledWith("SPRING", 2024, 10);
});
it("should handle missing next season data gracefully (return only trending/popular)", async () => {
const mockReponse = {
trending: { media: [{ id: 1, title: "Trending" }] },
season: { media: [{ id: 2, title: "Popular" }] },
nextSeason: { media: [] },
};
const mockStub = {
browsePopular: vi.fn().mockResolvedValue(mockReponse),
};
// @ts-expect-error - Partial mock
env.ANILIST_DO = {
getByName: vi.fn().mockReturnValue(mockStub),
};
const result = await fetchPopularTitlesFromAnilist(10);
expect(result.trending).toHaveLength(1);
expect(result.popular).toHaveLength(1);
expect(result.upcoming).toBeUndefined(); // Or check implementation if it returns empty array or undefined
});
});

View File

@@ -0,0 +1,90 @@
import { env } from "cloudflare:workers";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fetchPopularTitlesFromAnilist } from "./anilist";
// Mock getCurrentAndNextSeason
vi.mock("~/libs/getCurrentAndNextSeason", () => ({
getCurrentAndNextSeason: vi.fn(() => ({
current: { season: "WINTER", year: 2024 },
next: { season: "SPRING", year: 2024 },
})),
}));
vi.mock("../mapTitle", () => ({
mapTitle: vi.fn((title) => ({ id: title.id, title: title.title })),
}));
describe("fetchPopularTitlesFromAnilist (Category)", () => {
const mockStub = {
getTrendingTitles: vi.fn(),
getPopularTitles: vi.fn(),
nextSeasonPopular: vi.fn(),
};
beforeEach(() => {
vi.clearAllMocks();
// @ts-expect-error - Partial mock
env.ANILIST_DO = {
idFromName: vi.fn().mockReturnValue("global-id"),
get: vi.fn().mockReturnValue(mockStub),
};
});
it("should fetch 'trending' titles from Durable Object", async () => {
mockStub.getTrendingTitles.mockResolvedValue({
media: [{ id: 1, title: "Trending" }],
pageInfo: { hasNextPage: true },
});
const result = await fetchPopularTitlesFromAnilist("trending", 1, 10);
expect(result.results).toHaveLength(1);
expect(result.hasNextPage).toBe(true);
expect(mockStub.getTrendingTitles).toHaveBeenCalledWith(1, 10);
});
it("should fetch 'popular' titles from Durable Object", async () => {
mockStub.getPopularTitles.mockResolvedValue({
media: [{ id: 2, title: "Popular" }],
pageInfo: { hasNextPage: false },
});
const result = await fetchPopularTitlesFromAnilist("popular", 1, 10);
expect(result.results).toHaveLength(1);
expect(mockStub.getPopularTitles).toHaveBeenCalledWith(
1,
10,
"WINTER",
2024,
);
});
it("should fetch 'upcoming' titles from Durable Object", async () => {
mockStub.nextSeasonPopular.mockResolvedValue({
media: [{ id: 3, title: "Upcoming" }],
pageInfo: { hasNextPage: true },
});
const result = await fetchPopularTitlesFromAnilist("upcoming", 1, 10);
expect(result.results).toHaveLength(1);
expect(mockStub.nextSeasonPopular).toHaveBeenCalledWith("SPRING", 2024, 10);
});
it("should throw error for unknown category", async () => {
await expect(
fetchPopularTitlesFromAnilist("unknown" as any, 1, 10),
).rejects.toThrow("Unknown category: unknown");
});
it("should return empty results if DO returns null", async () => {
mockStub.getTrendingTitles.mockResolvedValue(null);
const result = await fetchPopularTitlesFromAnilist("trending", 1, 10);
expect(result.results).toEqual([]);
expect(result.hasNextPage).toBe(false);
});
});

View File

@@ -8,7 +8,7 @@ export async function fetchSearchResultsFromAnilist(
// Check if we should use mock data
const { useMockData } = await import("~/libs/useMockData");
if (useMockData()) {
const { mockSearchResults } = await import("~/mocks/mockData");
const { mockSearchResults } = await import("~/mocks");
// Paginate mock results
const startIndex = (page - 1) * limit;

View File

@@ -0,0 +1,72 @@
import { describe, expect, it, vi } from "vitest";
import { maybeUpdateWatchStatusOnAnilist } from "./anilist";
const mockRequest = vi.fn();
vi.mock("graphql-request", () => ({
GraphQLClient: vi.fn(() => ({
request: mockRequest,
})),
}));
vi.mock("~/libs/errors/TitleNotFound", () => ({
AnilistTitleNotFoundError: class extends Error {
constructor() {
super("AnilistTitleNotFoundError");
}
},
}));
describe("maybeUpdateWatchStatusOnAnilist service", () => {
it("should return true immediately if token is missing", async () => {
const result = await maybeUpdateWatchStatusOnAnilist(
1,
"CURRENT",
undefined,
);
expect(result).toBe(true);
});
it("should perform SaveMediaListEntry mutation if watch status is provided", async () => {
mockRequest.mockResolvedValue({ SaveMediaListEntry: { id: 123 } });
const result = await maybeUpdateWatchStatusOnAnilist(1, "CURRENT", "token");
expect(result).toBe(true);
expect(mockRequest).toHaveBeenCalledWith(
expect.anything(),
{ titleId: 1, watchStatus: "CURRENT" },
expect.anything(),
);
});
it("should perform DeleteMediaListEntry if watch status is null", async () => {
mockRequest
.mockResolvedValueOnce({ Media: { mediaListEntry: { id: 456 } } }) // Fetch ID
.mockResolvedValueOnce({ DeleteMediaListEntry: { deleted: true } }); // Delete
const result = await maybeUpdateWatchStatusOnAnilist(1, null, "token");
expect(result).toBe(true);
// First call to get ID
expect(mockRequest).toHaveBeenCalledWith(
expect.anything(),
{ titleId: 1 },
expect.anything(),
);
// Second call to delete
expect(mockRequest).toHaveBeenCalledWith(
expect.anything(),
{ entryId: 456 },
expect.anything(),
);
});
it("should throw AnilistTitleNotFoundError if trying to delete non-existent entry", async () => {
mockRequest.mockResolvedValueOnce({ Media: { mediaListEntry: null } });
await expect(
maybeUpdateWatchStatusOnAnilist(1, null, "token"),
).rejects.toThrow("AnilistTitleNotFoundError");
});
});

View File

@@ -1,44 +0,0 @@
import { formatCmd } from "node_modules/zx/build/util";
import { $, minimist } from "zx";
import { getTestEnvVariables } from "./libs/test/getTestEnv";
const args = minimist(process.argv.slice(2));
if (!args["dbCommand"]) {
throw new Error("dbCommand is required");
}
const filteredKeys = new Set(["_", "dbCommand", "db", "$0", "db-command"]);
const positionalArgs = Object.entries(args)
.filter(([key]) => !filteredKeys.has(key))
.map(([key, value]) => {
if (typeof value === "boolean") {
return `--${key}`;
}
return `--${key}=${value}`;
})
.concat(args._);
console.log(formatCmd(args["dbCommand"]));
const dbProcess = $({ quote: (arg) => arg })`${args["dbCommand"]}`;
let exitCode = 0;
try {
$.env = {
...getTestEnvVariables(),
PATH: process.env["PATH"],
HOME: process.env["HOME"],
SHOULD_LOG_ERRORS: process.env["SHOULD_LOG_ERRORS"] ?? "true",
};
await $`bun db:migrate`;
const testProcess = await $({
verbose: true,
quote: (arg) => arg,
})`FORCE_COLOR=1 bun test ${positionalArgs.join(" ")}`.nothrow();
exitCode = (await testProcess.exitCode) ?? 0;
} finally {
await dbProcess.kill("SIGINT");
}
process.exit(exitCode);

View File

@@ -1,3 +1,26 @@
if (process.env.SHOULD_LOG_ERRORS === "false") {
console.error = () => {};
import { vi } from "vitest";
const shouldLogErrors = process.env["SHOULD_LOG_ERRORS"] === "true";
if (!shouldLogErrors) {
const originalConsoleError = console.error;
console.error = (...args) => {
// Suppress specific error messages
if (
args[0]?.includes?.("Error: No email provided") ||
args[0]?.includes?.('TypeError: "pkcs8" must be PKCS#8 formatted string')
) {
return;
}
originalConsoleError(...args);
};
}
global.fetch = vi.fn();
vi.mock("cloudflare:workers", () => {
return {
env: {},
DurableObject: class DurableObject {},
};
});

View File

@@ -1,32 +1,26 @@
{
"compilerOptions": {
"types": ["@types/bun"],
"baseUrl": "./",
"paths": {
"~/*": ["src/*"]
},
// Enable latest features
"lib": ["ESNext"],
"target": "ESNext",
"module": "ESNext",
// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
// Some stricter flags
"noUnusedLocals": true,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": true,
// plugins
"plugins": [
{

View File

@@ -1,8 +1,26 @@
import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config";
import {
defineWorkersProject,
readD1Migrations,
} from "@cloudflare/vitest-pool-workers/config";
import tsconfigPaths from "vite-tsconfig-paths";
import { configDefaults } from "vitest/config";
export default defineWorkersConfig({
import path from "node:path";
export default defineWorkersProject(async () => {
const migrationsPath = path.join(__dirname, "drizzle");
let migrations: Awaited<ReturnType<typeof readD1Migrations>>;
try {
migrations = await readD1Migrations(migrationsPath);
} catch (e) {
console.warn("Could not read migrations", e);
migrations = [];
}
return {
plugins: [tsconfigPaths()],
test: {
globals: true,
globals: false,
setupFiles: ["./testSetup.ts"],
poolOptions: {
workers: {
@@ -10,15 +28,21 @@ export default defineWorkersConfig({
},
},
coverage: {
provider: "v8",
...configDefaults.coverage,
provider: "istanbul",
reporter: ["text", "json", "html"],
exclude: [
...configDefaults.coverage.exclude,
"node_modules/**",
"dist/**",
"**/*.spec.ts",
"**/*.d.ts",
"**/mocks/**",
"drizzle.config.ts",
"src/schema.ts",
"src/libs/test",
],
},
},
};
});