| 107 | const encoder = new TextEncoder(); |
| 108 | |
| 109 | function truncate(value: string, maxBytes: number): string { |
| 110 | if (!value) return value; |
| 111 | const totalBytes = encoder.encode(value).byteLength; |
| 112 | if (totalBytes <= maxBytes) return value; |
| 113 | |
| 114 | let usedBytes = 0; |
| 115 | let endOffset = 0; |
| 116 | for (const char of value) { |
| 117 | const charBytes = encoder.encode(char).byteLength; |
| 118 | if (usedBytes + charBytes > maxBytes) break; |
| 119 | usedBytes += charBytes; |
| 120 | endOffset += char.length; |
| 121 | } |
| 122 | |
| 123 | return `${value.slice(0, endOffset)}\n\n[truncated, ${totalBytes - usedBytes} more bytes]`; |
| 124 | } |