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

Function legacyDetectEncoding

src/pkg/utils/encoding.ts:179–223  ·  view source on GitHub ↗
(data: Uint8Array)

Source from the content-addressed store, hash-verified

177 * Header charset, BOM, UTF null-patterns, and valid UTF-8 are handled before this runs.
178 */
179const legacyDetectEncoding = (data: Uint8Array): string => {
180 const sample = createLegacyDetectionSample(data);
181 const analysedResult = chardet.analyse(sample).sort((a, b) => b.confidence - a.confidence);
182 let highestConfidence = -1;
183 const results = [];
184 let leastCharLen = Infinity;
185 for (const entry of analysedResult) {
186 const encoding = entry.name.toLowerCase();
187 if (unicodeEncodings.has(encoding)) continue;
188 let decodedText;
189 try {
190 // 验证检测到的编码是否有效
191 decodedText = bytesDecode(encoding, sample);
192 } catch (_e: any) {
193 // ignored
194 }
195 if (!decodedText) continue;
196 if (highestConfidence < 0) {
197 highestConfidence = entry.confidence;
198 if (highestConfidence > 90) return encoding;
199 } else if (highestConfidence > 70 && entry.confidence < 30) {
200 // 不考虑 confidence 过低的编码
201 break;
202 } else if (highestConfidence > 50 && entry.confidence < 20) {
203 // 不考虑 confidence 过低的编码
204 break;
205 }
206 // 当字元符少,不足以自动判断时,改用文本重复性测试
207 const chars = new Set(decodedText);
208 let charLen = chars.size;
209 if (charLen > leastCharLen) continue;
210 if (chars.has("\ufffd")) {
211 // 发现 REPLACEMENT CHARACTER,每个替代符视为独立字符,并至少增加1
212 const rplCharLen = decodedText.split("\ufffd").length - 1;
213 charLen += Math.max(rplCharLen, 1);
214 }
215 results.push({
216 encoding,
217 charLen: charLen,
218 });
219 if (charLen < leastCharLen) leastCharLen = charLen;
220 }
221 const ret = results.find((e) => e.charLen === leastCharLen);
222 return ret?.encoding || "windows-1252";
223};
224
225const detectBOM = (u8: Uint8Array): string | null => {
226 // UTF-8 BOM

Callers 1

readRawContentFunction · 0.85

Calls 5

bytesDecodeFunction · 0.85
sortMethod · 0.80
pushMethod · 0.80
hasMethod · 0.65

Tested by

no test coverage detected