2
0

route.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * API Route: 获取 json-render 组件提示词
  3. *
  4. * 返回 catalog.prompt() 生成的提示词
  5. * 前端可以在初始化时调用此 API 获取最新提示词
  6. */
  7. import { NextResponse } from 'next/server';
  8. import { readFile } from 'fs/promises';
  9. import { join } from 'path';
  10. // 缓存提示词(5分钟过期)
  11. let cachedPrompt: string | null = null;
  12. let cacheTime: number = 0;
  13. const CACHE_TTL = 5 * 60 * 1000; // 5 分钟
  14. export async function GET() {
  15. try {
  16. // 检查缓存
  17. const now = Date.now();
  18. if (cachedPrompt && (now - cacheTime) < CACHE_TTL) {
  19. return NextResponse.json({
  20. success: true,
  21. prompt: cachedPrompt,
  22. cached: true,
  23. length: cachedPrompt.length,
  24. });
  25. }
  26. // 读取预生成的提示词文件
  27. const promptPath = join(process.cwd(), 'lib/catalog/generated-prompt.txt');
  28. const prompt = await readFile(promptPath, 'utf-8');
  29. // 更新缓存
  30. cachedPrompt = prompt;
  31. cacheTime = now;
  32. return NextResponse.json({
  33. success: true,
  34. prompt,
  35. cached: false,
  36. length: prompt.length,
  37. generatedAt: new Date().toISOString(),
  38. });
  39. } catch (error) {
  40. console.error('Failed to read components prompt:', error);
  41. // 返回 fallback 提示词
  42. const fallbackPrompt = generateFallbackPrompt();
  43. return NextResponse.json({
  44. success: false,
  45. prompt: fallbackPrompt,
  46. error: 'Failed to read generated prompt, using fallback',
  47. length: fallbackPrompt.length,
  48. });
  49. }
  50. }
  51. /**
  52. * 生成 fallback 提示词(当文件读取失败时使用)
  53. */
  54. function generateFallbackPrompt(): string {
  55. return `## 可用的 json-render 组件
  56. 你可以使用以下组件来展示结构化数据。
  57. ### 基础组件
  58. - card: 卡片容器
  59. - stack: 弹性布局
  60. - heading: 标题 (h1-h6)
  61. - text: 文本
  62. - button: 按钮
  63. - badge: 徽章
  64. - code-block: 代码块
  65. ### MCP 专用组件
  66. - translation-result: 翻译结果
  67. - novel-list: 小说列表
  68. - chapter-reader: 章节阅读器
  69. - tool-call: 工具调用状态
  70. 组件格式示例:
  71. \`\`\`json
  72. {
  73. "type": "card",
  74. "title": "标题",
  75. "children": []
  76. }
  77. \`\`\`
  78. `;
  79. }