@andrew_l/toolkit 0.3.3 → 0.3.4

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,433 @@ 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
+ return [
1829
+ `var ${field.id}_high = (data['${field.name}'] / 0x100000000) | 0;`,
1830
+ `var ${field.id}_low = (data['${field.name}'] >>> 0);`
1831
+ ].join("\n");
1832
+ }
1833
+ if (field.take === "high") {
1834
+ return `var ${field.id} = (data['${field.name}'] / 0x100000000) | 0;`;
1835
+ }
1836
+ return `var ${field.id} = (data['${field.name}'] & 0x${field.mask.toString(16)}) >>> 0;`;
1837
+ }).join("\n");
1838
+ }
1839
+ function buildBufferResult(containersCount) {
1840
+ const lines = [`var buf = this.__buf;`];
1841
+ for (let i = 0; i < containersCount; i++) {
1842
+ const containerIndex = containersCount - 1 - i;
1843
+ lines.push(
1844
+ `buf[${i * 4}] = c_${containerIndex} >>> 24;`,
1845
+ `buf[${i * 4 + 1}] = c_${containerIndex} >>> 16;`,
1846
+ `buf[${i * 4 + 2}] = c_${containerIndex} >>> 8;`,
1847
+ `buf[${i * 4 + 3}] = c_${containerIndex};`
1848
+ );
1849
+ }
1850
+ lines.push("return buf;");
1851
+ return lines.join("\n");
1852
+ }
1853
+ function buildBigIntResult(containersCount) {
1854
+ const parts = [];
1855
+ for (let i = 0; i < containersCount; i++) {
1856
+ const containerIndex = containersCount - 1 - i;
1857
+ if (containerIndex > 0) {
1858
+ parts.push(
1859
+ `(BigInt(c_${containerIndex} >>> 0) << ${containerIndex * 32}n)`
1860
+ );
1861
+ } else {
1862
+ parts.push(`BigInt(c_${containerIndex} >>> 0)`);
1863
+ }
1864
+ }
1865
+ return `return (
1866
+ ${parts.join(" |\n ")}
1867
+ );`;
1868
+ }
1869
+ function buildNumberResult(containersCount) {
1870
+ return `return c_0;`;
1871
+ }
1872
+ function buildBitsResult(containersCount, totalBits) {
1873
+ const parts = [];
1874
+ for (let i = 0; i < containersCount; i++) {
1875
+ const containerIndex = containersCount - 1 - i;
1876
+ if (containerIndex > 0) {
1877
+ parts.push(
1878
+ `(BigInt(c_${containerIndex} >>> 0) << ${containerIndex * 32}n)`
1879
+ );
1880
+ } else {
1881
+ parts.push(`BigInt(c_${containerIndex} >>> 0)`);
1882
+ }
1883
+ }
1884
+ return `return (
1885
+ ${parts.join(" |\n ")}
1886
+ ).toString(2).padStart(${totalBits}, '0');`;
1887
+ }
1888
+ function compilePlan(plan, optimize) {
1889
+ if (optimize) {
1890
+ plan = optimizePlan(plan);
1891
+ }
1892
+ const assigned = /* @__PURE__ */ new Set();
1893
+ return plan.map((item) => compilePlanItem(item, assigned)).join("\n");
1894
+ }
1895
+ function optimizePlan(plan) {
1896
+ return plan.reduce((result, item) => {
1897
+ const prev = result.at(-1);
1898
+ if (canMergeSetOperations(prev, item)) {
1899
+ result.pop();
1900
+ result.push({
1901
+ object: "set",
1902
+ container: item.container,
1903
+ child: {
1904
+ object: "value",
1905
+ value: [
1906
+ compilePlanItem(prev.child),
1907
+ compilePlanItem(item.child)
1908
+ ].join(" |\n ")
1909
+ }
1910
+ });
1911
+ } else {
1912
+ result.push(item);
1913
+ }
1914
+ return result;
1915
+ }, []);
1916
+ }
1917
+ function canMergeSetOperations(prev, current) {
1918
+ return prev?.object === "set" && current.object === "set" && prev.container === current.container;
1919
+ }
1920
+ function compilePlanItem(plan, assigned) {
1921
+ switch (plan.object) {
1922
+ case "set":
1923
+ if (assigned && !assigned.has(plan.container)) {
1924
+ assigned.add(plan.container);
1925
+ return `var c_${plan.container} = ${compilePlanItem(plan.child)};`;
1926
+ }
1927
+ return `c_${plan.container} |= ${compilePlanItem(plan.child)};`;
1928
+ case "value":
1929
+ const offset = plan.offset ?? 0;
1930
+ return offset > 0 ? `(${plan.value}) << ${offset}` : `(${plan.value})`;
1931
+ default:
1932
+ throw new Error(`Unknown plan object: ${plan.object}`);
1933
+ }
1934
+ }
1935
+ function buildPlan(fields) {
1936
+ const result = [];
1937
+ for (const field of fields) {
1938
+ const startContainer = Math.floor(field.startBit / 32);
1939
+ const endContainer = Math.floor(field.endBit / 32);
1940
+ if (startContainer === endContainer) {
1941
+ addSingleContainerField(field, result);
1942
+ } else if (field.bits <= 32) {
1943
+ addSpanningField(field, result);
1944
+ } else {
1945
+ addLargeField(field, result);
1946
+ }
1947
+ }
1948
+ return result;
1949
+ }
1950
+ function addSingleContainerField(field, result) {
1951
+ result.push({
1952
+ object: "set",
1953
+ container: Math.floor(field.startBit / 32),
1954
+ child: {
1955
+ object: "value",
1956
+ offset: field.startBit % 32,
1957
+ value: field.id
1958
+ }
1959
+ });
1960
+ }
1961
+ function addSpanningField(field, result) {
1962
+ const startContainer = Math.floor(field.startBit / 32);
1963
+ const endContainer = Math.floor(field.endBit / 32);
1964
+ const firstContainerBits = 32 - field.startBit % 32;
1965
+ result.push({
1966
+ object: "set",
1967
+ container: startContainer,
1968
+ child: {
1969
+ object: "value",
1970
+ offset: field.startBit % 32,
1971
+ value: `(${field.id}) & ${(1 << firstContainerBits) - 1}`
1972
+ }
1973
+ });
1974
+ result.push({
1975
+ object: "set",
1976
+ container: endContainer,
1977
+ child: {
1978
+ object: "value",
1979
+ value: `(${field.id}) >>> ${firstContainerBits}`
1980
+ }
1981
+ });
1982
+ }
1983
+ function addLargeField(field, result) {
1984
+ const startContainer = Math.floor(field.startBit / 32);
1985
+ const endContainer = Math.floor(field.endBit / 32);
1986
+ const startOffset = field.startBit % 32;
1987
+ ok(
1988
+ startContainer !== endContainer,
1989
+ `Large field ${field.name} fits in single container - logic error`
1990
+ );
1991
+ ok(
1992
+ endContainer - startContainer === 1,
1993
+ `Fields spanning more than 2 containers (${field.bits} bits) not yet supported`
1994
+ );
1995
+ const bitsInLowerContainer = 32 - startOffset;
1996
+ result.push({
1997
+ object: "set",
1998
+ container: endContainer,
1999
+ child: {
2000
+ object: "value",
2001
+ offset: startOffset,
2002
+ value: `${field.id}_high`
2003
+ }
2004
+ });
2005
+ if (bitsInLowerContainer < 32) {
2006
+ result.push({
2007
+ object: "set",
2008
+ container: endContainer,
2009
+ child: {
2010
+ object: "value",
2011
+ value: `${field.id}_low >>> ${bitsInLowerContainer}`
2012
+ }
2013
+ });
2014
+ }
2015
+ if (field.bits > 32) {
2016
+ result.push({
2017
+ object: "set",
2018
+ container: startContainer,
2019
+ child: {
2020
+ object: "value",
2021
+ offset: startOffset,
2022
+ value: `${field.id}_low`
2023
+ }
2024
+ });
2025
+ }
2026
+ }
2027
+ function buildFieldsInfo$1(fields, totalBits) {
2028
+ const result = [];
2029
+ let currentBitPosition = totalBits;
2030
+ fields.forEach((field, idx) => {
2031
+ const startBit = currentBitPosition - field.bits;
2032
+ const endBit = currentBitPosition - 1;
2033
+ result.push({
2034
+ id: `f_${idx}`,
2035
+ ...field,
2036
+ startBit,
2037
+ endBit,
2038
+ mask: Math.pow(2, field.bits) - 1
2039
+ });
2040
+ currentBitPosition -= field.bits;
2041
+ });
2042
+ return result;
2043
+ }
2044
+
2045
+ function bitUnpack(options) {
2046
+ notEmpty(options.fields, "fields cannot be empty");
2047
+ greaterThan(options.totalBits, 0, "totalBits must be greater than 0");
2048
+ const fields = buildFieldsInfo(options.fields, options.totalBits);
2049
+ const fnBigIntCode = [`return ${compileFields(fields)};`].join("\n");
2050
+ const fnBigInt = createFunction(
2051
+ "bigint",
2052
+ fnBigIntCode,
2053
+ "data"
2054
+ );
2055
+ const fnNumberCode = [
2056
+ "\n// Extract container from number",
2057
+ "data = BigInt(data);",
2058
+ "\n// Return result",
2059
+ `return ${compileFields(fields)};`
2060
+ ].join("\n");
2061
+ const fnNumber = createFunction(
2062
+ "number",
2063
+ fnNumberCode,
2064
+ "data"
2065
+ );
2066
+ const fnBufferCode = [
2067
+ "\n// Extract bytes from buffer (big-endian)",
2068
+ extractBigIntFromBuffer(options.totalBits),
2069
+ "\n// Return result",
2070
+ `return ${compileFields(fields)};`
2071
+ ].join("\n");
2072
+ const fnBuffer = createFunction(
2073
+ "buffer",
2074
+ fnBufferCode,
2075
+ "data"
2076
+ );
2077
+ const fnBitsCode = [
2078
+ "\n// Convert bits string to bigint",
2079
+ 'var data = BigInt("0b" + bits);',
2080
+ "\n// Return result",
2081
+ `return ${compileFields(fields)};`
2082
+ ].join("\n");
2083
+ const fnBits = createFunction("bits", fnBitsCode, "bits");
2084
+ if (!options.debug) {
2085
+ def(fnBuffer, "code", void 0);
2086
+ def(fnBigInt, "code", void 0);
2087
+ def(fnNumber, "code", void 0);
2088
+ def(fnBits, "code", void 0);
2089
+ }
2090
+ return {
2091
+ buffer: fnBuffer,
2092
+ bigint: fnBigInt,
2093
+ number: fnNumber,
2094
+ bits: fnBits
2095
+ };
2096
+ }
2097
+ function compileFields(fields) {
2098
+ const lines = ["{"];
2099
+ for (const field of fields) {
2100
+ if (field.startBit === 0) {
2101
+ lines.push(
2102
+ ` ['${field.name}']: Number(data & 0x${field.mask.toString(16)}n),`
2103
+ );
2104
+ } else {
2105
+ lines.push(
2106
+ ` ['${field.name}']: Number((data >> ${field.startBit}n) & 0x${field.mask.toString(16)}n),`
2107
+ );
2108
+ }
2109
+ }
2110
+ lines.push("}");
2111
+ return lines.join("\n");
2112
+ }
2113
+ function extractBigIntFromBuffer(totalBits) {
2114
+ const totalBytes = Math.ceil(totalBits / 8);
2115
+ const chunks = [];
2116
+ let byteIndex = 0;
2117
+ let remainingBytes = totalBytes;
2118
+ while (remainingBytes > 0) {
2119
+ if (remainingBytes >= 4) {
2120
+ const shift = (remainingBytes - 4) * 8;
2121
+ const chunk = `((data[${byteIndex}] << 24) | (data[${byteIndex + 1}] << 16) | (data[${byteIndex + 2}] << 8) | data[${byteIndex + 3}]) >>> 0`;
2122
+ if (shift === 0) {
2123
+ chunks.push(`BigInt(${chunk})`);
2124
+ } else {
2125
+ chunks.push(`(BigInt(${chunk}) << ${shift}n)`);
2126
+ }
2127
+ byteIndex += 4;
2128
+ remainingBytes -= 4;
2129
+ } else {
2130
+ let chunk;
2131
+ if (remainingBytes === 3) {
2132
+ chunk = `(data[${byteIndex}] << 16) | (data[${byteIndex + 1}] << 8) | data[${byteIndex + 2}]`;
2133
+ } else if (remainingBytes === 2) {
2134
+ chunk = `(data[${byteIndex}] << 8) | data[${byteIndex + 1}]`;
2135
+ } else {
2136
+ chunk = `data[${byteIndex}]`;
2137
+ }
2138
+ chunks.push(`BigInt(${chunk})`);
2139
+ remainingBytes = 0;
2140
+ }
2141
+ }
2142
+ return `data =
2143
+ ${chunks.join("\n | ")};`;
2144
+ }
2145
+ function buildFieldsInfo(fields, totalBits) {
2146
+ const result = [];
2147
+ let currentBitPosition = totalBits;
2148
+ fields.forEach((field, idx) => {
2149
+ const startBit = currentBitPosition - field.bits;
2150
+ const endBit = currentBitPosition - 1;
2151
+ result.push({
2152
+ id: `f_${idx}`,
2153
+ ...field,
2154
+ mask: (1n << BigInt(field.bits)) - 1n,
2155
+ startBit,
2156
+ endBit
2157
+ });
2158
+ currentBitPosition -= field.bits;
2159
+ });
2160
+ return result;
2161
+ }
2162
+
1736
2163
  function bytesToBase64(data, { encoding = "base64", padding } = {}) {
1737
2164
  if (encoding === "base64") {
1738
2165
  return base64.encode(data, { includePadding: padding ?? true });
@@ -2865,15 +3292,6 @@ function captureStackTrace(till) {
2865
3292
  return (err.stack || "").slice(6);
2866
3293
  }
2867
3294
 
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
3295
  function catchError(fn) {
2878
3296
  try {
2879
3297
  const res = fn();
@@ -5623,6 +6041,8 @@ exports.base64url = base64url;
5623
6041
  exports.basex = basex;
5624
6042
  exports.bigIntBytes = bigIntBytes;
5625
6043
  exports.bigIntFromBytes = bigIntFromBytes;
6044
+ exports.bitPack = bitPack;
6045
+ exports.bitUnpack = bitUnpack;
5626
6046
  exports.blendColors = blendColors;
5627
6047
  exports.buildCssColor = buildCssColor;
5628
6048
  exports.bytesToBase64 = bytesToBase64;
@@ -5656,6 +6076,7 @@ exports.createDeepCloneWith = createDeepCloneWith;
5656
6076
  exports.createEJSON = createEJSON;
5657
6077
  exports.createEJSONStream = createEJSONStream;
5658
6078
  exports.createEnvParser = createEnvParser;
6079
+ exports.createFunction = createFunction;
5659
6080
  exports.createRandomizer = createRandomizer;
5660
6081
  exports.createSecureCustomizer = createSecureCustomizer;
5661
6082
  exports.createTimeObject = createTimeObject;