MCPcopy Index your code
hub / github.com/scriptscat/scriptcat / readRawContent

Function readRawContent

src/pkg/utils/encoding.ts:293–349  ·  view source on GitHub ↗
(
  raw: Blob | File | Response | Uint8Array<ArrayBuffer>,
  contentType: string | null
)

Source from the content-addressed store, hash-verified

291 * @returns {Promise<string>}
292 */
293export 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};

Callers 6

fetchIconByDomainFunction · 0.90
fetchScriptBodyFunction · 0.90
fetchScriptBodyFunction · 0.90
encoding.test.tsFile · 0.90

Calls 10

bytesDecodeFunction · 0.85
detectBOMFunction · 0.85
guessByNullPatternFunction · 0.85
assertLikelyUtf8Function · 0.85
decodeMostlyUtf8Function · 0.85
legacyDetectEncodingFunction · 0.85
warnMethod · 0.80
arrayBufferMethod · 0.45

Tested by 1