document-bytes 1.6.3 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -0
- package/dist/index.cjs +324 -0
- package/dist/index.d.cts +84 -1
- package/dist/index.d.ts +84 -1
- package/dist/index.js +320 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -53,6 +53,33 @@ To run a single test file, pass its path to vitest directly, e.g. `pnpm exec vit
|
|
|
53
53
|
| `image/png-decode` | `decodePng` (PNG bytes → raw pixels, handling every PNG colour type including indexed/palette via its own PLTE/tRNS lookup), `RawImage` |
|
|
54
54
|
| `image/png-filter` | `filterScanlines`, `unfilterScanlines` (the five PNG scanline filters) |
|
|
55
55
|
| `image/jpeg-info` | `readJpegInfo` (JPEG header reader: dimensions, components, progressive flag — no sample decoding) |
|
|
56
|
+
| `text/decode` | `decodeText`, `tryDecodeText`, `isProbablyText`, `UndecodableTextError`, `TEXT_DECODE_CHUNK_CODE_UNITS` (bytes → text with the character encoding worked out from the bytes; see [Text decoding](#text-decoding) below) |
|
|
57
|
+
|
|
58
|
+
## Text decoding
|
|
59
|
+
|
|
60
|
+
`decodeText` turns bytes into text without being told which character encoding they hold. It exists because the plain-text formats in this family used to assume UTF-8 and refuse everything else, which turns away Excel's own "CSV (Comma delimited)" export (the Windows ANSI code page) and anything Notepad saved as "Unicode" or PowerShell 5.1 wrote with a redirection operator (UTF-16 with a byte order mark).
|
|
61
|
+
|
|
62
|
+
The encoding is settled in a fixed order, and the result says which step settled it:
|
|
63
|
+
|
|
64
|
+
| Step | `source` | `confidence` | What decides it |
|
|
65
|
+
| ---- | ---------- | -------------------------------- | ----------------------------------------------------------------------------- |
|
|
66
|
+
| 1 | `declared` | `certain` | The caller's own `encoding` option, which skips detection entirely |
|
|
67
|
+
| 2 | `bom` | `certain` | A byte order mark: UTF-8, UTF-16LE/BE, UTF-32LE/BE |
|
|
68
|
+
| 3 | `detected` | `low` | The NUL interleave a mark-less UTF-16 file holding Latin-script text produces |
|
|
69
|
+
| 4 | `utf8` | `certain` for ASCII, else `high` | The bytes satisfy UTF-8's own validity rules |
|
|
70
|
+
| 5 | `detected` | `low` | windows-1252, behind a check that the bytes read as Western text |
|
|
71
|
+
|
|
72
|
+
Anything guessed (`confidence: "low"`) also carries a `warnings` entry naming what was guessed and on what evidence, so a guess can be shown as a guess rather than presented as fact. windows-1252 has a character for all but five of its byte values, so trying it and seeing whether it fails proves nothing: the plausibility check, and reporting the result as a guess, are what stand in for a test that cannot exist.
|
|
73
|
+
|
|
74
|
+
Bytes that are not text at all are refused with an `UndecodableTextError` before any guess is made, since without that gate windows-1252 would read a PNG as a page of mojibake instead of refusing it. `isProbablyText` is that judgement on its own, for a caller whose real question is whether bytes are text: a NUL byte, or more than one C0 control byte other than tab, line feed, form feed and carriage return per 64 bytes, says binary.
|
|
75
|
+
|
|
76
|
+
Everything except UTF-8 is decoded by this package rather than through `TextDecoder`. `TextDecoder`'s legacy single-byte and UTF-16 support comes from the host's ICU build, which a Node binary compiled with small-icu does not carry, and the [Encoding Standard](https://encoding.spec.whatwg.org/#names-and-labels) has no UTF-32 at all, so delegating would make the same bytes decode differently, or not at all, depending on where the code runs. The `pnpm test:workers` suite decodes windows-1252, UTF-16 and UTF-32 inside a real `workerd` isolate for exactly that reason, and one unit test checks the whole windows-1252 table, all 256 bytes, against the platform's own decoder wherever the platform has one.
|
|
77
|
+
|
|
78
|
+
Three limits are worth knowing rather than discovering:
|
|
79
|
+
|
|
80
|
+
- UTF-16 holding CJK text has no NUL interleave to see, so without a byte order mark it is not detected. Pass `encoding` for it.
|
|
81
|
+
- A legacy CJK or Cyrillic code page is refused rather than guessed at, since nothing distinguishes those from one another without a statistical model this package deliberately does not carry.
|
|
82
|
+
- A truncated UTF-8 sequence is genuinely indistinguishable from windows-1252 text containing the same characters, so it decodes as the latter, with a `low` confidence and a warning.
|
|
56
83
|
|
|
57
84
|
## Conventions
|
|
58
85
|
|
package/dist/index.cjs
CHANGED
|
@@ -224,6 +224,325 @@ function inflateTolerant(data) {
|
|
|
224
224
|
};
|
|
225
225
|
}
|
|
226
226
|
//#endregion
|
|
227
|
+
//#region src/text/decode.ts
|
|
228
|
+
/** Thrown when bytes cannot be turned into text: they are not text at all, they contradict a declared or marked encoding, or they match none of the supported encodings. */
|
|
229
|
+
var UndecodableTextError = class extends Error {
|
|
230
|
+
/** Which of the three failures this was, for a caller that treats them differently. */
|
|
231
|
+
reason;
|
|
232
|
+
constructor(reason, message) {
|
|
233
|
+
super(message);
|
|
234
|
+
this.name = "UndecodableTextError";
|
|
235
|
+
this.reason = reason;
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
/** NUL, as a byte and as a code unit alike: it belongs to no text under either reading. */
|
|
239
|
+
const NUL_CODE = 0;
|
|
240
|
+
/** The first character code that is not a C0 control. */
|
|
241
|
+
const FIRST_NON_CONTROL_CODE = 32;
|
|
242
|
+
/** The first byte outside ASCII, which is also where every encoding in the supported set stops agreeing with every other. */
|
|
243
|
+
const FIRST_HIGH_BYTE = 128;
|
|
244
|
+
/** The C1 control range, which is both where windows-1252 differs from ISO-8859-1 and the range whose presence in a decoded result says the guess was wrong. Its start doubles as the first byte the windows-1252 table below covers. */
|
|
245
|
+
const C1_CONTROL_START = 128;
|
|
246
|
+
const C1_CONTROL_END = 159;
|
|
247
|
+
/** C0 controls that appear in real text: tab, line feed, form feed, carriage return. Every other code below {@link FIRST_NON_CONTROL_CODE} belongs to binary content. */
|
|
248
|
+
const TEXTUAL_CONTROL_CODES = /* @__PURE__ */ new Set([
|
|
249
|
+
9,
|
|
250
|
+
10,
|
|
251
|
+
12,
|
|
252
|
+
13
|
|
253
|
+
]);
|
|
254
|
+
/** One C0 control outside {@link TEXTUAL_CONTROL_CODES} is permitted per this many characters before the content is taken for binary. Plain text carries none at all, so the allowance exists only to tolerate a stray one, an end-of-file Ctrl-Z left by a DOS-era editor being the case that actually occurs; compressed and image data puts roughly an eighth of its bytes in the C0 range, more than an order of magnitude above this. Counted as integer arithmetic against the length rather than a floating-point ratio so the boundary is exact. */
|
|
255
|
+
const CODES_PER_PERMITTED_CONTROL = 64;
|
|
256
|
+
/** The longest run of consecutive bytes at or above {@link FIRST_HIGH_BYTE} the windows-1252 guess accepts. Latin-script text sets an accented letter inside otherwise-ASCII words, so even the most accent-dense Western orthography never strings many together; text in a non-Latin single-byte code page, and bytes that are not text at all, put whole words above that boundary and run far longer. A caller holding bytes that genuinely do (a line of nothing but bullets, say) names the encoding explicitly rather than relying on the guess. */
|
|
257
|
+
const MAX_HIGH_BYTE_RUN = 4;
|
|
258
|
+
/** windows-1252's own mapping for the bytes from {@link C1_CONTROL_START} to {@link C1_CONTROL_END}, the one range where it differs from ISO-8859-1: bytes below are ASCII and bytes above are ISO-8859-1 exactly, so neither needs a table. Held as a string rather than an array so a lookup is a `charCodeAt` on a fixed-length string, with no index the type system has to be told is in range. Five positions (0x81, 0x8D, 0x8F, 0x90, 0x9D) have no character in Microsoft's own code page; the Encoding Standard maps them to the matching C1 control characters so that its decoder is total, and this table does the same, so decoding here and decoding through a TextDecoder that does support the label agree byte for byte. */
|
|
259
|
+
const WINDOWS_1252_HIGH_RANGE = "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";
|
|
260
|
+
/** The bytes windows-1252 leaves without a character of their own, derived from {@link WINDOWS_1252_HIGH_RANGE} as exactly those positions whose mapping lands back in the C1 control range instead of on a real character. A C1 control appears in no text document, so one of these bytes says the content is not windows-1252 text whatever else it may be. */
|
|
261
|
+
const WINDOWS_1252_UNDEFINED_BYTES = new Set(Array.from(WINDOWS_1252_HIGH_RANGE).flatMap((character, index) => {
|
|
262
|
+
const codePoint = character.charCodeAt(0);
|
|
263
|
+
return codePoint >= C1_CONTROL_START && codePoint <= C1_CONTROL_END ? [C1_CONTROL_START + index] : [];
|
|
264
|
+
}));
|
|
265
|
+
/** UTF-16's surrogate range, whose halves pair up to carry a code point above the basic plane and which is never a code point in its own right. */
|
|
266
|
+
const HIGH_SURROGATE_START = 55296;
|
|
267
|
+
const HIGH_SURROGATE_END = 56319;
|
|
268
|
+
const LOW_SURROGATE_START = 56320;
|
|
269
|
+
const LOW_SURROGATE_END = 57343;
|
|
270
|
+
/** The highest code point Unicode defines, and the first one that needs a surrogate pair to reach in UTF-16. */
|
|
271
|
+
const MAX_CODE_POINT = 1114111;
|
|
272
|
+
const SUPPLEMENTARY_PLANE_START = 65536;
|
|
273
|
+
/** How a supplementary code point splits across a surrogate pair: the ten low bits go to the low half and the rest to the high half, both biased by the start of their own range. */
|
|
274
|
+
const SURROGATE_BITS = 10;
|
|
275
|
+
const LOW_SURROGATE_MASK = 1023;
|
|
276
|
+
/**
|
|
277
|
+
* Code units converted by one `String.fromCharCode.apply` call. JavaScriptCore rejects a call with more than 65536 arguments, a limit MDN documents as hard-coded (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), and other engines bound the same thing by stack size, so this is half that stated figure, leaving the engine room for whatever else it puts on its argument stack. The same quantum src/bytes/base64.ts's own chunked encode uses, for the same reason: appending one character at a time to a string is what made converting a few megabytes take seconds under instrumentation.
|
|
278
|
+
*
|
|
279
|
+
* Exported so tests can place inputs on and around a chunk boundary without repeating the figure.
|
|
280
|
+
*/
|
|
281
|
+
const TEXT_DECODE_CHUNK_CODE_UNITS = 32768;
|
|
282
|
+
function fromCodeUnits(units) {
|
|
283
|
+
return Array.from({ length: Math.ceil(units.length / TEXT_DECODE_CHUNK_CODE_UNITS) }, (_unused, chunk) => {
|
|
284
|
+
const start = chunk * TEXT_DECODE_CHUNK_CODE_UNITS;
|
|
285
|
+
return String.fromCharCode.apply(null, units.slice(start, start + TEXT_DECODE_CHUNK_CODE_UNITS));
|
|
286
|
+
}).join("");
|
|
287
|
+
}
|
|
288
|
+
/** Every byte order mark, longest first: UTF-32LE's begins with UTF-16LE's, so the four-byte marks have to be tested before the two-byte ones. Unicode resolves that overlap the same way, the alternative reading being a UTF-16LE file whose first character is U+0000, which is not a file that occurs. */
|
|
289
|
+
const BOM_SIGNATURES = [
|
|
290
|
+
{
|
|
291
|
+
encoding: "utf-32be",
|
|
292
|
+
bytes: [
|
|
293
|
+
0,
|
|
294
|
+
0,
|
|
295
|
+
254,
|
|
296
|
+
255
|
|
297
|
+
]
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
encoding: "utf-32le",
|
|
301
|
+
bytes: [
|
|
302
|
+
255,
|
|
303
|
+
254,
|
|
304
|
+
0,
|
|
305
|
+
0
|
|
306
|
+
]
|
|
307
|
+
},
|
|
308
|
+
{
|
|
309
|
+
encoding: "utf-8",
|
|
310
|
+
bytes: [
|
|
311
|
+
239,
|
|
312
|
+
187,
|
|
313
|
+
191
|
|
314
|
+
]
|
|
315
|
+
},
|
|
316
|
+
{
|
|
317
|
+
encoding: "utf-16be",
|
|
318
|
+
bytes: [254, 255]
|
|
319
|
+
},
|
|
320
|
+
{
|
|
321
|
+
encoding: "utf-16le",
|
|
322
|
+
bytes: [255, 254]
|
|
323
|
+
}
|
|
324
|
+
];
|
|
325
|
+
function findBom(bytes) {
|
|
326
|
+
return BOM_SIGNATURES.find((signature) => signature.bytes.every((value, index) => bytes[index] === value));
|
|
327
|
+
}
|
|
328
|
+
/** The bytes past a byte order mark for `encoding`, or the bytes unchanged when they carry no such mark. A mark for a different encoding is left alone: under a declared encoding it is content, not a mark. */
|
|
329
|
+
function stripBom(bytes, encoding) {
|
|
330
|
+
const bom = findBom(bytes);
|
|
331
|
+
return bom?.encoding === encoding ? bytes.subarray(bom.bytes.length) : bytes;
|
|
332
|
+
}
|
|
333
|
+
function tryDecodeUtf8(bytes) {
|
|
334
|
+
try {
|
|
335
|
+
return new TextDecoder("utf-8", {
|
|
336
|
+
fatal: true,
|
|
337
|
+
ignoreBOM: true
|
|
338
|
+
}).decode(bytes);
|
|
339
|
+
} catch {
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
function decodeUtf16(bytes, littleEndian) {
|
|
344
|
+
if (bytes.byteLength % 2 !== 0) throw new UndecodableTextError("malformed", "UTF-16 text must hold a whole number of 16-bit code units");
|
|
345
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
346
|
+
const units = [];
|
|
347
|
+
for (let offset = 0; offset < bytes.byteLength; offset += 2) units.push(view.getUint16(offset, littleEndian));
|
|
348
|
+
let awaitingLowSurrogate = false;
|
|
349
|
+
for (const unit of units) {
|
|
350
|
+
if (awaitingLowSurrogate !== (unit >= LOW_SURROGATE_START && unit <= LOW_SURROGATE_END)) throw new UndecodableTextError("malformed", "UTF-16 text must pair every surrogate half with its partner");
|
|
351
|
+
awaitingLowSurrogate = unit >= HIGH_SURROGATE_START && unit <= HIGH_SURROGATE_END;
|
|
352
|
+
}
|
|
353
|
+
if (awaitingLowSurrogate) throw new UndecodableTextError("malformed", "UTF-16 text must pair every surrogate half with its partner");
|
|
354
|
+
return fromCodeUnits(units);
|
|
355
|
+
}
|
|
356
|
+
function tryDecodeUtf16(bytes, littleEndian) {
|
|
357
|
+
try {
|
|
358
|
+
return decodeUtf16(bytes, littleEndian);
|
|
359
|
+
} catch {
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
function decodeUtf32(bytes, littleEndian) {
|
|
364
|
+
if (bytes.byteLength % 4 !== 0) throw new UndecodableTextError("malformed", "UTF-32 text must hold a whole number of 32-bit code units");
|
|
365
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
366
|
+
const units = [];
|
|
367
|
+
for (let offset = 0; offset < bytes.byteLength; offset += 4) {
|
|
368
|
+
const codePoint = view.getUint32(offset, littleEndian);
|
|
369
|
+
if (codePoint > MAX_CODE_POINT || codePoint >= HIGH_SURROGATE_START && codePoint <= LOW_SURROGATE_END) throw new UndecodableTextError("malformed", "UTF-32 text must hold only Unicode scalar values");
|
|
370
|
+
if (codePoint < SUPPLEMENTARY_PLANE_START) {
|
|
371
|
+
units.push(codePoint);
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
const supplementary = codePoint - SUPPLEMENTARY_PLANE_START;
|
|
375
|
+
units.push(HIGH_SURROGATE_START + (supplementary >> SURROGATE_BITS));
|
|
376
|
+
units.push(LOW_SURROGATE_START + (supplementary & LOW_SURROGATE_MASK));
|
|
377
|
+
}
|
|
378
|
+
return fromCodeUnits(units);
|
|
379
|
+
}
|
|
380
|
+
function decodeWindows1252(bytes) {
|
|
381
|
+
const units = [];
|
|
382
|
+
for (const byte of bytes) units.push(byte < C1_CONTROL_START || byte > C1_CONTROL_END ? byte : WINDOWS_1252_HIGH_RANGE.charCodeAt(byte - C1_CONTROL_START));
|
|
383
|
+
return fromCodeUnits(units);
|
|
384
|
+
}
|
|
385
|
+
function decodeUtf8(bytes) {
|
|
386
|
+
const text = tryDecodeUtf8(bytes);
|
|
387
|
+
if (text === void 0) throw new UndecodableTextError("malformed", "UTF-8 text must hold only well-formed byte sequences");
|
|
388
|
+
return text;
|
|
389
|
+
}
|
|
390
|
+
/** One decoder per supported encoding, as a record keyed by the encoding union itself so that adding an encoding to {@link TextEncodingLabel} without a decoder for it is a compile error rather than a run-time gap. */
|
|
391
|
+
const DECODERS = {
|
|
392
|
+
"utf-8": decodeUtf8,
|
|
393
|
+
"utf-16le": (bytes) => decodeUtf16(bytes, true),
|
|
394
|
+
"utf-16be": (bytes) => decodeUtf16(bytes, false),
|
|
395
|
+
"utf-32le": (bytes) => decodeUtf32(bytes, true),
|
|
396
|
+
"utf-32be": (bytes) => decodeUtf32(bytes, false),
|
|
397
|
+
"windows-1252": decodeWindows1252
|
|
398
|
+
};
|
|
399
|
+
/** The text-versus-binary rule itself, over character codes: a NUL settles it outright, and every other C0 control outside {@link TEXTUAL_CONTROL_CODES} is allowed only up to one per {@link CODES_PER_PERMITTED_CONTROL}. Reading codes through an accessor rather than taking an array lets the identical rule run over a Uint8Array's bytes and over a decoded string's code units without copying either into one. */
|
|
400
|
+
function codesAreTextual(codeAt, length) {
|
|
401
|
+
let controlCodes = 0;
|
|
402
|
+
for (let index = 0; index < length; index += 1) {
|
|
403
|
+
const code = codeAt(index);
|
|
404
|
+
if (code === NUL_CODE) return false;
|
|
405
|
+
if (code < FIRST_NON_CONTROL_CODE && !TEXTUAL_CONTROL_CODES.has(code)) controlCodes += 1;
|
|
406
|
+
}
|
|
407
|
+
return controlCodes * CODES_PER_PERMITTED_CONTROL <= length;
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Whether bytes can hold text at all, judged without reference to which encoding they might be in.
|
|
411
|
+
*
|
|
412
|
+
* A NUL byte belongs to no text document format, and outside NUL the only C0 control bytes text carries are tab, line feed, form feed and carriage return, so a density of any others says binary. {@link decodeText} asks this before it guesses at windows-1252, which maps nearly every byte to some character and would otherwise read a PNG as a page of mojibake rather than refusing it.
|
|
413
|
+
*
|
|
414
|
+
* UTF-16 is the one text encoding this returns `false` for, since it interleaves NUL bytes by design. {@link decodeText} settles UTF-16 from a byte order mark or that same interleave before it reaches this check, and applies the identical rule to the characters a mark-less UTF-16 guess produced, so that guess cannot smuggle binary past this one.
|
|
415
|
+
* @param bytes - The bytes to judge.
|
|
416
|
+
* @returns Whether the bytes carry no NUL and few enough other C0 control bytes to be text.
|
|
417
|
+
*/
|
|
418
|
+
function isProbablyText(bytes) {
|
|
419
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
420
|
+
return codesAreTextual((index) => view.getUint8(index), bytes.byteLength);
|
|
421
|
+
}
|
|
422
|
+
/** {@link isProbablyText}'s own question asked of characters rather than of bytes, for a decode that has already happened. A multi-byte encoding puts NULs and other low bytes into its bytes as part of how it spells ordinary characters, so the bytes cannot answer it; the characters that came out can. */
|
|
423
|
+
function isTextualString(text) {
|
|
424
|
+
return codesAreTextual((index) => text.charCodeAt(index), text.length);
|
|
425
|
+
}
|
|
426
|
+
/** Whether the bytes could be windows-1252 text, as opposed to some other single-byte code page or no text at all. windows-1252 has a character for all but five of its byte values, so trying it and seeing whether it fails proves nothing; these two structural tests are what stands in for that. */
|
|
427
|
+
function looksLikeWindows1252Text(bytes) {
|
|
428
|
+
let highByteRun = 0;
|
|
429
|
+
for (const byte of bytes) {
|
|
430
|
+
if (WINDOWS_1252_UNDEFINED_BYTES.has(byte)) return false;
|
|
431
|
+
if (byte < FIRST_HIGH_BYTE) {
|
|
432
|
+
highByteRun = 0;
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
highByteRun += 1;
|
|
436
|
+
if (highByteRun > MAX_HIGH_BYTE_RUN) return false;
|
|
437
|
+
}
|
|
438
|
+
return true;
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* UTF-16 without a byte order mark, recognised from the NUL a code unit below U+0100 puts on one fixed side of every unit pair.
|
|
442
|
+
*
|
|
443
|
+
* The recognised case is UTF-16 holding mostly Latin-script text, which is the only case a NUL interleave makes visible at all: UTF-16 holding CJK text has no NUL high bytes to see and is indistinguishable from other byte sequences without the statistical model this module does not carry.
|
|
444
|
+
*
|
|
445
|
+
* A majority of the units carrying a NUL on one fixed side is the whole of the test, and it is deliberately not also a comparison between the two sides. Bytes that put NULs on both sides, padding rather than text, do satisfy it, and are answered by the decode rather than here: a unit whose two bytes are both NUL decodes to U+0000, which is not text, so the caller's own check on the decoded characters refuses them. Requiring one side to beat the other would be unobservable, since a tie can only arise when some unit carries NULs on both sides, which is exactly the case that cannot survive that check. An odd byte count is left to the decoder for the same reason: it has no whole final code unit, so decoding it fails and the bytes are refused there.
|
|
446
|
+
*/
|
|
447
|
+
function detectBomlessUtf16(bytes) {
|
|
448
|
+
let evenIndexNuls = 0;
|
|
449
|
+
let oddIndexNuls = 0;
|
|
450
|
+
let atEvenIndex = true;
|
|
451
|
+
for (const byte of bytes) {
|
|
452
|
+
if (byte === NUL_CODE) {
|
|
453
|
+
if (atEvenIndex) evenIndexNuls += 1;
|
|
454
|
+
else oddIndexNuls += 1;
|
|
455
|
+
}
|
|
456
|
+
atEvenIndex = !atEvenIndex;
|
|
457
|
+
}
|
|
458
|
+
const units = bytes.length / 2;
|
|
459
|
+
if (oddIndexNuls * 2 > units) return "utf-16le";
|
|
460
|
+
if (evenIndexNuls * 2 > units) return "utf-16be";
|
|
461
|
+
}
|
|
462
|
+
const BINARY_MESSAGE = "bytes are not text: they carry a NUL byte, or too many other C0 control bytes for any text encoding";
|
|
463
|
+
function refuseAsBinary() {
|
|
464
|
+
throw new UndecodableTextError("binary", BINARY_MESSAGE);
|
|
465
|
+
}
|
|
466
|
+
function guessWarning(encoding, evidence) {
|
|
467
|
+
return `encoding was guessed as ${encoding}: ${evidence}. Pass an explicit encoding if that is wrong.`;
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Decodes bytes to text, working out which character encoding they hold.
|
|
471
|
+
*
|
|
472
|
+
* The encoding is settled in a fixed order: the `encoding` option if the caller gave one, then a byte order mark, then the NUL interleave UTF-16 leaves when it holds Latin-script text and carries no mark, then UTF-8 if the bytes satisfy its own validity rules, then windows-1252 if the bytes read as Western text. Anything a byte order mark or the caller names is decoded under that encoding alone and fails if the bytes contradict it. Everything reached by detection reports how it was reached, so a caller can show the encoding, and a guess additionally carries a warning and a `low` confidence rather than being presented as fact.
|
|
473
|
+
*
|
|
474
|
+
* Bytes that are not text (a NUL byte, or a density of other C0 control bytes) are refused before any guess is made, so detection never widens what counts as text. The readings whose bytes carry NULs legitimately, mark-less UTF-16 and anything behind a UTF-16 or UTF-32 byte order mark, are judged by the same rule applied to the characters they produced instead. Only an explicit `encoding` from the caller skips the judgement entirely, since that is the caller overriding detection outright. A byte order mark is removed from the result rather than left as a leading U+FEFF.
|
|
475
|
+
* @param bytes - The bytes to decode.
|
|
476
|
+
* @param options - An explicit `encoding` to decode under, skipping detection.
|
|
477
|
+
* @throws UndecodableTextError When the bytes are not text, contradict a declared or marked encoding, or match none of the supported encodings.
|
|
478
|
+
* @returns The text, the encoding it was decoded under, and how far that account of the encoding can be relied on.
|
|
479
|
+
*/
|
|
480
|
+
function decodeText(bytes, options = {}) {
|
|
481
|
+
const declared = options.encoding;
|
|
482
|
+
if (declared !== void 0) return {
|
|
483
|
+
text: DECODERS[declared](stripBom(bytes, declared)),
|
|
484
|
+
encoding: declared,
|
|
485
|
+
source: "declared",
|
|
486
|
+
confidence: "certain",
|
|
487
|
+
warnings: []
|
|
488
|
+
};
|
|
489
|
+
const bom = findBom(bytes);
|
|
490
|
+
if (bom !== void 0) {
|
|
491
|
+
const text = DECODERS[bom.encoding](bytes.subarray(bom.bytes.length));
|
|
492
|
+
if (!isTextualString(text)) refuseAsBinary();
|
|
493
|
+
return {
|
|
494
|
+
text,
|
|
495
|
+
encoding: bom.encoding,
|
|
496
|
+
source: "bom",
|
|
497
|
+
confidence: "certain",
|
|
498
|
+
warnings: []
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
const interleaved = detectBomlessUtf16(bytes);
|
|
502
|
+
if (interleaved !== void 0) {
|
|
503
|
+
const guessed = tryDecodeUtf16(bytes, interleaved === "utf-16le");
|
|
504
|
+
if (guessed !== void 0 && isTextualString(guessed)) return {
|
|
505
|
+
text: guessed,
|
|
506
|
+
encoding: interleaved,
|
|
507
|
+
source: "detected",
|
|
508
|
+
confidence: "low",
|
|
509
|
+
warnings: [guessWarning(interleaved, "the bytes carry no byte order mark, but interleave NUL bytes in the pattern UTF-16 gives Latin-script text")]
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
if (!isProbablyText(bytes)) refuseAsBinary();
|
|
513
|
+
const utf8 = tryDecodeUtf8(bytes);
|
|
514
|
+
if (utf8 !== void 0) return {
|
|
515
|
+
text: utf8,
|
|
516
|
+
encoding: "utf-8",
|
|
517
|
+
source: "utf8",
|
|
518
|
+
confidence: utf8.length === bytes.length ? "certain" : "high",
|
|
519
|
+
warnings: []
|
|
520
|
+
};
|
|
521
|
+
if (looksLikeWindows1252Text(bytes)) return {
|
|
522
|
+
text: decodeWindows1252(bytes),
|
|
523
|
+
encoding: "windows-1252",
|
|
524
|
+
source: "detected",
|
|
525
|
+
confidence: "low",
|
|
526
|
+
warnings: [guessWarning("windows-1252", "the bytes carry no byte order mark, are not well-formed UTF-8, and read as Western text")]
|
|
527
|
+
};
|
|
528
|
+
throw new UndecodableTextError("unrecognised", "bytes are text but match none of the supported encodings: not UTF-8, and not plausible as windows-1252");
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* {@link decodeText}, returning `undefined` where it would throw.
|
|
532
|
+
*
|
|
533
|
+
* For a caller asking whether bytes are decodable at all, a schema refinement being the case this exists for, where an exception would be control flow rather than an error.
|
|
534
|
+
* @param bytes - The bytes to decode.
|
|
535
|
+
* @param options - An explicit `encoding` to decode under, skipping detection.
|
|
536
|
+
* @returns What {@link decodeText} would return, or `undefined` where it would throw.
|
|
537
|
+
*/
|
|
538
|
+
function tryDecodeText(bytes, options = {}) {
|
|
539
|
+
try {
|
|
540
|
+
return decodeText(bytes, options);
|
|
541
|
+
} catch {
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
//#endregion
|
|
227
546
|
//#region src/image/png-filter.ts
|
|
228
547
|
function paethPredictor(a, b, c) {
|
|
229
548
|
const p = a + b - c;
|
|
@@ -713,11 +1032,14 @@ exports.ByteWriter = ByteWriter;
|
|
|
713
1032
|
exports.MAX_INFLATE_OUTPUT_BYTES = MAX_INFLATE_OUTPUT_BYTES;
|
|
714
1033
|
exports.PNG_MAX_DIMENSION = PNG_MAX_DIMENSION;
|
|
715
1034
|
exports.PNG_MAX_PIXELS = PNG_MAX_PIXELS;
|
|
1035
|
+
exports.TEXT_DECODE_CHUNK_CODE_UNITS = TEXT_DECODE_CHUNK_CODE_UNITS;
|
|
1036
|
+
exports.UndecodableTextError = UndecodableTextError;
|
|
716
1037
|
exports.base64ToBytes = base64ToBytes;
|
|
717
1038
|
exports.bytesToBase64 = bytesToBase64;
|
|
718
1039
|
exports.concatBytes = concatBytes;
|
|
719
1040
|
exports.crc32 = crc32;
|
|
720
1041
|
exports.decodePng = decodePng;
|
|
1042
|
+
exports.decodeText = decodeText;
|
|
721
1043
|
exports.deflate = deflate;
|
|
722
1044
|
exports.encodePng = encodePng;
|
|
723
1045
|
exports.exceedsMaxPixelCount = exceedsMaxPixelCount;
|
|
@@ -725,5 +1047,7 @@ exports.filterScanlines = filterScanlines;
|
|
|
725
1047
|
exports.inflate = inflate;
|
|
726
1048
|
exports.inflateTolerant = inflateTolerant;
|
|
727
1049
|
exports.isAsciiWhitespace = isAsciiWhitespace;
|
|
1050
|
+
exports.isProbablyText = isProbablyText;
|
|
728
1051
|
exports.readJpegInfo = readJpegInfo;
|
|
1052
|
+
exports.tryDecodeText = tryDecodeText;
|
|
729
1053
|
exports.unfilterScanlines = unfilterScanlines;
|
package/dist/index.d.cts
CHANGED
|
@@ -64,6 +64,89 @@ interface InflateResult {
|
|
|
64
64
|
}
|
|
65
65
|
declare function inflateTolerant(data: Uint8Array<ArrayBuffer>): InflateResult;
|
|
66
66
|
//#endregion
|
|
67
|
+
//#region src/text/decode.d.ts
|
|
68
|
+
/**
|
|
69
|
+
* The character encodings {@link decodeText} can produce text from.
|
|
70
|
+
*
|
|
71
|
+
* Deliberately bounded: each is either self-identifying through a byte order mark, structurally checkable through its own validity rules, or guessable behind a stated plausibility test. Legacy CJK and Cyrillic code pages are outside the set on purpose, since nothing tells them apart from one another without the statistical model this module does not carry; bytes that look like one are refused rather than guessed at. That boundary also limits what {@link DecodeTextOptions.encoding} can name, which is a narrower restriction than detection itself needs (ExaDev/documents.js#1361).
|
|
72
|
+
*/
|
|
73
|
+
type TextEncodingLabel = "utf-8" | "utf-16le" | "utf-16be" | "utf-32le" | "utf-32be" | "windows-1252";
|
|
74
|
+
/**
|
|
75
|
+
* How {@link decodeText} arrived at the encoding it used.
|
|
76
|
+
*
|
|
77
|
+
* `declared` is the caller's own `encoding` option, `bom` a byte order mark, `utf8` a successful decode under UTF-8's own validity rules with nothing declaring it, and `detected` a guess from one of the plausibility tests.
|
|
78
|
+
*/
|
|
79
|
+
type DecodedTextSource = "declared" | "bom" | "utf8" | "detected";
|
|
80
|
+
/**
|
|
81
|
+
* How far the reported encoding can be relied on.
|
|
82
|
+
*
|
|
83
|
+
* `certain`: the bytes settle it, or the caller declared it. A byte order mark identifies its encoding unambiguously, and bytes entirely below 0x80 decode to the same text under every encoding in the supported set. `high`: the bytes satisfy UTF-8's multi-byte validity rules, which text in a single-byte code page essentially never does by accident. `low`: a guess from a plausibility test. Show the encoding to whoever supplied the bytes and let them override it.
|
|
84
|
+
*/
|
|
85
|
+
type DecodedTextConfidence = "certain" | "high" | "low";
|
|
86
|
+
/** What {@link decodeText} produced, and how far its own account of the encoding can be trusted. */
|
|
87
|
+
interface DecodedText {
|
|
88
|
+
/** The decoded text, with any byte order mark removed rather than left as a leading U+FEFF. */
|
|
89
|
+
readonly text: string;
|
|
90
|
+
/** The encoding the bytes were decoded under. */
|
|
91
|
+
readonly encoding: TextEncodingLabel;
|
|
92
|
+
/** What settled that encoding. */
|
|
93
|
+
readonly source: DecodedTextSource;
|
|
94
|
+
/** How far {@link DecodedText.encoding} can be relied on. */
|
|
95
|
+
readonly confidence: DecodedTextConfidence;
|
|
96
|
+
/** One entry per reason the caller should look at the result before trusting it, and empty whenever the confidence is `certain` or `high`. */
|
|
97
|
+
readonly warnings: readonly string[];
|
|
98
|
+
}
|
|
99
|
+
/** Options for {@link decodeText} and {@link tryDecodeText}. */
|
|
100
|
+
interface DecodeTextOptions {
|
|
101
|
+
/** The encoding to decode under, skipping detection entirely. A byte order mark for this same encoding is still removed, so the option can be given for bytes that carry one. */
|
|
102
|
+
readonly encoding?: TextEncodingLabel;
|
|
103
|
+
}
|
|
104
|
+
/** Why {@link UndecodableTextError} was thrown: `binary` for bytes no text encoding could hold, `malformed` for bytes that contradict the encoding a mark or the caller named, and `unrecognised` for text-shaped bytes matching none of the supported encodings. */
|
|
105
|
+
type UndecodableTextReason = "binary" | "malformed" | "unrecognised";
|
|
106
|
+
/** Thrown when bytes cannot be turned into text: they are not text at all, they contradict a declared or marked encoding, or they match none of the supported encodings. */
|
|
107
|
+
declare class UndecodableTextError extends Error {
|
|
108
|
+
/** Which of the three failures this was, for a caller that treats them differently. */
|
|
109
|
+
readonly reason: UndecodableTextReason;
|
|
110
|
+
constructor(reason: UndecodableTextReason, message: string);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Code units converted by one `String.fromCharCode.apply` call. JavaScriptCore rejects a call with more than 65536 arguments, a limit MDN documents as hard-coded (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), and other engines bound the same thing by stack size, so this is half that stated figure, leaving the engine room for whatever else it puts on its argument stack. The same quantum src/bytes/base64.ts's own chunked encode uses, for the same reason: appending one character at a time to a string is what made converting a few megabytes take seconds under instrumentation.
|
|
114
|
+
*
|
|
115
|
+
* Exported so tests can place inputs on and around a chunk boundary without repeating the figure.
|
|
116
|
+
*/
|
|
117
|
+
declare const TEXT_DECODE_CHUNK_CODE_UNITS: number;
|
|
118
|
+
/**
|
|
119
|
+
* Whether bytes can hold text at all, judged without reference to which encoding they might be in.
|
|
120
|
+
*
|
|
121
|
+
* A NUL byte belongs to no text document format, and outside NUL the only C0 control bytes text carries are tab, line feed, form feed and carriage return, so a density of any others says binary. {@link decodeText} asks this before it guesses at windows-1252, which maps nearly every byte to some character and would otherwise read a PNG as a page of mojibake rather than refusing it.
|
|
122
|
+
*
|
|
123
|
+
* UTF-16 is the one text encoding this returns `false` for, since it interleaves NUL bytes by design. {@link decodeText} settles UTF-16 from a byte order mark or that same interleave before it reaches this check, and applies the identical rule to the characters a mark-less UTF-16 guess produced, so that guess cannot smuggle binary past this one.
|
|
124
|
+
* @param bytes - The bytes to judge.
|
|
125
|
+
* @returns Whether the bytes carry no NUL and few enough other C0 control bytes to be text.
|
|
126
|
+
*/
|
|
127
|
+
declare function isProbablyText(bytes: Uint8Array): boolean;
|
|
128
|
+
/**
|
|
129
|
+
* Decodes bytes to text, working out which character encoding they hold.
|
|
130
|
+
*
|
|
131
|
+
* The encoding is settled in a fixed order: the `encoding` option if the caller gave one, then a byte order mark, then the NUL interleave UTF-16 leaves when it holds Latin-script text and carries no mark, then UTF-8 if the bytes satisfy its own validity rules, then windows-1252 if the bytes read as Western text. Anything a byte order mark or the caller names is decoded under that encoding alone and fails if the bytes contradict it. Everything reached by detection reports how it was reached, so a caller can show the encoding, and a guess additionally carries a warning and a `low` confidence rather than being presented as fact.
|
|
132
|
+
*
|
|
133
|
+
* Bytes that are not text (a NUL byte, or a density of other C0 control bytes) are refused before any guess is made, so detection never widens what counts as text. The readings whose bytes carry NULs legitimately, mark-less UTF-16 and anything behind a UTF-16 or UTF-32 byte order mark, are judged by the same rule applied to the characters they produced instead. Only an explicit `encoding` from the caller skips the judgement entirely, since that is the caller overriding detection outright. A byte order mark is removed from the result rather than left as a leading U+FEFF.
|
|
134
|
+
* @param bytes - The bytes to decode.
|
|
135
|
+
* @param options - An explicit `encoding` to decode under, skipping detection.
|
|
136
|
+
* @throws UndecodableTextError When the bytes are not text, contradict a declared or marked encoding, or match none of the supported encodings.
|
|
137
|
+
* @returns The text, the encoding it was decoded under, and how far that account of the encoding can be relied on.
|
|
138
|
+
*/
|
|
139
|
+
declare function decodeText(bytes: Uint8Array, options?: DecodeTextOptions): DecodedText;
|
|
140
|
+
/**
|
|
141
|
+
* {@link decodeText}, returning `undefined` where it would throw.
|
|
142
|
+
*
|
|
143
|
+
* For a caller asking whether bytes are decodable at all, a schema refinement being the case this exists for, where an exception would be control flow rather than an error.
|
|
144
|
+
* @param bytes - The bytes to decode.
|
|
145
|
+
* @param options - An explicit `encoding` to decode under, skipping detection.
|
|
146
|
+
* @returns What {@link decodeText} would return, or `undefined` where it would throw.
|
|
147
|
+
*/
|
|
148
|
+
declare function tryDecodeText(bytes: Uint8Array, options?: DecodeTextOptions): DecodedText | undefined;
|
|
149
|
+
//#endregion
|
|
67
150
|
//#region src/image/png-decode.d.ts
|
|
68
151
|
interface RawImage {
|
|
69
152
|
readonly width: number;
|
|
@@ -102,4 +185,4 @@ interface JpegInfo {
|
|
|
102
185
|
}
|
|
103
186
|
declare function readJpegInfo(bytes: Uint8Array<ArrayBuffer>): JpegInfo;
|
|
104
187
|
//#endregion
|
|
105
|
-
export { BASE64_ENCODE_CHUNK_CHARS, ByteReader, ByteWriter, DeflateLevel, InflateResult, JpegInfo, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, PngDecodeOptions, PngEncodeOptions, PngFilterType, RawImage, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, deflate, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, readJpegInfo, unfilterScanlines };
|
|
188
|
+
export { BASE64_ENCODE_CHUNK_CHARS, ByteReader, ByteWriter, DecodeTextOptions, DecodedText, DecodedTextConfidence, DecodedTextSource, DeflateLevel, InflateResult, JpegInfo, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, PngDecodeOptions, PngEncodeOptions, PngFilterType, RawImage, TEXT_DECODE_CHUNK_CODE_UNITS, TextEncodingLabel, UndecodableTextError, UndecodableTextReason, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, tryDecodeText, unfilterScanlines };
|
package/dist/index.d.ts
CHANGED
|
@@ -64,6 +64,89 @@ interface InflateResult {
|
|
|
64
64
|
}
|
|
65
65
|
declare function inflateTolerant(data: Uint8Array<ArrayBuffer>): InflateResult;
|
|
66
66
|
//#endregion
|
|
67
|
+
//#region src/text/decode.d.ts
|
|
68
|
+
/**
|
|
69
|
+
* The character encodings {@link decodeText} can produce text from.
|
|
70
|
+
*
|
|
71
|
+
* Deliberately bounded: each is either self-identifying through a byte order mark, structurally checkable through its own validity rules, or guessable behind a stated plausibility test. Legacy CJK and Cyrillic code pages are outside the set on purpose, since nothing tells them apart from one another without the statistical model this module does not carry; bytes that look like one are refused rather than guessed at. That boundary also limits what {@link DecodeTextOptions.encoding} can name, which is a narrower restriction than detection itself needs (ExaDev/documents.js#1361).
|
|
72
|
+
*/
|
|
73
|
+
type TextEncodingLabel = "utf-8" | "utf-16le" | "utf-16be" | "utf-32le" | "utf-32be" | "windows-1252";
|
|
74
|
+
/**
|
|
75
|
+
* How {@link decodeText} arrived at the encoding it used.
|
|
76
|
+
*
|
|
77
|
+
* `declared` is the caller's own `encoding` option, `bom` a byte order mark, `utf8` a successful decode under UTF-8's own validity rules with nothing declaring it, and `detected` a guess from one of the plausibility tests.
|
|
78
|
+
*/
|
|
79
|
+
type DecodedTextSource = "declared" | "bom" | "utf8" | "detected";
|
|
80
|
+
/**
|
|
81
|
+
* How far the reported encoding can be relied on.
|
|
82
|
+
*
|
|
83
|
+
* `certain`: the bytes settle it, or the caller declared it. A byte order mark identifies its encoding unambiguously, and bytes entirely below 0x80 decode to the same text under every encoding in the supported set. `high`: the bytes satisfy UTF-8's multi-byte validity rules, which text in a single-byte code page essentially never does by accident. `low`: a guess from a plausibility test. Show the encoding to whoever supplied the bytes and let them override it.
|
|
84
|
+
*/
|
|
85
|
+
type DecodedTextConfidence = "certain" | "high" | "low";
|
|
86
|
+
/** What {@link decodeText} produced, and how far its own account of the encoding can be trusted. */
|
|
87
|
+
interface DecodedText {
|
|
88
|
+
/** The decoded text, with any byte order mark removed rather than left as a leading U+FEFF. */
|
|
89
|
+
readonly text: string;
|
|
90
|
+
/** The encoding the bytes were decoded under. */
|
|
91
|
+
readonly encoding: TextEncodingLabel;
|
|
92
|
+
/** What settled that encoding. */
|
|
93
|
+
readonly source: DecodedTextSource;
|
|
94
|
+
/** How far {@link DecodedText.encoding} can be relied on. */
|
|
95
|
+
readonly confidence: DecodedTextConfidence;
|
|
96
|
+
/** One entry per reason the caller should look at the result before trusting it, and empty whenever the confidence is `certain` or `high`. */
|
|
97
|
+
readonly warnings: readonly string[];
|
|
98
|
+
}
|
|
99
|
+
/** Options for {@link decodeText} and {@link tryDecodeText}. */
|
|
100
|
+
interface DecodeTextOptions {
|
|
101
|
+
/** The encoding to decode under, skipping detection entirely. A byte order mark for this same encoding is still removed, so the option can be given for bytes that carry one. */
|
|
102
|
+
readonly encoding?: TextEncodingLabel;
|
|
103
|
+
}
|
|
104
|
+
/** Why {@link UndecodableTextError} was thrown: `binary` for bytes no text encoding could hold, `malformed` for bytes that contradict the encoding a mark or the caller named, and `unrecognised` for text-shaped bytes matching none of the supported encodings. */
|
|
105
|
+
type UndecodableTextReason = "binary" | "malformed" | "unrecognised";
|
|
106
|
+
/** Thrown when bytes cannot be turned into text: they are not text at all, they contradict a declared or marked encoding, or they match none of the supported encodings. */
|
|
107
|
+
declare class UndecodableTextError extends Error {
|
|
108
|
+
/** Which of the three failures this was, for a caller that treats them differently. */
|
|
109
|
+
readonly reason: UndecodableTextReason;
|
|
110
|
+
constructor(reason: UndecodableTextReason, message: string);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Code units converted by one `String.fromCharCode.apply` call. JavaScriptCore rejects a call with more than 65536 arguments, a limit MDN documents as hard-coded (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), and other engines bound the same thing by stack size, so this is half that stated figure, leaving the engine room for whatever else it puts on its argument stack. The same quantum src/bytes/base64.ts's own chunked encode uses, for the same reason: appending one character at a time to a string is what made converting a few megabytes take seconds under instrumentation.
|
|
114
|
+
*
|
|
115
|
+
* Exported so tests can place inputs on and around a chunk boundary without repeating the figure.
|
|
116
|
+
*/
|
|
117
|
+
declare const TEXT_DECODE_CHUNK_CODE_UNITS: number;
|
|
118
|
+
/**
|
|
119
|
+
* Whether bytes can hold text at all, judged without reference to which encoding they might be in.
|
|
120
|
+
*
|
|
121
|
+
* A NUL byte belongs to no text document format, and outside NUL the only C0 control bytes text carries are tab, line feed, form feed and carriage return, so a density of any others says binary. {@link decodeText} asks this before it guesses at windows-1252, which maps nearly every byte to some character and would otherwise read a PNG as a page of mojibake rather than refusing it.
|
|
122
|
+
*
|
|
123
|
+
* UTF-16 is the one text encoding this returns `false` for, since it interleaves NUL bytes by design. {@link decodeText} settles UTF-16 from a byte order mark or that same interleave before it reaches this check, and applies the identical rule to the characters a mark-less UTF-16 guess produced, so that guess cannot smuggle binary past this one.
|
|
124
|
+
* @param bytes - The bytes to judge.
|
|
125
|
+
* @returns Whether the bytes carry no NUL and few enough other C0 control bytes to be text.
|
|
126
|
+
*/
|
|
127
|
+
declare function isProbablyText(bytes: Uint8Array): boolean;
|
|
128
|
+
/**
|
|
129
|
+
* Decodes bytes to text, working out which character encoding they hold.
|
|
130
|
+
*
|
|
131
|
+
* The encoding is settled in a fixed order: the `encoding` option if the caller gave one, then a byte order mark, then the NUL interleave UTF-16 leaves when it holds Latin-script text and carries no mark, then UTF-8 if the bytes satisfy its own validity rules, then windows-1252 if the bytes read as Western text. Anything a byte order mark or the caller names is decoded under that encoding alone and fails if the bytes contradict it. Everything reached by detection reports how it was reached, so a caller can show the encoding, and a guess additionally carries a warning and a `low` confidence rather than being presented as fact.
|
|
132
|
+
*
|
|
133
|
+
* Bytes that are not text (a NUL byte, or a density of other C0 control bytes) are refused before any guess is made, so detection never widens what counts as text. The readings whose bytes carry NULs legitimately, mark-less UTF-16 and anything behind a UTF-16 or UTF-32 byte order mark, are judged by the same rule applied to the characters they produced instead. Only an explicit `encoding` from the caller skips the judgement entirely, since that is the caller overriding detection outright. A byte order mark is removed from the result rather than left as a leading U+FEFF.
|
|
134
|
+
* @param bytes - The bytes to decode.
|
|
135
|
+
* @param options - An explicit `encoding` to decode under, skipping detection.
|
|
136
|
+
* @throws UndecodableTextError When the bytes are not text, contradict a declared or marked encoding, or match none of the supported encodings.
|
|
137
|
+
* @returns The text, the encoding it was decoded under, and how far that account of the encoding can be relied on.
|
|
138
|
+
*/
|
|
139
|
+
declare function decodeText(bytes: Uint8Array, options?: DecodeTextOptions): DecodedText;
|
|
140
|
+
/**
|
|
141
|
+
* {@link decodeText}, returning `undefined` where it would throw.
|
|
142
|
+
*
|
|
143
|
+
* For a caller asking whether bytes are decodable at all, a schema refinement being the case this exists for, where an exception would be control flow rather than an error.
|
|
144
|
+
* @param bytes - The bytes to decode.
|
|
145
|
+
* @param options - An explicit `encoding` to decode under, skipping detection.
|
|
146
|
+
* @returns What {@link decodeText} would return, or `undefined` where it would throw.
|
|
147
|
+
*/
|
|
148
|
+
declare function tryDecodeText(bytes: Uint8Array, options?: DecodeTextOptions): DecodedText | undefined;
|
|
149
|
+
//#endregion
|
|
67
150
|
//#region src/image/png-decode.d.ts
|
|
68
151
|
interface RawImage {
|
|
69
152
|
readonly width: number;
|
|
@@ -102,4 +185,4 @@ interface JpegInfo {
|
|
|
102
185
|
}
|
|
103
186
|
declare function readJpegInfo(bytes: Uint8Array<ArrayBuffer>): JpegInfo;
|
|
104
187
|
//#endregion
|
|
105
|
-
export { BASE64_ENCODE_CHUNK_CHARS, ByteReader, ByteWriter, DeflateLevel, InflateResult, JpegInfo, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, PngDecodeOptions, PngEncodeOptions, PngFilterType, RawImage, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, deflate, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, readJpegInfo, unfilterScanlines };
|
|
188
|
+
export { BASE64_ENCODE_CHUNK_CHARS, ByteReader, ByteWriter, DecodeTextOptions, DecodedText, DecodedTextConfidence, DecodedTextSource, DeflateLevel, InflateResult, JpegInfo, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, PngDecodeOptions, PngEncodeOptions, PngFilterType, RawImage, TEXT_DECODE_CHUNK_CODE_UNITS, TextEncodingLabel, UndecodableTextError, UndecodableTextReason, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, tryDecodeText, unfilterScanlines };
|
package/dist/index.js
CHANGED
|
@@ -223,6 +223,325 @@ function inflateTolerant(data) {
|
|
|
223
223
|
};
|
|
224
224
|
}
|
|
225
225
|
//#endregion
|
|
226
|
+
//#region src/text/decode.ts
|
|
227
|
+
/** Thrown when bytes cannot be turned into text: they are not text at all, they contradict a declared or marked encoding, or they match none of the supported encodings. */
|
|
228
|
+
var UndecodableTextError = class extends Error {
|
|
229
|
+
/** Which of the three failures this was, for a caller that treats them differently. */
|
|
230
|
+
reason;
|
|
231
|
+
constructor(reason, message) {
|
|
232
|
+
super(message);
|
|
233
|
+
this.name = "UndecodableTextError";
|
|
234
|
+
this.reason = reason;
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
/** NUL, as a byte and as a code unit alike: it belongs to no text under either reading. */
|
|
238
|
+
const NUL_CODE = 0;
|
|
239
|
+
/** The first character code that is not a C0 control. */
|
|
240
|
+
const FIRST_NON_CONTROL_CODE = 32;
|
|
241
|
+
/** The first byte outside ASCII, which is also where every encoding in the supported set stops agreeing with every other. */
|
|
242
|
+
const FIRST_HIGH_BYTE = 128;
|
|
243
|
+
/** The C1 control range, which is both where windows-1252 differs from ISO-8859-1 and the range whose presence in a decoded result says the guess was wrong. Its start doubles as the first byte the windows-1252 table below covers. */
|
|
244
|
+
const C1_CONTROL_START = 128;
|
|
245
|
+
const C1_CONTROL_END = 159;
|
|
246
|
+
/** C0 controls that appear in real text: tab, line feed, form feed, carriage return. Every other code below {@link FIRST_NON_CONTROL_CODE} belongs to binary content. */
|
|
247
|
+
const TEXTUAL_CONTROL_CODES = /* @__PURE__ */ new Set([
|
|
248
|
+
9,
|
|
249
|
+
10,
|
|
250
|
+
12,
|
|
251
|
+
13
|
|
252
|
+
]);
|
|
253
|
+
/** One C0 control outside {@link TEXTUAL_CONTROL_CODES} is permitted per this many characters before the content is taken for binary. Plain text carries none at all, so the allowance exists only to tolerate a stray one, an end-of-file Ctrl-Z left by a DOS-era editor being the case that actually occurs; compressed and image data puts roughly an eighth of its bytes in the C0 range, more than an order of magnitude above this. Counted as integer arithmetic against the length rather than a floating-point ratio so the boundary is exact. */
|
|
254
|
+
const CODES_PER_PERMITTED_CONTROL = 64;
|
|
255
|
+
/** The longest run of consecutive bytes at or above {@link FIRST_HIGH_BYTE} the windows-1252 guess accepts. Latin-script text sets an accented letter inside otherwise-ASCII words, so even the most accent-dense Western orthography never strings many together; text in a non-Latin single-byte code page, and bytes that are not text at all, put whole words above that boundary and run far longer. A caller holding bytes that genuinely do (a line of nothing but bullets, say) names the encoding explicitly rather than relying on the guess. */
|
|
256
|
+
const MAX_HIGH_BYTE_RUN = 4;
|
|
257
|
+
/** windows-1252's own mapping for the bytes from {@link C1_CONTROL_START} to {@link C1_CONTROL_END}, the one range where it differs from ISO-8859-1: bytes below are ASCII and bytes above are ISO-8859-1 exactly, so neither needs a table. Held as a string rather than an array so a lookup is a `charCodeAt` on a fixed-length string, with no index the type system has to be told is in range. Five positions (0x81, 0x8D, 0x8F, 0x90, 0x9D) have no character in Microsoft's own code page; the Encoding Standard maps them to the matching C1 control characters so that its decoder is total, and this table does the same, so decoding here and decoding through a TextDecoder that does support the label agree byte for byte. */
|
|
258
|
+
const WINDOWS_1252_HIGH_RANGE = "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";
|
|
259
|
+
/** The bytes windows-1252 leaves without a character of their own, derived from {@link WINDOWS_1252_HIGH_RANGE} as exactly those positions whose mapping lands back in the C1 control range instead of on a real character. A C1 control appears in no text document, so one of these bytes says the content is not windows-1252 text whatever else it may be. */
|
|
260
|
+
const WINDOWS_1252_UNDEFINED_BYTES = new Set(Array.from(WINDOWS_1252_HIGH_RANGE).flatMap((character, index) => {
|
|
261
|
+
const codePoint = character.charCodeAt(0);
|
|
262
|
+
return codePoint >= C1_CONTROL_START && codePoint <= C1_CONTROL_END ? [C1_CONTROL_START + index] : [];
|
|
263
|
+
}));
|
|
264
|
+
/** UTF-16's surrogate range, whose halves pair up to carry a code point above the basic plane and which is never a code point in its own right. */
|
|
265
|
+
const HIGH_SURROGATE_START = 55296;
|
|
266
|
+
const HIGH_SURROGATE_END = 56319;
|
|
267
|
+
const LOW_SURROGATE_START = 56320;
|
|
268
|
+
const LOW_SURROGATE_END = 57343;
|
|
269
|
+
/** The highest code point Unicode defines, and the first one that needs a surrogate pair to reach in UTF-16. */
|
|
270
|
+
const MAX_CODE_POINT = 1114111;
|
|
271
|
+
const SUPPLEMENTARY_PLANE_START = 65536;
|
|
272
|
+
/** How a supplementary code point splits across a surrogate pair: the ten low bits go to the low half and the rest to the high half, both biased by the start of their own range. */
|
|
273
|
+
const SURROGATE_BITS = 10;
|
|
274
|
+
const LOW_SURROGATE_MASK = 1023;
|
|
275
|
+
/**
|
|
276
|
+
* Code units converted by one `String.fromCharCode.apply` call. JavaScriptCore rejects a call with more than 65536 arguments, a limit MDN documents as hard-coded (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), and other engines bound the same thing by stack size, so this is half that stated figure, leaving the engine room for whatever else it puts on its argument stack. The same quantum src/bytes/base64.ts's own chunked encode uses, for the same reason: appending one character at a time to a string is what made converting a few megabytes take seconds under instrumentation.
|
|
277
|
+
*
|
|
278
|
+
* Exported so tests can place inputs on and around a chunk boundary without repeating the figure.
|
|
279
|
+
*/
|
|
280
|
+
const TEXT_DECODE_CHUNK_CODE_UNITS = 32768;
|
|
281
|
+
function fromCodeUnits(units) {
|
|
282
|
+
return Array.from({ length: Math.ceil(units.length / TEXT_DECODE_CHUNK_CODE_UNITS) }, (_unused, chunk) => {
|
|
283
|
+
const start = chunk * TEXT_DECODE_CHUNK_CODE_UNITS;
|
|
284
|
+
return String.fromCharCode.apply(null, units.slice(start, start + TEXT_DECODE_CHUNK_CODE_UNITS));
|
|
285
|
+
}).join("");
|
|
286
|
+
}
|
|
287
|
+
/** Every byte order mark, longest first: UTF-32LE's begins with UTF-16LE's, so the four-byte marks have to be tested before the two-byte ones. Unicode resolves that overlap the same way, the alternative reading being a UTF-16LE file whose first character is U+0000, which is not a file that occurs. */
|
|
288
|
+
const BOM_SIGNATURES = [
|
|
289
|
+
{
|
|
290
|
+
encoding: "utf-32be",
|
|
291
|
+
bytes: [
|
|
292
|
+
0,
|
|
293
|
+
0,
|
|
294
|
+
254,
|
|
295
|
+
255
|
|
296
|
+
]
|
|
297
|
+
},
|
|
298
|
+
{
|
|
299
|
+
encoding: "utf-32le",
|
|
300
|
+
bytes: [
|
|
301
|
+
255,
|
|
302
|
+
254,
|
|
303
|
+
0,
|
|
304
|
+
0
|
|
305
|
+
]
|
|
306
|
+
},
|
|
307
|
+
{
|
|
308
|
+
encoding: "utf-8",
|
|
309
|
+
bytes: [
|
|
310
|
+
239,
|
|
311
|
+
187,
|
|
312
|
+
191
|
|
313
|
+
]
|
|
314
|
+
},
|
|
315
|
+
{
|
|
316
|
+
encoding: "utf-16be",
|
|
317
|
+
bytes: [254, 255]
|
|
318
|
+
},
|
|
319
|
+
{
|
|
320
|
+
encoding: "utf-16le",
|
|
321
|
+
bytes: [255, 254]
|
|
322
|
+
}
|
|
323
|
+
];
|
|
324
|
+
function findBom(bytes) {
|
|
325
|
+
return BOM_SIGNATURES.find((signature) => signature.bytes.every((value, index) => bytes[index] === value));
|
|
326
|
+
}
|
|
327
|
+
/** The bytes past a byte order mark for `encoding`, or the bytes unchanged when they carry no such mark. A mark for a different encoding is left alone: under a declared encoding it is content, not a mark. */
|
|
328
|
+
function stripBom(bytes, encoding) {
|
|
329
|
+
const bom = findBom(bytes);
|
|
330
|
+
return bom?.encoding === encoding ? bytes.subarray(bom.bytes.length) : bytes;
|
|
331
|
+
}
|
|
332
|
+
function tryDecodeUtf8(bytes) {
|
|
333
|
+
try {
|
|
334
|
+
return new TextDecoder("utf-8", {
|
|
335
|
+
fatal: true,
|
|
336
|
+
ignoreBOM: true
|
|
337
|
+
}).decode(bytes);
|
|
338
|
+
} catch {
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
function decodeUtf16(bytes, littleEndian) {
|
|
343
|
+
if (bytes.byteLength % 2 !== 0) throw new UndecodableTextError("malformed", "UTF-16 text must hold a whole number of 16-bit code units");
|
|
344
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
345
|
+
const units = [];
|
|
346
|
+
for (let offset = 0; offset < bytes.byteLength; offset += 2) units.push(view.getUint16(offset, littleEndian));
|
|
347
|
+
let awaitingLowSurrogate = false;
|
|
348
|
+
for (const unit of units) {
|
|
349
|
+
if (awaitingLowSurrogate !== (unit >= LOW_SURROGATE_START && unit <= LOW_SURROGATE_END)) throw new UndecodableTextError("malformed", "UTF-16 text must pair every surrogate half with its partner");
|
|
350
|
+
awaitingLowSurrogate = unit >= HIGH_SURROGATE_START && unit <= HIGH_SURROGATE_END;
|
|
351
|
+
}
|
|
352
|
+
if (awaitingLowSurrogate) throw new UndecodableTextError("malformed", "UTF-16 text must pair every surrogate half with its partner");
|
|
353
|
+
return fromCodeUnits(units);
|
|
354
|
+
}
|
|
355
|
+
function tryDecodeUtf16(bytes, littleEndian) {
|
|
356
|
+
try {
|
|
357
|
+
return decodeUtf16(bytes, littleEndian);
|
|
358
|
+
} catch {
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
function decodeUtf32(bytes, littleEndian) {
|
|
363
|
+
if (bytes.byteLength % 4 !== 0) throw new UndecodableTextError("malformed", "UTF-32 text must hold a whole number of 32-bit code units");
|
|
364
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
365
|
+
const units = [];
|
|
366
|
+
for (let offset = 0; offset < bytes.byteLength; offset += 4) {
|
|
367
|
+
const codePoint = view.getUint32(offset, littleEndian);
|
|
368
|
+
if (codePoint > MAX_CODE_POINT || codePoint >= HIGH_SURROGATE_START && codePoint <= LOW_SURROGATE_END) throw new UndecodableTextError("malformed", "UTF-32 text must hold only Unicode scalar values");
|
|
369
|
+
if (codePoint < SUPPLEMENTARY_PLANE_START) {
|
|
370
|
+
units.push(codePoint);
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
const supplementary = codePoint - SUPPLEMENTARY_PLANE_START;
|
|
374
|
+
units.push(HIGH_SURROGATE_START + (supplementary >> SURROGATE_BITS));
|
|
375
|
+
units.push(LOW_SURROGATE_START + (supplementary & LOW_SURROGATE_MASK));
|
|
376
|
+
}
|
|
377
|
+
return fromCodeUnits(units);
|
|
378
|
+
}
|
|
379
|
+
function decodeWindows1252(bytes) {
|
|
380
|
+
const units = [];
|
|
381
|
+
for (const byte of bytes) units.push(byte < C1_CONTROL_START || byte > C1_CONTROL_END ? byte : WINDOWS_1252_HIGH_RANGE.charCodeAt(byte - C1_CONTROL_START));
|
|
382
|
+
return fromCodeUnits(units);
|
|
383
|
+
}
|
|
384
|
+
function decodeUtf8(bytes) {
|
|
385
|
+
const text = tryDecodeUtf8(bytes);
|
|
386
|
+
if (text === void 0) throw new UndecodableTextError("malformed", "UTF-8 text must hold only well-formed byte sequences");
|
|
387
|
+
return text;
|
|
388
|
+
}
|
|
389
|
+
/** One decoder per supported encoding, as a record keyed by the encoding union itself so that adding an encoding to {@link TextEncodingLabel} without a decoder for it is a compile error rather than a run-time gap. */
|
|
390
|
+
const DECODERS = {
|
|
391
|
+
"utf-8": decodeUtf8,
|
|
392
|
+
"utf-16le": (bytes) => decodeUtf16(bytes, true),
|
|
393
|
+
"utf-16be": (bytes) => decodeUtf16(bytes, false),
|
|
394
|
+
"utf-32le": (bytes) => decodeUtf32(bytes, true),
|
|
395
|
+
"utf-32be": (bytes) => decodeUtf32(bytes, false),
|
|
396
|
+
"windows-1252": decodeWindows1252
|
|
397
|
+
};
|
|
398
|
+
/** The text-versus-binary rule itself, over character codes: a NUL settles it outright, and every other C0 control outside {@link TEXTUAL_CONTROL_CODES} is allowed only up to one per {@link CODES_PER_PERMITTED_CONTROL}. Reading codes through an accessor rather than taking an array lets the identical rule run over a Uint8Array's bytes and over a decoded string's code units without copying either into one. */
|
|
399
|
+
function codesAreTextual(codeAt, length) {
|
|
400
|
+
let controlCodes = 0;
|
|
401
|
+
for (let index = 0; index < length; index += 1) {
|
|
402
|
+
const code = codeAt(index);
|
|
403
|
+
if (code === NUL_CODE) return false;
|
|
404
|
+
if (code < FIRST_NON_CONTROL_CODE && !TEXTUAL_CONTROL_CODES.has(code)) controlCodes += 1;
|
|
405
|
+
}
|
|
406
|
+
return controlCodes * CODES_PER_PERMITTED_CONTROL <= length;
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Whether bytes can hold text at all, judged without reference to which encoding they might be in.
|
|
410
|
+
*
|
|
411
|
+
* A NUL byte belongs to no text document format, and outside NUL the only C0 control bytes text carries are tab, line feed, form feed and carriage return, so a density of any others says binary. {@link decodeText} asks this before it guesses at windows-1252, which maps nearly every byte to some character and would otherwise read a PNG as a page of mojibake rather than refusing it.
|
|
412
|
+
*
|
|
413
|
+
* UTF-16 is the one text encoding this returns `false` for, since it interleaves NUL bytes by design. {@link decodeText} settles UTF-16 from a byte order mark or that same interleave before it reaches this check, and applies the identical rule to the characters a mark-less UTF-16 guess produced, so that guess cannot smuggle binary past this one.
|
|
414
|
+
* @param bytes - The bytes to judge.
|
|
415
|
+
* @returns Whether the bytes carry no NUL and few enough other C0 control bytes to be text.
|
|
416
|
+
*/
|
|
417
|
+
function isProbablyText(bytes) {
|
|
418
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
419
|
+
return codesAreTextual((index) => view.getUint8(index), bytes.byteLength);
|
|
420
|
+
}
|
|
421
|
+
/** {@link isProbablyText}'s own question asked of characters rather than of bytes, for a decode that has already happened. A multi-byte encoding puts NULs and other low bytes into its bytes as part of how it spells ordinary characters, so the bytes cannot answer it; the characters that came out can. */
|
|
422
|
+
function isTextualString(text) {
|
|
423
|
+
return codesAreTextual((index) => text.charCodeAt(index), text.length);
|
|
424
|
+
}
|
|
425
|
+
/** Whether the bytes could be windows-1252 text, as opposed to some other single-byte code page or no text at all. windows-1252 has a character for all but five of its byte values, so trying it and seeing whether it fails proves nothing; these two structural tests are what stands in for that. */
|
|
426
|
+
function looksLikeWindows1252Text(bytes) {
|
|
427
|
+
let highByteRun = 0;
|
|
428
|
+
for (const byte of bytes) {
|
|
429
|
+
if (WINDOWS_1252_UNDEFINED_BYTES.has(byte)) return false;
|
|
430
|
+
if (byte < FIRST_HIGH_BYTE) {
|
|
431
|
+
highByteRun = 0;
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
highByteRun += 1;
|
|
435
|
+
if (highByteRun > MAX_HIGH_BYTE_RUN) return false;
|
|
436
|
+
}
|
|
437
|
+
return true;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* UTF-16 without a byte order mark, recognised from the NUL a code unit below U+0100 puts on one fixed side of every unit pair.
|
|
441
|
+
*
|
|
442
|
+
* The recognised case is UTF-16 holding mostly Latin-script text, which is the only case a NUL interleave makes visible at all: UTF-16 holding CJK text has no NUL high bytes to see and is indistinguishable from other byte sequences without the statistical model this module does not carry.
|
|
443
|
+
*
|
|
444
|
+
* A majority of the units carrying a NUL on one fixed side is the whole of the test, and it is deliberately not also a comparison between the two sides. Bytes that put NULs on both sides, padding rather than text, do satisfy it, and are answered by the decode rather than here: a unit whose two bytes are both NUL decodes to U+0000, which is not text, so the caller's own check on the decoded characters refuses them. Requiring one side to beat the other would be unobservable, since a tie can only arise when some unit carries NULs on both sides, which is exactly the case that cannot survive that check. An odd byte count is left to the decoder for the same reason: it has no whole final code unit, so decoding it fails and the bytes are refused there.
|
|
445
|
+
*/
|
|
446
|
+
function detectBomlessUtf16(bytes) {
|
|
447
|
+
let evenIndexNuls = 0;
|
|
448
|
+
let oddIndexNuls = 0;
|
|
449
|
+
let atEvenIndex = true;
|
|
450
|
+
for (const byte of bytes) {
|
|
451
|
+
if (byte === NUL_CODE) {
|
|
452
|
+
if (atEvenIndex) evenIndexNuls += 1;
|
|
453
|
+
else oddIndexNuls += 1;
|
|
454
|
+
}
|
|
455
|
+
atEvenIndex = !atEvenIndex;
|
|
456
|
+
}
|
|
457
|
+
const units = bytes.length / 2;
|
|
458
|
+
if (oddIndexNuls * 2 > units) return "utf-16le";
|
|
459
|
+
if (evenIndexNuls * 2 > units) return "utf-16be";
|
|
460
|
+
}
|
|
461
|
+
const BINARY_MESSAGE = "bytes are not text: they carry a NUL byte, or too many other C0 control bytes for any text encoding";
|
|
462
|
+
function refuseAsBinary() {
|
|
463
|
+
throw new UndecodableTextError("binary", BINARY_MESSAGE);
|
|
464
|
+
}
|
|
465
|
+
function guessWarning(encoding, evidence) {
|
|
466
|
+
return `encoding was guessed as ${encoding}: ${evidence}. Pass an explicit encoding if that is wrong.`;
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Decodes bytes to text, working out which character encoding they hold.
|
|
470
|
+
*
|
|
471
|
+
* The encoding is settled in a fixed order: the `encoding` option if the caller gave one, then a byte order mark, then the NUL interleave UTF-16 leaves when it holds Latin-script text and carries no mark, then UTF-8 if the bytes satisfy its own validity rules, then windows-1252 if the bytes read as Western text. Anything a byte order mark or the caller names is decoded under that encoding alone and fails if the bytes contradict it. Everything reached by detection reports how it was reached, so a caller can show the encoding, and a guess additionally carries a warning and a `low` confidence rather than being presented as fact.
|
|
472
|
+
*
|
|
473
|
+
* Bytes that are not text (a NUL byte, or a density of other C0 control bytes) are refused before any guess is made, so detection never widens what counts as text. The readings whose bytes carry NULs legitimately, mark-less UTF-16 and anything behind a UTF-16 or UTF-32 byte order mark, are judged by the same rule applied to the characters they produced instead. Only an explicit `encoding` from the caller skips the judgement entirely, since that is the caller overriding detection outright. A byte order mark is removed from the result rather than left as a leading U+FEFF.
|
|
474
|
+
* @param bytes - The bytes to decode.
|
|
475
|
+
* @param options - An explicit `encoding` to decode under, skipping detection.
|
|
476
|
+
* @throws UndecodableTextError When the bytes are not text, contradict a declared or marked encoding, or match none of the supported encodings.
|
|
477
|
+
* @returns The text, the encoding it was decoded under, and how far that account of the encoding can be relied on.
|
|
478
|
+
*/
|
|
479
|
+
function decodeText(bytes, options = {}) {
|
|
480
|
+
const declared = options.encoding;
|
|
481
|
+
if (declared !== void 0) return {
|
|
482
|
+
text: DECODERS[declared](stripBom(bytes, declared)),
|
|
483
|
+
encoding: declared,
|
|
484
|
+
source: "declared",
|
|
485
|
+
confidence: "certain",
|
|
486
|
+
warnings: []
|
|
487
|
+
};
|
|
488
|
+
const bom = findBom(bytes);
|
|
489
|
+
if (bom !== void 0) {
|
|
490
|
+
const text = DECODERS[bom.encoding](bytes.subarray(bom.bytes.length));
|
|
491
|
+
if (!isTextualString(text)) refuseAsBinary();
|
|
492
|
+
return {
|
|
493
|
+
text,
|
|
494
|
+
encoding: bom.encoding,
|
|
495
|
+
source: "bom",
|
|
496
|
+
confidence: "certain",
|
|
497
|
+
warnings: []
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
const interleaved = detectBomlessUtf16(bytes);
|
|
501
|
+
if (interleaved !== void 0) {
|
|
502
|
+
const guessed = tryDecodeUtf16(bytes, interleaved === "utf-16le");
|
|
503
|
+
if (guessed !== void 0 && isTextualString(guessed)) return {
|
|
504
|
+
text: guessed,
|
|
505
|
+
encoding: interleaved,
|
|
506
|
+
source: "detected",
|
|
507
|
+
confidence: "low",
|
|
508
|
+
warnings: [guessWarning(interleaved, "the bytes carry no byte order mark, but interleave NUL bytes in the pattern UTF-16 gives Latin-script text")]
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
if (!isProbablyText(bytes)) refuseAsBinary();
|
|
512
|
+
const utf8 = tryDecodeUtf8(bytes);
|
|
513
|
+
if (utf8 !== void 0) return {
|
|
514
|
+
text: utf8,
|
|
515
|
+
encoding: "utf-8",
|
|
516
|
+
source: "utf8",
|
|
517
|
+
confidence: utf8.length === bytes.length ? "certain" : "high",
|
|
518
|
+
warnings: []
|
|
519
|
+
};
|
|
520
|
+
if (looksLikeWindows1252Text(bytes)) return {
|
|
521
|
+
text: decodeWindows1252(bytes),
|
|
522
|
+
encoding: "windows-1252",
|
|
523
|
+
source: "detected",
|
|
524
|
+
confidence: "low",
|
|
525
|
+
warnings: [guessWarning("windows-1252", "the bytes carry no byte order mark, are not well-formed UTF-8, and read as Western text")]
|
|
526
|
+
};
|
|
527
|
+
throw new UndecodableTextError("unrecognised", "bytes are text but match none of the supported encodings: not UTF-8, and not plausible as windows-1252");
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* {@link decodeText}, returning `undefined` where it would throw.
|
|
531
|
+
*
|
|
532
|
+
* For a caller asking whether bytes are decodable at all, a schema refinement being the case this exists for, where an exception would be control flow rather than an error.
|
|
533
|
+
* @param bytes - The bytes to decode.
|
|
534
|
+
* @param options - An explicit `encoding` to decode under, skipping detection.
|
|
535
|
+
* @returns What {@link decodeText} would return, or `undefined` where it would throw.
|
|
536
|
+
*/
|
|
537
|
+
function tryDecodeText(bytes, options = {}) {
|
|
538
|
+
try {
|
|
539
|
+
return decodeText(bytes, options);
|
|
540
|
+
} catch {
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
//#endregion
|
|
226
545
|
//#region src/image/png-filter.ts
|
|
227
546
|
function paethPredictor(a, b, c) {
|
|
228
547
|
const p = a + b - c;
|
|
@@ -706,4 +1025,4 @@ function readJpegInfo(bytes) {
|
|
|
706
1025
|
throw new Error("no SOF marker found in JPEG file");
|
|
707
1026
|
}
|
|
708
1027
|
//#endregion
|
|
709
|
-
export { BASE64_ENCODE_CHUNK_CHARS, ByteReader, ByteWriter, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, deflate, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, readJpegInfo, unfilterScanlines };
|
|
1028
|
+
export { BASE64_ENCODE_CHUNK_CHARS, ByteReader, ByteWriter, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, TEXT_DECODE_CHUNK_CODE_UNITS, UndecodableTextError, base64ToBytes, bytesToBase64, concatBytes, crc32, decodePng, decodeText, deflate, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, isProbablyText, readJpegInfo, tryDecodeText, unfilterScanlines };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "document-bytes",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"description": "Generic byte-level primitives (ByteWriter, ByteReader, CRC-32, deflate/inflate, base64) and PNG/JPEG image encoding/decoding with zero PDF knowledge — the shared utility package for the documents.js family.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|