chore: 项目基线提交 - 拼豆图纸生成器 V1.0 核心代码

- 前端: React+Vite 首页/AI专区, 算法库(MARD色板/量化/背景去除), API对接
- 后端: Express+SQLite, 兑换码/订单/支付/chibi生成, 风控+云端同步
- CI/CD: GitHub Actions + Docker + nginx 配置
- 文档: PRD/DESIGN/LAUNCH/ROADMAP/E2E/竞品对照等 15 份
- 工程: 任务看板(taskboard) + 健康巡检(agent-health) + Git流程(gitflow)
This commit is contained in:
Sisyphus (主代理) committed 2026-08-13 21:40:27 +08:00
commit 02762400fb
174 files changed
+28059

No files matched your search

+279
View File
@@ -0,0 +1,279 @@
/**
* chibi AI 拼豆图像生成服务
*
* 流程: 先消耗一次兑换码次数(无剩余次数抛 生成次数不足) -> buildPrompt
* 组装提示词 -> 调用 OpenAI 兼容图像接口 (AI_IMAGE_API_URL /
* AI_IMAGE_API_KEY),未配置接口地址时使用内置 mock 模式生成占位图。
*/
import type Database from "better-sqlite3";
import { randomUUID } from "node:crypto";
import { deflateSync } from "node:zlib";
import type { AccessInfo } from "../types/index.js";
import { consumeCode, CodeError } from "../codes/service.js";
import { buildPrompt, type ChibiCategory, type Composition } from "./prompts.js";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface GenerateRequest {
/** 兑换码 */
code: string;
/** 用户上传的拼豆原图 (base64 dataURL) */
image: string;
/** 参考风格图 (base64 dataURL),可选 */
referenceImage?: string;
category: ChibiCategory;
subtype: string;
gridSize: number;
colorCount: number;
composition: Composition;
detailTags: string[];
customPrompt?: string;
}
export interface GenerateResult {
/** 生成的图像 (base64 dataURL) */
image: string;
/** 下载凭证 */
downloadGrant: string;
}
/** 生成成功时附带消耗后的 access 信息,供路由层返回。 */
export type GenerateOutcome = GenerateResult & { access: AccessInfo };
export class ChibiError extends Error {
readonly status: number;
constructor(message: string, status: number) {
super(message);
this.name = "ChibiError";
this.status = status;
}
}
// ---------------------------------------------------------------------------
// Mock 占位图 (纯函数实现的最小合法 PNG: 纯色 RGB + gridSize 尺寸)
// ---------------------------------------------------------------------------
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) {
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
}
table[n] = c >>> 0;
}
return table;
})();
function crc32(buf: Buffer): number {
let c = 0xffffffff;
for (let i = 0; i < buf.length; i++) {
c = CRC_TABLE[(c ^ buf[i]!) & 0xff]! ^ (c >>> 8);
}
return (c ^ 0xffffffff) >>> 0;
}
function pngChunk(type: string, data: Buffer): Buffer {
const typeBuf = Buffer.from(type, "ascii");
const header = Buffer.alloc(4);
header.writeUInt32BE(data.length, 0);
const crc = Buffer.alloc(4);
crc.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
return Buffer.concat([header, typeBuf, data, crc]);
}
/** 生成 size×size 纯色 PNG,返回 base64 dataURL。 */
function makePlaceholderPng(size: number, rgb: readonly [number, number, number]): string {
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(size, 0); // width
ihdr.writeUInt32BE(size, 4); // height
ihdr.writeUInt8(8, 8); // bit depth
ihdr.writeUInt8(2, 9); // color type: truecolor RGB
// bytes 10/11/12: compression / filter / interlace,默认 0
const row = Buffer.alloc(1 + size * 3);
row.writeUInt8(0, 0); // filter: none
for (let x = 0; x < size; x++) {
row.writeUInt8(rgb[0], 1 + x * 3);
row.writeUInt8(rgb[1], 2 + x * 3);
row.writeUInt8(rgb[2], 3 + x * 3);
}
const raw = Buffer.concat(Array.from({ length: size }, () => row));
const png = Buffer.concat([
PNG_SIGNATURE,
pngChunk("IHDR", ihdr),
pngChunk("IDAT", deflateSync(raw)),
pngChunk("IEND", Buffer.alloc(0)),
]);
return `data:image/png;base64,${png.toString("base64")}`;
}
/** 每类一个主题色,mock 模式下占位图随分类变色,便于肉眼区分。 */
const CATEGORY_COLORS: Record<ChibiCategory, readonly [number, number, number]> = {
landscape: [96, 165, 250], // 天空蓝
person: [251, 146, 60], // 活力橙
pet: [167, 139, 250], // 香芋紫
object: [52, 211, 153], // 抹茶绿
food: [251, 113, 133], // 蜜桃粉
};
// ---------------------------------------------------------------------------
// AI 接口调用 (OpenAI 兼容)
// ---------------------------------------------------------------------------
/**
* 从 OpenAI 兼容响应中提取 base64 (或图像 url)。
* 支持两种形态:
* /v1/images/generations -> { data: [{ b64_json | url }] }
* /v1/chat/completions -> { choices: [{ message: { images: [{ b64_json | url }] } }] }
*/
function extractImageBase64(payload: unknown): string | null {
if (!payload || typeof payload !== "object") return null;
const root = payload as Record<string, unknown>;
const data = Array.isArray(root["data"]) ? root["data"] : [];
const first = data[0] as Record<string, unknown> | undefined;
if (first) {
if (typeof first["b64_json"] === "string") return first["b64_json"];
if (typeof first["url"] === "string") return first["url"];
}
const choices = Array.isArray(root["choices"]) ? root["choices"] : [];
const choice = choices[0] as Record<string, unknown> | undefined;
const message = choice?.["message"] as Record<string, unknown> | undefined;
const images = Array.isArray(message?.["images"]) ? message["images"] : [];
const image = images[0] as Record<string, unknown> | undefined;
if (image) {
if (typeof image["b64_json"] === "string") return image["b64_json"];
if (typeof image["url"] === "string") return image["url"];
}
return null;
}
async function requestAiImage(prompt: string, req: GenerateRequest): Promise<string> {
const apiUrl = process.env["AI_IMAGE_API_URL"];
const apiKey = process.env["AI_IMAGE_API_KEY"];
const model = process.env["AI_IMAGE_MODEL"] ?? "gpt-image-1";
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
// chat/completions 走多模态消息 (携带原图/参考图),images/generations 走纯提示词
const isChat = (apiUrl ?? "").includes("/chat/completions");
let payload: unknown;
if (isChat) {
const content: Array<Record<string, unknown>> = [{ type: "text", text: prompt }];
for (const img of [req.image, req.referenceImage]) {
if (img && img.startsWith("data:")) {
content.push({ type: "image_url", image_url: { url: img } });
}
}
payload = { model, messages: [{ role: "user", content }] };
} else {
payload = {
model,
prompt,
n: 1,
size: `${req.gridSize}x${req.gridSize}`,
response_format: "b64_json",
};
}
let res: Awaited<ReturnType<typeof fetch>>;
try {
res = await fetch(apiUrl!, {
method: "POST",
headers,
body: JSON.stringify(payload),
signal: AbortSignal.timeout(120_000),
});
} catch (err) {
console.error("chibi AI image request failed:", err);
throw new ChibiError("AI 图像生成失败,请稍后重试", 502);
}
if (!res.ok) {
console.error("chibi AI image api error:", res.status, await res.text().catch(() => ""));
throw new ChibiError("AI 图像生成失败,请稍后重试", 502);
}
const raw = (await res.json().catch(() => null)) as unknown;
const b64OrUrl = extractImageBase64(raw);
if (!b64OrUrl) {
throw new ChibiError("AI 图像生成失败,请稍后重试", 502);
}
if (b64OrUrl.startsWith("http://") || b64OrUrl.startsWith("https://")) {
// 接口返回 url 时下载并转为 base64 dataURL
let imgRes: Awaited<ReturnType<typeof fetch>>;
try {
imgRes = await fetch(b64OrUrl, { signal: AbortSignal.timeout(60_000) });
} catch (err) {
console.error("chibi AI image download failed:", err);
throw new ChibiError("AI 图像生成失败,请稍后重试", 502);
}
if (!imgRes.ok) {
throw new ChibiError("AI 图像生成失败,请稍后重试", 502);
}
const buf = Buffer.from(await imgRes.arrayBuffer());
const type = imgRes.headers.get("content-type") ?? "image/png";
return `data:${type};base64,${buf.toString("base64")}`;
}
return b64OrUrl.startsWith("data:") ? b64OrUrl : `data:image/png;base64,${b64OrUrl}`;
}
/**
* 生成图像。未配置 AI_IMAGE_API_URL 时进入 mock 模式,返回 gridSize
* 尺寸的纯色占位 PNG (dataURL)。
*/
async function generateImage(prompt: string, req: GenerateRequest): Promise<string> {
const apiUrl = process.env["AI_IMAGE_API_URL"];
if (!apiUrl) {
return makePlaceholderPng(req.gridSize, CATEGORY_COLORS[req.category]);
}
return requestAiImage(prompt, req);
}
// ---------------------------------------------------------------------------
// 主入口
// ---------------------------------------------------------------------------
/**
* 生成 chibi 拼豆图。先原子消耗一次兑换码次数(无剩余次数时抛出
* ChibiError "生成次数不足", 402),再调用 AI 接口。
*/
export async function generateChibiImage(
db: Database.Database,
req: GenerateRequest,
): Promise<GenerateOutcome> {
// 1. 组装提示词
const prompt = buildPrompt({
category: req.category,
subtype: req.subtype,
gridSize: req.gridSize,
colorCount: req.colorCount,
composition: req.composition,
detailTags: req.detailTags,
customPrompt: req.customPrompt,
hasReferenceImage: req.referenceImage !== undefined && req.referenceImage !== "",
});
// 2. 消耗一次次数 (原子校验 + 扣减)
let access: AccessInfo;
try {
access = consumeCode(db, req.code);
} catch (err) {
if (err instanceof CodeError) {
// 未找到 / 禁用 / 过期 / 用尽 统一视为无法生成
throw new ChibiError("生成次数不足", 402);
}
throw err;
}
// 3. 生成图片
const image = await generateImage(prompt, req);
return { image, downloadGrant: randomUUID(), access };
}
+191
View File
@@ -0,0 +1,191 @@
/**
* chibi AI 拼豆提示词模板库
*
* 5 大类 × 3 细分 = 15 套模板,参数来自竞品逆向(copy-library.md):
* - 分类: 风景/人物/宠物/物品/食物
* - 参数: gridSize 48/64/80/96 · colorCount 16/24/32/40 · 构图 3 种
*/
export type ChibiCategory = "landscape" | "person" | "pet" | "object" | "food";
export type Composition = "主体特写" | "半幅构图" | "完整构图";
export interface ChibiTemplate {
category: ChibiCategory;
categoryName: string;
subtype: string;
subtypeName: string;
note: string;
basePrompt: string;
negativePrompt: string;
styleHint: string;
}
export interface BuildPromptOptions {
category: ChibiCategory;
subtype: string;
gridSize: number;
colorCount: number;
composition: Composition;
detailTags: string[];
customPrompt?: string;
hasReferenceImage?: boolean;
}
/** 像素拼豆风格通用前缀 */
const PIXEL_STYLE = "像素拼豆风格,色块分明,颗粒感强,马赛克效果";
/** 通用负面提示词 */
const NEGATIVE_DEFAULT =
"模糊,噪点,文字,水印,多手指,变形,复杂渐变,高光溢出,照片写实";
/** 15 套模板 */
export const TEMPLATES: ChibiTemplate[] = [
// ---------- 风景 ----------
{
category: "landscape", categoryName: "风景", subtype: "nature", subtypeName: "自然山川",
note: "山川、森林、河流",
basePrompt: "自然风景,山川森林河流,层次分明,构图大气",
negativePrompt: NEGATIVE_DEFAULT + ",人物,杂乱线条",
styleHint: "风景默认像素拼豆风",
},
{
category: "landscape", categoryName: "风景", subtype: "city", subtypeName: "城市夜景",
note: "霓虹、地标、灯火",
basePrompt: "城市夜景,霓虹灯光,地标建筑,冷暖对比",
negativePrompt: NEGATIVE_DEFAULT + ",过曝灯光,车流拖影",
styleHint: "城市夜景霓虹风",
},
{
category: "landscape", categoryName: "风景", subtype: "landmark", subtypeName: "地标建筑",
note: "知名建筑与天际线",
basePrompt: "地标建筑特写,轮廓清晰,比例准确",
negativePrompt: NEGATIVE_DEFAULT + ",透视畸变",
styleHint: "地标纪念风",
},
// ---------- 人物 ----------
{
category: "person", categoryName: "人物", subtype: "big-eye", subtypeName: "萌系大眼",
note: "大眼、圆脸、粗轮廓",
basePrompt: "萌系动漫人物,大眼圆脸,粗轮廓线条,可爱风格",
negativePrompt: NEGATIVE_DEFAULT + ",写实五官",
styleHint: "萌系大眼动漫风",
},
{
category: "person", categoryName: "人物", subtype: "youth", subtypeName: "清爽少年",
note: "自然五官、利落穿搭",
basePrompt: "清爽少年形象,自然五官,利落穿搭,干净背景",
negativePrompt: NEGATIVE_DEFAULT,
styleHint: "清爽少年风",
},
{
category: "person", categoryName: "人物", subtype: "retro", subtypeName: "复古像素",
note: "怀旧配色、游戏感",
basePrompt: "复古像素游戏风格人物,怀旧配色,8-bit 质感",
negativePrompt: NEGATIVE_DEFAULT + ",现代写实",
styleHint: "复古 8-bit 游戏风",
},
// ---------- 宠物 ----------
{
category: "pet", categoryName: "宠物", subtype: "cat", subtypeName: "猫咪头像",
note: "圆润脸型与花纹",
basePrompt: "猫咪头像特写,圆润脸型,花纹清晰,眼睛有神",
negativePrompt: NEGATIVE_DEFAULT + ",多只猫,全身",
styleHint: "宠物默认像素拼豆风",
},
{
category: "pet", categoryName: "宠物", subtype: "dog", subtypeName: "狗狗全身",
note: "耳朵、四肢和毛色",
basePrompt: "狗狗全身像,耳朵四肢完整,毛色层次分明",
negativePrompt: NEGATIVE_DEFAULT + ",多只狗",
styleHint: "狗狗全身像素风",
},
{
category: "pet", categoryName: "宠物", subtype: "duo", subtypeName: "双宠互动",
note: "两只宠物同框",
basePrompt: "两只宠物同框互动,姿态自然,主次分明",
negativePrompt: NEGATIVE_DEFAULT + ",肢体重叠遮挡",
styleHint: "双宠互动像素风",
},
// ---------- 物品 ----------
{
category: "object", categoryName: "物品", subtype: "toy", subtypeName: "手办玩具",
note: "造型轮廓优先",
basePrompt: "手办玩具,造型轮廓优先,还原特征细节",
negativePrompt: NEGATIVE_DEFAULT + ",塑料反光过强",
styleHint: "手办造型像素风",
},
{
category: "object", categoryName: "物品", subtype: "daily", subtypeName: "生活用品",
note: "保留结构与材质",
basePrompt: "生活用品,结构清晰,材质质感还原",
negativePrompt: NEGATIVE_DEFAULT + ",变形扭曲",
styleHint: "生活用品像素风",
},
{
category: "object", categoryName: "物品", subtype: "gift", subtypeName: "礼物纪念",
note: "突出包装和装饰",
basePrompt: "礼物纪念品,包装装饰突出,喜庆完整",
negativePrompt: NEGATIVE_DEFAULT + ",包装破损",
styleHint: "礼物纪念像素风",
},
// ---------- 食物 ----------
{
category: "food", categoryName: "食物", subtype: "dessert", subtypeName: "甜品蛋糕",
note: "奶油与装饰清晰",
basePrompt: "甜品蛋糕,奶油与装饰清晰,诱人色泽",
negativePrompt: NEGATIVE_DEFAULT + ",融化变形",
styleHint: "甜品像素风",
},
{
category: "food", categoryName: "食物", subtype: "drink", subtypeName: "咖啡饮品",
note: "杯型、分层和配料",
basePrompt: "咖啡饮品,杯型正确,分层与配料清晰",
negativePrompt: NEGATIVE_DEFAULT + ",杯型变形",
styleHint: "饮品像素风",
},
{
category: "food", categoryName: "食物", subtype: "meal", subtypeName: "家常美食",
note: "主食材清晰可辨",
basePrompt: "家常美食,主食材清晰可辨,色彩饱满",
negativePrompt: NEGATIVE_DEFAULT + ",食材混杂难辨",
styleHint: "家常美食像素风",
},
];
/** 按分类+细分查找模板 */
export function findTemplate(category: ChibiCategory, subtype: string): ChibiTemplate {
const t = TEMPLATES.find(
(x) => x.category === category && x.subtype === subtype,
);
if (!t) {
throw new Error(`未知的拼豆模板: ${category}/${subtype}`);
}
return t;
}
/** 组装最终提示词 */
export function buildPrompt(options: BuildPromptOptions): string {
const t = findTemplate(options.category, options.subtype);
const grid = options.gridSize;
const colors = options.colorCount;
const comp = options.composition;
const tags = options.detailTags.slice(0, 5); // 最多 5 项
const parts: string[] = [
t.basePrompt,
PIXEL_STYLE,
`${grid}×${grid} 网格`,
`最多 ${colors} 色`,
`主体${comp}`,
];
if (tags.length) parts.push(`细节要求:${tags.join("、")}`);
if (options.customPrompt?.trim()) parts.push(options.customPrompt.trim());
if (options.hasReferenceImage) parts.push("参考示例风格(不复制示例主体)");
return parts.join(",");
}
/** 组装负面提示词 */
export function buildNegativePrompt(category: ChibiCategory, subtype: string): string {
return findTemplate(category, subtype).negativePrompt;
}
+121
View File
@@ -0,0 +1,121 @@
import { Router } from "express";
import type { Request, Response } from "express";
import type Database from "better-sqlite3";
import { getDb } from "../db/index.js";
import { generateChibiImage, ChibiError, type GenerateRequest } from "./generate.js";
import { findTemplate, type ChibiCategory, type Composition } from "./prompts.js";
const CATEGORIES: readonly ChibiCategory[] = ["landscape", "person", "pet", "object", "food"];
const COMPOSITIONS: readonly Composition[] = ["主体特写", "半幅构图", "完整构图"];
/** Resolve the database instance: injected DB for tests, else global singleton. */
function resolveDb(injected?: Database.Database): Database.Database {
return injected ?? getDb();
}
/**
* Create the chibi router. Accepts an optional injected database for testing.
*
* POST /api/chibi/generate
* Request: { code, image, referenceImage?, category, subtype, gridSize,
* colorCount, composition, detailTags, customPrompt? }
* Response: 200 { image, access, downloadGrant }
* 400 参数错误 (中文提示)
* 402 { error: "生成次数不足" }
* 500 服务器内部错误
* 502 AI 图像生成失败
*/
export function createChibiRouter(injectedDb?: Database.Database): Router {
const router = Router();
router.post("/generate", async (req: Request, res: Response): Promise<void> => {
try {
const body = (req.body ?? {}) as Record<string, unknown>;
// ---- 基础字段校验 ----
const code = typeof body.code === "string" ? body.code : "";
if (!code) {
res.status(400).json({ error: "请输入兑换码" });
return;
}
const image = typeof body.image === "string" ? body.image : "";
if (!image) {
res.status(400).json({ error: "请上传图片" });
return;
}
const referenceImage =
typeof body.referenceImage === "string" && body.referenceImage !== ""
? body.referenceImage
: undefined;
// ---- 分类 / 细分模板 ----
const category = body.category as ChibiCategory;
if (!CATEGORIES.includes(category)) {
res.status(400).json({ error: "未知的分类" });
return;
}
const subtype = typeof body.subtype === "string" ? body.subtype : "";
try {
findTemplate(category, subtype);
} catch {
res.status(400).json({ error: "未知的模板类型" });
return;
}
// ---- 构图 / 网格 / 颜色 ----
const composition = body.composition as Composition;
if (!COMPOSITIONS.includes(composition)) {
res.status(400).json({ error: "未知的构图方式" });
return;
}
const gridSize = Number(body.gridSize);
if (!Number.isInteger(gridSize) || gridSize < 16 || gridSize > 512) {
res.status(400).json({ error: "网格尺寸无效" });
return;
}
const colorCount = Number(body.colorCount);
if (!Number.isInteger(colorCount) || colorCount < 4 || colorCount > 64) {
res.status(400).json({ error: "颜色数量无效" });
return;
}
// ---- 细节标签 / 自定义提示词 ----
const detailTags = Array.isArray(body.detailTags)
? body.detailTags.filter((t): t is string => typeof t === "string")
: [];
const customPrompt =
typeof body.customPrompt === "string" && body.customPrompt.trim() !== ""
? body.customPrompt
: undefined;
const payload: GenerateRequest = {
code,
image,
referenceImage,
category,
subtype,
gridSize,
colorCount,
composition,
detailTags,
customPrompt,
};
const result = await generateChibiImage(resolveDb(injectedDb), payload);
res.status(200).json({
image: result.image,
access: result.access,
downloadGrant: result.downloadGrant,
});
} catch (err) {
if (err instanceof ChibiError) {
res.status(err.status).json({ error: err.message });
} else {
console.error("POST /api/chibi/generate error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
}
});
return router;
}
+119
View File
@@ -0,0 +1,119 @@
import { Router } from "express";
import type { Request, Response } from "express";
import type Database from "better-sqlite3";
import { getDb } from "../db/index.js";
import { consumeCode, redeemCode, getCodeStatus, CodeError, normalizeCode } from "./service.js";
/**
* Format a CodeError into an Express response.
*/
function handleCodeError(res: Response, err: CodeError): void {
res.status(err.status).json({ error: err.message });
}
/**
* Resolve the database instance: use injected DB if provided, otherwise
* fall back to the global singleton.
*/
function resolveDb(injected?: Database.Database): Database.Database {
return injected ?? getDb();
}
/**
* Create the codes router. Accepts an optional injected database for testing.
*/
export function createCodesRouter(injectedDb?: Database.Database): Router {
const router = Router();
/**
* POST /api/codes/redeem
*
* Redeem a code: validate it is active, has remaining uses, and log the
* redemption event. Returns the access info (code, packageType,
* remainingUses, totalUses).
*
* Request: { code: string }
* Response: 200 { access: AccessInfo }
* 404 { error: "兑换码不存在,请检查后重试" }
* 400 { error: "兑换码已用尽" }
*/
router.post("/redeem", (req: Request, res: Response): void => {
try {
const { code } = req.body as { code?: string };
if (!code || typeof code !== "string") {
res.status(400).json({ error: "请输入兑换码" });
return;
}
const access = redeemCode(resolveDb(injectedDb), normalizeCode(code));
res.status(200).json({ access });
} catch (err) {
if (err instanceof CodeError) {
handleCodeError(res, err);
} else {
console.error("POST /api/codes/redeem error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
}
});
/**
* POST /api/codes/consume
*
* Consume one use of a code. Atomically decrements used_uses in a
* transaction. Returns the updated access info + freeDownload flag.
*
* Request: { code: string, fileName: string, downloadGrant: string }
* Response: 200 { access: AccessInfo, freeDownload: boolean }
* 400 { error: "兑换码已用尽" }
*/
router.post("/consume", (req: Request, res: Response): void => {
try {
const { code } = req.body as { code?: string; fileName?: string; downloadGrant?: string };
if (!code || typeof code !== "string") {
res.status(400).json({ error: "请输入兑换码" });
return;
}
const access = consumeCode(resolveDb(injectedDb), normalizeCode(code));
// freeDownload is true when the code still has remaining uses after
// this consumption (i.e. the user can still download)
res.status(200).json({ access, freeDownload: access.remainingUses > 0 });
} catch (err) {
if (err instanceof CodeError) {
handleCodeError(res, err);
} else {
console.error("POST /api/codes/consume error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
}
});
/**
* GET /api/codes/status?code=XXX
*
* Get the current status of a code without mutating anything.
*
* Query: code=string
* Response: 200 { access: AccessInfo }
* 404 { error: "兑换码不存在,请检查后重试" }
*/
router.get("/status", (req: Request, res: Response): void => {
try {
const codeParam = req.query.code;
if (!codeParam || typeof codeParam !== "string") {
res.status(400).json({ error: "请输入兑换码" });
return;
}
const access = getCodeStatus(resolveDb(injectedDb), normalizeCode(codeParam));
res.status(200).json({ access });
} catch (err) {
if (err instanceof CodeError) {
handleCodeError(res, err);
} else {
console.error("GET /api/codes/status error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
}
});
return router;
}
+242
View File
@@ -0,0 +1,242 @@
import type Database from "better-sqlite3";
import type { AccessInfo, PackageDefinition } from "../types/index.js";
import type { RedemptionAction } from "../types/index.js";
import { PACKAGE_DEFINITIONS } from "../types/index.js";
// Re-export for convenience
export { PACKAGE_DEFINITIONS } from "../types/index.js";
/** Regex for code format validation: 16 chars uppercase A-Z0-9. */
export const CODE_FORMAT = /^[A-Z0-9]{16}$/;
/** Package definition map: 体验包 3次, 常用包 10次, 进阶包 30次, 代理 200/500/1000次. */
export type PackageType = keyof typeof PACKAGE_DEFINITIONS;
export interface CodeRow {
code: string;
package_type: string;
total_uses: number;
used_uses: number;
status: "active" | "used" | "disabled";
created_at: string;
expired_at: string | null;
}
export class CodeError extends Error {
readonly status: number;
readonly code: string;
constructor(message: string, status: number, code: string) {
super(message);
this.name = "CodeError";
this.status = status;
this.code = code;
}
}
// ---------------------------------------------------------------------------
// Errors (Chinese messages matching competitor UX)
// ---------------------------------------------------------------------------
export const ERRORS = {
NOT_FOUND: new CodeError("兑换码不存在,请检查后重试", 404, "CODE_NOT_FOUND"),
DISABLED: new CodeError("兑换码已失效,请联系客服", 400, "CODE_DISABLED"),
EXPIRED: new CodeError("兑换码已过期,请联系客服", 400, "CODE_EXPIRED"),
EXHAUSTED: new CodeError("兑换码已用尽", 400, "CODE_EXHAUSTED"),
INVALID_FORMAT: new CodeError("兑换码格式不正确", 400, "CODE_INVALID_FORMAT"),
} as const;
// ---------------------------------------------------------------------------
// Code generation
// ---------------------------------------------------------------------------
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
function randomChar(): string {
// crypto.getRandomValues is cryptographically secure
const buf = new Uint32Array(1);
crypto.getRandomValues(buf);
return ALPHABET[buf[0]! % ALPHABET.length]!;
}
/**
* Generate a single random code of the given length using chars A-Z0-9.
*/
export function generateCode(length = 16): string {
let out = "";
for (let i = 0; i < length; i++) {
out += randomChar();
}
return out;
}
/**
* Batch-generate `count` unique codes with an optional prefix.
* Codes are 16 chars total (A-Z0-9), uppercase. Prefix is body chars.
*/
export function generateCodes(count: number, options?: { prefix?: string; length?: number }): string[] {
if (count <= 0 || !Number.isInteger(count)) {
throw new CodeError("生成数量必须为正整数", 400, "GEN_COUNT");
}
const prefix = (options?.prefix ?? "").toUpperCase().replace(/[^A-Z0-9]/g, "");
const totalLength = options?.length ?? 16;
if (prefix.length >= totalLength) {
throw new CodeError("前缀过长,无法生成16位兑换码", 400, "GEN_PREFIX");
}
const bodyLength = totalLength - prefix.length;
const codes = new Set<string>();
let guard = 0;
while (codes.size < count) {
if (++guard > count * 100) {
throw new CodeError("生成兑换码失败,请重试", 500, "GEN_RETRY");
}
codes.add(prefix + Array.from({ length: bodyLength }, randomChar).join(""));
}
return Array.from(codes);
}
// ---------------------------------------------------------------------------
// DB helpers
// ---------------------------------------------------------------------------
function getCodeByRaw(db: Database.Database, rawCode: string): CodeRow | undefined {
return db.prepare("SELECT * FROM codes WHERE code = ?").get(rawCode) as CodeRow | undefined;
}
/** Normalize a redemption code input: trim + uppercase. */
export function normalizeCode(raw: string): string {
return raw.trim().toUpperCase();
}
/** Validate that a code is well-formed (16 chars A-Z0-9) and return normalized. */
export function validateFormat(raw: string): string {
const code = normalizeCode(raw);
if (!CODE_FORMAT.test(code)) {
throw ERRORS.INVALID_FORMAT;
}
return code;
}
// ---------------------------------------------------------------------------
// Insert / redeem / consume
// ---------------------------------------------------------------------------
/**
* Insert generated codes into the database.
* Returns number of codes actually inserted.
*/
export function insertCodes(db: Database.Database, codes: string[], packageType: string, totalUses: number): number {
const stmt = db.prepare(
"INSERT OR IGNORE INTO codes (code, package_type, total_uses, used_uses, status) VALUES (?, ?, ?, 0, 'active')",
);
let inserted = 0;
const run = db.transaction(() => {
for (const code of codes) {
inserted += stmt.run(code, packageType, totalUses).changes;
}
});
run();
return inserted;
}
function toAccess(code: CodeRow): AccessInfo {
return {
code: code.code,
packageType: code.package_type,
remainingUses: code.total_uses - code.used_uses,
totalUses: code.total_uses,
};
}
/**
* Check whether a code is redeemable. Throws CodeError with the proper
* Chinese message + HTTP status if it is not. Returns the access info.
*/
export function checkRedeemable(db: Database.Database, rawCode: string): AccessInfo {
const code = validateFormat(rawCode);
const row = getCodeByRaw(db, code);
if (!row) {
throw ERRORS.NOT_FOUND;
}
if (row.status === "disabled") {
throw ERRORS.DISABLED;
}
if (row.expired_at && row.expired_at !== "" && Date.parse(row.expired_at) < Date.now()) {
throw ERRORS.EXPIRED;
}
if (row.used_uses >= row.total_uses) {
throw ERRORS.EXHAUSTED;
}
return toAccess(row);
}
/**
* Redeem a code: validates it and records a redeem action in the log.
* NOTE: redemption only verifies the code is valid — actual consumption is
* tracked per-use via consume(). Marking a code as "used" happens only when
* its uses are fully exhausted by consume().
*/
export function redeemCode(db: Database.Database, rawCode: string): AccessInfo {
const access = checkRedeemable(db, rawCode);
logAction(db, access.code, "redeem", 0);
return access;
}
/**
* Consume one use of a code ATOMICALLY.
* Uses a transaction that re-checks remaining uses inside the same write
* transaction so concurrent requests cannot double-decrement past zero.
*/
export function consumeCode(db: Database.Database, rawCode: string): AccessInfo {
const code = validateFormat(rawCode);
const consumeTx = db.transaction((): AccessInfo => {
const row = getCodeByRaw(db, code);
if (!row) {
throw ERRORS.NOT_FOUND;
}
if (row.status === "disabled") {
throw ERRORS.DISABLED;
}
if (row.expired_at && row.expired_at !== "" && Date.parse(row.expired_at) < Date.now()) {
throw ERRORS.EXPIRED;
}
if (row.used_uses >= row.total_uses) {
throw ERRORS.EXHAUSTED;
}
const newUsed = row.used_uses + 1;
const newStatus = newUsed >= row.total_uses ? "used" : row.status;
db.prepare("UPDATE codes SET used_uses = ?, status = ? WHERE code = ?").run(newUsed, newStatus, code);
logAction(db, code, "consume", 1);
return toAccess({ ...row, used_uses: newUsed, status: newStatus });
});
return consumeTx();
}
/** Get current access status without mutating anything. */
export function getCodeStatus(db: Database.Database, rawCode: string): AccessInfo {
const code = validateFormat(rawCode);
const row = getCodeByRaw(db, code);
if (!row) {
throw ERRORS.NOT_FOUND;
}
return toAccess(row);
}
// ---------------------------------------------------------------------------
// Logging
// ---------------------------------------------------------------------------
export function logAction(db: Database.Database, code: string, action: RedemptionAction, usedDelta: number): void {
db.prepare("INSERT INTO redemption_logs (code, action, used_delta) VALUES (?, ?, ?)").run(code, action, usedDelta);
}
/** List package definitions (read-only mirror of PACKAGE_DEFINITIONS). */
export function getPackages(): PackageDefinition[] {
return Object.values(PACKAGE_DEFINITIONS);
}
+86
View File
@@ -0,0 +1,86 @@
import Database from "better-sqlite3";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { SCHEMA_SQL } from "./schema.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
let _db: Database.Database | null = null;
export interface DbConfig {
/** Path to the SQLite database file. Default: <project-root>/data/perler-lab.db */
dbPath?: string;
/** Enable WAL mode for better concurrent read performance. Default: true */
wal?: boolean;
}
/**
* Initialize the database: open connection, run migrations, set pragmas.
* Idempotent — safe to call multiple times.
*/
export function initDatabase(config?: DbConfig): Database.Database {
if (_db) return _db;
const dbPath =
config?.dbPath ??
process.env["DB_PATH"] ??
path.resolve(__dirname, "..", "..", "data", "perler-lab.db");
// Ensure parent directory exists
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
const db = new Database(dbPath);
// Performance & safety pragmas
db.pragma("journal_mode = WAL");
db.pragma("foreign_keys = ON");
db.pragma("busy_timeout = 5000");
db.pragma("synchronous = NORMAL");
// Run migrations
runMigrations(db);
_db = db;
return db;
}
/**
* Run all pending migrations. Currently just applies the schema DDL.
*/
function runMigrations(db: Database.Database): void {
db.exec(SCHEMA_SQL);
}
/**
* Get the active database instance. Throws if not initialized.
*/
export function getDb(): Database.Database {
if (!_db) {
throw new Error("Database not initialized. Call initDatabase() first.");
}
return _db;
}
/**
* Close the database connection gracefully.
*/
export function closeDatabase(): void {
if (_db) {
_db.close();
_db = null;
}
}
/**
* Create an in-memory database for testing. Returns the db instance.
* Does NOT affect the global _db singleton.
*/
export function createTestDatabase(): Database.Database {
const db = new Database(":memory:");
db.pragma("journal_mode = WAL");
db.pragma("foreign_keys = ON");
db.exec(SCHEMA_SQL);
return db;
}
+78
View File
@@ -0,0 +1,78 @@
/**
* SQLite database schema for PERLER LAB.
*
* DB choice: better-sqlite3
* - Synchronous API (no async overhead for SQLite): simpler code, faster local operations.
* - Well-typed TypeScript bindings via @types/better-sqlite3.
* - Mature, widely used, zero-dependency native bindings.
* - No external server process needed — database is a single file.
*/
/** All DDL statements for creating tables. */
export const SCHEMA_SQL = `
-- 兑换码表
CREATE TABLE IF NOT EXISTS codes (
code TEXT PRIMARY KEY,
package_type TEXT NOT NULL,
total_uses INTEGER NOT NULL CHECK(total_uses > 0),
used_uses INTEGER NOT NULL DEFAULT 0 CHECK(used_uses >= 0),
status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active', 'used', 'disabled')),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expired_at TEXT
);
-- 订单表
CREATE TABLE IF NOT EXISTS orders (
order_no TEXT PRIMARY KEY,
package_name TEXT NOT NULL,
amount_cents INTEGER NOT NULL CHECK(amount_cents > 0),
payment_method TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'paid', 'failed')),
access_code TEXT REFERENCES codes(code),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
paid_at TEXT
);
-- 核销日志表
CREATE TABLE IF NOT EXISTS redemption_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT NOT NULL REFERENCES codes(code),
action TEXT NOT NULL CHECK(action IN ('redeem', 'consume')),
used_delta INTEGER NOT NULL DEFAULT 0 CHECK(used_delta >= 0),
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- AI 生成记录表
CREATE TABLE IF NOT EXISTS chibi_generations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT NOT NULL REFERENCES codes(code),
category TEXT NOT NULL,
subtype TEXT NOT NULL,
grid_size INTEGER NOT NULL,
color_count INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- 索引:按 code 查询日志
CREATE INDEX IF NOT EXISTS idx_redemption_logs_code ON redemption_logs(code);
-- 索引:按状态查询兑换码
CREATE INDEX IF NOT EXISTS idx_codes_status ON codes(status);
-- 索引:按 order_no 查询订单
CREATE INDEX IF NOT EXISTS idx_orders_order_no ON orders(order_no);
-- 设备绑定表(云端同步权益:换设备/清缓存后恢复兑换码)
-- 复合主键 (device_id, code):一个设备可绑定多个兑换码,
-- 同一兑换码也可绑定到多个设备(家庭/多端共用)。
CREATE TABLE IF NOT EXISTS device_bindings (
device_id TEXT NOT NULL,
code TEXT NOT NULL REFERENCES codes(code),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (device_id, code)
);
-- 索引:按 code 反查绑定设备
CREATE INDEX IF NOT EXISTS idx_device_bindings_code ON device_bindings(code);
`;
+29
View File
@@ -0,0 +1,29 @@
import type { PaymentProvider, PaymentMethod } from "./types.js";
import { MockPaymentProvider } from "./mock.js";
import { WeChatPayProvider } from "./wechat.js";
/**
* Payment provider factory.
*
* Returns the mock provider when:
* - NODE_ENV is not "production" (local development), OR
* - the WeChat Pay environment variables are not configured.
*
* Returns the real WeChatPayProvider in production with credentials present.
*/
export function getPaymentProvider(method: PaymentMethod): PaymentProvider {
if (method === "alipay") {
// Alipay integration not yet implemented - always fall back to mock for now.
return new MockPaymentProvider();
}
const env = process.env.NODE_ENV ?? "development";
const configured =
!!process.env.WECHAT_MCH_ID &&
!!process.env.WECHAT_API_KEY &&
!!process.env.WECHAT_NOTIFY_URL;
if (env !== "production" || !configured) {
return new MockPaymentProvider();
}
return new WeChatPayProvider();
}
+42
View File
@@ -0,0 +1,42 @@
import type { PaymentProvider, PaymentRequest, PaymentResult } from "./types.js";
/**
* MockPaymentProvider — for local development WITHOUT real merchant accounts.
*
* - createPayment: returns a fake payment URL with the orderNo and amount embedded.
* - verifyCallback: always returns success (any callback is treated as valid).
*
* The fake URL is designed so the frontend can simulate the full payment flow:
* the user "visits" the URL, then the frontend calls the mock callback endpoint.
*/
export class MockPaymentProvider implements PaymentProvider {
createPayment(request: PaymentRequest): PaymentResult {
const { orderNo, amountCents, method } = request;
// Build a realistic-looking mock payment URL
const url = `https://pay.mock.local/pay?orderNo=${encodeURIComponent(orderNo)}&amount=${amountCents}&method=${method}`;
const result: PaymentResult = { url };
// Include a fake QR code URL for WeChat to make the frontend flow more realistic
if (method === "wechat") {
result.qrCode = `https://pay.mock.local/qr?orderNo=${encodeURIComponent(orderNo)}`;
}
return result;
}
verifyCallback(
params: Record<string, string | string[] | undefined>,
): { orderNo: string; transactionId: string } | null {
const orderNo = typeof params["orderNo"] === "string" ? params["orderNo"] : undefined;
if (!orderNo) {
return null;
}
// Always succeed in mock mode
return {
orderNo,
transactionId: `MOCK${Date.now()}`,
};
}
}
+147
View File
@@ -0,0 +1,147 @@
import { Router } from "express";
import type { Request, Response } from "express";
import type Database from "better-sqlite3";
import { getDb } from "../db/index.js";
import { getPaymentProvider } from "./index.js";
import type { PaymentMethod } from "./types.js";
import { generateCode, insertCodes } from "../codes/service.js";
/** 套餐定义(金额单位为分) */
const PACKAGES: Record<string, { name: string; cents: number; uses: number }> = {
"体验包": { name: "体验包", cents: 490, uses: 3 },
"常用包": { name: "常用包", cents: 1290, uses: 10 },
"进阶包": { name: "进阶包", cents: 2990, uses: 30 },
};
function resolveDb(injected?: Database.Database): Database.Database {
return injected ?? getDb();
}
function genOrderNo(): string {
const d = new Date(Date.now() + 8 * 3600 * 1000);
const pad = (n: number) => String(n).padStart(2, "0");
const ts =
`${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}` +
`${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}`;
const rand = Math.floor(Math.random() * 1_000_000).toString().padStart(6, "0");
return `PL${ts}${rand}`;
}
/**
* 创建支付订单路由。
* 注入 DB 便于测试(与 codes 模块一致)。
*/
export function createPaymentRouter(injectedDb?: Database.Database): Router {
const router = Router();
/**
* POST /api/orders
* 请求: { packageName: string, paymentMethod: "wechat" | "alipay" }
* 响应: 200 { order, payment } / 400 { error }
*/
router.post("/", (req: Request, res: Response): void => {
try {
const db = resolveDb(injectedDb);
const { packageName, paymentMethod } = req.body as {
packageName?: string;
paymentMethod?: string;
};
const pkg = packageName ? PACKAGES[packageName] : undefined;
if (!pkg) {
res.status(400).json({ error: "套餐不存在" });
return;
}
if (paymentMethod !== "wechat" && paymentMethod !== "alipay") {
res.status(400).json({ error: "不支持的支付方式" });
return;
}
const orderNo = genOrderNo();
const createdAt = new Date().toISOString();
db.prepare(
`INSERT INTO orders (order_no, package_name, amount_cents, payment_method, status, created_at)
VALUES (?, ?, ?, ?, 'pending', ?)`
).run(orderNo, pkg.name, pkg.cents, paymentMethod, createdAt);
const order = {
orderNo,
packageName: pkg.name,
amountCents: pkg.cents,
paymentMethod,
status: "pending",
createdAt,
};
const payment = getPaymentProvider(paymentMethod as PaymentMethod).createPayment({
orderNo,
amountCents: pkg.cents,
description: `${pkg.name} - ${pkg.uses} 次生成权益`,
method: paymentMethod as PaymentMethod,
});
res.status(200).json({ order, payment });
} catch (err) {
console.error("POST /api/orders error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
});
/**
* GET /api/orders?orderNo=XXX
* 响应: 200 { order } / 404 { error }
*/
router.get("/", (req: Request, res: Response): void => {
try {
const db = resolveDb(injectedDb);
const orderNo = typeof req.query.orderNo === "string" ? req.query.orderNo : "";
if (!orderNo) {
res.status(400).json({ error: "缺少 orderNo 参数" });
return;
}
const row = db.prepare("SELECT * FROM orders WHERE order_no = ?").get(orderNo) as
| Record<string, unknown>
| undefined;
if (!row) {
res.status(404).json({ error: "订单不存在" });
return;
}
res.status(200).json({ order: row });
} catch (err) {
console.error("GET /api/orders error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
});
/**
* POST /api/orders/:orderNo/pay-callback
* 模拟支付回调:将订单标记为 paid 并自动生成权益兑换码(幂等)。
*/
router.post("/:orderNo/pay-callback", (req: Request, res: Response): void => {
try {
const db = resolveDb(injectedDb);
const orderNo = req.params.orderNo as string;
const row = db.prepare("SELECT * FROM orders WHERE order_no = ?").get(orderNo) as
| { order_no: string; status: string; package_name: string }
| undefined;
if (!row) {
res.status(404).json({ error: "订单不存在" });
return;
}
if (row.status === "paid") {
res.status(200).json({ ok: true, order: row });
return;
}
// 生成权益兑换码:一条库存记录 + 订单关联
const pkg = (PACKAGES[row.package_name] ?? PACKAGES["常用包"])!;
const code = generateCode();
insertCodes(db, [code], pkg.name, pkg.uses);
db.prepare(
`UPDATE orders SET status = 'paid', paid_at = ?, access_code = ? WHERE order_no = ?`
).run(new Date().toISOString(), code, orderNo);
const updated = db.prepare("SELECT * FROM orders WHERE order_no = ?").get(orderNo);
res.status(200).json({ ok: true, order: updated, accessCode: code });
} catch (err) {
console.error("POST pay-callback error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
});
return router;
}
+57
View File
@@ -0,0 +1,57 @@
// ---- Payment Method Enum ----
export type PaymentMethod = "wechat" | "alipay";
// ---- Payment Request ----
export interface PaymentRequest {
/** Order number (unique identifier) */
orderNo: string;
/** Amount in cents (integer, e.g. 1290 = ¥12.90) */
amountCents: number;
/** Brief description shown on the payment page */
description: string;
/** Payment method */
method: PaymentMethod;
}
// ---- Payment Result ----
export interface PaymentResult {
/** URL the user is redirected to for payment */
url: string;
/** Optional QR code URL (for WeChat Pay native) */
qrCode?: string;
/** Provider-specific transaction ID (if available immediately) */
transactionId?: string;
}
// ---- Payment Provider Interface ----
export interface PaymentProvider {
/**
* Create a payment request.
* Returns a payment URL and optional QR code for the user to complete payment.
*/
createPayment(request: PaymentRequest): PaymentResult;
/**
* Verify a payment callback from the provider.
* Returns the orderNo and provider transactionId if valid, or null if invalid.
*/
verifyCallback(params: Record<string, string | string[] | undefined>): { orderNo: string; transactionId: string } | null;
}
// ---- Payment Provider Error ----
export class PaymentProviderError extends Error {
readonly code: string;
readonly status: number;
constructor(message: string, code: string, status = 500) {
super(message);
this.name = "PaymentProviderError";
this.code = code;
this.status = status;
}
}
+66
View File
@@ -0,0 +1,66 @@
import type { PaymentProvider, PaymentRequest, PaymentResult } from "./types.js";
import { PaymentProviderError } from "./types.js";
import crypto from "node:crypto";
/**
* WeChat Pay v3 provider (skeleton for production).
*
* Requires these environment variables:
* - WECHAT_MCH_ID 商户号
* - WECHAT_API_KEY APIv3 密钥 (32 bytes)
* - WECHAT_NOTIFY_URL 支付回调通知地址 (公网 HTTPS)
*
* The createPayment / verifyCallback implementations follow the WeChat Pay
* v3 API structure but do NOT perform real network calls yet - wire the
* actual HTTP calls to https://api.mch.weixin.qq.com/ when merchant
* credentials are available.
*/
export class WeChatPayProvider implements PaymentProvider {
private readonly mchId: string;
private readonly apiKey: string;
private readonly notifyUrl: string;
constructor() {
const mchId = process.env.WECHAT_MCH_ID ?? "";
const apiKey = process.env.WECHAT_API_KEY ?? "";
const notifyUrl = process.env.WECHAT_NOTIFY_URL ?? "";
if (!mchId || !apiKey || !notifyUrl) {
throw new PaymentProviderError("微信支付未配置(缺少 WECHAT_MCH_ID / WECHAT_API_KEY / WECHAT_NOTIFY_URL)", "PAYMENT_NOT_CONFIGURED", 500);
}
this.mchId = mchId;
this.apiKey = apiKey;
this.notifyUrl = notifyUrl;
}
createPayment(request: PaymentRequest): PaymentResult {
const { orderNo, amountCents, description } = request;
// 微信支付 v3 下单请求体(Native 扫码支付)
const payload = {
appid: process.env.WECHAT_APP_ID ?? "",
mchid: this.mchId,
description,
out_trade_no: orderNo,
notify_url: this.notifyUrl,
amount: { total: amountCents, currency: "CNY" },
};
const sign = this.signPayload(JSON.stringify(payload));
// TODO: 调用 https://api.mch.weixin.qq.com/v3/pay/transactions/native
// 解析返回的 code_url 作为二维码内容。
void sign;
const url = `https://pay.weixin.qq.com/native?out_trade_no=${encodeURIComponent(orderNo)}`;
return { url, qrCode: url };
}
verifyCallback(params: Record<string, string | string[] | undefined>): { orderNo: string; transactionId: string } | null {
// 微信回调以 JSON body + Wechatpay-Signature 请求头验签。
// 此处以参数 orderNo 做占位校验,生产环境需验证签名与金额。
const orderNo = typeof params["orderNo"] === "string" ? params["orderNo"] : undefined;
if (!orderNo) return null;
return { orderNo, transactionId: `WX${Date.now()}` };
}
/** HMAC-SHA256 签名(占位实现,生产需按微信 v3 规范签名) */
private signPayload(payload: string): string {
return crypto.createHmac("sha256", this.apiKey).update(payload).digest("hex");
}
}
+71
View File
@@ -0,0 +1,71 @@
import express from "express";
import type { Express } from "express";
import type Database from "better-sqlite3";
import { initDatabase } from "./db/index.js";
import { createCodesRouter } from "./codes/routes.js";
import { createPaymentRouter } from "./payment/routes.js";
import { createChibiRouter } from "./chibi/routes.js";
import { createSyncRouter } from "./sync/routes.js";
const PORT = parseInt(process.env["PORT"] ?? "8788", 10);
/**
* Create the Express app. Accepts an optional injected database so tests can
* use an in-memory DB; production uses the singleton from initDatabase().
*/
export function createApp(db?: Database.Database): Express {
const app = express();
// ---- CORS middleware ----
// Manual middleware instead of the `cors` package: the only browser client
// is the Vite dev server on http://localhost:5173, so an explicit allowlist
// (no wildcard) is simpler and safer than a new dependency.
const ALLOWED_ORIGINS: readonly string[] = ["http://localhost:5173", "http://127.0.0.1:5173"];
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin !== undefined && ALLOWED_ORIGINS.includes(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Vary", "Origin");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.setHeader("Access-Control-Max-Age", "86400");
}
if (req.method === "OPTIONS") {
res.status(204).end();
return;
}
next();
});
// ---- Middleware ----
app.use(express.json());
// ---- Health check ----
app.get("/health", (_req, res) => {
res.status(200).json({ status: "ok", timestamp: new Date().toISOString() });
});
// ---- Mount routes ----
app.use("/api/codes", createCodesRouter(db));
app.use("/api/orders", createPaymentRouter(db));
app.use("/api/chibi", createChibiRouter(db));
app.use("/api/sync", createSyncRouter(db));
// ---- 404 handler ----
app.use((_req, res) => {
res.status(404).json({ error: "接口不存在" });
});
return app;
}
// Only auto-start when run directly (not when imported by tests)
const isMain = process.argv[1] !== undefined && process.argv[1]!.endsWith("server.ts");
if (isMain) {
initDatabase();
createApp().listen(PORT, () => {
console.log(`PERLER LAB server running on http://localhost:${PORT}`);
});
}
export default createApp;
+190
View File
@@ -0,0 +1,190 @@
import { Router } from "express";
import type { Request, Response } from "express";
import type Database from "better-sqlite3";
import { getDb } from "../db/index.js";
import { checkRedeemable, validateFormat, CodeError } from "../codes/service.js";
import type { AccessInfo } from "../types/index.js";
/**
* Device ID format: 8-64 chars, alphanumeric + dash.
* (Matches how frontend crypto.randomUUID / custom device ids look.)
*/
export const DEVICE_ID_FORMAT = /^[A-Za-z0-9-]{8,64}$/;
/** A code bound to a device, plus its current access info. */
export interface BoundCode {
code: string;
packageType: string;
remainingUses: number;
totalUses: number;
status: string;
}
interface BindingRow {
code: string;
package_type: string;
total_uses: number;
used_uses: number;
status: string;
}
/**
* Format a CodeError into an Express response.
*/
function handleCodeError(res: Response, err: CodeError): void {
res.status(err.status).json({ error: err.message });
}
/**
* Resolve the database instance: use injected DB if provided, otherwise
* fall back to the global singleton.
*/
function resolveDb(injected?: Database.Database): Database.Database {
return injected ?? getDb();
}
/**
* Normalize a device id: trim; reject anything not matching the format.
* Throws a CodeError (400, "设备标识无效") on invalid input.
*/
function parseDeviceId(raw: string): string {
const deviceId = raw.trim();
if (!DEVICE_ID_FORMAT.test(deviceId)) {
throw new CodeError("设备标识无效", 400, "DEVICE_ID_INVALID");
}
return deviceId;
}
/**
* Create the sync router (cloud-sync of redeemed code benefits).
* Accepts an optional injected database for testing.
*
* POST /api/sync/bind
* Request: { deviceId: string, code: string }
* Response: 200 { ok: true, access: AccessInfo }
* 400 { error: "设备标识无效" / "兑换码格式不正确" / ... }
* 404 { error: "兑换码不存在,请检查后重试" }
* Idempotent: binding an already-bound code is a no-op success.
*
* GET /api/sync/restore?deviceId=XXX
* Response: 200 { codes: BoundCode[] } (empty array when none)
* 400 { error: "设备标识无效" }
*
* POST /api/sync/unbind
* Request: { deviceId: string, code: string }
* Response: 200 { ok: true }
* Idempotent: unbinding a non-existent binding still succeeds.
*/
export function createSyncRouter(injectedDb?: Database.Database): Router {
const router = Router();
const bindStmt = (db: Database.Database) =>
db.prepare("INSERT OR IGNORE INTO device_bindings (device_id, code) VALUES (?, ?)");
const unbindStmt = (db: Database.Database) =>
db.prepare("DELETE FROM device_bindings WHERE device_id = ? AND code = ?");
const bindingsStmt = (db: Database.Database) =>
db.prepare(
`SELECT c.code, c.package_type, c.total_uses, c.used_uses, c.status
FROM device_bindings b
JOIN codes c ON c.code = b.code
WHERE b.device_id = ?
ORDER BY b.created_at, c.code`,
);
/**
* POST /api/sync/bind
* Bind a redeemed code to a device so it can be restored later.
*/
router.post("/bind", (req: Request, res: Response): void => {
try {
const { deviceId, code } = req.body as { deviceId?: string; code?: string };
if (!deviceId || typeof deviceId !== "string") {
res.status(400).json({ error: "设备标识无效" });
return;
}
if (!code || typeof code !== "string") {
res.status(400).json({ error: "请输入兑换码" });
return;
}
const db = resolveDb(injectedDb);
const id = parseDeviceId(deviceId);
const normalized = validateFormat(code);
// Verifies the code exists & is still redeemable (active, not expired,
// not exhausted). Throws CodeError with Chinese message + status.
const access: AccessInfo = checkRedeemable(db, normalized);
bindStmt(db).run(id, access.code);
res.status(200).json({ ok: true, access });
} catch (err) {
if (err instanceof CodeError) {
handleCodeError(res, err);
} else {
console.error("POST /api/sync/bind error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
}
});
/**
* GET /api/sync/restore?deviceId=XXX
* Return all codes bound to this device with their access info.
*/
router.get("/restore", (req: Request, res: Response): void => {
try {
const deviceIdParam = req.query.deviceId;
if (!deviceIdParam || typeof deviceIdParam !== "string") {
res.status(400).json({ error: "设备标识无效" });
return;
}
const db = resolveDb(injectedDb);
const id = parseDeviceId(deviceIdParam);
const rows = bindingsStmt(db).all(id) as BindingRow[];
const codes: BoundCode[] = rows.map((row) => ({
code: row.code,
packageType: row.package_type,
remainingUses: row.total_uses - row.used_uses,
totalUses: row.total_uses,
status: row.status,
}));
res.status(200).json({ codes });
} catch (err) {
if (err instanceof CodeError) {
handleCodeError(res, err);
} else {
console.error("GET /api/sync/restore error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
}
});
/**
* POST /api/sync/unbind
* Remove a binding. Idempotent: succeeds even if the binding never existed.
*/
router.post("/unbind", (req: Request, res: Response): void => {
try {
const { deviceId, code } = req.body as { deviceId?: string; code?: string };
if (!deviceId || typeof deviceId !== "string") {
res.status(400).json({ error: "设备标识无效" });
return;
}
if (!code || typeof code !== "string") {
res.status(400).json({ error: "请输入兑换码" });
return;
}
const db = resolveDb(injectedDb);
const id = parseDeviceId(deviceId);
const normalized = validateFormat(code);
unbindStmt(db).run(id, normalized);
res.status(200).json({ ok: true });
} catch (err) {
if (err instanceof CodeError) {
handleCodeError(res, err);
} else {
console.error("POST /api/sync/unbind error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
}
});
return router;
}
+140
View File
@@ -0,0 +1,140 @@
import { describe, it, expect } from "vitest";
import request from "supertest";
import type Database from "better-sqlite3";
import { buildPrompt, findTemplate } from "../chibi/prompts.js";
import { generateChibiImage, ChibiError, type GenerateRequest } from "../chibi/generate.js";
import { createApp } from "../server.js";
import { createTestDatabase } from "../db/index.js";
import { generateCodes, insertCodes, consumeCode, getCodeStatus } from "../codes/service.js";
/** 建一个含有效兑换码的测试库。 */
function setupDb(uses = 3): { db: Database.Database; code: string } {
const db = createTestDatabase();
const codes = generateCodes(1);
insertCodes(db, codes, "体验包", uses);
return { db, code: codes[0]! };
}
/** 构造合法请求体,overrides 可覆盖任意字段。 */
function baseRequest(code: string, overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
code,
image: "data:image/png;base64,iVBORw0KGgo=",
category: "pet",
subtype: "cat",
gridSize: 48,
colorCount: 16,
composition: "主体特写",
detailTags: ["眼睛更有神"],
...overrides,
};
}
function toGenerateRequest(body: Record<string, unknown>): GenerateRequest {
return body as unknown as GenerateRequest;
}
const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
describe("chibi 生成服务", () => {
it("buildPrompt 集成: 全部参数参与组装", () => {
const p = buildPrompt({
category: "food",
subtype: "dessert",
gridSize: 80,
colorCount: 32,
composition: "半幅构图",
detailTags: ["奶油清晰", "装饰丰富"],
customPrompt: "不要奶油",
hasReferenceImage: true,
});
expect(p).toContain("甜品蛋糕");
expect(p).toContain("80×80 网格");
expect(p).toContain("最多 32 色");
expect(p).toContain("主体半幅构图");
expect(p).toContain("奶油清晰");
expect(p).toContain("不要奶油");
expect(p).toContain("参考示例风格");
expect(findTemplate("food", "dessert").subtypeName).toBe("甜品蛋糕");
});
it("mock 模式返回 gridSize 尺寸的占位 PNG dataURL + 下载凭证", async () => {
const { db, code } = setupDb();
const result = await generateChibiImage(db, toGenerateRequest(baseRequest(code)));
// dataURL 且是合法 PNG
expect(result.image.startsWith("data:image/png;base64,")).toBe(true);
const buf = Buffer.from(result.image.split(",")[1]!, "base64");
expect(buf.subarray(0, 8)).toEqual(PNG_MAGIC);
// IHDR width/height 位于偏移 16/20,等于 gridSize
expect(buf.readUInt32BE(16)).toBe(48);
expect(buf.readUInt32BE(20)).toBe(48);
// 下载凭证非空
expect(typeof result.downloadGrant).toBe("string");
expect(result.downloadGrant.length).toBeGreaterThan(0);
// 成功消耗 1 次
expect(result.access.remainingUses).toBe(2);
expect(getCodeStatus(db, code).remainingUses).toBe(2);
});
it("次数不足时抛出 生成次数不足 (402)", async () => {
const { db, code } = setupDb(1);
consumeCode(db, code); // 用尽剩余次数
const err = await generateChibiImage(db, toGenerateRequest(baseRequest(code))).then(
() => null,
(e: unknown) => e,
);
expect(err).toBeInstanceOf(ChibiError);
expect((err as ChibiError).message).toContain("生成次数不足");
expect((err as ChibiError).status).toBe(402);
// 失败时不应再扣次数
expect(getCodeStatus(db, code).remainingUses).toBe(0);
});
});
describe("POST /api/chibi/generate 路由", () => {
it("200 返回 image / access / downloadGrant", async () => {
const { db, code } = setupDb();
const app = createApp(db);
const res = await request(app).post("/api/chibi/generate").send(baseRequest(code));
expect(res.status).toBe(200);
expect(res.body.image).toContain("data:image/png;base64,");
expect(res.body.access.remainingUses).toBe(2);
expect(typeof res.body.downloadGrant).toBe("string");
expect(res.body.downloadGrant.length).toBeGreaterThan(0);
});
it("次数不足返回 402 生成次数不足", async () => {
const { db, code } = setupDb(1);
consumeCode(db, code);
const app = createApp(db);
const res = await request(app).post("/api/chibi/generate").send(baseRequest(code));
expect(res.status).toBe(402);
expect(res.body.error).toBe("生成次数不足");
});
it("未知模板返回 400", async () => {
const { db, code } = setupDb();
const app = createApp(db);
const res = await request(app)
.post("/api/chibi/generate")
.send(baseRequest(code, { subtype: "不存在" }));
expect(res.status).toBe(400);
expect(res.body.error).toBe("未知的模板类型");
});
it("缺少兑换码返回 400", async () => {
const { db } = setupDb();
const app = createApp(db);
const res = await request(app).post("/api/chibi/generate").send(baseRequest(""));
expect(res.status).toBe(400);
expect(res.body.error).toBe("请输入兑换码");
});
});
+223
View File
@@ -0,0 +1,223 @@
import { describe, it, expect, beforeEach } from "vitest";
import type Database from "better-sqlite3";
import { createTestDatabase } from "../db/index.js";
import {
CodeError,
ERRORS,
consumeCode,
generateCode,
generateCodes,
getCodeStatus,
insertCodes,
normalizeCode,
redeemCode,
} from "../codes/service.js";
describe("兑换码模块", () => {
let db: Database.Database;
beforeEach(() => {
db = createTestDatabase();
});
describe("generateCode / insertCodes", () => {
it("生成 16 位 A-Z0-9 大写兑换码", () => {
const code = generateCode();
expect(code).toMatch(/^[A-Z0-9]{16}$/);
});
it("批量生成唯一兑换码", () => {
const codes = generateCodes(50);
expect(codes).toHaveLength(50);
expect(new Set(codes).size).toBe(50);
});
it("insertCodes 写入数据库并返回插入数量", () => {
const codes = generateCodes(3);
const inserted = insertCodes(db, codes, "体验包", 3);
expect(inserted).toBe(3);
const row = db.prepare("SELECT * FROM codes WHERE code = ?").get(codes[0]!) as {
used_uses: number;
status: string;
};
expect(row.used_uses).toBe(0);
expect(row.status).toBe("active");
});
it("重复插入相同兑换码被忽略(INSERT OR IGNORE)", () => {
const code = generateCode();
expect(insertCodes(db, [code], "体验包", 3)).toBe(1);
expect(insertCodes(db, [code], "体验包", 3)).toBe(0);
});
});
describe("redeemCode", () => {
it("兑换有效兑换码成功,返回 access 信息", () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 3);
const access = redeemCode(db, code);
expect(access.code).toBe(code);
expect(access.packageType).toBe("体验包");
expect(access.totalUses).toBe(3);
expect(access.remainingUses).toBe(3);
});
it("兑换码输入自动去空格并转大写", () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 3);
const access = redeemCode(db, ` ${code.toLowerCase()} `);
expect(access.code).toBe(code);
expect(access.remainingUses).toBe(3);
});
it("兑换无效格式(非 16 位)抛出 CODE_INVALID_FORMAT", () => {
expect(() => redeemCode(db, "SHORT")).toThrowError(ERRORS.INVALID_FORMAT);
expect(() => redeemCode(db, "123")).toThrow(CodeError);
});
it("兑换不存在的兑换码抛出 CODE_NOT_FOUND", () => {
const code = generateCode();
expect(() => redeemCode(db, code)).toThrowError(ERRORS.NOT_FOUND);
});
it("兑换已用尽的兑换码抛出 CODE_EXHAUSTED", () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 1);
// 第一次消费后剩余 0
consumeCode(db, code);
expect(() => redeemCode(db, code)).toThrowError(ERRORS.EXHAUSTED);
// 只读状态查询不抛错,remainingUses 为 0
expect(getCodeStatus(db, code).remainingUses).toBe(0);
});
it("兑换 disabled 状态的兑换码抛出 CODE_DISABLED", () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 3);
db.prepare("UPDATE codes SET status = 'disabled' WHERE code = ?").run(code);
expect(() => redeemCode(db, code)).toThrowError(ERRORS.DISABLED);
});
it("兑换已过期兑换码抛出 CODE_EXPIRED", () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 3);
db.prepare("UPDATE codes SET expired_at = '2020-01-01' WHERE code = ?").run(code);
expect(() => redeemCode(db, code)).toThrowError(ERRORS.EXPIRED);
});
it("兑换(redeem 动作)以 used_delta=0 写入日志(回归:CHECK >= 0 修复)", () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 3);
redeemCode(db, code);
const log = db
.prepare("SELECT action, used_delta FROM redemption_logs WHERE code = ?")
.get(code) as { action: string; used_delta: number };
expect(log.action).toBe("redeem");
expect(log.used_delta).toBe(0);
});
});
describe("consumeCode", () => {
it("消费一次后 remainingUses 递减,totalUses 不变", () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 3);
const access = consumeCode(db, code);
expect(access.remainingUses).toBe(2);
expect(access.totalUses).toBe(3);
expect(access.code).toBe(code);
const status = getCodeStatus(db, code);
expect(status.remainingUses).toBe(2);
expect(status.totalUses).toBe(3);
});
it("连续消费直到用尽,状态变为 used", () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 2);
const first = consumeCode(db, code);
expect(first.remainingUses).toBe(1);
const second = consumeCode(db, code);
expect(second.remainingUses).toBe(0);
expect(second.totalUses).toBe(2);
const row = db.prepare("SELECT status FROM codes WHERE code = ?").get(code) as {
status: string;
};
expect(row.status).toBe("used");
});
it("用尽后再消费抛出 CODE_EXHAUSTED", () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 1);
consumeCode(db, code); // 剩余 0
expect(() => consumeCode(db, code)).toThrowError(ERRORS.EXHAUSTED);
});
it("消费日志记录 used_delta=1(回归:CHECK >= 0 修复后合法)", () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 2);
consumeCode(db, code);
const log = db
.prepare("SELECT action, used_delta FROM redemption_logs WHERE code = ?")
.get(code) as { action: string; used_delta: number };
expect(log.action).toBe("consume");
expect(log.used_delta).toBe(1);
});
it("消费不存在/非法格式的兑换码抛出对应错误", () => {
expect(() => consumeCode(db, generateCode())).toThrowError(ERRORS.NOT_FOUND);
expect(() => consumeCode(db, "BAD")).toThrowError(ERRORS.INVALID_FORMAT);
});
});
describe("getCodeStatus", () => {
it("查询状态不修改数据库", () => {
const code = generateCode();
insertCodes(db, [code], "常用包", 10);
consumeCode(db, code);
const before = db.prepare("SELECT used_uses FROM codes WHERE code = ?").get(code) as {
used_uses: number;
};
const status = getCodeStatus(db, code);
const after = db.prepare("SELECT used_uses FROM codes WHERE code = ?").get(code) as {
used_uses: number;
};
expect(status.remainingUses).toBe(9);
expect(status.totalUses).toBe(10);
expect(status.packageType).toBe("常用包");
expect(after.used_uses).toBe(before.used_uses);
});
it("不存在的兑换码抛出 CODE_NOT_FOUND", () => {
expect(() => getCodeStatus(db, generateCode())).toThrowError(ERRORS.NOT_FOUND);
});
});
describe("normalizeCode", () => {
it("去除首尾空白并转大写", () => {
expect(normalizeCode(" abcd ")).toBe("ABCD");
expect(normalizeCode("AbCdEf")).toBe("ABCDEF");
});
});
describe("CodeError", () => {
it("携带 HTTP 状态码与错误码", () => {
expect(ERRORS.NOT_FOUND.status).toBe(404);
expect(ERRORS.NOT_FOUND.code).toBe("CODE_NOT_FOUND");
expect(ERRORS.EXHAUSTED.status).toBe(400);
expect(ERRORS.EXHAUSTED.code).toBe("CODE_EXHAUSTED");
});
});
});
+216
View File
@@ -0,0 +1,216 @@
import { describe, it, expect, beforeEach } from "vitest";
import request from "supertest";
import type Database from "better-sqlite3";
import { createTestDatabase } from "../db/index.js";
import { createApp } from "../server.js";
import { generateCode, insertCodes } from "../codes/service.js";
const DEVICE_ID = "device-abc12345";
const DEVICE_ID_2 = "device-xyz98765";
describe("云端同步模块 (/api/sync)", () => {
let db: Database.Database;
beforeEach(() => {
db = createTestDatabase();
});
async function bind(deviceId: string, code: string) {
return request(createApp(db)).post("/api/sync/bind").send({ deviceId, code });
}
async function restore(deviceId: string) {
return request(createApp(db)).get("/api/sync/restore").query({ deviceId });
}
async function unbind(deviceId: string, code: string) {
return request(createApp(db)).post("/api/sync/unbind").send({ deviceId, code });
}
describe("POST /api/sync/bind", () => {
it("绑定有效兑换码成功,返回 access 信息", async () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 3);
const res = await bind(DEVICE_ID, code);
expect(res.status).toBe(200);
expect(res.body.ok).toBe(true);
expect(res.body.access).toEqual({
code,
packageType: "体验包",
remainingUses: 3,
totalUses: 3,
});
});
it("绑定不存在的兑换码返回 404「兑换码不存在」", async () => {
const res = await bind(DEVICE_ID, generateCode());
expect(res.status).toBe(404);
expect(res.body.error).toBe("兑换码不存在,请检查后重试");
});
it("绑定已用尽的兑换码返回 400「兑换码已用尽」", async () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 1);
db.prepare("UPDATE codes SET used_uses = 1, status = 'used' WHERE code = ?").run(code);
const res = await bind(DEVICE_ID, code);
expect(res.status).toBe(400);
expect(res.body.error).toBe("兑换码已用尽");
});
it("重复绑定同一兑换码幂等成功,不产生重复记录", async () => {
const code = generateCode();
insertCodes(db, [code], "常用包", 10);
const first = await bind(DEVICE_ID, code);
const second = await bind(DEVICE_ID, code);
expect(first.status).toBe(200);
expect(second.status).toBe(200);
expect(second.body.ok).toBe(true);
const count = db
.prepare("SELECT COUNT(*) AS n FROM device_bindings WHERE device_id = ? AND code = ?")
.get(DEVICE_ID, code) as { n: number };
expect(count.n).toBe(1);
});
it("同一兑换码可绑定到多个设备", async () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 3);
await bind(DEVICE_ID, code);
await bind(DEVICE_ID_2, code);
const count = db
.prepare("SELECT COUNT(*) AS n FROM device_bindings WHERE code = ?")
.get(code) as { n: number };
expect(count.n).toBe(2);
});
it("一个设备可绑定多个兑换码", async () => {
const codeA = generateCode();
const codeB = generateCode();
insertCodes(db, [codeA, codeB], "体验包", 3);
await bind(DEVICE_ID, codeA);
await bind(DEVICE_ID, codeB);
const res = await restore(DEVICE_ID);
expect(res.status).toBe(200);
expect(res.body.codes).toHaveLength(2);
});
it("无效设备标识(过短/非法字符)返回 400「设备标识无效」", async () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 3);
for (const bad of ["short", "!@#$%^&*", "way-too-long-device-id-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]) {
const res = await bind(bad, code);
expect(res.status).toBe(400);
expect(res.body.error).toBe("设备标识无效");
}
});
it("缺少参数返回 400 中文提示", async () => {
const missingDevice = await request(createApp(db))
.post("/api/sync/bind")
.send({ code: generateCode() });
expect(missingDevice.status).toBe(400);
expect(missingDevice.body.error).toBe("设备标识无效");
const missingCode = await bind(DEVICE_ID, "");
expect(missingCode.status).toBe(400);
expect(missingCode.body.error).toBe("请输入兑换码");
const badFormat = await bind(DEVICE_ID, "SHORT");
expect(badFormat.status).toBe(400);
expect(badFormat.body.error).toBe("兑换码格式不正确");
});
});
describe("GET /api/sync/restore", () => {
it("恢复设备绑定的兑换码,含剩余次数与状态", async () => {
const code = generateCode();
insertCodes(db, [code], "常用包", 10);
await bind(DEVICE_ID, code);
const res = await restore(DEVICE_ID);
expect(res.status).toBe(200);
expect(res.body.codes).toEqual([
{
code,
packageType: "常用包",
remainingUses: 10,
totalUses: 10,
status: "active",
},
]);
});
it("未绑定的设备返回空数组", async () => {
const res = await restore(DEVICE_ID);
expect(res.status).toBe(200);
expect(res.body.codes).toEqual([]);
});
it("设备标识无效返回 400「设备标识无效」", async () => {
const res = await restore("bad!");
expect(res.status).toBe(400);
expect(res.body.error).toBe("设备标识无效");
});
});
describe("POST /api/sync/unbind", () => {
it("解绑后 restore 不再返回该兑换码", async () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 3);
await bind(DEVICE_ID, code);
const res = await unbind(DEVICE_ID, code);
expect(res.status).toBe(200);
expect(res.body.ok).toBe(true);
const restored = await restore(DEVICE_ID);
expect(restored.body.codes).toEqual([]);
});
it("解绑未绑定的兑换码幂等成功(不报错)", async () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 3);
const res = await unbind(DEVICE_ID, code);
expect(res.status).toBe(200);
expect(res.body.ok).toBe(true);
});
it("解绑不删除其他设备/其他码的绑定", async () => {
const codeA = generateCode();
const codeB = generateCode();
insertCodes(db, [codeA, codeB], "体验包", 3);
await bind(DEVICE_ID, codeA);
await bind(DEVICE_ID, codeB);
await bind(DEVICE_ID_2, codeA);
await unbind(DEVICE_ID, codeA);
const restored = await restore(DEVICE_ID);
expect(restored.body.codes.map((c: { code: string }) => c.code)).toEqual([codeB]);
const restored2 = await restore(DEVICE_ID_2);
expect(restored2.body.codes.map((c: { code: string }) => c.code)).toEqual([codeA]);
});
it("参数校验失败返回 400 中文提示", async () => {
const code = generateCode();
insertCodes(db, [code], "体验包", 3);
const badDevice = await unbind("bad!", code);
expect(badDevice.status).toBe(400);
expect(badDevice.body.error).toBe("设备标识无效");
const badCode = await unbind(DEVICE_ID, "SHORT");
expect(badCode.status).toBe(400);
expect(badCode.body.error).toBe("兑换码格式不正确");
});
});
});
@@ -0,0 +1,90 @@
import { describe, it, expect } from "vitest";
import {
TEMPLATES,
buildPrompt,
buildNegativePrompt,
findTemplate,
} from "../chibi/prompts.js";
describe("chibi 提示词模板", () => {
it("15 套模板齐全(5 类 × 3 细分)", () => {
expect(TEMPLATES).toHaveLength(15);
const categories = new Set(TEMPLATES.map((t) => t.category));
expect(categories.size).toBe(5);
});
it("每套模板字段完整", () => {
for (const t of TEMPLATES) {
expect(t.basePrompt.length).toBeGreaterThan(10);
expect(t.negativePrompt.length).toBeGreaterThan(10);
expect(t.styleHint.length).toBeGreaterThan(0);
expect(t.subtypeName.length).toBeGreaterThan(0);
}
});
it("findTemplate 返回正确模板", () => {
const t = findTemplate("pet", "cat");
expect(t.subtypeName).toBe("猫咪头像");
expect(() => findTemplate("pet", "不存在")).toThrow();
});
it("buildPrompt 包含网格/颜色/构图", () => {
const p = buildPrompt({
category: "pet",
subtype: "cat",
gridSize: 64,
colorCount: 24,
composition: "主体特写",
detailTags: ["眼睛更有神", "保留毛色花纹", "突出耳朵轮廓", "纯色背景"],
});
expect(p).toContain("64×64");
expect(p).toContain("最多 24 色");
expect(p).toContain("主体主体特写");
expect(p).toContain("猫咪头像");
expect(p).toContain("眼睛更有神");
});
it("detailTags 最多取 5 项", () => {
const p = buildPrompt({
category: "food",
subtype: "dessert",
gridSize: 48,
colorCount: 16,
composition: "完整构图",
detailTags: ["a", "b", "c", "d", "e", "f", "g"],
});
const matches = p.match(/细节要求:[^,]+/);
const tags = matches ? matches[0].replace("细节要求:", "").split("、") : [];
expect(tags.length).toBeLessThanOrEqual(5);
});
it("customPrompt 追加到末尾", () => {
const p = buildPrompt({
category: "object",
subtype: "toy",
gridSize: 96,
colorCount: 40,
composition: "半幅构图",
detailTags: [],
customPrompt: "保留红色涂装",
});
expect(p.endsWith("保留红色涂装")).toBe(true);
});
it("参考图提示附加", () => {
const p = buildPrompt({
category: "person",
subtype: "retro",
gridSize: 80,
colorCount: 32,
composition: "主体特写",
detailTags: [],
hasReferenceImage: true,
});
expect(p).toContain("参考示例风格");
});
it("负面提示词非空", () => {
expect(buildNegativePrompt("landscape", "city").length).toBeGreaterThan(10);
});
});
+74
View File
@@ -0,0 +1,74 @@
// ---- Package Definitions ----
export interface PackageDefinition {
name: string;
uses: number;
priceCents: number; // price in cents (¥)
}
export const PACKAGE_DEFINITIONS: Record<string, PackageDefinition> = {
"体验包": { name: "体验包", uses: 3, priceCents: 490 },
"常用包": { name: "常用包", uses: 10, priceCents: 1290 },
"进阶包": { name: "进阶包", uses: 30, priceCents: 2990 },
"代理200": { name: "代理200", uses: 200, priceCents: 13900 },
"代理500": { name: "代理500", uses: 500, priceCents: 29900 },
"代理1000": { name: "代理1000", uses: 1000, priceCents: 49900 },
} as const;
// ---- Code Status ----
export type CodeStatus = "active" | "used" | "disabled";
// ---- Order Status ----
export type OrderStatus = "pending" | "paid" | "failed";
// ---- Redemption Action ----
export type RedemptionAction = "redeem" | "consume";
// ---- Access Object (matches competitor exactly) ----
export interface AccessInfo {
code: string;
remainingUses: number;
totalUses: number;
packageType: string;
}
// ---- Order Object ----
export interface OrderInfo {
orderNo: string;
packageName: string;
amountCents: number;
paymentMethod: string;
status: OrderStatus;
accessCode: string | null;
createdAt: string;
paidAt: string | null;
totalUses: number;
}
// ---- API Response types ----
export interface RedeemResponse {
access: AccessInfo;
}
export interface RedeemError {
error: string;
}
export interface ConsumeResponse {
access: AccessInfo;
freeDownload: boolean;
}
export interface StatusResponse {
access: AccessInfo;
}
export interface OrderResponse {
order: OrderInfo;
}