Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import puppeteer from 'puppeteer'
3import { marked } from 'marked'
4import type { UIMessage } from '@tanstack/ai-client'
5
6interface MessagePart {
7 type: string
8 content?: string
9 name?: string
10 arguments?: string
11 output?: unknown
12}
13
14function messagesToMarkdown(
15 messages: Array<UIMessage>,
16 title?: string,
17): string {
18 const lines: Array<string> = []
19
20 // Embed CSS styles directly in the markdown
21 lines.push(`<style>
22body {
23 font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
24 line-height: 1.6;
25 color: #333;
26}
27h1 { color: #1a1a1a; border-bottom: 2px solid #0ea5e9; padding-bottom: 0.5em; }
28h2 { color: #374151; margin-top: 1.5em; }
29h3 { color: #4b5563; }
30code { background: #f3f4f6; padding: 0.2em 0.4em; border-radius: 4px; font-size: 0.9em; }
31pre { background: #1e293b; color: #e2e8f0; padding: 1em; border-radius: 8px; overflow-x: auto; }
32pre code { background: transparent; padding: 0; color: inherit; }
33hr { border: none; border-top: 1px solid #e5e7eb; margin: 1.5em 0; }
34blockquote { border-left: 4px solid #0ea5e9; margin: 1em 0; padding-left: 1em; color: #6b7280; }
35</style>`)
36 lines.push('')
37
38 lines.push(`# ${title || 'Conversation Export'}`)
39 lines.push('')
40 lines.push(`*Exported on ${new Date().toLocaleString()}*`)
41 lines.push('')
42 lines.push('---')
43 lines.push('')
44
45 for (const message of messages) {
46 const role =
47 message.role === 'assistant' ? '🤖 **Assistant**' : '👤 **User**'
48 lines.push(`## ${role}`)
49 lines.push('')
50
51 for (const part of message.parts as Array<MessagePart>) {
52 if (part.type === 'text' && part.content) {
53 lines.push(part.content)
54 lines.push('')
55 }
56
57 if (part.type === 'tool-call' && part.name === 'execute_typescript') {
58 lines.push('### 🔧 Code Execution')
59 lines.push('')
60
61 // Parse the arguments to get the code
62 let code = ''
63 try {
64 const args = JSON.parse(part.arguments || '{}')
65 code = args.typescriptCode || ''
66 } catch {
67 code = part.arguments || ''
68 }
69
70 if (code) {
71 lines.push('```typescript')
72 lines.push(code)
73 lines.push('```')
74 lines.push('')
75 }
76
77 // Add output if available
78 if (part.output !== undefined) {
79 lines.push('**Result:**')
80 lines.push('')
81 lines.push('```json')
82 lines.push(JSON.stringify(part.output, null, 2))
83 lines.push('```')
84 lines.push('')
85 }
86 }
87
88 // Handle tool results
89 if (part.type === 'tool-result') {
90 // Tool results are typically handled with their corresponding tool-call
91 // but we can still show them if they appear separately
92 }
93 }
94
95 lines.push('---')
96 lines.push('')
97 }
98
99 return lines.join('\n')
100}
101
102export const Route = createFileRoute('/_npm-github-chat/api/generate-pdf')({
103 server: {
104 handlers: {
105 POST: async ({ request }) => {
106 try {
107 const body = await request.json()
108 const { messages, title } = body as {
109 messages: Array<UIMessage>
110 title?: string
111 }
112
113 if (!messages || !Array.isArray(messages)) {
114 return new Response(
115 JSON.stringify({ error: 'Messages array is required' }),
116 {
117 status: 400,
118 headers: { 'Content-Type': 'application/json' },
119 },
120 )
121 }
122
123 // Convert messages to markdown
124 const markdown = messagesToMarkdown(messages, title)
125
126 // Convert markdown to HTML, then to PDF via puppeteer
127 const html = `<!DOCTYPE html>
128<html><head><meta charset="utf-8"><style>
129body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; max-width: 800px; margin: 0 auto; padding: 2em; }
130h1 { color: #1a1a1a; border-bottom: 2px solid #0ea5e9; padding-bottom: 0.5em; }
131h2 { color: #374151; margin-top: 1.5em; }
132h3 { color: #4b5563; }
133code { background: #f3f4f6; padding: 0.2em 0.4em; border-radius: 4px; font-size: 0.9em; }
134pre { background: #1e293b; color: #e2e8f0; padding: 1em; border-radius: 8px; overflow-x: auto; }
135pre code { background: transparent; padding: 0; color: inherit; }
136hr { border: none; border-top: 1px solid #e5e7eb; margin: 1.5em 0; }
137blockquote { border-left: 4px solid #0ea5e9; margin: 1em 0; padding-left: 1em; color: #6b7280; }
138</style></head><body>${await marked(markdown)}</body></html>`
139
140 const browser = await puppeteer.launch({ headless: true })
141 try {
142 const page = await browser.newPage()
143 await page.setContent(html, { waitUntil: 'networkidle0' })
144 const pdfBuffer = await page.pdf({
145 format: 'A4',
146 margin: {
147 top: '20mm',
148 right: '20mm',
149 bottom: '20mm',
150 left: '20mm',
151 },
152 printBackground: true,
153 })
154
155 const timestamp = new Date()
156 .toISOString()
157 .replace(/[:.]/g, '-')
158 .slice(0, 19)
159 const filename = `conversation-${timestamp}.pdf`
160
161 return new Response(new Uint8Array(pdfBuffer), {
162 status: 200,
163 headers: {
164 'Content-Type': 'application/pdf',
165 'Content-Disposition': `attachment; filename="${filename}"`,
166 'Content-Length': pdfBuffer.length.toString(),
167 },
168 })
169 } finally {
170 await browser.close()
171 }
172 } catch (error) {
173 console.error('[Generate PDF] Error:', error)
174 return new Response(
175 JSON.stringify({
176 error:
177 error instanceof Error
178 ? error.message
179 : 'Failed to generate PDF',
180 }),
181 {
182 status: 500,
183 headers: { 'Content-Type': 'application/json' },
184 },
185 )
186 }
187 },
188 },
189 },
190})