@js-ak/excel-toolbox 1.2.6 → 1.2.7

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.
@@ -1,4 +1,5 @@
1
1
  import zlib from "node:zlib";
2
+ import * as Utils from "./utils/index.js";
2
3
  /**
3
4
  * Parses a ZIP archive from a buffer and extracts the files within.
4
5
  *
@@ -21,22 +22,37 @@ export function readSync(buffer) {
21
22
  const fileNameEnd = fileNameStart + fileNameLength;
22
23
  const fileName = buffer.subarray(fileNameStart, fileNameEnd).toString();
23
24
  const dataStart = fileNameEnd + extraFieldLength;
24
- const compressedSize = buffer.readUInt32LE(offset + 18);
25
25
  const useDataDescriptor = (generalPurposeBitFlag & 0x08) !== 0;
26
- if (useDataDescriptor) {
27
- throw new Error(`File ${fileName} uses data descriptor. Not supported in this minimal parser.`);
28
- }
29
- const compressedData = buffer.subarray(dataStart, dataStart + compressedSize);
26
+ let compressedData;
30
27
  let content;
31
28
  try {
32
- if (compressionMethod === 0) {
33
- content = compressedData;
34
- }
35
- else if (compressionMethod === 8) {
36
- content = zlib.inflateRawSync(compressedData);
29
+ if (useDataDescriptor) {
30
+ const { compressedSize, offset: ddOffset } = Utils.findDataDescriptor(buffer, dataStart);
31
+ compressedData = buffer.subarray(dataStart, dataStart + compressedSize);
32
+ if (compressionMethod === 0) {
33
+ content = compressedData;
34
+ }
35
+ else if (compressionMethod === 8) {
36
+ content = zlib.inflateRawSync(compressedData);
37
+ }
38
+ else {
39
+ throw new Error(`Unsupported compression method ${compressionMethod}`);
40
+ }
41
+ offset = ddOffset + 16; // Skip over data descriptor
37
42
  }
38
43
  else {
39
- throw new Error(`Unsupported compression method ${compressionMethod}`);
44
+ const compressedSize = buffer.readUInt32LE(offset + 18);
45
+ compressedData = buffer.subarray(dataStart, dataStart + compressedSize);
46
+ if (compressionMethod === 0) {
47
+ content = compressedData;
48
+ }
49
+ else if (compressionMethod === 8) {
50
+ content = zlib.inflateRawSync(compressedData);
51
+ }
52
+ else {
53
+ throw new Error(`Unsupported compression method ${compressionMethod}`);
54
+ }
55
+ offset = dataStart + compressedSize;
40
56
  }
41
57
  }
42
58
  catch (error) {
@@ -44,7 +60,6 @@ export function readSync(buffer) {
44
60
  throw new Error(`Error unpacking file ${fileName}: ${message}`);
45
61
  }
46
62
  files[fileName] = content;
47
- offset = dataStart + compressedSize;
48
63
  }
49
64
  return files;
50
65
  }
@@ -1,5 +1,6 @@
1
1
  import util from "node:util";
2
2
  import zlib from "node:zlib";
3
+ import * as Utils from "./utils/index.js";
3
4
  const inflateRaw = util.promisify(zlib.inflateRaw);
4
5
  /**
5
6
  * Parses a ZIP archive from a buffer and extracts the files within.
@@ -23,22 +24,37 @@ export async function read(buffer) {
23
24
  const fileNameEnd = fileNameStart + fileNameLength;
24
25
  const fileName = buffer.subarray(fileNameStart, fileNameEnd).toString();
25
26
  const dataStart = fileNameEnd + extraFieldLength;
26
- const compressedSize = buffer.readUInt32LE(offset + 18);
27
27
  const useDataDescriptor = (generalPurposeBitFlag & 0x08) !== 0;
28
- if (useDataDescriptor) {
29
- throw new Error(`File ${fileName} uses data descriptor. Not supported in this minimal parser.`);
30
- }
31
- const compressedData = buffer.subarray(dataStart, dataStart + compressedSize);
28
+ let compressedData;
32
29
  let content;
33
30
  try {
34
- if (compressionMethod === 0) {
35
- content = compressedData;
36
- }
37
- else if (compressionMethod === 8) {
38
- content = await inflateRaw(compressedData);
31
+ if (useDataDescriptor) {
32
+ const { compressedSize, offset: ddOffset } = Utils.findDataDescriptor(buffer, dataStart);
33
+ compressedData = buffer.subarray(dataStart, dataStart + compressedSize);
34
+ if (compressionMethod === 0) {
35
+ content = compressedData;
36
+ }
37
+ else if (compressionMethod === 8) {
38
+ content = await inflateRaw(compressedData);
39
+ }
40
+ else {
41
+ throw new Error(`Unsupported compression method ${compressionMethod}`);
42
+ }
43
+ offset = ddOffset + 16; // Skip over data descriptor
39
44
  }
40
45
  else {
41
- throw new Error(`Unsupported compression method ${compressionMethod}`);
46
+ const compressedSize = buffer.readUInt32LE(offset + 18);
47
+ compressedData = buffer.subarray(dataStart, dataStart + compressedSize);
48
+ if (compressionMethod === 0) {
49
+ content = compressedData;
50
+ }
51
+ else if (compressionMethod === 8) {
52
+ content = await inflateRaw(compressedData);
53
+ }
54
+ else {
55
+ throw new Error(`Unsupported compression method ${compressionMethod}`);
56
+ }
57
+ offset = dataStart + compressedSize;
42
58
  }
43
59
  }
44
60
  catch (error) {
@@ -46,7 +62,6 @@ export async function read(buffer) {
46
62
  throw new Error(`Error unpacking file ${fileName}: ${message}`);
47
63
  }
48
64
  files[fileName] = content;
49
- offset = dataStart + compressedSize;
50
65
  }
51
66
  return files;
52
67
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Precomputed CRC-32 lookup table for optimized checksum calculation.
3
+ * The table is generated using the standard IEEE 802.3 (Ethernet) polynomial:
4
+ * 0xEDB88320 (reversed representation of 0x04C11DB7).
5
+ *
6
+ * The table is immediately invoked and cached as a constant for performance,
7
+ * following the common implementation pattern for CRC algorithms.
8
+ */
9
+ const crcTable = (() => {
10
+ // Create a typed array for better performance with 256 32-bit unsigned integers
11
+ const table = new Uint32Array(256);
12
+ // Generate table entries for all possible byte values (0-255)
13
+ for (let i = 0; i < 256; i++) {
14
+ let crc = i; // Initialize with current byte value
15
+ // Process each bit (8 times)
16
+ for (let j = 0; j < 8; j++) {
17
+ /*
18
+ * CRC division algorithm:
19
+ * 1. If LSB is set (crc & 1), XOR with polynomial
20
+ * 2. Right-shift by 1 (unsigned)
21
+ *
22
+ * The polynomial 0xEDB88320 is:
23
+ * - Bit-reversed version of 0x04C11DB7
24
+ * - Uses reflected input/output algorithm
25
+ */
26
+ crc = crc & 1
27
+ ? 0xedb88320 ^ (crc >>> 1) // XOR with polynomial if LSB is set
28
+ : crc >>> 1; // Just shift right if LSB is not set
29
+ }
30
+ // Store final 32-bit value (>>> 0 ensures unsigned 32-bit representation)
31
+ table[i] = crc >>> 0;
32
+ }
33
+ return table;
34
+ })();
35
+ /**
36
+ * Computes a CRC-32 checksum for the given Buffer using the standard IEEE 802.3 polynomial.
37
+ * This implementation uses a precomputed lookup table for optimal performance.
38
+ *
39
+ * The algorithm follows these characteristics:
40
+ * - Polynomial: 0xEDB88320 (reversed representation of 0x04C11DB7)
41
+ * - Initial value: 0xFFFFFFFF (inverted by ~0)
42
+ * - Final XOR value: 0xFFFFFFFF (achieved by inverting the result)
43
+ * - Input and output reflection: Yes
44
+ *
45
+ * @param {Buffer} buf - The input buffer to calculate checksum for
46
+ * @returns {number} - The 32-bit unsigned CRC-32 checksum (0x00000000 to 0xFFFFFFFF)
47
+ */
48
+ export function crc32(buf) {
49
+ // Initialize CRC with all 1's (0xFFFFFFFF) using bitwise NOT
50
+ let crc = ~0;
51
+ // Process each byte in the buffer
52
+ for (let i = 0; i < buf.length; i++) {
53
+ /*
54
+ * CRC update algorithm steps:
55
+ * 1. XOR current CRC with next byte (lowest 8 bits)
56
+ * 2. Use result as index in precomputed table (0-255)
57
+ * 3. XOR the table value with right-shifted CRC (8 bits)
58
+ *
59
+ * The operation breakdown:
60
+ * - (crc ^ buf[i]) - XOR with next byte
61
+ * - & 0xff - Isolate lowest 8 bits
62
+ * - crc >>> 8 - Shift CRC right by 8 bits (unsigned)
63
+ * - ^ crcTable[...] - XOR with precomputed table value
64
+ */
65
+ crc = (crc >>> 8) ^ crcTable[(crc ^ buf[i]) & 0xff];
66
+ }
67
+ /*
68
+ * Final processing:
69
+ * 1. Invert all bits (~crc) to match standard CRC-32 output
70
+ * 2. Convert to unsigned 32-bit integer (>>> 0)
71
+ */
72
+ return ~crc >>> 0;
73
+ }
@@ -0,0 +1,47 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { toBytes } from "./to-bytes.js";
3
+ /**
4
+ * Converts a JavaScript Date object to a 4-byte Buffer in MS-DOS date/time format
5
+ * as specified in the ZIP file format specification (PKZIP APPNOTE.TXT).
6
+ *
7
+ * The MS-DOS date/time format packs both date and time into 4 bytes (32 bits) with
8
+ * the following bit layout:
9
+ *
10
+ * Time portion (2 bytes/16 bits):
11
+ * - Bits 00-04: Seconds divided by 2 (0-29, representing 0-58 seconds)
12
+ * - Bits 05-10: Minutes (0-59)
13
+ * - Bits 11-15: Hours (0-23)
14
+ *
15
+ * Date portion (2 bytes/16 bits):
16
+ * - Bits 00-04: Day (1-31)
17
+ * - Bits 05-08: Month (1-12)
18
+ * - Bits 09-15: Year offset from 1980 (0-127, representing 1980-2107)
19
+ *
20
+ * @param {Date} date - The JavaScript Date object to convert
21
+ * @returns {Buffer} - 4-byte Buffer containing:
22
+ * - Bytes 0-1: DOS time (hours, minutes, seconds/2)
23
+ * - Bytes 2-3: DOS date (year-1980, month, day)
24
+ * @throws {RangeError} - If the date is before 1980 or after 2107
25
+ */
26
+ export function dosTime(date) {
27
+ // Pack time components into 2 bytes (16 bits):
28
+ // - Hours (5 bits) shifted left 11 positions (bits 11-15)
29
+ // - Minutes (6 bits) shifted left 5 positions (bits 5-10)
30
+ // - Seconds/2 (5 bits) in least significant bits (bits 0-4)
31
+ const time = (date.getHours() << 11) | // Hours occupy bits 11-15
32
+ (date.getMinutes() << 5) | // Minutes occupy bits 5-10
33
+ (Math.floor(date.getSeconds() / 2)); // Seconds/2 occupy bits 0-4
34
+ // Pack date components into 2 bytes (16 bits):
35
+ // - (Year-1980) (7 bits) shifted left 9 positions (bits 9-15)
36
+ // - Month (4 bits) shifted left 5 positions (bits 5-8)
37
+ // - Day (5 bits) in least significant bits (bits 0-4)
38
+ const day = ((date.getFullYear() - 1980) << 9) | // Years since 1980 (bits 9-15)
39
+ ((date.getMonth() + 1) << 5) | // Month 1-12 (bits 5-8)
40
+ date.getDate(); // Day 1-31 (bits 0-4)
41
+ // Combine both 2-byte values into a single 4-byte Buffer
42
+ // Note: Using little-endian byte order for each 2-byte segment
43
+ return Buffer.from([
44
+ ...toBytes(time, 2), // Convert time to 2 bytes (LSB first)
45
+ ...toBytes(day, 2), // Convert date to 2 bytes (LSB first)
46
+ ]);
47
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Finds a Data Descriptor in a ZIP archive buffer.
3
+ *
4
+ * The Data Descriptor is an optional 16-byte structure that appears at the end of a file's compressed data.
5
+ * It contains the compressed size of the file, and must be used when the Local File Header does not contain this information.
6
+ *
7
+ * @param buffer - The buffer containing the ZIP archive data.
8
+ * @param start - The starting offset in the buffer to search for the Data Descriptor.
9
+ * @returns - An object with `offset` and `compressedSize` properties.
10
+ * @throws {Error} - If the Data Descriptor is not found.
11
+ */
12
+ export function findDataDescriptor(buffer, start) {
13
+ const DATA_DESCRIPTOR_SIGNATURE = 0x08074b50;
14
+ const DATA_DESCRIPTOR_TOTAL_LENGTH = 16;
15
+ const COMPRESSED_SIZE_OFFSET_FROM_SIGNATURE = 8;
16
+ for (let i = start; i <= buffer.length - DATA_DESCRIPTOR_TOTAL_LENGTH; i++) {
17
+ if (buffer.readUInt32LE(i) === DATA_DESCRIPTOR_SIGNATURE) {
18
+ const compressedSize = buffer.readUInt32LE(i + COMPRESSED_SIZE_OFFSET_FROM_SIGNATURE);
19
+ return {
20
+ compressedSize,
21
+ offset: i,
22
+ };
23
+ }
24
+ }
25
+ throw new Error("Data Descriptor not found");
26
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./crc-32.js";
2
+ export * from "./dos-time.js";
3
+ export * from "./find-data-descriptor.js";
4
+ export * from "./to-bytes.js";
@@ -0,0 +1,34 @@
1
+ import { Buffer } from "node:buffer";
2
+ /**
3
+ * Converts a numeric value into a fixed-length Buffer representation,
4
+ * storing the value in little-endian format with right-padding of zeros.
5
+ *
6
+ * This is particularly useful for binary protocols or file formats that
7
+ * require fixed-width numeric fields.
8
+ *
9
+ * @param {number} value - The numeric value to convert to bytes.
10
+ * Note: JavaScript numbers are IEEE 754 doubles, but only the
11
+ * integer portion will be used (up to 53-bit precision).
12
+ * @param {number} len - The desired length of the output Buffer in bytes.
13
+ * Must be a positive integer.
14
+ * @returns {Buffer} - A new Buffer of exactly `len` bytes containing:
15
+ * 1. The value's bytes in little-endian order (least significant byte first)
16
+ * 2. Zero padding in any remaining higher-order bytes
17
+ * @throws {RangeError} - If the value requires more bytes than `len` to represent
18
+ * (though this is currently not explicitly checked)
19
+ */
20
+ export function toBytes(value, len) {
21
+ // Allocate a new Buffer of the requested length, automatically zero-filled
22
+ const buf = Buffer.alloc(len);
23
+ // Process each byte position from least significant to most significant
24
+ for (let i = 0; i < len; i++) {
25
+ // Store the least significant byte of the current value
26
+ buf[i] = value & 0xff; // Mask to get bottom 8 bits
27
+ // Right-shift the value by 8 bits to process the next byte
28
+ // Note: This uses unsigned right shift (>>> would be signed)
29
+ value >>= 8;
30
+ // If the loop completes with value != 0, we've overflowed the buffer length,
31
+ // but this isn't currently checked/handled
32
+ }
33
+ return buf;
34
+ }
@@ -0,0 +1,15 @@
1
+ import { Buffer } from "node:buffer";
2
+ /**
3
+ * Computes a CRC-32 checksum for the given Buffer using the standard IEEE 802.3 polynomial.
4
+ * This implementation uses a precomputed lookup table for optimal performance.
5
+ *
6
+ * The algorithm follows these characteristics:
7
+ * - Polynomial: 0xEDB88320 (reversed representation of 0x04C11DB7)
8
+ * - Initial value: 0xFFFFFFFF (inverted by ~0)
9
+ * - Final XOR value: 0xFFFFFFFF (achieved by inverting the result)
10
+ * - Input and output reflection: Yes
11
+ *
12
+ * @param {Buffer} buf - The input buffer to calculate checksum for
13
+ * @returns {number} - The 32-bit unsigned CRC-32 checksum (0x00000000 to 0xFFFFFFFF)
14
+ */
15
+ export declare function crc32(buf: Buffer): number;
@@ -0,0 +1,25 @@
1
+ import { Buffer } from "node:buffer";
2
+ /**
3
+ * Converts a JavaScript Date object to a 4-byte Buffer in MS-DOS date/time format
4
+ * as specified in the ZIP file format specification (PKZIP APPNOTE.TXT).
5
+ *
6
+ * The MS-DOS date/time format packs both date and time into 4 bytes (32 bits) with
7
+ * the following bit layout:
8
+ *
9
+ * Time portion (2 bytes/16 bits):
10
+ * - Bits 00-04: Seconds divided by 2 (0-29, representing 0-58 seconds)
11
+ * - Bits 05-10: Minutes (0-59)
12
+ * - Bits 11-15: Hours (0-23)
13
+ *
14
+ * Date portion (2 bytes/16 bits):
15
+ * - Bits 00-04: Day (1-31)
16
+ * - Bits 05-08: Month (1-12)
17
+ * - Bits 09-15: Year offset from 1980 (0-127, representing 1980-2107)
18
+ *
19
+ * @param {Date} date - The JavaScript Date object to convert
20
+ * @returns {Buffer} - 4-byte Buffer containing:
21
+ * - Bytes 0-1: DOS time (hours, minutes, seconds/2)
22
+ * - Bytes 2-3: DOS date (year-1980, month, day)
23
+ * @throws {RangeError} - If the date is before 1980 or after 2107
24
+ */
25
+ export declare function dosTime(date: Date): Buffer;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Finds a Data Descriptor in a ZIP archive buffer.
3
+ *
4
+ * The Data Descriptor is an optional 16-byte structure that appears at the end of a file's compressed data.
5
+ * It contains the compressed size of the file, and must be used when the Local File Header does not contain this information.
6
+ *
7
+ * @param buffer - The buffer containing the ZIP archive data.
8
+ * @param start - The starting offset in the buffer to search for the Data Descriptor.
9
+ * @returns - An object with `offset` and `compressedSize` properties.
10
+ * @throws {Error} - If the Data Descriptor is not found.
11
+ */
12
+ export declare function findDataDescriptor(buffer: Buffer, start: number): {
13
+ offset: number;
14
+ compressedSize: number;
15
+ };
@@ -0,0 +1,4 @@
1
+ export * from "./crc-32.js";
2
+ export * from "./dos-time.js";
3
+ export * from "./find-data-descriptor.js";
4
+ export * from "./to-bytes.js";
@@ -0,0 +1,20 @@
1
+ import { Buffer } from "node:buffer";
2
+ /**
3
+ * Converts a numeric value into a fixed-length Buffer representation,
4
+ * storing the value in little-endian format with right-padding of zeros.
5
+ *
6
+ * This is particularly useful for binary protocols or file formats that
7
+ * require fixed-width numeric fields.
8
+ *
9
+ * @param {number} value - The numeric value to convert to bytes.
10
+ * Note: JavaScript numbers are IEEE 754 doubles, but only the
11
+ * integer portion will be used (up to 53-bit precision).
12
+ * @param {number} len - The desired length of the output Buffer in bytes.
13
+ * Must be a positive integer.
14
+ * @returns {Buffer} - A new Buffer of exactly `len` bytes containing:
15
+ * 1. The value's bytes in little-endian order (least significant byte first)
16
+ * 2. Zero padding in any remaining higher-order bytes
17
+ * @throws {RangeError} - If the value requires more bytes than `len` to represent
18
+ * (though this is currently not explicitly checked)
19
+ */
20
+ export declare function toBytes(value: number, len: number): Buffer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@js-ak/excel-toolbox",
3
- "version": "1.2.6",
3
+ "version": "1.2.7",
4
4
  "description": "excel-toolbox",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -1,157 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.crc32 = crc32;
4
- exports.dosTime = dosTime;
5
- exports.toBytes = toBytes;
6
- const node_buffer_1 = require("node:buffer");
7
- /**
8
- * Precomputed CRC-32 lookup table for optimized checksum calculation.
9
- * The table is generated using the standard IEEE 802.3 (Ethernet) polynomial:
10
- * 0xEDB88320 (reversed representation of 0x04C11DB7).
11
- *
12
- * The table is immediately invoked and cached as a constant for performance,
13
- * following the common implementation pattern for CRC algorithms.
14
- */
15
- const crcTable = (() => {
16
- // Create a typed array for better performance with 256 32-bit unsigned integers
17
- const table = new Uint32Array(256);
18
- // Generate table entries for all possible byte values (0-255)
19
- for (let i = 0; i < 256; i++) {
20
- let crc = i; // Initialize with current byte value
21
- // Process each bit (8 times)
22
- for (let j = 0; j < 8; j++) {
23
- /*
24
- * CRC division algorithm:
25
- * 1. If LSB is set (crc & 1), XOR with polynomial
26
- * 2. Right-shift by 1 (unsigned)
27
- *
28
- * The polynomial 0xEDB88320 is:
29
- * - Bit-reversed version of 0x04C11DB7
30
- * - Uses reflected input/output algorithm
31
- */
32
- crc = crc & 1
33
- ? 0xedb88320 ^ (crc >>> 1) // XOR with polynomial if LSB is set
34
- : crc >>> 1; // Just shift right if LSB is not set
35
- }
36
- // Store final 32-bit value (>>> 0 ensures unsigned 32-bit representation)
37
- table[i] = crc >>> 0;
38
- }
39
- return table;
40
- })();
41
- /**
42
- * Computes a CRC-32 checksum for the given Buffer using the standard IEEE 802.3 polynomial.
43
- * This implementation uses a precomputed lookup table for optimal performance.
44
- *
45
- * The algorithm follows these characteristics:
46
- * - Polynomial: 0xEDB88320 (reversed representation of 0x04C11DB7)
47
- * - Initial value: 0xFFFFFFFF (inverted by ~0)
48
- * - Final XOR value: 0xFFFFFFFF (achieved by inverting the result)
49
- * - Input and output reflection: Yes
50
- *
51
- * @param {Buffer} buf - The input buffer to calculate checksum for
52
- * @returns {number} - The 32-bit unsigned CRC-32 checksum (0x00000000 to 0xFFFFFFFF)
53
- */
54
- function crc32(buf) {
55
- // Initialize CRC with all 1's (0xFFFFFFFF) using bitwise NOT
56
- let crc = ~0;
57
- // Process each byte in the buffer
58
- for (let i = 0; i < buf.length; i++) {
59
- /*
60
- * CRC update algorithm steps:
61
- * 1. XOR current CRC with next byte (lowest 8 bits)
62
- * 2. Use result as index in precomputed table (0-255)
63
- * 3. XOR the table value with right-shifted CRC (8 bits)
64
- *
65
- * The operation breakdown:
66
- * - (crc ^ buf[i]) - XOR with next byte
67
- * - & 0xff - Isolate lowest 8 bits
68
- * - crc >>> 8 - Shift CRC right by 8 bits (unsigned)
69
- * - ^ crcTable[...] - XOR with precomputed table value
70
- */
71
- crc = (crc >>> 8) ^ crcTable[(crc ^ buf[i]) & 0xff];
72
- }
73
- /*
74
- * Final processing:
75
- * 1. Invert all bits (~crc) to match standard CRC-32 output
76
- * 2. Convert to unsigned 32-bit integer (>>> 0)
77
- */
78
- return ~crc >>> 0;
79
- }
80
- /**
81
- * Converts a JavaScript Date object to a 4-byte Buffer in MS-DOS date/time format
82
- * as specified in the ZIP file format specification (PKZIP APPNOTE.TXT).
83
- *
84
- * The MS-DOS date/time format packs both date and time into 4 bytes (32 bits) with
85
- * the following bit layout:
86
- *
87
- * Time portion (2 bytes/16 bits):
88
- * - Bits 00-04: Seconds divided by 2 (0-29, representing 0-58 seconds)
89
- * - Bits 05-10: Minutes (0-59)
90
- * - Bits 11-15: Hours (0-23)
91
- *
92
- * Date portion (2 bytes/16 bits):
93
- * - Bits 00-04: Day (1-31)
94
- * - Bits 05-08: Month (1-12)
95
- * - Bits 09-15: Year offset from 1980 (0-127, representing 1980-2107)
96
- *
97
- * @param {Date} date - The JavaScript Date object to convert
98
- * @returns {Buffer} - 4-byte Buffer containing:
99
- * - Bytes 0-1: DOS time (hours, minutes, seconds/2)
100
- * - Bytes 2-3: DOS date (year-1980, month, day)
101
- * @throws {RangeError} - If the date is before 1980 or after 2107
102
- */
103
- function dosTime(date) {
104
- // Pack time components into 2 bytes (16 bits):
105
- // - Hours (5 bits) shifted left 11 positions (bits 11-15)
106
- // - Minutes (6 bits) shifted left 5 positions (bits 5-10)
107
- // - Seconds/2 (5 bits) in least significant bits (bits 0-4)
108
- const time = (date.getHours() << 11) | // Hours occupy bits 11-15
109
- (date.getMinutes() << 5) | // Minutes occupy bits 5-10
110
- (Math.floor(date.getSeconds() / 2)); // Seconds/2 occupy bits 0-4
111
- // Pack date components into 2 bytes (16 bits):
112
- // - (Year-1980) (7 bits) shifted left 9 positions (bits 9-15)
113
- // - Month (4 bits) shifted left 5 positions (bits 5-8)
114
- // - Day (5 bits) in least significant bits (bits 0-4)
115
- const day = ((date.getFullYear() - 1980) << 9) | // Years since 1980 (bits 9-15)
116
- ((date.getMonth() + 1) << 5) | // Month 1-12 (bits 5-8)
117
- date.getDate(); // Day 1-31 (bits 0-4)
118
- // Combine both 2-byte values into a single 4-byte Buffer
119
- // Note: Using little-endian byte order for each 2-byte segment
120
- return node_buffer_1.Buffer.from([
121
- ...toBytes(time, 2), // Convert time to 2 bytes (LSB first)
122
- ...toBytes(day, 2), // Convert date to 2 bytes (LSB first)
123
- ]);
124
- }
125
- /**
126
- * Converts a numeric value into a fixed-length Buffer representation,
127
- * storing the value in little-endian format with right-padding of zeros.
128
- *
129
- * This is particularly useful for binary protocols or file formats that
130
- * require fixed-width numeric fields.
131
- *
132
- * @param {number} value - The numeric value to convert to bytes.
133
- * Note: JavaScript numbers are IEEE 754 doubles, but only the
134
- * integer portion will be used (up to 53-bit precision).
135
- * @param {number} len - The desired length of the output Buffer in bytes.
136
- * Must be a positive integer.
137
- * @returns {Buffer} - A new Buffer of exactly `len` bytes containing:
138
- * 1. The value's bytes in little-endian order (least significant byte first)
139
- * 2. Zero padding in any remaining higher-order bytes
140
- * @throws {RangeError} - If the value requires more bytes than `len` to represent
141
- * (though this is currently not explicitly checked)
142
- */
143
- function toBytes(value, len) {
144
- // Allocate a new Buffer of the requested length, automatically zero-filled
145
- const buf = node_buffer_1.Buffer.alloc(len);
146
- // Process each byte position from least significant to most significant
147
- for (let i = 0; i < len; i++) {
148
- // Store the least significant byte of the current value
149
- buf[i] = value & 0xff; // Mask to get bottom 8 bits
150
- // Right-shift the value by 8 bits to process the next byte
151
- // Note: This uses unsigned right shift (>>> would be signed)
152
- value >>= 8;
153
- // If the loop completes with value != 0, we've overflowed the buffer length,
154
- // but this isn't currently checked/handled
155
- }
156
- return buf;
157
- }