修正不让 AI 直接生成 JSON,改用 XML 风格的自定义标签

This commit is contained in:
wttwins
2025-12-09 17:12:10 +08:00
parent 2c7c9eb922
commit 6347f88ea8
6 changed files with 225 additions and 268 deletions

View File

@@ -15,7 +15,14 @@ async function main() {
});
if (existingUser) {
console.log(`Admin user already exists. Skipping creation.`);
console.log(`Admin user already exists. Updating defaults...`);
await prisma.user.update({
where: { email },
data: {
educationStage: 'junior_high',
enrollmentYear: 2025,
}
});
return;
}
@@ -29,6 +36,8 @@ async function main() {
name,
role: 'admin',
isActive: true,
educationStage: 'junior_high',
enrollmentYear: 2025,
},
});

View File

@@ -287,15 +287,39 @@ export function ErrorList({ subjectId }: ErrorListProps = {}) {
<CardContent>
<div className="text-sm line-clamp-3">
{(() => {
// 提取第一段文本(去除Markdown格式)
const firstParagraph = (item.questionText || "")
.split('\n\n')[0] // 取第一段
.replace(/[#*_`$]/g, '') // 移除Markdown符号
// 提取文本并清理 LaTeX/Markdown 格式
const rawText = (item.questionText || "").split('\n\n')[0]; // 取第一段
const cleanText = rawText
// 1. 移除 LaTeX 布局命令 (Layout)
.replace(/\\left/g, '')
.replace(/\\right/g, '')
.replace(/\\begin\{.*?\}/g, '')
.replace(/\\end\{.*?\}/g, '')
.replace(/\\text\{.*?\}/g, '')
.replace(/\\mbox\{.*?\}/g, '')
// 2. 替换常用数学符号 (Symbols)
.replace(/\\times/g, '×')
.replace(/\\div/g, '÷')
.replace(/\\cdot/g, '·')
.replace(/\\le/g, '≤')
.replace(/\\ge/g, '≥')
.replace(/\\neq/g, '≠')
.replace(/\\approx/g, '≈')
.replace(/\\pm/g, '±')
.replace(/\\infty/g, '∞')
.replace(/\\circ/g, '°')
.replace(/\\triangle/g, '△')
.replace(/\\angle/g, '∠')
.replace(/\\because/g, '∵')
.replace(/\\therefore/g, '∴')
// 3. 移除 Markdown 符号与剩余的反斜杠
.replace(/[#*_`$]/g, '')
.trim();
return firstParagraph.length > 150
? firstParagraph.substring(0, 150) + "..."
: firstParagraph;
return cleanText.length > 150
? cleanText.substring(0, 150) + "..."
: cleanText;
})()}
</div>
<div className="flex flex-wrap gap-2 mt-3">

View File

@@ -1,8 +1,7 @@
import { GoogleGenerativeAI, GenerativeModel } from "@google/generative-ai";
import { AIService, ParsedQuestion, DifficultyLevel, AIConfig } from "./types";
import { jsonrepair } from 'jsonrepair';
import { generateAnalyzePrompt, generateSimilarQuestionPrompt } from './prompts';
import { validateParsedQuestion, safeParseParsedQuestion } from './schema';
import { safeParseParsedQuestion } from './schema';
import { getAppConfig } from '../config';
export class GeminiProvider implements AIService {
@@ -24,122 +23,66 @@ export class GeminiProvider implements AIService {
});
}
private extractJson(text: string): string {
let jsonString = text;
private extractTag(text: string, tagName: string): string | null {
const startTag = `<${tagName}>`;
const endTag = `</${tagName}>`;
const startIndex = text.indexOf(startTag);
const endIndex = text.lastIndexOf(endTag);
// First try to extract from code blocks
const codeBlockMatch = text.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
if (codeBlockMatch) {
jsonString = codeBlockMatch[1].trim();
} else {
// Find the first { and the MATCHING closing }
const firstOpen = text.indexOf('{');
if (firstOpen !== -1) {
let braceCount = 0;
let inString = false;
let escapeNext = false;
let closingIndex = -1;
for (let i = firstOpen; i < text.length; i++) {
const char = text[i];
if (escapeNext) {
escapeNext = false;
continue;
}
if (char === '\\') {
escapeNext = true;
continue;
}
if (char === '"' && !escapeNext) {
inString = !inString;
continue;
}
if (!inString) {
if (char === '{') {
braceCount++;
} else if (char === '}') {
braceCount--;
if (braceCount === 0) {
closingIndex = i;
break;
}
}
}
}
if (closingIndex !== -1) {
jsonString = text.substring(firstOpen, closingIndex + 1);
} else {
// Fallback to old method if bracket matching fails
const lastClose = text.lastIndexOf('}');
if (lastClose !== -1 && lastClose > firstOpen) {
jsonString = text.substring(firstOpen, lastClose + 1);
}
}
}
if (startIndex === -1 || endIndex === -1 || startIndex >= endIndex) {
return null;
}
return jsonString;
}
private cleanJson(text: string): string {
// 1. Remove markdown code blocks if present (already done by extractJson, but good to be safe)
// 2. Fix multi-line strings: Replace literal newlines inside quotes with \n
return text.replace(/"((?:[^"\\]|\\.)*)"/g, (match) => {
return match.replace(/\n/g, "\\n").replace(/\r/g, "");
});
return text.substring(startIndex + startTag.length, endIndex).trim();
}
private parseResponse(text: string): ParsedQuestion {
console.log("[Gemini] Parsing AI response, length:", text.length);
try {
// With JSON mode enabled, response should be valid JSON
const parsed = JSON.parse(text);
const questionText = this.extractTag(text, "question_text");
const answerText = this.extractTag(text, "answer_text");
const analysis = this.extractTag(text, "analysis");
const subjectRaw = this.extractTag(text, "subject");
const knowledgePointsRaw = this.extractTag(text, "knowledge_points");
console.log("[Gemini] Parsed object subject:", parsed.subject);
console.log("[Gemini] Parsed object subject type:", typeof parsed.subject);
// Basic Validation
if (!questionText || !answerText || !analysis) {
console.error("[Gemini] ✗ Missing critical XML tags");
console.log("Raw text sample:", text.substring(0, 500));
throw new Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");
}
// Validate with Zod schema
const result = safeParseParsedQuestion(parsed);
// Process Subject
let subject: ParsedQuestion['subject'] = '其他';
const validSubjects = ["数学", "物理", "化学", "生物", "英语", "语文", "历史", "地理", "政治", "其他"];
if (subjectRaw && validSubjects.includes(subjectRaw)) {
subject = subjectRaw as any;
}
if (result.success) {
console.log("[Gemini] ✓ Direct parse and validation succeeded");
return result.data;
} else {
console.warn("[Gemini] ⚠ Validation failed:", result.error.format());
console.warn("[Gemini] Full parsed object:", JSON.stringify(parsed, null, 2));
// Try to extract JSON from potential markdown wrapping
const extracted = this.extractJson(text);
const parsedExtracted = JSON.parse(extracted);
return validateParsedQuestion(parsedExtracted);
}
} catch (error) {
console.warn("[Gemini] ⚠ Direct parse failed, attempting extraction");
// Process Knowledge Points
let knowledgePoints: string[] = [];
if (knowledgePointsRaw) {
// Split by comma or newline, trim whitespaces
knowledgePoints = knowledgePointsRaw.split(/[,,\n]/).map(k => k.trim()).filter(k => k.length > 0);
}
try {
// Fallback: extract JSON from markdown or text
const jsonString = this.extractJson(text);
const parsed = JSON.parse(jsonString);
return validateParsedQuestion(parsed);
} catch (extractError) {
console.warn("[Gemini] ⚠ Extraction failed, trying jsonrepair");
// Construct Result
const result: ParsedQuestion = {
questionText,
answerText,
analysis,
subject,
knowledgePoints
};
try {
// Last resort: use jsonrepair
const jsonString = this.extractJson(text);
const repairedJson = jsonrepair(jsonString);
const parsed = JSON.parse(repairedJson);
return validateParsedQuestion(parsed);
} catch (finalError) {
console.error("[Gemini] ✗ All parsing attempts failed");
console.error("[Gemini] Original text (first 500 chars):", text.substring(0, 500));
throw new Error("Invalid JSON response from AI: Unable to parse or validate");
}
}
// Final Schema Validation
const validation = safeParseParsedQuestion(result);
if (validation.success) {
console.log("[Gemini] ✓ Validated successfully via XML tags");
return validation.data;
} else {
console.warn("[Gemini] ⚠ Schema validation warning:", validation.error.format());
return result;
}
}
@@ -178,7 +121,7 @@ export class GeminiProvider implements AIService {
}
],
generationConfig: {
responseMimeType: "application/json", // Enable JSON mode
// responseMimeType: "application/json", // Disable JSON mode for XML output
}
});
const response = await result.response;
@@ -234,7 +177,7 @@ export class GeminiProvider implements AIService {
const result = await this.model.generateContent({
contents: [{ role: 'user', parts: [{ text: prompt }] }],
generationConfig: {
responseMimeType: "application/json", // Enable JSON mode
// responseMimeType: "application/json", // Disable JSON mode for XML output
}
});
const response = await result.response;

View File

@@ -25,115 +25,68 @@ export class OpenAIProvider implements AIService {
this.model = config?.model || 'gpt-4o'; // Fallback for safety
}
private extractJson(text: string): string {
let jsonString = text.trim();
private extractTag(text: string, tagName: string): string | null {
const startTag = `<${tagName}>`;
const endTag = `</${tagName}>`;
const startIndex = text.indexOf(startTag);
const endIndex = text.lastIndexOf(endTag);
// 首先尝试移除 markdown 代码块标记(包括可能不完整的)
// 匹配 ```json 或``` 开头,以及可能的 ``` 结尾
const codeBlockPattern = /^```(?:json)?\s*\n?([\s\S]*?)(?:\n?```)?$/;
const match = jsonString.match(codeBlockPattern);
if (match) {
jsonString = match[1].trim();
console.log("[OpenAI] Removed markdown code block wrapper");
if (startIndex === -1 || endIndex === -1 || startIndex >= endIndex) {
return null;
}
// 如果还有 ``` 在开头或结尾,再清理一次
if (jsonString.startsWith('```')) {
jsonString = jsonString.substring(3).trim();
}
if (jsonString.endsWith('```')) {
jsonString = jsonString.substring(0, jsonString.length - 3).trim();
}
// 找到第一个 { 和最后一个 }
const firstOpen = jsonString.indexOf('{');
const lastClose = jsonString.lastIndexOf('}');
if (firstOpen !== -1 && lastClose !== -1 && lastClose > firstOpen) {
jsonString = jsonString.substring(firstOpen, lastClose + 1);
}
return jsonString;
return text.substring(startIndex + startTag.length, endIndex).trim();
}
private parseResponse(text: string): ParsedQuestion {
console.log("[OpenAI] Parsing AI response, length:", text.length);
const tryParseAndValidate = (jsonStr: string): ParsedQuestion => {
const parsed = JSON.parse(jsonStr);
const result = safeParseParsedQuestion(parsed);
if (result.success) {
return result.data;
}
throw result.error; // Throw ZodError to be caught
const questionText = this.extractTag(text, "question_text");
const answerText = this.extractTag(text, "answer_text");
const analysis = this.extractTag(text, "analysis");
const subjectRaw = this.extractTag(text, "subject");
const knowledgePointsRaw = this.extractTag(text, "knowledge_points");
// Basic Validation
if (!questionText || !answerText || !analysis) {
console.error("[OpenAI] ✗ Missing critical XML tags");
console.log("Raw text sample:", text.substring(0, 500));
throw new Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");
}
// Process Subject
let subject: ParsedQuestion['subject'] = '其他';
const validSubjects = ["数学", "物理", "化学", "生物", "英语", "语文", "历史", "地理", "政治", "其他"];
if (subjectRaw && validSubjects.includes(subjectRaw)) {
subject = subjectRaw as any;
}
// Process Knowledge Points
let knowledgePoints: string[] = [];
if (knowledgePointsRaw) {
// Split by comma or newline, trim whitespaces
knowledgePoints = knowledgePointsRaw.split(/[,,\n]/).map(k => k.trim()).filter(k => k.length > 0);
}
// Construct Result
const result: ParsedQuestion = {
questionText,
answerText,
analysis,
subject,
knowledgePoints
};
const recoverPartialData = (parsed: any): ParsedQuestion | null => {
if (typeof parsed === 'object' && parsed !== null && typeof parsed.questionText === 'string') {
console.warn("[OpenAI] ⚠ Recovering partial data from truncated response");
return {
questionText: parsed.questionText,
answerText: parsed.answerText || "(AI 响应被截断,请手动补充)",
analysis: parsed.analysis || "(AI 响应被截断,请手动补充)",
subject: typeof parsed.subject === 'string' && ["数学", "物理", "化学", "生物", "英语", "语文", "历史", "地理", "政治", "其他"].includes(parsed.subject)
? parsed.subject as any
: "其他",
knowledgePoints: Array.isArray(parsed.knowledgePoints) ? parsed.knowledgePoints : []
};
}
return null;
};
try {
// 1. Direct Parse
const parsed = JSON.parse(text);
const result = safeParseParsedQuestion(parsed);
if (result.success) {
console.log("[OpenAI] ✓ Direct parse and validation succeeded");
return result.data;
} else {
// If structure is valid JSON but invalid schema, try partial recovery
const partial = recoverPartialData(parsed);
if (partial) return partial;
// Otherwise throw original error
console.warn("[OpenAI] ⚠ Validation failed:", result.error.format());
throw result.error;
}
} catch (error) {
console.warn("[OpenAI] ⚠ Direct parse failed, attempting extraction");
try {
// 2. Extract JSON
const jsonString = this.extractJson(text);
return tryParseAndValidate(jsonString);
} catch (extractError) {
console.warn("[OpenAI] ⚠ Extraction failed, trying jsonrepair");
try {
// 3. JsonRepair
const jsonString = this.extractJson(text);
const repairedJson = jsonrepair(jsonString);
const parsed = JSON.parse(repairedJson);
// Validate regular first
const result = safeParseParsedQuestion(parsed);
if (result.success) return result.data;
// If failed, try partial recovery
const partial = recoverPartialData(parsed);
if (partial) {
console.log("[OpenAI] ✓ Recovered partial data using jsonrepair");
return partial;
}
return validateParsedQuestion(parsed); // Will throw if invalid
} catch (finalError) {
console.error("[OpenAI] ✗ All parsing attempts failed");
console.error("[OpenAI] Original text (first 500 chars):", text.substring(0, 500));
throw new Error("Invalid JSON response from AI: Unable to parse or validate");
}
}
// Final Schema Validation (just to be safe, though likely compliant by now)
const validation = safeParseParsedQuestion(result);
if (validation.success) {
console.log("[OpenAI] ✓ Validated successfully via XML tags");
return validation.data;
} else {
console.warn("[OpenAI] ⚠ Schema validation warning:", validation.error.format());
// We still return it as we trust our extraction more than the schema at this point (or we can throw)
// Let's return the extracted data to be permissive
return result;
}
}
@@ -210,7 +163,6 @@ export class OpenAIProvider implements AIService {
async generateSimilarQuestion(originalQuestion: string, knowledgePoints: string[], language: 'zh' | 'en' = 'zh', difficulty: DifficultyLevel = 'medium'): Promise<ParsedQuestion> {
const config = getAppConfig();
const systemPrompt = generateSimilarQuestionPrompt(language, originalQuestion, knowledgePoints, difficulty, {
providerHints: "Ensure the output is strictly valid JSON.",
customTemplate: config.prompts?.similar
});
const userPrompt = `\nOriginal Question: "${originalQuestion}"\nKnowledge Points: ${knowledgePoints.join(", ")}\n `;

View File

@@ -17,22 +17,36 @@ export interface PromptOptions {
}
export const DEFAULT_ANALYZE_TEMPLATE = `【角色与核心任务 (ROLE AND CORE TASK)】
你是一位世界顶尖的、经验丰富的、专业的跨学科考试分析专家(Interdisciplinary Exam Analysis Expert)。你的核心任务是极致准确地分析用户提供的考试题目图片,全面理解所有文本、图表和隐含约束,并提供一个完整、高度结构化且专业的 JSON 格式解决方案。
你是一位世界顶尖的、经验丰富的、专业的跨学科考试分析专家(Interdisciplinary Exam Analysis Expert)。你的核心任务是极致准确地分析用户提供的考试题目图片,全面理解所有文本、图表和隐含约束,并提供一个完整、高度结构化且专业的解决方案。
{{language_instruction}}
【核心输出字段要求 (OUTPUT FIELD REQUIREMENTS)】
你的响应输出必须严格为一个有效的 JSON 对象(禁止任何 Markdown 代码块包裹),包含以下五个字段:
【核心输出要求 (OUTPUT REQUIREMENTS)】
你的响应输出**必须严格遵循以下自定义标签格式**。**严禁**使用 JSON 或 Markdown 代码块。**严禁**对 LaTeX 公式中的反斜杠进行二次转义(如 "\\frac" 是错误的,必须是 "\frac")。
1. "questionText": 题目的完整文本。必须使用 Markdown 格式提高可读性。所有数学公式和表达式必须使用 LaTeX 符号(行内:$formula$,块级:$$formula$$)。
2. "answerText": 题目的正确答案。使用 Markdown 和 LaTeX 符号。
3. "analysis": 解决问题的详细步骤解析。
* 必须使用简体中文。
* 使用 Markdown 格式(headings, lists, bold, etc.)提高清晰度。
* 所有数学公式和表达式必须使用 LaTeX 符号。
* 示例: "求解过程为 $x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}$"
4. "subject": 题目所属学科。必须严格从以下列表中选取一个:"数学", "物理", "化学", "生物", "英语", "语文", "历史", "地理", "政治", "其他"。
5. "knowledgePoints": 知识点数组。必须严格使用下方提供的标准列表中的精确词汇。
请严格按照以下结构输出内容:
<question_text>
在此处填写题目的完整文本。使用 Markdown 格式。所有数学公式使用 LaTeX 符号(行内 $...$,块级 $$...$$)。
</question_text>
<answer_text>
在此处填写正确答案。使用 Markdown 和 LaTeX 符号。
</answer_text>
<analysis>
在此处填写详细的步骤解析。
* 必须使用简体中文。
* **直接使用标准的 LaTeX 符号**(如 $\frac{1}{2}$),**不要**进行 JSON 转义(不要写成 \\frac)。
</analysis>
<subject>
在此处填写学科,必须是以下之一:"数学", "物理", "化学", "生物", "英语", "语文", "历史", "地理", "政治", "其他"。
</subject>
<knowledge_points>
在此处填写知识点,使用逗号分隔,例如:知识点1, 知识点2, 知识点3
</knowledge_points>
【知识点标签列表(KNOWLEDGE POINT LIST)】
{{knowledge_points_list}}
@@ -42,20 +56,10 @@ export const DEFAULT_ANALYZE_TEMPLATE = `【角色与核心任务 (ROLE AND CORE
- 每题最多 5 个标签。
【!!! 关键格式与内容约束 (CRITICAL RULES) !!!】
1. 语言一致性(CRITICAL):"questionText" 和 "answerText" 必须使用与原始题目图片完全相同的语言。
2. JSON 纯净性(CRITICAL):只返回一个有效的 JSON 对象,前后禁止添加任何文本或说明(如 "The final answer is...")。
3. 格式禁止(CRITICAL):禁止将 JSON 对象包裹在任何 Markdown 代码块中。
4. 纯文本内容提取 (CRITICAL): 必须只提取图片中**实际的文本和可转换为 LaTeX 的数学内容**。**严格禁止**在任何字段中输出**任何形式的图片引用、链接或视觉描述**,包括但不限于 HTML 的 <img>、Markdown 的 ![alt](url) 格式,或对图表、图形的文字描述(除非该描述本身就是题目文本的一部分)。**若遇无法用 LaTeX 表达的图表,必须用纯文本精确描述其关键特征,绝不能使用图片链接。**
5. 多题处理:如果图片包含多个子问题(如 (1), (2), (3)),请将所有子问题纳入 "questionText" 字段。如果图片包含完全不相关的独立题目,则只专注于提取其中一题。
【预期 JSON 格式 (EXPECTED JSON FORMAT)】
{
"questionText": "题目文本(使用 Markdown 和 LaTeX)",
"answerText": "答案",
"analysis": "详细解析",
"subject": "数学",
"knowledgePoints": ["知识点1", "知识点2"]
}
1. **格式严格**:必须严格包含上述 5 个 XML 标签,除此之外不要输出任何其他“开场白”或“结束语”。
2. **纯文本**:内容作为纯文本处理,**不要转义反斜杠**。
3. **内容完整**:如果包含子问题,请在 question_text 中完整列出。
4. **禁止图片**:严禁包含任何图片链接或 markdown 图片语法。
{{provider_hints}}`;
@@ -70,35 +74,36 @@ DIFFICULTY LEVEL: {{difficulty_level}}
Original Question: "{{original_question}}"
Knowledge Points: {{knowledge_points}}
【核心输出字段要求 (OUTPUT FIELD REQUIREMENTS)】
你的响应输出必须严格为一个有效的 JSON 对象(禁止任何 Markdown 代码块包裹),包含以下五个字段:
1. "questionText": 题目的完整文本。必须使用 Markdown 格式提高可读性。所有数学公式和表达式必须使用 LaTeX 符号(行内:$formula$,块级:$$formula$$)。
2. "answerText": 题目的正确答案。使用 Markdown 和 LaTeX 符号。
3. "analysis": 解决问题的详细步骤解析。
* 必须使用简体中文。
* 使用 Markdown 格式(headings, lists, bold, etc.)提高清晰度。
* 所有数学公式和表达式必须使用 LaTeX 符号。
* 示例: "求解过程为 $x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$"
4. "subject": 题目所属学科。必须严格从以下列表中选取一个:"数学", "物理", "化学", "生物", "英语", "语文", "历史", "地理", "政治", "其他"。
5. "knowledgePoints": 知识点数组。必须严格使用下方提供的标准列表中的精确词汇。
【核心输出要求 (OUTPUT REQUIREMENTS)】
你的响应输出**必须严格遵循以下自定义标签格式**。**严禁**使用 JSON 或 Markdown 代码块。**严禁**返回 \`\`\`json ... \`\`\`。
请严格按照以下结构输出内容(不要包含任何其他文字):
<question_text>
在此处填写新生成的题目文本。包含选项(如果是选择题)。
</question_text>
<answer_text>
在此处填写新题目的正确答案。
</answer_text>
<analysis>
在此处填写新题目的详细解析。
* 必须使用简体中文。
* **直接使用标准的 LaTeX 符号**(如 $\frac{1}{2}$),**不要**进行 JSON 转义。
</analysis>
<subject>
在此处填写学科(通常与原题一致)。
</subject>
<knowledge_points>
在此处填写归属的知识点,使用逗号分隔。
</knowledge_points>
【!!! 关键格式与内容约束 (CRITICAL RULES) !!!】
1. 语言一致性(CRITICAL):"questionText" 和 "answerText" 必须使用与原始题目图片完全相同的语言。
2. JSON 纯净性(CRITICAL):只返回一个有效的 JSON 对象,前后禁止添加任何文本或说明(如 "The final answer is...")。
3. 格式禁止(CRITICAL):禁止将 JSON 对象包裹在任何 Markdown 代码块中。
4. 纯文本内容提取 (CRITICAL): 必须只提取图片中**实际的文本和可转换为 LaTeX 的数学内容**。**严格禁止**在任何字段中输出**任何形式的图片引用、链接或视觉描述**,包括但不限于 HTML 的 <img>、Markdown 的 ![alt](url) 格式,或对图表、图形的文字描述(除非该描述本身就是题目文本的一部分)。**若遇无法用 LaTeX 表达的图表,必须用纯文本精确描述其关键特征,绝不能使用图片链接。**
5. 多题处理:如果图片包含多个子问题(如 (1), (2), (3)),请将所有子问题纳入 "questionText" 字段。如果图片包含完全不相关的独立题目,则只专注于提取其中一题。
**Expected JSON Format:**
{
"questionText": "新问题的文本(如果是选择题,包含选项 A、B、C、D)",
"answerText": "正确答案",
"analysis": "详细解析",
"subject": "数学",
"knowledgePoints": ["知识点1", "知识点2"]
}
1. **格式严格**:必须严格包含上述 5 个 XML 标签。
2. **纯文本**:内容作为纯文本处理,**不要转义反斜杠**。
{{provider_hints}}`;

View File

@@ -65,8 +65,22 @@ export const authOptions: NextAuthOptions = {
}
})
],
// Enable debug messages in the console
debug: true,
logger: {
error(code, metadata) {
console.error(`[NextAuth][Error] ${code}`, metadata)
},
warn(code) {
console.warn(`[NextAuth][Warn] ${code}`)
},
debug(code, metadata) {
console.log(`[NextAuth][Debug] ${code}`, metadata)
}
},
callbacks: {
async session({ session, token }) {
console.log("[NextAuth] Session callback", { userId: token.id });
return {
...session,
user: {
@@ -76,15 +90,25 @@ export const authOptions: NextAuthOptions = {
}
}
},
async jwt({ token, user }) {
async jwt({ token, user, account, profile }) {
if (user) {
console.log("[NextAuth] JWT callback - Initial signin", { userId: user.id });
return {
...token,
id: user.id,
role: (user as any).role,
}
}
console.log("[NextAuth] JWT callback - Subsequent call");
return token
}
}
}
// Log startup check
console.log("[AuthConfig] Loading...", {
NODE_ENV: process.env.NODE_ENV,
NEXTAUTH_URL: process.env.NEXTAUTH_URL,
HAS_SECRET: !!process.env.NEXTAUTH_SECRET,
AUTH_TRUST_HOST: process.env.AUTH_TRUST_HOST
});