| 291 | * @returns {Promise<string>} |
| 292 | */ |
| 293 | export const readRawContent = async ( |
| 294 | raw: Blob | File | Response | Uint8Array<ArrayBuffer>, |
| 295 | contentType: string | null |
| 296 | ): Promise<string> => { |
| 297 | let uint8: Uint8Array<ArrayBuffer>; |
| 298 | if (ArrayBuffer.isView(raw)) { |
| 299 | uint8 = new Uint8Array<ArrayBuffer>(raw.buffer, raw.byteOffset, raw.byteLength); |
| 300 | } else { |
| 301 | const buffer = await raw.arrayBuffer(); |
| 302 | uint8 = new Uint8Array<ArrayBuffer>(buffer); |
| 303 | } |
| 304 | |
| 305 | if (uint8.length === 0) { |
| 306 | return ""; |
| 307 | } |
| 308 | |
| 309 | // 优先尝试使用 Content-Type header 中的 charset |
| 310 | const headerCharset = parseCharsetFromContentType(contentType); |
| 311 | if (headerCharset) { |
| 312 | try { |
| 313 | // 验证 charset 是否有效 |
| 314 | return bytesDecode(headerCharset, uint8); |
| 315 | } catch (e: any) { |
| 316 | console.warn(`Invalid charset from Content-Type header: ${headerCharset}, error: ${e.message}`); |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | // BOM detection (after Content-Type header) |
| 321 | const bomEncoding = detectBOM(uint8); |
| 322 | if (bomEncoding) return bytesDecode(bomEncoding, uint8); |
| 323 | |
| 324 | const checkSize = Math.min(uint8.length, CHECK_SIZE); |
| 325 | |
| 326 | // Heuristic detection (first 16 KB) |
| 327 | const heuristicEncoding = guessByNullPattern(uint8, checkSize); |
| 328 | if (heuristicEncoding && validatesHeuristicEncoding(heuristicEncoding, uint8)) { |
| 329 | try { |
| 330 | return bytesDecode(heuristicEncoding, uint8); |
| 331 | } catch { |
| 332 | // Invalid full decode despite a valid sample: fall through to UTF-8/legacy. |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | // UTF-8 validation → legacy detection |
| 337 | let encoding = "utf-8"; |
| 338 | try { |
| 339 | assertLikelyUtf8(uint8); |
| 340 | } catch { |
| 341 | const mostlyUtf8 = decodeMostlyUtf8(uint8); |
| 342 | if (mostlyUtf8 !== null) return mostlyUtf8; |
| 343 | |
| 344 | // Invalid UTF-8 → use chardet-based legacy detection |
| 345 | encoding = legacyDetectEncoding(uint8); |
| 346 | } |
| 347 | |
| 348 | return bytesDecode(encoding, uint8); |
| 349 | }; |