document-bytes 1.5.8 → 1.6.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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![GitHub](https://img.shields.io/badge/GitHub-181717?logo=github&logoColor=white)](https://github.com/ExaDev/documents.js/tree/main/packages/byte-codec) [![npm](https://img.shields.io/badge/npm-CB3837?logo=npm&logoColor=white)](https://www.npmjs.com/package/byte-codec) [![npm version](https://img.shields.io/npm/v/byte-codec)](https://www.npmjs.com/package/byte-codec) [![CI](https://img.shields.io/github/actions/workflow/status/ExaDev/documents.js/ci.yml?branch=main)](https://github.com/ExaDev/documents.js/actions)
4
4
 
5
- > Generic byte-level primitives (ByteWriter, ByteReader, CRC-32, deflate/inflate) and PNG/JPEG image encoding/decoding with zero PDF knowledge — the shared utility package for the [documents.js family](../../README.md).
5
+ > 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](../../README.md).
6
6
 
7
7
  Extracted from [pdf-codec](../pdf-codec/README.md), where these utilities lived as a directory-isolated subgraph under `src/bytes/` + `src/image/` with no PDF imports. Both pdf-codec and documents.js consume them from this neutral home rather than one fetching byte utilities from a backend.
8
8
 
@@ -46,6 +46,7 @@ To run a single test file, pass its path to vitest directly, e.g. `pnpm exec vit
46
46
  | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
47
47
  | `bytes/writer` | `ByteWriter` (chunked growable byte-output builder), `concatBytes` |
48
48
  | `bytes/reader` | `ByteReader` (sequential big/little-endian byte reader), `isAsciiWhitespace` |
49
+ | `bytes/base64` | `bytesToBase64`, `base64ToBytes` (standard-alphabet base64, RFC 4648 section 4, with padding — the one implementation every package in the family shares for image payloads and `data:` URIs), `BASE64_ENCODE_CHUNK_CHARS` |
49
50
  | `bytes/crc32` | `crc32` (IEEE 802.3 / ZIP / PNG polynomial table-driven CRC-32) |
50
51
  | `bytes/flate` | `deflate`, `inflate`, `inflateTolerant` (fflate-backed DEFLATE compression/decompression with a safety cap) |
51
52
  | `image/png-encode` | `encodePng` (raw RGB/RGBA pixels → PNG bytes; a truecolour source image whose pixels reduce to 256 or fewer distinct colours is encoded both as indexed colour, PNG colour type 3 with a PLTE and, where needed, a tRNS chunk, and as plain truecolour, and whichever comes out smaller is returned -- indexed colour wins for the large flat-colour images typical of diagrams and screenshots, but the PLTE/tRNS chunk overhead can make it larger for small images, so the encoder measures rather than assumes, at the cost of a full second encode for every eligible image; throws if either `width` or `height` is not a positive integer no greater than the PNG spec's own IHDR limit, or if their product exceeds a practical per-call pixel-count ceiling, since PNG's IHDR chunk has no valid encoding for zero, negative, fractional, or non-finite dimensions and this bounds an otherwise-unbounded encode to a fixed worst case) |
package/dist/index.cjs CHANGED
@@ -90,6 +90,76 @@ var ByteReader = class {
90
90
  }
91
91
  };
92
92
  //#endregion
93
+ //#region src/bytes/base64.ts
94
+ const TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
95
+ const PADDING_CODE = "=".charCodeAt(0);
96
+ const BYTE_VALUES$1 = 256;
97
+ /** What `DECODE` holds at every code point the alphabet does not cover. Any value outside the 0-63 range a real alphabet index occupies would serve; this one is the largest a byte can hold, so no arithmetic below can ever produce it by accident. */
98
+ const DECODE_MISS = 255;
99
+ const DECODE = (() => {
100
+ const map = new Uint8Array(BYTE_VALUES$1).fill(DECODE_MISS);
101
+ for (let index = 0; index < 64; index += 1) map[TABLE.charCodeAt(index)] = index;
102
+ return map;
103
+ })();
104
+ /** Output characters converted by one `String.fromCharCode.apply` call: half of MAX_CALL_ARGUMENTS, which is also the quantum MDN's own chunked-apply example uses, leaving the engine room for whatever else it puts on its argument stack. It is divisible by four, so every chunk holds whole four-character groups. Exported so the tests can place inputs on and around a chunk boundary without repeating the figure. */
105
+ const BASE64_ENCODE_CHUNK_CHARS = 32768;
106
+ /**
107
+ * Encodes bytes as padded standard-alphabet base64 (RFC 4648 section 4).
108
+ *
109
+ * Output characters are collected as character codes and turned into a string one chunk at a time rather than appended to a string one character at a time, which is what made encoding a few megabytes take seconds under instrumentation.
110
+ * @param bytes - The bytes to encode; only the view's own bytes are read.
111
+ * @returns The base64 text, four characters per three input bytes with `=` padding, and an empty string for empty input.
112
+ */
113
+ function bytesToBase64(bytes) {
114
+ const len = bytes.length;
115
+ const codes = new Array(BASE64_ENCODE_CHUNK_CHARS);
116
+ const chunkBytes = codes.length / 4 * 3;
117
+ return Array.from({ length: Math.ceil(len / chunkBytes) }, (_unused, chunk) => {
118
+ const start = chunk * chunkBytes;
119
+ const end = Math.min(start + chunkBytes, len);
120
+ let filled = 0;
121
+ for (let index = start; index < end; index += 3) {
122
+ const b0 = bytes[index] ?? 0;
123
+ const b1 = bytes[index + 1] ?? 0;
124
+ const b2 = bytes[index + 2] ?? 0;
125
+ codes[filled++] = TABLE.charCodeAt(b0 >> 2);
126
+ codes[filled++] = TABLE.charCodeAt((b0 & 3) << 4 | b1 >> 4);
127
+ codes[filled++] = index + 1 < len ? TABLE.charCodeAt((b1 & 15) << 2 | b2 >> 6) : PADDING_CODE;
128
+ codes[filled++] = index + 2 < len ? TABLE.charCodeAt(b2 & 63) : PADDING_CODE;
129
+ }
130
+ return String.fromCharCode.apply(null, codes.slice(0, filled));
131
+ }).join("");
132
+ }
133
+ /**
134
+ * Decodes standard-alphabet base64 (RFC 4648 section 4) back to the bytes it was made from.
135
+ *
136
+ * Characters outside the alphabet and the padding character are removed before decoding, so text wrapped across lines -- which several of the formats built on this deliberately emit -- decodes the same as an unwrapped run of the same characters.
137
+ * @param base64 - The base64 text to decode.
138
+ * @throws Error `invalid base64 input` when a four-character group's first two characters are not both in the alphabet, which is the point at which no byte at all can be recovered from that group.
139
+ * @returns The decoded bytes, and an empty array for input that holds no alphabet characters.
140
+ */
141
+ function base64ToBytes(base64) {
142
+ const clean = base64.replace(/[^A-Za-z0-9+/=]/g, "");
143
+ const out = [];
144
+ for (let index = 0; index < clean.length; index += 4) {
145
+ const c0 = DECODE[clean.charCodeAt(index)] ?? DECODE_MISS;
146
+ const c1 = DECODE[clean.charCodeAt(index + 1)] ?? DECODE_MISS;
147
+ const c2 = clean.charCodeAt(index + 2);
148
+ const c3 = clean.charCodeAt(index + 3);
149
+ if (c0 === DECODE_MISS || c1 === DECODE_MISS) throw new Error("invalid base64 input");
150
+ out.push(c0 << 2 | c1 >> 4);
151
+ if (c2 !== PADDING_CODE) {
152
+ const d2 = DECODE[c2] ?? DECODE_MISS;
153
+ out.push((c1 & 15) << 4 | d2 >> 2);
154
+ if (c3 !== PADDING_CODE) {
155
+ const d3 = DECODE[c3] ?? DECODE_MISS;
156
+ out.push((d2 & 3) << 6 | d3);
157
+ }
158
+ }
159
+ }
160
+ return Uint8Array.from(out);
161
+ }
162
+ //#endregion
93
163
  //#region src/bytes/crc32.ts
94
164
  const CRC32_POLYNOMIAL = 3988292384;
95
165
  const BYTE_VALUES = 256;
@@ -637,11 +707,14 @@ function readJpegInfo(bytes) {
637
707
  throw new Error("no SOF marker found in JPEG file");
638
708
  }
639
709
  //#endregion
710
+ exports.BASE64_ENCODE_CHUNK_CHARS = BASE64_ENCODE_CHUNK_CHARS;
640
711
  exports.ByteReader = ByteReader;
641
712
  exports.ByteWriter = ByteWriter;
642
713
  exports.MAX_INFLATE_OUTPUT_BYTES = MAX_INFLATE_OUTPUT_BYTES;
643
714
  exports.PNG_MAX_DIMENSION = PNG_MAX_DIMENSION;
644
715
  exports.PNG_MAX_PIXELS = PNG_MAX_PIXELS;
716
+ exports.base64ToBytes = base64ToBytes;
717
+ exports.bytesToBase64 = bytesToBase64;
645
718
  exports.concatBytes = concatBytes;
646
719
  exports.crc32 = crc32;
647
720
  exports.decodePng = decodePng;
package/dist/index.d.cts CHANGED
@@ -29,6 +29,27 @@ declare class ByteReader {
29
29
  matchKeyword(keyword: string): boolean;
30
30
  }
31
31
  //#endregion
32
+ //#region src/bytes/base64.d.ts
33
+ /** Output characters converted by one `String.fromCharCode.apply` call: half of MAX_CALL_ARGUMENTS, which is also the quantum MDN's own chunked-apply example uses, leaving the engine room for whatever else it puts on its argument stack. It is divisible by four, so every chunk holds whole four-character groups. Exported so the tests can place inputs on and around a chunk boundary without repeating the figure. */
34
+ declare const BASE64_ENCODE_CHUNK_CHARS: number;
35
+ /**
36
+ * Encodes bytes as padded standard-alphabet base64 (RFC 4648 section 4).
37
+ *
38
+ * Output characters are collected as character codes and turned into a string one chunk at a time rather than appended to a string one character at a time, which is what made encoding a few megabytes take seconds under instrumentation.
39
+ * @param bytes - The bytes to encode; only the view's own bytes are read.
40
+ * @returns The base64 text, four characters per three input bytes with `=` padding, and an empty string for empty input.
41
+ */
42
+ declare function bytesToBase64(bytes: Uint8Array): string;
43
+ /**
44
+ * Decodes standard-alphabet base64 (RFC 4648 section 4) back to the bytes it was made from.
45
+ *
46
+ * Characters outside the alphabet and the padding character are removed before decoding, so text wrapped across lines -- which several of the formats built on this deliberately emit -- decodes the same as an unwrapped run of the same characters.
47
+ * @param base64 - The base64 text to decode.
48
+ * @throws Error `invalid base64 input` when a four-character group's first two characters are not both in the alphabet, which is the point at which no byte at all can be recovered from that group.
49
+ * @returns The decoded bytes, and an empty array for input that holds no alphabet characters.
50
+ */
51
+ declare function base64ToBytes(base64: string): Uint8Array<ArrayBuffer>;
52
+ //#endregion
32
53
  //#region src/bytes/crc32.d.ts
33
54
  declare function crc32(bytes: Uint8Array<ArrayBuffer>): number;
34
55
  //#endregion
@@ -81,4 +102,4 @@ interface JpegInfo {
81
102
  }
82
103
  declare function readJpegInfo(bytes: Uint8Array<ArrayBuffer>): JpegInfo;
83
104
  //#endregion
84
- export { ByteReader, ByteWriter, DeflateLevel, InflateResult, JpegInfo, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, PngDecodeOptions, PngEncodeOptions, PngFilterType, RawImage, concatBytes, crc32, decodePng, deflate, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, readJpegInfo, unfilterScanlines };
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 };
package/dist/index.d.ts CHANGED
@@ -29,6 +29,27 @@ declare class ByteReader {
29
29
  matchKeyword(keyword: string): boolean;
30
30
  }
31
31
  //#endregion
32
+ //#region src/bytes/base64.d.ts
33
+ /** Output characters converted by one `String.fromCharCode.apply` call: half of MAX_CALL_ARGUMENTS, which is also the quantum MDN's own chunked-apply example uses, leaving the engine room for whatever else it puts on its argument stack. It is divisible by four, so every chunk holds whole four-character groups. Exported so the tests can place inputs on and around a chunk boundary without repeating the figure. */
34
+ declare const BASE64_ENCODE_CHUNK_CHARS: number;
35
+ /**
36
+ * Encodes bytes as padded standard-alphabet base64 (RFC 4648 section 4).
37
+ *
38
+ * Output characters are collected as character codes and turned into a string one chunk at a time rather than appended to a string one character at a time, which is what made encoding a few megabytes take seconds under instrumentation.
39
+ * @param bytes - The bytes to encode; only the view's own bytes are read.
40
+ * @returns The base64 text, four characters per three input bytes with `=` padding, and an empty string for empty input.
41
+ */
42
+ declare function bytesToBase64(bytes: Uint8Array): string;
43
+ /**
44
+ * Decodes standard-alphabet base64 (RFC 4648 section 4) back to the bytes it was made from.
45
+ *
46
+ * Characters outside the alphabet and the padding character are removed before decoding, so text wrapped across lines -- which several of the formats built on this deliberately emit -- decodes the same as an unwrapped run of the same characters.
47
+ * @param base64 - The base64 text to decode.
48
+ * @throws Error `invalid base64 input` when a four-character group's first two characters are not both in the alphabet, which is the point at which no byte at all can be recovered from that group.
49
+ * @returns The decoded bytes, and an empty array for input that holds no alphabet characters.
50
+ */
51
+ declare function base64ToBytes(base64: string): Uint8Array<ArrayBuffer>;
52
+ //#endregion
32
53
  //#region src/bytes/crc32.d.ts
33
54
  declare function crc32(bytes: Uint8Array<ArrayBuffer>): number;
34
55
  //#endregion
@@ -81,4 +102,4 @@ interface JpegInfo {
81
102
  }
82
103
  declare function readJpegInfo(bytes: Uint8Array<ArrayBuffer>): JpegInfo;
83
104
  //#endregion
84
- export { ByteReader, ByteWriter, DeflateLevel, InflateResult, JpegInfo, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, PngDecodeOptions, PngEncodeOptions, PngFilterType, RawImage, concatBytes, crc32, decodePng, deflate, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, readJpegInfo, unfilterScanlines };
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 };
package/dist/index.js CHANGED
@@ -89,6 +89,76 @@ var ByteReader = class {
89
89
  }
90
90
  };
91
91
  //#endregion
92
+ //#region src/bytes/base64.ts
93
+ const TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
94
+ const PADDING_CODE = "=".charCodeAt(0);
95
+ const BYTE_VALUES$1 = 256;
96
+ /** What `DECODE` holds at every code point the alphabet does not cover. Any value outside the 0-63 range a real alphabet index occupies would serve; this one is the largest a byte can hold, so no arithmetic below can ever produce it by accident. */
97
+ const DECODE_MISS = 255;
98
+ const DECODE = (() => {
99
+ const map = new Uint8Array(BYTE_VALUES$1).fill(DECODE_MISS);
100
+ for (let index = 0; index < 64; index += 1) map[TABLE.charCodeAt(index)] = index;
101
+ return map;
102
+ })();
103
+ /** Output characters converted by one `String.fromCharCode.apply` call: half of MAX_CALL_ARGUMENTS, which is also the quantum MDN's own chunked-apply example uses, leaving the engine room for whatever else it puts on its argument stack. It is divisible by four, so every chunk holds whole four-character groups. Exported so the tests can place inputs on and around a chunk boundary without repeating the figure. */
104
+ const BASE64_ENCODE_CHUNK_CHARS = 32768;
105
+ /**
106
+ * Encodes bytes as padded standard-alphabet base64 (RFC 4648 section 4).
107
+ *
108
+ * Output characters are collected as character codes and turned into a string one chunk at a time rather than appended to a string one character at a time, which is what made encoding a few megabytes take seconds under instrumentation.
109
+ * @param bytes - The bytes to encode; only the view's own bytes are read.
110
+ * @returns The base64 text, four characters per three input bytes with `=` padding, and an empty string for empty input.
111
+ */
112
+ function bytesToBase64(bytes) {
113
+ const len = bytes.length;
114
+ const codes = new Array(BASE64_ENCODE_CHUNK_CHARS);
115
+ const chunkBytes = codes.length / 4 * 3;
116
+ return Array.from({ length: Math.ceil(len / chunkBytes) }, (_unused, chunk) => {
117
+ const start = chunk * chunkBytes;
118
+ const end = Math.min(start + chunkBytes, len);
119
+ let filled = 0;
120
+ for (let index = start; index < end; index += 3) {
121
+ const b0 = bytes[index] ?? 0;
122
+ const b1 = bytes[index + 1] ?? 0;
123
+ const b2 = bytes[index + 2] ?? 0;
124
+ codes[filled++] = TABLE.charCodeAt(b0 >> 2);
125
+ codes[filled++] = TABLE.charCodeAt((b0 & 3) << 4 | b1 >> 4);
126
+ codes[filled++] = index + 1 < len ? TABLE.charCodeAt((b1 & 15) << 2 | b2 >> 6) : PADDING_CODE;
127
+ codes[filled++] = index + 2 < len ? TABLE.charCodeAt(b2 & 63) : PADDING_CODE;
128
+ }
129
+ return String.fromCharCode.apply(null, codes.slice(0, filled));
130
+ }).join("");
131
+ }
132
+ /**
133
+ * Decodes standard-alphabet base64 (RFC 4648 section 4) back to the bytes it was made from.
134
+ *
135
+ * Characters outside the alphabet and the padding character are removed before decoding, so text wrapped across lines -- which several of the formats built on this deliberately emit -- decodes the same as an unwrapped run of the same characters.
136
+ * @param base64 - The base64 text to decode.
137
+ * @throws Error `invalid base64 input` when a four-character group's first two characters are not both in the alphabet, which is the point at which no byte at all can be recovered from that group.
138
+ * @returns The decoded bytes, and an empty array for input that holds no alphabet characters.
139
+ */
140
+ function base64ToBytes(base64) {
141
+ const clean = base64.replace(/[^A-Za-z0-9+/=]/g, "");
142
+ const out = [];
143
+ for (let index = 0; index < clean.length; index += 4) {
144
+ const c0 = DECODE[clean.charCodeAt(index)] ?? DECODE_MISS;
145
+ const c1 = DECODE[clean.charCodeAt(index + 1)] ?? DECODE_MISS;
146
+ const c2 = clean.charCodeAt(index + 2);
147
+ const c3 = clean.charCodeAt(index + 3);
148
+ if (c0 === DECODE_MISS || c1 === DECODE_MISS) throw new Error("invalid base64 input");
149
+ out.push(c0 << 2 | c1 >> 4);
150
+ if (c2 !== PADDING_CODE) {
151
+ const d2 = DECODE[c2] ?? DECODE_MISS;
152
+ out.push((c1 & 15) << 4 | d2 >> 2);
153
+ if (c3 !== PADDING_CODE) {
154
+ const d3 = DECODE[c3] ?? DECODE_MISS;
155
+ out.push((d2 & 3) << 6 | d3);
156
+ }
157
+ }
158
+ }
159
+ return Uint8Array.from(out);
160
+ }
161
+ //#endregion
92
162
  //#region src/bytes/crc32.ts
93
163
  const CRC32_POLYNOMIAL = 3988292384;
94
164
  const BYTE_VALUES = 256;
@@ -636,4 +706,4 @@ function readJpegInfo(bytes) {
636
706
  throw new Error("no SOF marker found in JPEG file");
637
707
  }
638
708
  //#endregion
639
- export { ByteReader, ByteWriter, MAX_INFLATE_OUTPUT_BYTES, PNG_MAX_DIMENSION, PNG_MAX_PIXELS, concatBytes, crc32, decodePng, deflate, encodePng, exceedsMaxPixelCount, filterScanlines, inflate, inflateTolerant, isAsciiWhitespace, readJpegInfo, unfilterScanlines };
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 };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "document-bytes",
3
- "version": "1.5.8",
4
- "description": "Generic byte-level primitives (ByteWriter, ByteReader, CRC-32, deflate/inflate) and PNG/JPEG image encoding/decoding with zero PDF knowledge — the shared utility package for the documents.js family.",
3
+ "version": "1.6.0",
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": {
7
7
  "type": "git",