@andrew_l/toolkit 0.3.3 → 0.3.5

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/dist/index.cjs CHANGED
@@ -941,7 +941,7 @@ function fn(value, message) {
941
941
  }
942
942
  }
943
943
  function greaterThan(value, target, message) {
944
- if (!isNumber(value) || value < target) {
944
+ if (!isNumber(value) || value <= target) {
945
945
  throw toError$1(
946
946
  greaterThan,
947
947
  value,
@@ -1733,6 +1733,438 @@ function bigIntFromBytes(bytes) {
1733
1733
  return decoded;
1734
1734
  }
1735
1735
 
1736
+ function toError(value, unknownMessage = "Unknown error") {
1737
+ if (isError(value)) {
1738
+ return value;
1739
+ }
1740
+ const error = new Error(unknownMessage, { cause: value });
1741
+ Error.captureStackTrace(error, toError);
1742
+ return error;
1743
+ }
1744
+
1745
+ function createFunction(fnName, code, ...args) {
1746
+ try {
1747
+ const fn = new Function(...args, code);
1748
+ fn.code = code;
1749
+ return fn;
1750
+ } catch (err) {
1751
+ throw new Error(
1752
+ `failed to create bitPack.${fnName}()
1753
+ Error: ${toError(err).message}
1754
+ -- CODE START --
1755
+ ${code}
1756
+ -- CODE END--`
1757
+ );
1758
+ }
1759
+ }
1760
+
1761
+ function bitPack(options) {
1762
+ notEmpty(options.fields, "fields cannot be empty");
1763
+ greaterThan(options.totalBits, 0, "totalBits must be greater than 0");
1764
+ const fields = buildFieldsInfo$1(options.fields, options.totalBits);
1765
+ const plan = buildPlan(fields);
1766
+ const containersCount = Math.ceil(options.totalBits / 32);
1767
+ const buf = new Uint8Array(containersCount * 4);
1768
+ const baseCode = [
1769
+ "\n// Field init",
1770
+ initFields(fields),
1771
+ "\n// Plan",
1772
+ compilePlan(plan, options.optimize)
1773
+ ];
1774
+ const fnBufferCode = [
1775
+ ...baseCode,
1776
+ "\n// Return result",
1777
+ buildBufferResult(containersCount)
1778
+ ].join("\n");
1779
+ const fnBuffer = createFunction(
1780
+ "buffer",
1781
+ fnBufferCode,
1782
+ "data"
1783
+ );
1784
+ const fnBigIntCode = [
1785
+ ...baseCode,
1786
+ "\n// Return result",
1787
+ buildBigIntResult(containersCount)
1788
+ ].join("\n");
1789
+ const fnBigInt = createFunction(
1790
+ "bigint",
1791
+ fnBigIntCode,
1792
+ "data"
1793
+ );
1794
+ const fnNumberCode = [
1795
+ ...baseCode,
1796
+ "\n// Return result",
1797
+ buildNumberResult()
1798
+ ].join("\n");
1799
+ const fnNumber = createFunction(
1800
+ "number",
1801
+ fnNumberCode,
1802
+ "data"
1803
+ );
1804
+ const fnBitsCode = [
1805
+ ...baseCode,
1806
+ "\n// Return result",
1807
+ buildBitsResult(containersCount, options.totalBits)
1808
+ ].join("\n");
1809
+ const fnBits = createFunction("bits", fnBitsCode, "data");
1810
+ if (!options.debug) {
1811
+ def(fnBuffer, "code", void 0);
1812
+ def(fnBigInt, "code", void 0);
1813
+ def(fnNumber, "code", void 0);
1814
+ def(fnBits, "code", void 0);
1815
+ }
1816
+ return {
1817
+ buffer: fnBuffer,
1818
+ bigint: fnBigInt,
1819
+ number: fnNumber,
1820
+ bits: fnBits,
1821
+ plan: options.debug ? plan : void 0,
1822
+ __buf: buf
1823
+ };
1824
+ }
1825
+ function initFields(fields) {
1826
+ return fields.map((field) => {
1827
+ if (field.bits > 32) {
1828
+ ok(
1829
+ field.take === "low",
1830
+ `Fields more than 32 bits with take 'high' not yet supported`
1831
+ );
1832
+ const highMask = Math.pow(2, field.bits - 32) - 1;
1833
+ return [
1834
+ `var ${field.id}_high = ((data['${field.name}'] / 0x100000000) | 0) & 0x${highMask.toString(16)};`,
1835
+ `var ${field.id}_low = (data['${field.name}'] >>> 0);`
1836
+ ].join("\n");
1837
+ }
1838
+ if (field.take === "high") {
1839
+ return `var ${field.id} = (data['${field.name}'] / 0x100000000) | 0;`;
1840
+ }
1841
+ return `var ${field.id} = (data['${field.name}'] & 0x${field.mask.toString(16)}) >>> 0;`;
1842
+ }).join("\n");
1843
+ }
1844
+ function buildBufferResult(containersCount) {
1845
+ const lines = [`var buf = this.__buf;`];
1846
+ for (let i = 0; i < containersCount; i++) {
1847
+ const containerIndex = containersCount - 1 - i;
1848
+ lines.push(
1849
+ `buf[${i * 4}] = c_${containerIndex} >>> 24;`,
1850
+ `buf[${i * 4 + 1}] = c_${containerIndex} >>> 16;`,
1851
+ `buf[${i * 4 + 2}] = c_${containerIndex} >>> 8;`,
1852
+ `buf[${i * 4 + 3}] = c_${containerIndex};`
1853
+ );
1854
+ }
1855
+ lines.push("return buf;");
1856
+ return lines.join("\n");
1857
+ }
1858
+ function buildBigIntResult(containersCount) {
1859
+ const parts = [];
1860
+ for (let i = 0; i < containersCount; i++) {
1861
+ const containerIndex = containersCount - 1 - i;
1862
+ if (containerIndex > 0) {
1863
+ parts.push(
1864
+ `(BigInt(c_${containerIndex} >>> 0) << ${containerIndex * 32}n)`
1865
+ );
1866
+ } else {
1867
+ parts.push(`BigInt(c_${containerIndex} >>> 0)`);
1868
+ }
1869
+ }
1870
+ return `return (
1871
+ ${parts.join(" |\n ")}
1872
+ );`;
1873
+ }
1874
+ function buildNumberResult(containersCount) {
1875
+ return `return c_0;`;
1876
+ }
1877
+ function buildBitsResult(containersCount, totalBits) {
1878
+ const parts = [];
1879
+ for (let i = 0; i < containersCount; i++) {
1880
+ const containerIndex = containersCount - 1 - i;
1881
+ if (containerIndex > 0) {
1882
+ parts.push(
1883
+ `(BigInt(c_${containerIndex} >>> 0) << ${containerIndex * 32}n)`
1884
+ );
1885
+ } else {
1886
+ parts.push(`BigInt(c_${containerIndex} >>> 0)`);
1887
+ }
1888
+ }
1889
+ return `return (
1890
+ ${parts.join(" |\n ")}
1891
+ ).toString(2).padStart(${totalBits}, '0');`;
1892
+ }
1893
+ function compilePlan(plan, optimize) {
1894
+ if (optimize) {
1895
+ plan = optimizePlan(plan);
1896
+ }
1897
+ const assigned = /* @__PURE__ */ new Set();
1898
+ return plan.map((item) => compilePlanItem(item, assigned)).join("\n");
1899
+ }
1900
+ function optimizePlan(plan) {
1901
+ return plan.reduce((result, item) => {
1902
+ const prev = result.at(-1);
1903
+ if (canMergeSetOperations(prev, item)) {
1904
+ result.pop();
1905
+ result.push({
1906
+ object: "set",
1907
+ container: item.container,
1908
+ child: {
1909
+ object: "value",
1910
+ value: [
1911
+ compilePlanItem(prev.child),
1912
+ compilePlanItem(item.child)
1913
+ ].join(" |\n ")
1914
+ }
1915
+ });
1916
+ } else {
1917
+ result.push(item);
1918
+ }
1919
+ return result;
1920
+ }, []);
1921
+ }
1922
+ function canMergeSetOperations(prev, current) {
1923
+ return prev?.object === "set" && current.object === "set" && prev.container === current.container;
1924
+ }
1925
+ function compilePlanItem(plan, assigned) {
1926
+ switch (plan.object) {
1927
+ case "set":
1928
+ if (assigned && !assigned.has(plan.container)) {
1929
+ assigned.add(plan.container);
1930
+ return `var c_${plan.container} = ${compilePlanItem(plan.child)};`;
1931
+ }
1932
+ return `c_${plan.container} |= ${compilePlanItem(plan.child)};`;
1933
+ case "value":
1934
+ const offset = plan.offset ?? 0;
1935
+ return offset > 0 ? `(${plan.value}) << ${offset}` : `(${plan.value})`;
1936
+ default:
1937
+ throw new Error(`Unknown plan object: ${plan.object}`);
1938
+ }
1939
+ }
1940
+ function buildPlan(fields) {
1941
+ const result = [];
1942
+ for (const field of fields) {
1943
+ const startContainer = Math.floor(field.startBit / 32);
1944
+ const endContainer = Math.floor(field.endBit / 32);
1945
+ if (startContainer === endContainer) {
1946
+ addSingleContainerField(field, result);
1947
+ } else if (field.bits <= 32) {
1948
+ addSpanningField(field, result);
1949
+ } else {
1950
+ addLargeField(field, result);
1951
+ }
1952
+ }
1953
+ return result;
1954
+ }
1955
+ function addSingleContainerField(field, result) {
1956
+ result.push({
1957
+ object: "set",
1958
+ container: Math.floor(field.startBit / 32),
1959
+ child: {
1960
+ object: "value",
1961
+ offset: field.startBit % 32,
1962
+ value: field.id
1963
+ }
1964
+ });
1965
+ }
1966
+ function addSpanningField(field, result) {
1967
+ const startContainer = Math.floor(field.startBit / 32);
1968
+ const endContainer = Math.floor(field.endBit / 32);
1969
+ const firstContainerBits = 32 - field.startBit % 32;
1970
+ result.push({
1971
+ object: "set",
1972
+ container: startContainer,
1973
+ child: {
1974
+ object: "value",
1975
+ offset: field.startBit % 32,
1976
+ value: `(${field.id}) & ${(1 << firstContainerBits) - 1}`
1977
+ }
1978
+ });
1979
+ result.push({
1980
+ object: "set",
1981
+ container: endContainer,
1982
+ child: {
1983
+ object: "value",
1984
+ value: `(${field.id}) >>> ${firstContainerBits}`
1985
+ }
1986
+ });
1987
+ }
1988
+ function addLargeField(field, result) {
1989
+ const startContainer = Math.floor(field.startBit / 32);
1990
+ const endContainer = Math.floor(field.endBit / 32);
1991
+ const startOffset = field.startBit % 32;
1992
+ ok(
1993
+ startContainer !== endContainer,
1994
+ `Large field ${field.name} fits in single container - logic error`
1995
+ );
1996
+ ok(
1997
+ endContainer - startContainer === 1,
1998
+ `Fields spanning more than 2 containers (${field.bits} bits) not yet supported`
1999
+ );
2000
+ const bitsInLowerContainer = 32 - startOffset;
2001
+ result.push({
2002
+ object: "set",
2003
+ container: endContainer,
2004
+ child: {
2005
+ object: "value",
2006
+ offset: startOffset,
2007
+ value: `${field.id}_high`
2008
+ }
2009
+ });
2010
+ if (bitsInLowerContainer < 32) {
2011
+ result.push({
2012
+ object: "set",
2013
+ container: endContainer,
2014
+ child: {
2015
+ object: "value",
2016
+ value: `${field.id}_low >>> ${bitsInLowerContainer}`
2017
+ }
2018
+ });
2019
+ }
2020
+ if (field.bits > 32) {
2021
+ result.push({
2022
+ object: "set",
2023
+ container: startContainer,
2024
+ child: {
2025
+ object: "value",
2026
+ offset: startOffset,
2027
+ value: `${field.id}_low`
2028
+ }
2029
+ });
2030
+ }
2031
+ }
2032
+ function buildFieldsInfo$1(fields, totalBits) {
2033
+ const result = [];
2034
+ let currentBitPosition = totalBits;
2035
+ fields.forEach((field, idx) => {
2036
+ const startBit = currentBitPosition - field.bits;
2037
+ const endBit = currentBitPosition - 1;
2038
+ result.push({
2039
+ id: `f_${idx}`,
2040
+ ...field,
2041
+ startBit,
2042
+ endBit,
2043
+ mask: Math.pow(2, field.bits) - 1
2044
+ });
2045
+ currentBitPosition -= field.bits;
2046
+ });
2047
+ return result;
2048
+ }
2049
+
2050
+ function bitUnpack(options) {
2051
+ notEmpty(options.fields, "fields cannot be empty");
2052
+ greaterThan(options.totalBits, 0, "totalBits must be greater than 0");
2053
+ const fields = buildFieldsInfo(options.fields, options.totalBits);
2054
+ const fnBigIntCode = [`return ${compileFields(fields)};`].join("\n");
2055
+ const fnBigInt = createFunction(
2056
+ "bigint",
2057
+ fnBigIntCode,
2058
+ "data"
2059
+ );
2060
+ const fnNumberCode = [
2061
+ "\n// Extract container from number",
2062
+ "data = BigInt(data);",
2063
+ "\n// Return result",
2064
+ `return ${compileFields(fields)};`
2065
+ ].join("\n");
2066
+ const fnNumber = createFunction(
2067
+ "number",
2068
+ fnNumberCode,
2069
+ "data"
2070
+ );
2071
+ const fnBufferCode = [
2072
+ "\n// Extract bytes from buffer (big-endian)",
2073
+ extractBigIntFromBuffer(options.totalBits),
2074
+ "\n// Return result",
2075
+ `return ${compileFields(fields)};`
2076
+ ].join("\n");
2077
+ const fnBuffer = createFunction(
2078
+ "buffer",
2079
+ fnBufferCode,
2080
+ "data"
2081
+ );
2082
+ const fnBitsCode = [
2083
+ "\n// Convert bits string to bigint",
2084
+ 'var data = BigInt("0b" + bits);',
2085
+ "\n// Return result",
2086
+ `return ${compileFields(fields)};`
2087
+ ].join("\n");
2088
+ const fnBits = createFunction("bits", fnBitsCode, "bits");
2089
+ if (!options.debug) {
2090
+ def(fnBuffer, "code", void 0);
2091
+ def(fnBigInt, "code", void 0);
2092
+ def(fnNumber, "code", void 0);
2093
+ def(fnBits, "code", void 0);
2094
+ }
2095
+ return {
2096
+ buffer: fnBuffer,
2097
+ bigint: fnBigInt,
2098
+ number: fnNumber,
2099
+ bits: fnBits
2100
+ };
2101
+ }
2102
+ function compileFields(fields) {
2103
+ const lines = ["{"];
2104
+ for (const field of fields) {
2105
+ if (field.startBit === 0) {
2106
+ lines.push(
2107
+ ` ['${field.name}']: Number(data & 0x${field.mask.toString(16)}n),`
2108
+ );
2109
+ } else {
2110
+ lines.push(
2111
+ ` ['${field.name}']: Number((data >> ${field.startBit}n) & 0x${field.mask.toString(16)}n),`
2112
+ );
2113
+ }
2114
+ }
2115
+ lines.push("}");
2116
+ return lines.join("\n");
2117
+ }
2118
+ function extractBigIntFromBuffer(totalBits) {
2119
+ const totalBytes = Math.ceil(totalBits / 8);
2120
+ const chunks = [];
2121
+ let byteIndex = 0;
2122
+ let remainingBytes = totalBytes;
2123
+ while (remainingBytes > 0) {
2124
+ if (remainingBytes >= 4) {
2125
+ const shift = (remainingBytes - 4) * 8;
2126
+ const chunk = `((data[${byteIndex}] << 24) | (data[${byteIndex + 1}] << 16) | (data[${byteIndex + 2}] << 8) | data[${byteIndex + 3}]) >>> 0`;
2127
+ if (shift === 0) {
2128
+ chunks.push(`BigInt(${chunk})`);
2129
+ } else {
2130
+ chunks.push(`(BigInt(${chunk}) << ${shift}n)`);
2131
+ }
2132
+ byteIndex += 4;
2133
+ remainingBytes -= 4;
2134
+ } else {
2135
+ let chunk;
2136
+ if (remainingBytes === 3) {
2137
+ chunk = `(data[${byteIndex}] << 16) | (data[${byteIndex + 1}] << 8) | data[${byteIndex + 2}]`;
2138
+ } else if (remainingBytes === 2) {
2139
+ chunk = `(data[${byteIndex}] << 8) | data[${byteIndex + 1}]`;
2140
+ } else {
2141
+ chunk = `data[${byteIndex}]`;
2142
+ }
2143
+ chunks.push(`BigInt(${chunk})`);
2144
+ remainingBytes = 0;
2145
+ }
2146
+ }
2147
+ return `data =
2148
+ ${chunks.join("\n | ")};`;
2149
+ }
2150
+ function buildFieldsInfo(fields, totalBits) {
2151
+ const result = [];
2152
+ let currentBitPosition = totalBits;
2153
+ fields.forEach((field, idx) => {
2154
+ const startBit = currentBitPosition - field.bits;
2155
+ const endBit = currentBitPosition - 1;
2156
+ result.push({
2157
+ id: `f_${idx}`,
2158
+ ...field,
2159
+ mask: (1n << BigInt(field.bits)) - 1n,
2160
+ startBit,
2161
+ endBit
2162
+ });
2163
+ currentBitPosition -= field.bits;
2164
+ });
2165
+ return result;
2166
+ }
2167
+
1736
2168
  function bytesToBase64(data, { encoding = "base64", padding } = {}) {
1737
2169
  if (encoding === "base64") {
1738
2170
  return base64.encode(data, { includePadding: padding ?? true });
@@ -2865,15 +3297,6 @@ function captureStackTrace(till) {
2865
3297
  return (err.stack || "").slice(6);
2866
3298
  }
2867
3299
 
2868
- function toError(value, unknownMessage = "Unknown error") {
2869
- if (isError(value)) {
2870
- return value;
2871
- }
2872
- const error = new Error(unknownMessage, { cause: value });
2873
- Error.captureStackTrace(error, toError);
2874
- return error;
2875
- }
2876
-
2877
3300
  function catchError(fn) {
2878
3301
  try {
2879
3302
  const res = fn();
@@ -5623,6 +6046,8 @@ exports.base64url = base64url;
5623
6046
  exports.basex = basex;
5624
6047
  exports.bigIntBytes = bigIntBytes;
5625
6048
  exports.bigIntFromBytes = bigIntFromBytes;
6049
+ exports.bitPack = bitPack;
6050
+ exports.bitUnpack = bitUnpack;
5626
6051
  exports.blendColors = blendColors;
5627
6052
  exports.buildCssColor = buildCssColor;
5628
6053
  exports.bytesToBase64 = bytesToBase64;
@@ -5656,6 +6081,7 @@ exports.createDeepCloneWith = createDeepCloneWith;
5656
6081
  exports.createEJSON = createEJSON;
5657
6082
  exports.createEJSONStream = createEJSONStream;
5658
6083
  exports.createEnvParser = createEnvParser;
6084
+ exports.createFunction = createFunction;
5659
6085
  exports.createRandomizer = createRandomizer;
5660
6086
  exports.createSecureCustomizer = createSecureCustomizer;
5661
6087
  exports.createTimeObject = createTimeObject;