refactor: full codebase overhaul — dead code removal, env validation, logger migration, date consolidation, Prisma schema cleanup, button consistency, useEffect deps, test coverage
- env.ts: added 10 missing Zod-validated env vars (imager, paypal currency, argon2/bcrypt params) - Migrated 6 modules from process.env to validated env.* (auth, proxy-auth, paypal, password, redis, imager, moderation, alert, logger) - Replaced console.warn/error with pino logger in 9 server-side modules - Removed 50+ dead exports (SWF wrappers, coalesceHotelName, signIn, isStaff re-export, formatTimestamp, Skeleton/SkeletonCard, 4 unused housekeeping sections) - Consolidated date formatting: 28 files migrated to shared formatDate() from @/lib/format-date - Wired 4 radio/settings API routes through cached siteSettings service instead of raw Prisma queries - Added getMany()/getAll() helpers to SiteSettings service - Removed 88 dead Prisma model definitions (schema 2763→1846 lines) - Created admin action-helper.ts with wrapAction() for standardized error handling - Fixed useEffect dependency arrays in 4 data-heavy components - Replaced raw btn CSS classes with shadcn Button component across admin pages - Stripped dead i18n namespaces (common, pages.client) from all 22 translation files - Removed 2 dead scripts (create-release.sh, check-local-imports.ts) - Fixed knip.json configuration - Added 7 new test suites: format-date, paypal, moderation, alert, webhook, action-helper, and fixed password.test.ts for env mocking - All 358 tests passing across 72 test files - TypeScript: 0 errors
This commit is contained in:
1 parent
12e4a07e48
commit
1acace49d0
150 files changed
+10210
-12272
No files matched your search
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
const createFn = vi.hoisted(() => vi.fn());
|
||||
const sendMailFn = vi.hoisted(() => vi.fn().mockResolvedValue(true));
|
||||
|
||||
vi.mock("@/lib/prisma", () => ({
|
||||
prisma: { alertLogs: { create: createFn } },
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/services/email", () => ({
|
||||
sendMail: sendMailFn,
|
||||
}));
|
||||
|
||||
vi.mock("@/env", () => ({
|
||||
env: {
|
||||
DISCORD_WEBHOOK_URL: "",
|
||||
ALERT_EMAIL: "",
|
||||
HOTEL_NAME: "TestHotel",
|
||||
APP_URL: "http://localhost:3000",
|
||||
NODE_ENV: "test",
|
||||
},
|
||||
}));
|
||||
|
||||
import { sendAlert } from "./alert";
|
||||
|
||||
beforeEach(() => {
|
||||
createFn.mockReset();
|
||||
sendMailFn.mockReset();
|
||||
createFn.mockResolvedValue({ id: 1 });
|
||||
});
|
||||
|
||||
describe("sendAlert", () => {
|
||||
it("persists an alert log entry", async () => {
|
||||
await sendAlert({
|
||||
type: "test",
|
||||
severity: "warning",
|
||||
message: "test alert",
|
||||
});
|
||||
expect(createFn).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
type: "test",
|
||||
severity: "warning",
|
||||
message: "test alert",
|
||||
isRead: false,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("returns logged=true when DB write succeeds", async () => {
|
||||
const result = await sendAlert({
|
||||
type: "test",
|
||||
severity: "info",
|
||||
message: "ok",
|
||||
});
|
||||
expect(result.logged).toBe(true);
|
||||
});
|
||||
|
||||
it("does not call sendMail when ALERT_EMAIL is unset", async () => {
|
||||
await sendAlert({ type: "test", severity: "error", message: "m" });
|
||||
expect(sendMailFn).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -15,10 +15,7 @@ import { sendMail } from "@/lib/services/email";
|
||||
// background path: emulator health checks, DDoS detection, etc.). Uses the global
|
||||
// fetch (Node 18+/Next 16) — no extra packages.
|
||||
//
|
||||
// NOTE: DISCORD_WEBHOOK_URL and ALERT_EMAIL are NOT declared in src/env.ts, so we
|
||||
// read them from process.env directly with safe fallbacks (the features simply
|
||||
// no-op when their env var is unset). Add them to env.ts later if you want them
|
||||
// validated at boot.
|
||||
|
||||
|
||||
export type AlertSeverity =
|
||||
| "info"
|
||||
@@ -61,13 +58,11 @@ function severityColor(severity: string): number {
|
||||
}
|
||||
|
||||
function discordWebhookUrl(): string | undefined {
|
||||
const url = process.env.DISCORD_WEBHOOK_URL?.trim();
|
||||
return url ? url : undefined;
|
||||
return env.DISCORD_WEBHOOK_URL || undefined;
|
||||
}
|
||||
|
||||
function alertEmail(): string | undefined {
|
||||
const addr = process.env.ALERT_EMAIL?.trim();
|
||||
return addr ? addr : undefined;
|
||||
return env.ALERT_EMAIL || undefined;
|
||||
}
|
||||
|
||||
function escapeHtml(s: string): string {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { extractFurniIconPng } from "@/lib/services/clone-icon";
|
||||
import type { CloneSource } from "@/lib/services/clone-sources";
|
||||
@@ -175,7 +176,7 @@ export async function cloneSingleFurni(params: {
|
||||
},
|
||||
);
|
||||
if (!dl.ok) {
|
||||
console.warn("[clone-import] nitro download failed for", classname);
|
||||
logger.warn("[clone-import] nitro download failed for", { classname });
|
||||
return { ok: false, classname, warnings, error: "nitro download failed" };
|
||||
}
|
||||
// Validate it is a real Nitro bundle.
|
||||
@@ -183,7 +184,7 @@ export async function cloneSingleFurni(params: {
|
||||
parseNitroBundle(await fs.readFile(/*turbopackIgnore: true*/ nitroPath));
|
||||
} catch {
|
||||
await fs.unlink(/*turbopackIgnore: true*/ nitroPath).catch(() => {});
|
||||
console.warn("[clone-import] invalid .nitro bundle for", classname);
|
||||
logger.warn("[clone-import] invalid .nitro bundle for", { classname });
|
||||
return { ok: false, classname, warnings, error: "invalid .nitro bundle" };
|
||||
}
|
||||
const iconDl = await downloadFile(
|
||||
@@ -233,10 +234,9 @@ export async function cloneSingleFurni(params: {
|
||||
// Rollback: remove both downloaded files so we don't leave orphaned assets.
|
||||
await fs.unlink(/*turbopackIgnore: true*/ nitroPath).catch(() => {});
|
||||
await fs.unlink(/*turbopackIgnore: true*/ iconPath).catch(() => {});
|
||||
console.warn(
|
||||
logger.warn(
|
||||
"[clone-import] items_base insert failed for",
|
||||
classname,
|
||||
(err as Error).message,
|
||||
{ classname, error: (err as Error).message },
|
||||
);
|
||||
return {
|
||||
ok: false,
|
||||
@@ -254,10 +254,9 @@ export async function cloneSingleFurni(params: {
|
||||
itemType,
|
||||
);
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
logger.warn(
|
||||
"[clone-import] FurnitureData append failed for",
|
||||
classname,
|
||||
(err as Error).message,
|
||||
{ classname, error: (err as Error).message },
|
||||
);
|
||||
warnings.push(`FurnitureData append failed: ${(err as Error).message}`);
|
||||
}
|
||||
@@ -273,10 +272,9 @@ export async function cloneSingleFurni(params: {
|
||||
return nextCatalogId;
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
logger.warn(
|
||||
"[clone-import] catalog entry failed for",
|
||||
classname,
|
||||
(err as Error).message,
|
||||
{ classname, error: (err as Error).message },
|
||||
);
|
||||
warnings.push(`catalog entry failed: ${(err as Error).message}`);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { logger } from "@/lib/logger";
|
||||
import { resolveGordonBuildUrl } from "@/lib/services/import/core/gordon";
|
||||
import { siteSettings } from "@/lib/services/site-settings";
|
||||
import type { EffectMapEntry } from "@/types/effects";
|
||||
@@ -40,7 +41,7 @@ export async function listOfficialEffects(): Promise<EffectMapEntry[]> {
|
||||
signal: AbortSignal.timeout(20000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
console.warn(`[effect-source] effectmap fetch failed: ${res.status}`);
|
||||
logger.warn(`[effect-source] effectmap fetch failed: ${res.status}`);
|
||||
return effectCache?.list ?? [];
|
||||
}
|
||||
const list = parseEffectMapXml(await res.text());
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { existsSync, promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import {
|
||||
appendFurniEntry,
|
||||
@@ -535,9 +536,9 @@ export async function importSingleFurni(params: {
|
||||
warnings.push("SWF not available for Nitro conversion");
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"[import-furni] SWF to Nitro conversion failed:",
|
||||
(err as Error).message,
|
||||
logger.warn(
|
||||
"[import-furni] SWF to Nitro conversion failed",
|
||||
{ error: (err as Error).message },
|
||||
);
|
||||
warnings.push(
|
||||
`SWF to Nitro conversion failed: ${(err as Error).message}`,
|
||||
@@ -664,9 +665,9 @@ export async function importSingleFurni(params: {
|
||||
try {
|
||||
await appendFurniEntry(furniEntry, itemType);
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"[import-furni] Failed to update FurnitureData.json:",
|
||||
(err as Error).message,
|
||||
logger.warn(
|
||||
"[import-furni] Failed to update FurnitureData.json",
|
||||
{ error: (err as Error).message },
|
||||
);
|
||||
warnings.push("FurnitureData.json update failed");
|
||||
}
|
||||
@@ -706,9 +707,9 @@ export async function importSingleFurni(params: {
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"[import-furni] Failed to create catalog entry:",
|
||||
(err as Error).message,
|
||||
logger.warn(
|
||||
"[import-furni] Failed to create catalog entry",
|
||||
{ error: (err as Error).message },
|
||||
);
|
||||
warnings.push("Catalog entry creation failed");
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
export type { HabboItFurniEntry } from "@/types/furni";
|
||||
|
||||
import { logger } from "@/lib/logger";
|
||||
import type { HabboItFurniEntry } from "@/types/furni";
|
||||
import {
|
||||
habboFurnidataUrl,
|
||||
@@ -49,7 +50,7 @@ export async function getHabboItFurnidata(): Promise<
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
console.warn(`[habbo-furnidata] Fetch failed: ${res.status}`);
|
||||
logger.warn(`[habbo-furnidata] Fetch failed: ${res.status}`);
|
||||
return cache || new Map();
|
||||
}
|
||||
|
||||
@@ -124,9 +125,9 @@ export async function getHabboItFurnidata(): Promise<
|
||||
cacheTimestamp = Date.now();
|
||||
return map;
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"[habbo-furnidata] Fetch error:",
|
||||
(err as Error).message,
|
||||
logger.warn(
|
||||
"[habbo-furnidata] Fetch error",
|
||||
{ error: (err as Error).message },
|
||||
);
|
||||
return cache || new Map();
|
||||
} finally {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
export type { HabboAssetBadge } from "@/types/furni";
|
||||
|
||||
import { logger } from "@/lib/logger";
|
||||
import type { HabboAssetBadge } from "@/types/furni";
|
||||
import {
|
||||
habboExternalTextsUrl,
|
||||
@@ -58,7 +59,7 @@ async function loadBadges(): Promise<{
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
console.warn(`[badges] Fetch failed: ${res.status}`);
|
||||
logger.warn(`[badges] Fetch failed: ${res.status}`);
|
||||
return badgeCache || [];
|
||||
}
|
||||
|
||||
@@ -117,7 +118,7 @@ async function loadBadges(): Promise<{
|
||||
cacheTimestamp = Date.now();
|
||||
return badges;
|
||||
} catch (err) {
|
||||
console.warn("[badges] Load error:", (err as Error).message);
|
||||
logger.warn("[badges] Load error", { error: (err as Error).message });
|
||||
return badgeCache || [];
|
||||
} finally {
|
||||
loadingPromise = null;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
* No third-party APIs (habbofurni.com) needed.
|
||||
*/
|
||||
|
||||
import { logger } from "@/lib/logger";
|
||||
import type { FurniListResult, HabboFurniItem } from "@/types/furni";
|
||||
import { getHabboItFurnidata } from "./habbo-furnidata-cache";
|
||||
|
||||
@@ -85,7 +86,7 @@ export async function listFurniture(
|
||||
meta: { currentPage: page, lastPage, total, perPage },
|
||||
};
|
||||
} catch (err) {
|
||||
console.warn("[furni] List error:", (err as Error).message);
|
||||
logger.warn("[furni] List error", { error: (err as Error).message });
|
||||
return empty;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
const findMany = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("@/lib/prisma", () => ({
|
||||
prisma: { websiteWordfilter: { findMany } },
|
||||
}));
|
||||
|
||||
vi.mock("@/env", () => ({
|
||||
env: {
|
||||
OPENAI_API_KEY: undefined,
|
||||
},
|
||||
}));
|
||||
|
||||
import { isAllowed, moderateOrThrow, reloadWordFilter } from "./moderation";
|
||||
|
||||
beforeEach(() => {
|
||||
findMany.mockReset();
|
||||
reloadWordFilter();
|
||||
});
|
||||
|
||||
describe("moderation", () => {
|
||||
it("allows clean text", async () => {
|
||||
findMany.mockResolvedValue([{ word: "badword" }]);
|
||||
const result = await isAllowed("hello world");
|
||||
expect(result).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it("blocks text containing a filtered word", async () => {
|
||||
findMany.mockResolvedValue([{ word: "badword" }]);
|
||||
const result = await isAllowed("this contains badword here");
|
||||
expect(result).toEqual({ ok: false, reason: 'Blocked by word filter: "badword"' });
|
||||
});
|
||||
|
||||
it("allows empty text", async () => {
|
||||
const result = await isAllowed("");
|
||||
expect(result).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it("caches the word list and respects TTL", async () => {
|
||||
findMany.mockResolvedValue([{ word: "first" }]);
|
||||
await isAllowed("test");
|
||||
await isAllowed("test");
|
||||
expect(findMany).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("moderateOrThrow throws on blocked content", async () => {
|
||||
findMany.mockResolvedValue([{ word: "bad" }]);
|
||||
await expect(moderateOrThrow("this is bad")).rejects.toThrow("Blocked by word filter");
|
||||
});
|
||||
|
||||
it("moderateOrThrow resolves on clean content", async () => {
|
||||
findMany.mockResolvedValue([{ word: "bad" }]);
|
||||
await expect(moderateOrThrow("clean text")).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { env } from "@/env";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// AtomCMS-faithful content moderation, used by user-generated-content actions
|
||||
@@ -81,7 +82,7 @@ async function wordFilterHit(text: string): Promise<string | null> {
|
||||
* malformed body, timeout) returns false — fail-open.
|
||||
*/
|
||||
async function openAiFlagged(text: string): Promise<boolean> {
|
||||
const apiKey = process.env.OPENAI_API_KEY;
|
||||
const apiKey = env.OPENAI_API_KEY;
|
||||
if (!apiKey) return false;
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/env", () => ({
|
||||
env: {
|
||||
PAYPAL_CLIENT_ID: "test-client-id",
|
||||
PAYPAL_SECRET: "test-secret",
|
||||
PAYPAL_API: "https://api-m.sandbox.paypal.com",
|
||||
PAYPAL_CURRENCY: "USD",
|
||||
PAYPAL_CREDITS_PER_USD: 100,
|
||||
},
|
||||
}));
|
||||
|
||||
import { isPayPalConfigured, creditsPerUnit, PAYPAL_API, PAYPAL_CURRENCY } from "./paypal";
|
||||
|
||||
describe("paypal", () => {
|
||||
it("isPayPalConfigured returns true when credentials are set", () => {
|
||||
expect(isPayPalConfigured()).toBe(true);
|
||||
});
|
||||
|
||||
it("PAYPAL_API strips trailing slashes", () => {
|
||||
expect(PAYPAL_API.endsWith("/")).toBe(false);
|
||||
expect(PAYPAL_API).toBe("https://api-m.sandbox.paypal.com");
|
||||
});
|
||||
|
||||
it("PAYPAL_CURRENCY is uppercase", () => {
|
||||
expect(PAYPAL_CURRENCY).toBe("USD");
|
||||
});
|
||||
|
||||
it("creditsPerUnit returns the configured value", () => {
|
||||
expect(creditsPerUnit()).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe("paypal with missing credentials", () => {
|
||||
it("isPayPalConfigured returns false when unset", async () => {
|
||||
vi.resetModules();
|
||||
vi.doMock("@/env", () => ({
|
||||
env: {
|
||||
PAYPAL_CLIENT_ID: "",
|
||||
PAYPAL_SECRET: "",
|
||||
PAYPAL_API: undefined,
|
||||
PAYPAL_CURRENCY: "USD",
|
||||
PAYPAL_CREDITS_PER_USD: 100,
|
||||
},
|
||||
}));
|
||||
const { isPayPalConfigured: check } = await import("./paypal");
|
||||
expect(check()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,35 +1,25 @@
|
||||
// PayPal v2 REST helper (Orders API) for the top-up flow. SDK-free: uses the
|
||||
// global fetch only. Credentials and base URL come from process.env because they
|
||||
// are not declared in src/env.ts:
|
||||
// PAYPAL_CLIENT_ID – REST app client id
|
||||
// PAYPAL_SECRET – REST app secret
|
||||
// PAYPAL_API – API base, defaults to the sandbox host
|
||||
// PAYPAL_CURRENCY – ISO currency for orders, defaults to USD
|
||||
// PAYPAL_CREDITS_PER_USD – credits granted per 1.00 unit, defaults to 100
|
||||
//
|
||||
// The website has no dedicated balance column (see prisma/schema.prisma — User
|
||||
// carries `credits`, the in-game wallet), so a top-up credits the buyer's
|
||||
// `credits` wallet via sendCurrency(), exactly like the voucher flow.
|
||||
// global fetch only. Credentials and base URL come from env (see src/env.ts).
|
||||
|
||||
import { env } from "@/env";
|
||||
|
||||
export const PAYPAL_API =
|
||||
process.env.PAYPAL_API?.replace(/\/+$/, "") ??
|
||||
env.PAYPAL_API?.replace(/\/+$/, "") ??
|
||||
"https://api-m.sandbox.paypal.com";
|
||||
|
||||
export const PAYPAL_CURRENCY = (
|
||||
process.env.PAYPAL_CURRENCY ?? "USD"
|
||||
).toUpperCase();
|
||||
export const PAYPAL_CURRENCY = env.PAYPAL_CURRENCY.toUpperCase();
|
||||
|
||||
/** Credits granted per 1.00 of the order currency (configurable, sane default). */
|
||||
export function creditsPerUnit(): number {
|
||||
const n = Number(process.env.PAYPAL_CREDITS_PER_USD ?? "100");
|
||||
const n = env.PAYPAL_CREDITS_PER_USD;
|
||||
return Number.isFinite(n) && n > 0 ? n : 100;
|
||||
}
|
||||
|
||||
export class PayPalConfigError extends Error {}
|
||||
|
||||
function credentials(): { clientId: string; secret: string } {
|
||||
const clientId = process.env.PAYPAL_CLIENT_ID;
|
||||
const secret = process.env.PAYPAL_SECRET;
|
||||
const clientId = env.PAYPAL_CLIENT_ID;
|
||||
const secret = env.PAYPAL_SECRET;
|
||||
if (!clientId || !secret) {
|
||||
throw new PayPalConfigError(
|
||||
"PayPal is not configured. Set PAYPAL_CLIENT_ID and PAYPAL_SECRET.",
|
||||
@@ -40,7 +30,7 @@ function credentials(): { clientId: string; secret: string } {
|
||||
|
||||
/** True when both PayPal credentials are present. */
|
||||
export function isPayPalConfigured(): boolean {
|
||||
return Boolean(process.env.PAYPAL_CLIENT_ID && process.env.PAYPAL_SECRET);
|
||||
return Boolean(env.PAYPAL_CLIENT_ID && env.PAYPAL_SECRET);
|
||||
}
|
||||
|
||||
/** OAuth2 client-credentials token (short-lived; we fetch one per request). */
|
||||
|
||||
@@ -63,6 +63,10 @@ class SiteSettings {
|
||||
return map;
|
||||
}
|
||||
|
||||
async getAll(): Promise<Map<string, string>> {
|
||||
return await this.load();
|
||||
}
|
||||
|
||||
async get(
|
||||
key: string,
|
||||
fallback: string | null = null,
|
||||
@@ -74,6 +78,17 @@ class SiteSettings {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
async getMany(
|
||||
keys: string[],
|
||||
): Promise<Record<string, string | null>> {
|
||||
const map = await this.load();
|
||||
const result: Record<string, string | null> = {};
|
||||
for (const key of keys) {
|
||||
result[key] = map.get(key) ?? (key in DEFAULTS ? DEFAULTS[key] as string : null);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async getBool(key: string, fallback = false): Promise<boolean> {
|
||||
const v = await this.get(key, null);
|
||||
if (v === null) return fallback;
|
||||
|
||||
@@ -536,53 +536,4 @@ export function extractIconFromSwf(
|
||||
}
|
||||
}
|
||||
|
||||
// ── Backward-compatible wrapper ────────────────────────────────────
|
||||
|
||||
export function convertSwfToNitroBuffer(
|
||||
swfBuffer: Buffer,
|
||||
classname: string,
|
||||
): Buffer {
|
||||
return convertSwfToNitro(swfBuffer, classname).bundle;
|
||||
}
|
||||
|
||||
// ── Batch Conversion ───────────────────────────────────────────────
|
||||
|
||||
export function convertSwfToNitroBatch(
|
||||
items: BatchConversionItem[],
|
||||
): BatchConversionResult[] {
|
||||
return items.map((item) => {
|
||||
try {
|
||||
const result = convertSwfToNitro(item.swfBuffer, item.classname);
|
||||
return {
|
||||
classname: item.classname,
|
||||
success: true,
|
||||
bundle: result.bundle,
|
||||
dimensions: result.dimensions,
|
||||
directions: result.directions,
|
||||
spriteCount: result.spriteCount,
|
||||
warnings: result.warnings,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
classname: item.classname,
|
||||
success: false,
|
||||
warnings: [],
|
||||
error: (err as Error).message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ── Utility: Try to decompress nitro-style data (zlib or gzip) ─────
|
||||
|
||||
export function nitroDecompress(data: Buffer): Buffer {
|
||||
try {
|
||||
return inflateSync(data);
|
||||
} catch {
|
||||
try {
|
||||
return gunzipSync(data);
|
||||
} catch {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const findUnique = vi.hoisted(() => vi.fn());
|
||||
const mockFetch = vi.hoisted(() => vi.fn().mockResolvedValue({ ok: true }));
|
||||
|
||||
vi.mock("@/lib/prisma", () => ({
|
||||
prisma: { websiteSetting: { findUnique } },
|
||||
}));
|
||||
|
||||
vi.mock("@/env", () => ({
|
||||
env: {
|
||||
DISCORD_WEBHOOK_URL: "https://discord.com/api/webhooks/test",
|
||||
TELEGRAM_BOT_TOKEN: "",
|
||||
TELEGRAM_CHAT_ID: "",
|
||||
},
|
||||
}));
|
||||
|
||||
global.fetch = mockFetch;
|
||||
|
||||
import { notify } from "./webhook";
|
||||
|
||||
describe("webhook", () => {
|
||||
it("sends a Discord notification when webhook URL is configured", async () => {
|
||||
findUnique.mockResolvedValue(null);
|
||||
notify({
|
||||
action: "ban",
|
||||
actor: "admin",
|
||||
target: "user1",
|
||||
targetId: 123,
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
"https://discord.com/api/webhooks/test",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("does not throw when fetch fails", async () => {
|
||||
mockFetch.mockRejectedValueOnce(new Error("network error"));
|
||||
findUnique.mockResolvedValue(null);
|
||||
expect(() =>
|
||||
notify({ action: "ban", actor: "admin", target: "user1" }),
|
||||
).not.toThrow();
|
||||
await vi.waitFor(() => {
|
||||
expect(mockFetch).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { logger } from "@/lib/logger";
|
||||
import { env } from "@/env";
|
||||
import { prisma } from "../prisma";
|
||||
|
||||
@@ -78,7 +79,7 @@ async function sendDiscord(payload: WebhookPayload): Promise<void> {
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Webhook] Discord send failed:", {
|
||||
logger.error("[Webhook] Discord send failed", {
|
||||
action: payload.action,
|
||||
error: (err as Error).message,
|
||||
});
|
||||
@@ -113,7 +114,7 @@ async function sendTelegram(payload: WebhookPayload): Promise<void> {
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Webhook] Telegram send failed:", {
|
||||
logger.error("[Webhook] Telegram send failed", {
|
||||
action: payload.action,
|
||||
error: (err as Error).message,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user