@ocap/util 1.30.24 → 1.30.26

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/esm/curve.d.mts CHANGED
@@ -23,11 +23,13 @@ declare function calcConstantPrice({
23
23
  declare function calcConstantCost({
24
24
  amount,
25
25
  fixedPrice,
26
- decimal
26
+ decimal,
27
+ direction
27
28
  }: {
28
29
  amount: string;
29
30
  fixedPrice: string;
30
31
  decimal: number;
32
+ direction?: Direction;
31
33
  }): bn_js0;
32
34
  /**
33
35
  * linear Curve
package/esm/curve.mjs CHANGED
@@ -10,28 +10,65 @@ let Direction = /* @__PURE__ */ function(Direction$1) {
10
10
  Direction$1["Burn"] = "burn";
11
11
  return Direction$1;
12
12
  }({});
13
+ function getDecimalFactor(decimal) {
14
+ if (!Number.isInteger(decimal) || decimal <= 0 || decimal > 78) throw new Error("INVALID_DECIMAL_FACTOR");
15
+ return TEN.pow(new BN(decimal));
16
+ }
17
+ function assertValidDirection(direction) {
18
+ if (direction !== Direction.Mint && direction !== Direction.Burn) throw new Error("INVALID_DIRECTION");
19
+ }
20
+ function validateCurveParams(params) {
21
+ if (params.direction !== void 0) assertValidDirection(params.direction);
22
+ if (params.fixedPrice?.lt(ZERO)) throw new Error("INVALID_FIXED_PRICE");
23
+ if (params.slope?.lte(ZERO)) throw new Error("INVALID_SLOPE");
24
+ if (params.constant?.lte(ZERO)) throw new Error("INVALID_CONSTANT");
25
+ if (params.amount?.lt(ZERO)) throw new Error("INVALID_AMOUNT");
26
+ if (params.currentSupply?.lt(ZERO)) throw new Error("INVALID_CURRENT_SUPPLY");
27
+ if (params.basePrice?.lt(ZERO)) throw new Error("INVALID_BASE_PRICE");
28
+ if (params.decimalFactor?.lte(ZERO)) throw new Error("INVALID_DECIMAL_FACTOR");
29
+ }
13
30
  /**
14
31
  * Constant Curve
15
32
  * Price = fixedPrice
16
33
  */
17
34
  function calcConstantPrice({ fixedPrice }) {
18
- return new BN(fixedPrice);
35
+ const price = new BN(fixedPrice);
36
+ validateCurveParams({ fixedPrice: price });
37
+ return price;
19
38
  }
20
39
  /**
21
40
  * Constant Curve
22
41
  * Cost = amount * fixedPrice
23
42
  */
24
- function calcConstantCost({ amount, fixedPrice, decimal }) {
25
- const decimalFactor = TEN.pow(new BN(decimal));
26
- return new BN(amount).mul(new BN(fixedPrice)).div(decimalFactor);
43
+ function calcConstantCost({ amount, fixedPrice, decimal, direction = Direction.Mint }) {
44
+ const amountBN = new BN(amount);
45
+ const priceBN = new BN(fixedPrice);
46
+ const decimalFactor = getDecimalFactor(decimal);
47
+ validateCurveParams({
48
+ amount: amountBN,
49
+ fixedPrice: priceBN,
50
+ decimalFactor,
51
+ direction
52
+ });
53
+ if (amountBN.isZero()) return ZERO;
54
+ return amountBN.mul(priceBN).div(decimalFactor);
27
55
  }
28
56
  /**
29
57
  * linear Curve
30
58
  * Price = basePrice + slope * currentSupply
31
59
  */
32
60
  function calcLinearPrice({ basePrice, slope, currentSupply, decimal }) {
33
- const decimalFactor = TEN.pow(new BN(decimal));
34
- return new BN(basePrice).add(new BN(slope).mul(new BN(currentSupply)).div(decimalFactor));
61
+ const basePriceBN = new BN(basePrice);
62
+ const slopeBN = new BN(slope);
63
+ const currentSupplyBN = new BN(currentSupply);
64
+ const decimalFactor = getDecimalFactor(decimal);
65
+ validateCurveParams({
66
+ basePrice: basePriceBN,
67
+ slope: slopeBN,
68
+ currentSupply: currentSupplyBN,
69
+ decimalFactor
70
+ });
71
+ return basePriceBN.add(slopeBN.mul(currentSupplyBN).div(decimalFactor));
35
72
  }
36
73
  /**
37
74
  * Linear Curve
@@ -43,13 +80,17 @@ function calcLinearCost(params) {
43
80
  const currentSupply = new BN(params.currentSupply);
44
81
  const basePrice = new BN(params.basePrice);
45
82
  const slope = new BN(params.slope);
46
- const decimalFactor = TEN.pow(new BN(params.decimal));
47
- if (slope.lte(ZERO)) throw new Error("INVALID_SLOPE");
48
- if (amount.lt(ZERO)) throw new Error("INVALID_AMOUNT");
49
- if (currentSupply.lt(ZERO)) throw new Error("INVALID_CURRENT_SUPPLY");
50
- if (basePrice.lt(ZERO)) throw new Error("INVALID_BASE_PRICE");
51
- if (decimalFactor.lte(ZERO)) throw new Error("INVALID_DECIMAL_FACTOR");
83
+ const decimalFactor = getDecimalFactor(params.decimal);
84
+ validateCurveParams({
85
+ direction: params.direction,
86
+ slope,
87
+ amount,
88
+ currentSupply,
89
+ basePrice,
90
+ decimalFactor
91
+ });
52
92
  if (params.direction === Direction.Burn && amount.gt(currentSupply)) throw new Error("SUPPLY_INSUFFICIENT");
93
+ if (amount.isZero()) return ZERO;
53
94
  const integralDelta = params.direction === Direction.Mint ? amount.mul(currentSupply.mul(TWO).add(amount)) : amount.mul(currentSupply.mul(TWO).sub(amount));
54
95
  const linearTerm = basePrice.mul(amount).div(decimalFactor);
55
96
  const integralTerm = slope.mul(integralDelta).div(TWO.mul(decimalFactor.sqr()));
@@ -63,11 +104,13 @@ function calcQuadraticPrice(params) {
63
104
  const basePrice = new BN(params.basePrice);
64
105
  const currentSupply = new BN(params.currentSupply);
65
106
  const constant = new BN(params.constant);
66
- const decimalFactor = TEN.pow(new BN(params.decimal));
67
- if (constant.lte(ZERO)) throw new Error("INVALID_CONSTANT");
68
- if (currentSupply.lt(ZERO)) throw new Error("INVALID_CURRENT_SUPPLY");
69
- if (basePrice.lt(ZERO)) throw new Error("INVALID_BASE_PRICE");
70
- if (decimalFactor.lte(ZERO)) throw new Error("INVALID_DECIMAL_FACTOR");
107
+ const decimalFactor = getDecimalFactor(params.decimal);
108
+ validateCurveParams({
109
+ constant,
110
+ currentSupply,
111
+ basePrice,
112
+ decimalFactor
113
+ });
71
114
  const denom = constant.mul(decimalFactor);
72
115
  const a = currentSupply.sqr().div(denom);
73
116
  return basePrice.add(a);
@@ -83,9 +126,15 @@ function calcQuadraticCost(params) {
83
126
  const currentSupply = new BN(params.currentSupply);
84
127
  const basePrice = new BN(params.basePrice);
85
128
  const constant = new BN(params.constant);
86
- const decimalFactor = TEN.pow(new BN(params.decimal));
87
- if (constant.lte(ZERO)) throw new Error("INVALID_CONSTANT");
88
- if (amount.lt(ZERO)) throw new Error("INVALID_AMOUNT");
129
+ const decimalFactor = getDecimalFactor(params.decimal);
130
+ validateCurveParams({
131
+ direction: params.direction,
132
+ constant,
133
+ amount,
134
+ currentSupply,
135
+ basePrice,
136
+ decimalFactor
137
+ });
89
138
  if (amount.isZero()) return ZERO;
90
139
  const newSupply = params.direction === Direction.Mint ? currentSupply.add(amount) : currentSupply.sub(amount);
91
140
  if (params.direction === Direction.Burn && newSupply.lt(ZERO)) throw new Error("SUPPLY_INSUFFICIENT");
@@ -98,7 +147,11 @@ function calcQuadraticCost(params) {
98
147
  return cubicCost.add(linearCost);
99
148
  }
100
149
  function calcFee({ reserveAmount, feeRate }) {
101
- return new BN(reserveAmount).mul(new BN(feeRate)).div(new BN(1e4));
150
+ const reserveBN = new BN(reserveAmount);
151
+ const feeRateBN = new BN(feeRate);
152
+ if (reserveBN.lt(ZERO)) throw new Error("INVALID_RESERVE_AMOUNT");
153
+ if (feeRateBN.lt(ZERO) || feeRateBN.gt(new BN(1e4))) throw new Error("INVALID_FEE_RATE");
154
+ return reserveBN.mul(feeRateBN).div(new BN(1e4));
102
155
  }
103
156
  function calcPrice({ currentSupply, decimal, curve }) {
104
157
  const calculator = {
@@ -117,7 +170,7 @@ function calcPrice({ currentSupply, decimal, curve }) {
117
170
  decimal,
118
171
  ...curve
119
172
  })
120
- }[curve.type];
173
+ }[curve?.type];
121
174
  if (!calculator) throw new Error("INVALID_CURVE_TYPE");
122
175
  return calculator();
123
176
  }
@@ -126,6 +179,7 @@ function calcCost({ amount, decimal, currentSupply, direction, curve }) {
126
179
  constant: () => calcConstantCost({
127
180
  amount,
128
181
  decimal,
182
+ direction,
129
183
  ...curve
130
184
  }),
131
185
  linear: () => calcLinearCost({
@@ -142,7 +196,7 @@ function calcCost({ amount, decimal, currentSupply, direction, curve }) {
142
196
  direction,
143
197
  ...curve
144
198
  })
145
- }[curve.type];
199
+ }[curve?.type];
146
200
  if (!calculator) throw new Error("INVALID_CURVE_TYPE");
147
201
  return calculator();
148
202
  }
@@ -1,6 +1,10 @@
1
1
  //#region src/get-list-field.ts
2
- const getByPath = (obj, path) => path.split(".").reduce((o, k) => o?.[k], obj);
3
- const getListField = (obj, key) => getByPath(obj, `${key}List`) || getByPath(obj, key) || [];
2
+ const getByPath = (obj, path) => obj?.[path] !== void 0 ? obj[path] : path.split(".").reduce((o, k) => o?.[k], obj);
3
+ const normalizeListKey = (key) => key.endsWith("List") ? key.slice(0, -4) : key;
4
+ const getListField = (obj, key) => {
5
+ const baseKey = normalizeListKey(key);
6
+ return getByPath(obj, `${baseKey}List`) || getByPath(obj, baseKey) || [];
7
+ };
4
8
  /**
5
9
  * Write a repeated field to its canonical (no-suffix) form and remove the
6
10
  * jspb `xxxList` twin. Keeps pipe code insulated from protobuf vs CBOR
@@ -9,8 +13,9 @@ const getListField = (obj, key) => getByPath(obj, `${key}List`) || getByPath(obj
9
13
  * ⚠️ Must use `delete` (not `= undefined`) — see CLAUDE.md Critical Lesson #1.
10
14
  */
11
15
  const setListField = (obj, key, value) => {
12
- delete obj[`${key}List`];
13
- obj[key] = value;
16
+ const baseKey = normalizeListKey(key);
17
+ delete obj[`${baseKey}List`];
18
+ obj[baseKey] = value;
14
19
  };
15
20
  /**
16
21
  * Remove both `xxx` and `xxxList` twins so the field is absent from any
@@ -18,8 +23,9 @@ const setListField = (obj, key, value) => {
18
23
  * the "clear" case. Uses `delete` for the same reason as `setListField`.
19
24
  */
20
25
  const deleteListField = (obj, key) => {
21
- delete obj[`${key}List`];
22
- delete obj[key];
26
+ const baseKey = normalizeListKey(key);
27
+ delete obj[`${baseKey}List`];
28
+ delete obj[baseKey];
23
29
  };
24
30
 
25
31
  //#endregion
package/esm/index.mjs CHANGED
@@ -46,6 +46,7 @@ const isBase58btc = (data) => {
46
46
  */
47
47
  const numberToBN = (arg) => {
48
48
  if (typeof arg === "string" || typeof arg === "number") {
49
+ if (typeof arg === "number" && !Number.isFinite(arg)) throw new Error("[number-to-bn] number must be finite");
49
50
  let multiplier = new BN(1);
50
51
  const formattedString = String(arg).toLowerCase().trim();
51
52
  const isHexPrefixed$1 = formattedString.substr(0, 2) === "0x" || formattedString.substr(0, 3) === "-0x";
@@ -135,7 +136,19 @@ const isHex = (hex) => (isString(hex) || isNumber(hex)) && /^(-0x|0x|0X|-0X)?[0-
135
136
  */
136
137
  const toBN = (num, base = 10) => {
137
138
  try {
138
- if (typeof num === "number" && num > 0) return new BN(Number(num).toLocaleString("fullwide", { useGrouping: false }), base);
139
+ if (typeof num === "number") {
140
+ if (!Number.isFinite(num)) throw new Error("Invalid number: must be finite");
141
+ if (num > 0) return new BN(Number(num).toLocaleString("fullwide", { useGrouping: false }), base);
142
+ }
143
+ if (typeof num === "string" && (base === 16 || base === "hex")) {
144
+ const formatted = num.trim();
145
+ const isNeg = formatted.startsWith("-");
146
+ const unsigned = stripHexPrefix(isNeg ? formatted.slice(1) : formatted);
147
+ if (/^[0-9a-fA-F]+$/.test(unsigned)) {
148
+ const parsed = new BN(unsigned, 16);
149
+ return isNeg ? parsed.mul(negative1) : parsed;
150
+ }
151
+ }
139
152
  return numberToBN(num);
140
153
  } catch (error) {
141
154
  throw new Error(`${error} Given value: "${num}"`);
@@ -199,6 +212,7 @@ const hexToUtf8 = (hex) => {
199
212
  */
200
213
  const hexToNumber = (value) => {
201
214
  if (!value) return 0;
215
+ if (typeof value === "string" && !/^-?[0-9]+$/.test(value.trim()) && /^-?(0x)?[0-9a-fA-F]+$/i.test(value.trim())) return toBN(value, 16).toNumber();
202
216
  return toBN(value).toNumber();
203
217
  };
204
218
  /**
@@ -267,7 +281,7 @@ const hexToBytes = (hex) => {
267
281
  * @returns {String}
268
282
  */
269
283
  const toHex = (value, returnType = false) => {
270
- if (isUint8Array(value) || Buffer.isBuffer(value)) return returnType ? "bytes" : bytesToHex(value);
284
+ if (isUint8Array(value) || typeof Buffer !== "undefined" && Buffer.isBuffer(value)) return returnType ? "bytes" : bytesToHex(value);
271
285
  if (isBase58btc(value)) return returnType ? "bytes" : bytesToHex(base58btc.decode(value));
272
286
  if (isBoolean(value)) return returnType ? "bool" : value ? "0x01" : "0x00";
273
287
  if (isObject(value) && !isBigNumber(value) && !isBN(value)) return returnType ? "string" : utf8ToHex(JSON.stringify(value));
@@ -319,9 +333,10 @@ const fromUnitToToken = (input, decimal = 18, optionsInput = {}) => {
319
333
  * Convert human readable token number to big number instance
320
334
  */
321
335
  const fromTokenToUnit = (input, decimal = 18) => {
336
+ if (!Number.isInteger(decimal) || decimal < 0 || decimal > 78) throw new Error(`error converting token ${input} to unit, invalid decimal ${decimal}`);
322
337
  let token = numberToString(input);
323
338
  const base = toBN(`1${"0".repeat(decimal)}`, 10);
324
- const baseLength = base.toString(10).length - 1 || 1;
339
+ const baseLength = base.toString(10).length - 1;
325
340
  const negative = token.substring(0, 1) === "-";
326
341
  if (negative) token = token.substring(1);
327
342
  if (token === ".") throw new Error(`error converting token ${input} to unit, invalid value`);
@@ -330,8 +345,8 @@ const fromTokenToUnit = (input, decimal = 18) => {
330
345
  let whole = comps[0];
331
346
  let fraction = comps[1];
332
347
  if (!whole) whole = "0";
348
+ if (fraction && fraction.length > baseLength) throw new Error(`error converting token ${input} to unit, too many decimal places`);
333
349
  if (!fraction) fraction = "0";
334
- if (fraction.length > baseLength) throw new Error(`error converting token ${input} to unit, too many decimal places`);
335
350
  while (fraction.length < baseLength) fraction += "0";
336
351
  whole = new BN(whole);
337
352
  fraction = new BN(fraction);
@@ -349,10 +364,13 @@ function isUint8Array(value) {
349
364
  * Generate a random UUID
350
365
  */
351
366
  function UUID() {
352
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
353
- const r = Math.random() * 16 | 0;
354
- return (c === "x" ? r : r & 3 | 8).toString(16);
355
- });
367
+ if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
368
+ const bytes = new Uint8Array(16);
369
+ globalThis.crypto.getRandomValues(bytes);
370
+ bytes[6] = bytes[6] & 15 | 64;
371
+ bytes[8] = bytes[8] & 63 | 128;
372
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
373
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
356
374
  }
357
375
  /**
358
376
  * Check if a string is valid UUID
@@ -370,7 +388,7 @@ function toUint8Array(v) {
370
388
  void 0,
371
389
  ""
372
390
  ].includes(v)) vb = new Uint8Array();
373
- else if (Buffer.isBuffer(v)) vb = new Uint8Array(v);
391
+ else if (typeof Buffer !== "undefined" && Buffer.isBuffer(v)) vb = new Uint8Array(v);
374
392
  else if (isHexStrict(v)) vb = new Uint8Array(hexToBytes(v));
375
393
  else if (isUint8Array(v)) vb = new Uint8Array(v);
376
394
  else if (isBase58btc(v)) vb = new Uint8Array(base58btc.decode(v));
@@ -382,27 +400,29 @@ function toUint8Array(v) {
382
400
  * Convert input to Buffer on best effort, base64 not supported
383
401
  */
384
402
  function toBuffer(v) {
385
- return Buffer.from(toUint8Array(v));
403
+ const bytes = toUint8Array(v);
404
+ return typeof Buffer !== "undefined" ? Buffer.from(bytes) : bytes;
386
405
  }
387
406
  /**
388
407
  * Convert input to base58btc format on best effort
389
408
  */
390
409
  function toBase58(v) {
391
410
  const buf = base58btc.encode(toUint8Array(v));
392
- return Buffer.from(buf).toString("utf-8");
411
+ return typeof Buffer !== "undefined" ? Buffer.from(buf).toString("utf-8") : new TextDecoder().decode(buf);
393
412
  }
394
413
  /**
395
414
  * Decode base58 string
396
415
  */
397
416
  function fromBase58(v) {
398
417
  if (isBase58btc(v) === false) throw new Error("fromBase58 expect strict base58 encoded string as input");
399
- return Buffer.from(base58btc.decode(v));
418
+ const decoded = base58btc.decode(v);
419
+ return typeof Buffer !== "undefined" ? Buffer.from(decoded) : decoded;
400
420
  }
401
421
  /**
402
422
  * Convert input to base64 format
403
423
  */
404
424
  function toBase64(v, escape = true) {
405
- const encoded = base64.encode(toBuffer(v));
425
+ const encoded = toBuffer(v).toString("base64");
406
426
  return escape ? base64.escape(encoded) : encoded;
407
427
  }
408
428
  /**
@@ -430,7 +450,18 @@ function toDid(address, method = "abt") {
430
450
  return `did:${method}:${toAddress(address)}`;
431
451
  }
432
452
  function isSameDid(a, b) {
433
- return toAddress(a).toLowerCase() === toAddress(b).toLowerCase();
453
+ if (typeof a !== "string" || typeof b !== "string" || !a || !b) return false;
454
+ const methodA = extractMethod(a);
455
+ const methodB = extractMethod(b);
456
+ const aIsName = methodA === "name";
457
+ const bIsName = methodB === "name";
458
+ if (aIsName !== bIsName) return false;
459
+ const addrA = toAddress(a);
460
+ const addrB = toAddress(b);
461
+ if (!addrA || !addrB) return false;
462
+ if (aIsName && bIsName) return addrA.normalize("NFC").toLowerCase() === addrB.normalize("NFC").toLowerCase();
463
+ if (/^0x[0-9a-fA-F]+$/i.test(addrA) && /^0x[0-9a-fA-F]+$/i.test(addrB)) return addrA.toLowerCase() === addrB.toLowerCase();
464
+ return addrA === addrB;
434
465
  }
435
466
  /**
436
467
  * Extract the method from a DID string.
package/esm/md5.d.mts CHANGED
@@ -1,4 +1,8 @@
1
1
  //#region src/md5.d.ts
2
+ /**
3
+ * Non-cryptographic MD5 digest for internal cache/bucketing keys only.
4
+ * Do not use for security-sensitive integrity, collision-resistant, or authentication purposes.
5
+ */
2
6
  declare const md5: (x: $TSFixMe) => string;
3
7
  //#endregion
4
8
  export { md5 };
package/esm/md5.mjs CHANGED
@@ -1,7 +1,14 @@
1
1
  import crypto from "node:crypto";
2
2
 
3
3
  //#region src/md5.ts
4
- const md5 = (x) => crypto.createHash("md5").update(x).digest("hex");
4
+ /**
5
+ * Non-cryptographic MD5 digest for internal cache/bucketing keys only.
6
+ * Do not use for security-sensitive integrity, collision-resistant, or authentication purposes.
7
+ */
8
+ const md5 = (x) => {
9
+ if (x === null || x === void 0) throw new Error("md5 requires a non-null input");
10
+ return crypto.createHash("md5").update(x).digest("hex");
11
+ };
5
12
 
6
13
  //#endregion
7
14
  export { md5 };
package/esm/url.d.mts CHANGED
@@ -3,7 +3,7 @@ import ipaddr from "ipaddr.js";
3
3
  //#region src/url.d.ts
4
4
  declare function parseIp(host: string): ipaddr.IPv4 | ipaddr.IPv6 | null;
5
5
  declare function isUnicastAddress(host: string): boolean;
6
- declare function resolveHostAddresses(host: string): Promise<string[]>;
6
+ declare function resolveHostAddresses(host: string, dnsServers?: string[]): Promise<string[]>;
7
7
  interface VerifyUrlOptions {
8
8
  allowIp?: boolean;
9
9
  maxLength?: number;
@@ -11,6 +11,8 @@ interface VerifyUrlOptions {
11
11
  blockedHosts?: string[];
12
12
  blockedSuffixes?: string[];
13
13
  checkDns?: boolean;
14
+ dnsServers?: string[];
15
+ resolveHost?: (host: string, dnsServers?: string[]) => Promise<string[]>;
14
16
  }
15
17
  declare function verifyUrl(url: string, options?: VerifyUrlOptions): Promise<boolean>;
16
18
  //#endregion
package/esm/url.mjs CHANGED
@@ -4,21 +4,36 @@ import ipaddr from "ipaddr.js";
4
4
 
5
5
  //#region src/url.ts
6
6
  const MAX_URL_LENGTH = 256;
7
+ function stripTrailingDots(host) {
8
+ return host.replace(/\.+$/, "");
9
+ }
10
+ function stripIpv6Brackets(host) {
11
+ const trimmed = host.trim();
12
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) return trimmed.slice(1, -1);
13
+ return trimmed;
14
+ }
15
+ function normalizeHostname(host) {
16
+ return stripTrailingDots(stripIpv6Brackets(stripTrailingDots(host)));
17
+ }
7
18
  function parseIp(host) {
8
- if (!ipaddr.isValid(host)) return null;
19
+ const normalized = normalizeHostname(host);
20
+ if (!normalized || !ipaddr.isValid(normalized)) return null;
9
21
  try {
10
- return ipaddr.parse(host);
22
+ return ipaddr.parse(normalized);
11
23
  } catch {
12
24
  return null;
13
25
  }
14
26
  }
15
- function stripTrailingDots(host) {
16
- return host.replace(/\.+$/, "");
17
- }
18
27
  function isBlockedHostname(host, blockedHosts, blockedSuffixes) {
19
- const normalized = host.toLowerCase();
20
- if (blockedHosts.includes(normalized)) return true;
21
- if (blockedSuffixes.some((suffix) => normalized.endsWith(suffix))) return true;
28
+ const normalized = normalizeHostname(host).toLowerCase();
29
+ if (blockedHosts.some((entry) => normalizeHostname(entry).toLowerCase() === normalized)) return true;
30
+ if (blockedSuffixes.some((suffix) => {
31
+ const trimmed = stripTrailingDots(suffix).toLowerCase();
32
+ const clean = trimmed.replace(/^\.+/, "");
33
+ if (!clean) return false;
34
+ if (trimmed.startsWith(".")) return normalized.endsWith(`.${clean}`);
35
+ return normalized === clean || normalized.endsWith(`.${clean}`);
36
+ })) return true;
22
37
  return false;
23
38
  }
24
39
  function isUnicastAddress(host) {
@@ -28,23 +43,16 @@ function isUnicastAddress(host) {
28
43
  if (range === "ipv4Mapped" && parsed.kind() === "ipv6") return parsed.toIPv4Address().range() === "unicast";
29
44
  return range === "unicast";
30
45
  }
31
- async function resolveHostAddresses(host) {
46
+ async function resolveHostAddresses(host, dnsServers) {
32
47
  try {
33
48
  const resolver = new Resolver();
34
- resolver.setServers(["8.8.8.8", "1.1.1.1"]);
49
+ if (Array.isArray(dnsServers) && dnsServers.length > 0) resolver.setServers(dnsServers);
50
+ const [ipv4Result, ipv6Result] = await Promise.allSettled([resolver.resolve4(host), resolver.resolve6(host)]);
35
51
  const addresses = [];
36
- try {
37
- const ipv4Addresses = await resolver.resolve4(host);
38
- addresses.push(...ipv4Addresses);
39
- } catch (error) {
40
- console.warn(`IPv4 resolution failed for ${host}:`, error?.message);
41
- }
42
- if (!addresses.length) try {
43
- const ipv6Addresses = await resolver.resolve6(host);
44
- addresses.push(...ipv6Addresses);
45
- } catch (error) {
46
- console.warn(`IPv6 resolution failed for ${host}:`, error?.message);
47
- }
52
+ if (ipv4Result.status === "fulfilled") addresses.push(...ipv4Result.value);
53
+ else console.warn(`IPv4 resolution failed for ${host}:`, ipv4Result.reason?.message);
54
+ if (ipv6Result.status === "fulfilled") addresses.push(...ipv6Result.value);
55
+ else console.warn(`IPv6 resolution failed for ${host}:`, ipv6Result.reason?.message);
48
56
  return addresses.filter(Boolean);
49
57
  } catch (error) {
50
58
  console.warn(`DNS resolution failed for host: ${host}, error: ${error?.message}`);
@@ -53,11 +61,11 @@ async function resolveHostAddresses(host) {
53
61
  }
54
62
  async function verifyUrl(url, options = {}) {
55
63
  if (!url) throw new Error("URL is required");
56
- const { maxLength = MAX_URL_LENGTH, protocols = ["https:"], blockedHosts = ["localhost"], blockedSuffixes = [], allowIp = false, checkDns = false } = options;
64
+ const { maxLength = MAX_URL_LENGTH, protocols = ["https:"], blockedHosts = ["localhost"], blockedSuffixes = [], allowIp = false, checkDns = false, dnsServers, resolveHost = resolveHostAddresses } = options;
57
65
  if (url.length > maxLength) throw new Error(`URL exceeds maximum length of ${maxLength} characters: ${url.length}`);
58
66
  const { hostname, protocol } = new URL(url);
59
67
  if (!protocols.includes(protocol)) throw new Error(`Protocol '${protocol}' is not allowed. Allowed protocols: ${protocols.join(", ")}`);
60
- const normalizedHost = stripTrailingDots(hostname);
68
+ const normalizedHost = normalizeHostname(hostname);
61
69
  if (isBlockedHostname(normalizedHost, blockedHosts, blockedSuffixes)) throw new Error(`Hostname '${normalizedHost}' is blocked`);
62
70
  const isIP = Boolean(parseIp(normalizedHost));
63
71
  if (isIP) {
@@ -65,7 +73,7 @@ async function verifyUrl(url, options = {}) {
65
73
  if (!isUnicastAddress(normalizedHost)) throw new Error(`IP address is not unicast: ${normalizedHost}`);
66
74
  }
67
75
  if (checkDns && !isIP) {
68
- const resolved = await resolveHostAddresses(normalizedHost);
76
+ const resolved = await resolveHost(normalizedHost, dnsServers);
69
77
  if (resolved.length === 0) throw new Error(`DNS resolution failed: no addresses found for ${normalizedHost}`);
70
78
  if (!resolved.every((address) => isUnicastAddress(address))) throw new Error(`DNS resolved to non-unicast addresses for ${normalizedHost}`);
71
79
  }
package/lib/curve.cjs CHANGED
@@ -10,28 +10,65 @@ let Direction = /* @__PURE__ */ function(Direction$1) {
10
10
  Direction$1["Burn"] = "burn";
11
11
  return Direction$1;
12
12
  }({});
13
+ function getDecimalFactor(decimal) {
14
+ if (!Number.isInteger(decimal) || decimal <= 0 || decimal > 78) throw new Error("INVALID_DECIMAL_FACTOR");
15
+ return TEN.pow(new require_bn.BN(decimal));
16
+ }
17
+ function assertValidDirection(direction) {
18
+ if (direction !== Direction.Mint && direction !== Direction.Burn) throw new Error("INVALID_DIRECTION");
19
+ }
20
+ function validateCurveParams(params) {
21
+ if (params.direction !== void 0) assertValidDirection(params.direction);
22
+ if (params.fixedPrice?.lt(ZERO)) throw new Error("INVALID_FIXED_PRICE");
23
+ if (params.slope?.lte(ZERO)) throw new Error("INVALID_SLOPE");
24
+ if (params.constant?.lte(ZERO)) throw new Error("INVALID_CONSTANT");
25
+ if (params.amount?.lt(ZERO)) throw new Error("INVALID_AMOUNT");
26
+ if (params.currentSupply?.lt(ZERO)) throw new Error("INVALID_CURRENT_SUPPLY");
27
+ if (params.basePrice?.lt(ZERO)) throw new Error("INVALID_BASE_PRICE");
28
+ if (params.decimalFactor?.lte(ZERO)) throw new Error("INVALID_DECIMAL_FACTOR");
29
+ }
13
30
  /**
14
31
  * Constant Curve
15
32
  * Price = fixedPrice
16
33
  */
17
34
  function calcConstantPrice({ fixedPrice }) {
18
- return new require_bn.BN(fixedPrice);
35
+ const price = new require_bn.BN(fixedPrice);
36
+ validateCurveParams({ fixedPrice: price });
37
+ return price;
19
38
  }
20
39
  /**
21
40
  * Constant Curve
22
41
  * Cost = amount * fixedPrice
23
42
  */
24
- function calcConstantCost({ amount, fixedPrice, decimal }) {
25
- const decimalFactor = TEN.pow(new require_bn.BN(decimal));
26
- return new require_bn.BN(amount).mul(new require_bn.BN(fixedPrice)).div(decimalFactor);
43
+ function calcConstantCost({ amount, fixedPrice, decimal, direction = Direction.Mint }) {
44
+ const amountBN = new require_bn.BN(amount);
45
+ const priceBN = new require_bn.BN(fixedPrice);
46
+ const decimalFactor = getDecimalFactor(decimal);
47
+ validateCurveParams({
48
+ amount: amountBN,
49
+ fixedPrice: priceBN,
50
+ decimalFactor,
51
+ direction
52
+ });
53
+ if (amountBN.isZero()) return ZERO;
54
+ return amountBN.mul(priceBN).div(decimalFactor);
27
55
  }
28
56
  /**
29
57
  * linear Curve
30
58
  * Price = basePrice + slope * currentSupply
31
59
  */
32
60
  function calcLinearPrice({ basePrice, slope, currentSupply, decimal }) {
33
- const decimalFactor = TEN.pow(new require_bn.BN(decimal));
34
- return new require_bn.BN(basePrice).add(new require_bn.BN(slope).mul(new require_bn.BN(currentSupply)).div(decimalFactor));
61
+ const basePriceBN = new require_bn.BN(basePrice);
62
+ const slopeBN = new require_bn.BN(slope);
63
+ const currentSupplyBN = new require_bn.BN(currentSupply);
64
+ const decimalFactor = getDecimalFactor(decimal);
65
+ validateCurveParams({
66
+ basePrice: basePriceBN,
67
+ slope: slopeBN,
68
+ currentSupply: currentSupplyBN,
69
+ decimalFactor
70
+ });
71
+ return basePriceBN.add(slopeBN.mul(currentSupplyBN).div(decimalFactor));
35
72
  }
36
73
  /**
37
74
  * Linear Curve
@@ -43,13 +80,17 @@ function calcLinearCost(params) {
43
80
  const currentSupply = new require_bn.BN(params.currentSupply);
44
81
  const basePrice = new require_bn.BN(params.basePrice);
45
82
  const slope = new require_bn.BN(params.slope);
46
- const decimalFactor = TEN.pow(new require_bn.BN(params.decimal));
47
- if (slope.lte(ZERO)) throw new Error("INVALID_SLOPE");
48
- if (amount.lt(ZERO)) throw new Error("INVALID_AMOUNT");
49
- if (currentSupply.lt(ZERO)) throw new Error("INVALID_CURRENT_SUPPLY");
50
- if (basePrice.lt(ZERO)) throw new Error("INVALID_BASE_PRICE");
51
- if (decimalFactor.lte(ZERO)) throw new Error("INVALID_DECIMAL_FACTOR");
83
+ const decimalFactor = getDecimalFactor(params.decimal);
84
+ validateCurveParams({
85
+ direction: params.direction,
86
+ slope,
87
+ amount,
88
+ currentSupply,
89
+ basePrice,
90
+ decimalFactor
91
+ });
52
92
  if (params.direction === Direction.Burn && amount.gt(currentSupply)) throw new Error("SUPPLY_INSUFFICIENT");
93
+ if (amount.isZero()) return ZERO;
53
94
  const integralDelta = params.direction === Direction.Mint ? amount.mul(currentSupply.mul(TWO).add(amount)) : amount.mul(currentSupply.mul(TWO).sub(amount));
54
95
  const linearTerm = basePrice.mul(amount).div(decimalFactor);
55
96
  const integralTerm = slope.mul(integralDelta).div(TWO.mul(decimalFactor.sqr()));
@@ -63,11 +104,13 @@ function calcQuadraticPrice(params) {
63
104
  const basePrice = new require_bn.BN(params.basePrice);
64
105
  const currentSupply = new require_bn.BN(params.currentSupply);
65
106
  const constant = new require_bn.BN(params.constant);
66
- const decimalFactor = TEN.pow(new require_bn.BN(params.decimal));
67
- if (constant.lte(ZERO)) throw new Error("INVALID_CONSTANT");
68
- if (currentSupply.lt(ZERO)) throw new Error("INVALID_CURRENT_SUPPLY");
69
- if (basePrice.lt(ZERO)) throw new Error("INVALID_BASE_PRICE");
70
- if (decimalFactor.lte(ZERO)) throw new Error("INVALID_DECIMAL_FACTOR");
107
+ const decimalFactor = getDecimalFactor(params.decimal);
108
+ validateCurveParams({
109
+ constant,
110
+ currentSupply,
111
+ basePrice,
112
+ decimalFactor
113
+ });
71
114
  const denom = constant.mul(decimalFactor);
72
115
  const a = currentSupply.sqr().div(denom);
73
116
  return basePrice.add(a);
@@ -83,9 +126,15 @@ function calcQuadraticCost(params) {
83
126
  const currentSupply = new require_bn.BN(params.currentSupply);
84
127
  const basePrice = new require_bn.BN(params.basePrice);
85
128
  const constant = new require_bn.BN(params.constant);
86
- const decimalFactor = TEN.pow(new require_bn.BN(params.decimal));
87
- if (constant.lte(ZERO)) throw new Error("INVALID_CONSTANT");
88
- if (amount.lt(ZERO)) throw new Error("INVALID_AMOUNT");
129
+ const decimalFactor = getDecimalFactor(params.decimal);
130
+ validateCurveParams({
131
+ direction: params.direction,
132
+ constant,
133
+ amount,
134
+ currentSupply,
135
+ basePrice,
136
+ decimalFactor
137
+ });
89
138
  if (amount.isZero()) return ZERO;
90
139
  const newSupply = params.direction === Direction.Mint ? currentSupply.add(amount) : currentSupply.sub(amount);
91
140
  if (params.direction === Direction.Burn && newSupply.lt(ZERO)) throw new Error("SUPPLY_INSUFFICIENT");
@@ -98,7 +147,11 @@ function calcQuadraticCost(params) {
98
147
  return cubicCost.add(linearCost);
99
148
  }
100
149
  function calcFee({ reserveAmount, feeRate }) {
101
- return new require_bn.BN(reserveAmount).mul(new require_bn.BN(feeRate)).div(new require_bn.BN(1e4));
150
+ const reserveBN = new require_bn.BN(reserveAmount);
151
+ const feeRateBN = new require_bn.BN(feeRate);
152
+ if (reserveBN.lt(ZERO)) throw new Error("INVALID_RESERVE_AMOUNT");
153
+ if (feeRateBN.lt(ZERO) || feeRateBN.gt(new require_bn.BN(1e4))) throw new Error("INVALID_FEE_RATE");
154
+ return reserveBN.mul(feeRateBN).div(new require_bn.BN(1e4));
102
155
  }
103
156
  function calcPrice({ currentSupply, decimal, curve }) {
104
157
  const calculator = {
@@ -117,7 +170,7 @@ function calcPrice({ currentSupply, decimal, curve }) {
117
170
  decimal,
118
171
  ...curve
119
172
  })
120
- }[curve.type];
173
+ }[curve?.type];
121
174
  if (!calculator) throw new Error("INVALID_CURVE_TYPE");
122
175
  return calculator();
123
176
  }
@@ -126,6 +179,7 @@ function calcCost({ amount, decimal, currentSupply, direction, curve }) {
126
179
  constant: () => calcConstantCost({
127
180
  amount,
128
181
  decimal,
182
+ direction,
129
183
  ...curve
130
184
  }),
131
185
  linear: () => calcLinearCost({
@@ -142,7 +196,7 @@ function calcCost({ amount, decimal, currentSupply, direction, curve }) {
142
196
  direction,
143
197
  ...curve
144
198
  })
145
- }[curve.type];
199
+ }[curve?.type];
146
200
  if (!calculator) throw new Error("INVALID_CURVE_TYPE");
147
201
  return calculator();
148
202
  }
package/lib/curve.d.cts CHANGED
@@ -22,11 +22,13 @@ declare function calcConstantPrice({
22
22
  declare function calcConstantCost({
23
23
  amount,
24
24
  fixedPrice,
25
- decimal
25
+ decimal,
26
+ direction
26
27
  }: {
27
28
  amount: string;
28
29
  fixedPrice: string;
29
30
  decimal: number;
31
+ direction?: Direction;
30
32
  }): bn_js0;
31
33
  /**
32
34
  * linear Curve
@@ -1,7 +1,11 @@
1
1
 
2
2
  //#region src/get-list-field.ts
3
- const getByPath = (obj, path) => path.split(".").reduce((o, k) => o?.[k], obj);
4
- const getListField = (obj, key) => getByPath(obj, `${key}List`) || getByPath(obj, key) || [];
3
+ const getByPath = (obj, path) => obj?.[path] !== void 0 ? obj[path] : path.split(".").reduce((o, k) => o?.[k], obj);
4
+ const normalizeListKey = (key) => key.endsWith("List") ? key.slice(0, -4) : key;
5
+ const getListField = (obj, key) => {
6
+ const baseKey = normalizeListKey(key);
7
+ return getByPath(obj, `${baseKey}List`) || getByPath(obj, baseKey) || [];
8
+ };
5
9
  /**
6
10
  * Write a repeated field to its canonical (no-suffix) form and remove the
7
11
  * jspb `xxxList` twin. Keeps pipe code insulated from protobuf vs CBOR
@@ -10,8 +14,9 @@ const getListField = (obj, key) => getByPath(obj, `${key}List`) || getByPath(obj
10
14
  * ⚠️ Must use `delete` (not `= undefined`) — see CLAUDE.md Critical Lesson #1.
11
15
  */
12
16
  const setListField = (obj, key, value) => {
13
- delete obj[`${key}List`];
14
- obj[key] = value;
17
+ const baseKey = normalizeListKey(key);
18
+ delete obj[`${baseKey}List`];
19
+ obj[baseKey] = value;
15
20
  };
16
21
  /**
17
22
  * Remove both `xxx` and `xxxList` twins so the field is absent from any
@@ -19,8 +24,9 @@ const setListField = (obj, key, value) => {
19
24
  * the "clear" case. Uses `delete` for the same reason as `setListField`.
20
25
  */
21
26
  const deleteListField = (obj, key) => {
22
- delete obj[`${key}List`];
23
- delete obj[key];
27
+ const baseKey = normalizeListKey(key);
28
+ delete obj[`${baseKey}List`];
29
+ delete obj[baseKey];
24
30
  };
25
31
 
26
32
  //#endregion
package/lib/index.cjs CHANGED
@@ -51,6 +51,7 @@ const isBase58btc = (data) => {
51
51
  */
52
52
  const numberToBN = (arg) => {
53
53
  if (typeof arg === "string" || typeof arg === "number") {
54
+ if (typeof arg === "number" && !Number.isFinite(arg)) throw new Error("[number-to-bn] number must be finite");
54
55
  let multiplier = new require_bn.BN(1);
55
56
  const formattedString = String(arg).toLowerCase().trim();
56
57
  const isHexPrefixed$1 = formattedString.substr(0, 2) === "0x" || formattedString.substr(0, 3) === "-0x";
@@ -140,7 +141,19 @@ const isHex = (hex) => (isString(hex) || isNumber(hex)) && /^(-0x|0x|0X|-0X)?[0-
140
141
  */
141
142
  const toBN = (num, base = 10) => {
142
143
  try {
143
- if (typeof num === "number" && num > 0) return new require_bn.BN(Number(num).toLocaleString("fullwide", { useGrouping: false }), base);
144
+ if (typeof num === "number") {
145
+ if (!Number.isFinite(num)) throw new Error("Invalid number: must be finite");
146
+ if (num > 0) return new require_bn.BN(Number(num).toLocaleString("fullwide", { useGrouping: false }), base);
147
+ }
148
+ if (typeof num === "string" && (base === 16 || base === "hex")) {
149
+ const formatted = num.trim();
150
+ const isNeg = formatted.startsWith("-");
151
+ const unsigned = stripHexPrefix(isNeg ? formatted.slice(1) : formatted);
152
+ if (/^[0-9a-fA-F]+$/.test(unsigned)) {
153
+ const parsed = new require_bn.BN(unsigned, 16);
154
+ return isNeg ? parsed.mul(negative1) : parsed;
155
+ }
156
+ }
144
157
  return numberToBN(num);
145
158
  } catch (error) {
146
159
  throw new Error(`${error} Given value: "${num}"`);
@@ -204,6 +217,7 @@ const hexToUtf8 = (hex) => {
204
217
  */
205
218
  const hexToNumber = (value) => {
206
219
  if (!value) return 0;
220
+ if (typeof value === "string" && !/^-?[0-9]+$/.test(value.trim()) && /^-?(0x)?[0-9a-fA-F]+$/i.test(value.trim())) return toBN(value, 16).toNumber();
207
221
  return toBN(value).toNumber();
208
222
  };
209
223
  /**
@@ -272,7 +286,7 @@ const hexToBytes = (hex) => {
272
286
  * @returns {String}
273
287
  */
274
288
  const toHex = (value, returnType = false) => {
275
- if (isUint8Array(value) || Buffer.isBuffer(value)) return returnType ? "bytes" : bytesToHex(value);
289
+ if (isUint8Array(value) || typeof Buffer !== "undefined" && Buffer.isBuffer(value)) return returnType ? "bytes" : bytesToHex(value);
276
290
  if (isBase58btc(value)) return returnType ? "bytes" : bytesToHex(base58btc.decode(value));
277
291
  if (isBoolean(value)) return returnType ? "bool" : value ? "0x01" : "0x00";
278
292
  if (isObject(value) && !isBigNumber(value) && !isBN(value)) return returnType ? "string" : utf8ToHex(JSON.stringify(value));
@@ -324,9 +338,10 @@ const fromUnitToToken = (input, decimal = 18, optionsInput = {}) => {
324
338
  * Convert human readable token number to big number instance
325
339
  */
326
340
  const fromTokenToUnit = (input, decimal = 18) => {
341
+ if (!Number.isInteger(decimal) || decimal < 0 || decimal > 78) throw new Error(`error converting token ${input} to unit, invalid decimal ${decimal}`);
327
342
  let token = numberToString(input);
328
343
  const base = toBN(`1${"0".repeat(decimal)}`, 10);
329
- const baseLength = base.toString(10).length - 1 || 1;
344
+ const baseLength = base.toString(10).length - 1;
330
345
  const negative = token.substring(0, 1) === "-";
331
346
  if (negative) token = token.substring(1);
332
347
  if (token === ".") throw new Error(`error converting token ${input} to unit, invalid value`);
@@ -335,8 +350,8 @@ const fromTokenToUnit = (input, decimal = 18) => {
335
350
  let whole = comps[0];
336
351
  let fraction = comps[1];
337
352
  if (!whole) whole = "0";
353
+ if (fraction && fraction.length > baseLength) throw new Error(`error converting token ${input} to unit, too many decimal places`);
338
354
  if (!fraction) fraction = "0";
339
- if (fraction.length > baseLength) throw new Error(`error converting token ${input} to unit, too many decimal places`);
340
355
  while (fraction.length < baseLength) fraction += "0";
341
356
  whole = new require_bn.BN(whole);
342
357
  fraction = new require_bn.BN(fraction);
@@ -354,10 +369,13 @@ function isUint8Array(value) {
354
369
  * Generate a random UUID
355
370
  */
356
371
  function UUID() {
357
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
358
- const r = Math.random() * 16 | 0;
359
- return (c === "x" ? r : r & 3 | 8).toString(16);
360
- });
372
+ if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
373
+ const bytes = new Uint8Array(16);
374
+ globalThis.crypto.getRandomValues(bytes);
375
+ bytes[6] = bytes[6] & 15 | 64;
376
+ bytes[8] = bytes[8] & 63 | 128;
377
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
378
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
361
379
  }
362
380
  /**
363
381
  * Check if a string is valid UUID
@@ -375,7 +393,7 @@ function toUint8Array(v) {
375
393
  void 0,
376
394
  ""
377
395
  ].includes(v)) vb = new Uint8Array();
378
- else if (Buffer.isBuffer(v)) vb = new Uint8Array(v);
396
+ else if (typeof Buffer !== "undefined" && Buffer.isBuffer(v)) vb = new Uint8Array(v);
379
397
  else if (isHexStrict(v)) vb = new Uint8Array(hexToBytes(v));
380
398
  else if (isUint8Array(v)) vb = new Uint8Array(v);
381
399
  else if (isBase58btc(v)) vb = new Uint8Array(base58btc.decode(v));
@@ -387,27 +405,29 @@ function toUint8Array(v) {
387
405
  * Convert input to Buffer on best effort, base64 not supported
388
406
  */
389
407
  function toBuffer(v) {
390
- return Buffer.from(toUint8Array(v));
408
+ const bytes = toUint8Array(v);
409
+ return typeof Buffer !== "undefined" ? Buffer.from(bytes) : bytes;
391
410
  }
392
411
  /**
393
412
  * Convert input to base58btc format on best effort
394
413
  */
395
414
  function toBase58(v) {
396
415
  const buf = base58btc.encode(toUint8Array(v));
397
- return Buffer.from(buf).toString("utf-8");
416
+ return typeof Buffer !== "undefined" ? Buffer.from(buf).toString("utf-8") : new TextDecoder().decode(buf);
398
417
  }
399
418
  /**
400
419
  * Decode base58 string
401
420
  */
402
421
  function fromBase58(v) {
403
422
  if (isBase58btc(v) === false) throw new Error("fromBase58 expect strict base58 encoded string as input");
404
- return Buffer.from(base58btc.decode(v));
423
+ const decoded = base58btc.decode(v);
424
+ return typeof Buffer !== "undefined" ? Buffer.from(decoded) : decoded;
405
425
  }
406
426
  /**
407
427
  * Convert input to base64 format
408
428
  */
409
429
  function toBase64(v, escape = true) {
410
- const encoded = base64_url.default.encode(toBuffer(v));
430
+ const encoded = toBuffer(v).toString("base64");
411
431
  return escape ? base64_url.default.escape(encoded) : encoded;
412
432
  }
413
433
  /**
@@ -435,7 +455,18 @@ function toDid(address, method = "abt") {
435
455
  return `did:${method}:${toAddress(address)}`;
436
456
  }
437
457
  function isSameDid(a, b) {
438
- return toAddress(a).toLowerCase() === toAddress(b).toLowerCase();
458
+ if (typeof a !== "string" || typeof b !== "string" || !a || !b) return false;
459
+ const methodA = extractMethod(a);
460
+ const methodB = extractMethod(b);
461
+ const aIsName = methodA === "name";
462
+ const bIsName = methodB === "name";
463
+ if (aIsName !== bIsName) return false;
464
+ const addrA = toAddress(a);
465
+ const addrB = toAddress(b);
466
+ if (!addrA || !addrB) return false;
467
+ if (aIsName && bIsName) return addrA.normalize("NFC").toLowerCase() === addrB.normalize("NFC").toLowerCase();
468
+ if (/^0x[0-9a-fA-F]+$/i.test(addrA) && /^0x[0-9a-fA-F]+$/i.test(addrB)) return addrA.toLowerCase() === addrB.toLowerCase();
469
+ return addrA === addrB;
439
470
  }
440
471
  /**
441
472
  * Extract the method from a DID string.
package/lib/md5.cjs CHANGED
@@ -3,7 +3,14 @@ let node_crypto = require("node:crypto");
3
3
  node_crypto = require_rolldown_runtime.__toESM(node_crypto);
4
4
 
5
5
  //#region src/md5.ts
6
- const md5 = (x) => node_crypto.default.createHash("md5").update(x).digest("hex");
6
+ /**
7
+ * Non-cryptographic MD5 digest for internal cache/bucketing keys only.
8
+ * Do not use for security-sensitive integrity, collision-resistant, or authentication purposes.
9
+ */
10
+ const md5 = (x) => {
11
+ if (x === null || x === void 0) throw new Error("md5 requires a non-null input");
12
+ return node_crypto.default.createHash("md5").update(x).digest("hex");
13
+ };
7
14
 
8
15
  //#endregion
9
16
  exports.md5 = md5;
package/lib/md5.d.cts CHANGED
@@ -1,4 +1,8 @@
1
1
  //#region src/md5.d.ts
2
+ /**
3
+ * Non-cryptographic MD5 digest for internal cache/bucketing keys only.
4
+ * Do not use for security-sensitive integrity, collision-resistant, or authentication purposes.
5
+ */
2
6
  declare const md5: (x: $TSFixMe) => string;
3
7
  //#endregion
4
8
  export { md5 };
package/lib/url.cjs CHANGED
@@ -6,21 +6,36 @@ ipaddr_js = require_rolldown_runtime.__toESM(ipaddr_js);
6
6
 
7
7
  //#region src/url.ts
8
8
  const MAX_URL_LENGTH = 256;
9
+ function stripTrailingDots(host) {
10
+ return host.replace(/\.+$/, "");
11
+ }
12
+ function stripIpv6Brackets(host) {
13
+ const trimmed = host.trim();
14
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) return trimmed.slice(1, -1);
15
+ return trimmed;
16
+ }
17
+ function normalizeHostname(host) {
18
+ return stripTrailingDots(stripIpv6Brackets(stripTrailingDots(host)));
19
+ }
9
20
  function parseIp(host) {
10
- if (!ipaddr_js.default.isValid(host)) return null;
21
+ const normalized = normalizeHostname(host);
22
+ if (!normalized || !ipaddr_js.default.isValid(normalized)) return null;
11
23
  try {
12
- return ipaddr_js.default.parse(host);
24
+ return ipaddr_js.default.parse(normalized);
13
25
  } catch {
14
26
  return null;
15
27
  }
16
28
  }
17
- function stripTrailingDots(host) {
18
- return host.replace(/\.+$/, "");
19
- }
20
29
  function isBlockedHostname(host, blockedHosts, blockedSuffixes) {
21
- const normalized = host.toLowerCase();
22
- if (blockedHosts.includes(normalized)) return true;
23
- if (blockedSuffixes.some((suffix) => normalized.endsWith(suffix))) return true;
30
+ const normalized = normalizeHostname(host).toLowerCase();
31
+ if (blockedHosts.some((entry) => normalizeHostname(entry).toLowerCase() === normalized)) return true;
32
+ if (blockedSuffixes.some((suffix) => {
33
+ const trimmed = stripTrailingDots(suffix).toLowerCase();
34
+ const clean = trimmed.replace(/^\.+/, "");
35
+ if (!clean) return false;
36
+ if (trimmed.startsWith(".")) return normalized.endsWith(`.${clean}`);
37
+ return normalized === clean || normalized.endsWith(`.${clean}`);
38
+ })) return true;
24
39
  return false;
25
40
  }
26
41
  function isUnicastAddress(host) {
@@ -30,23 +45,16 @@ function isUnicastAddress(host) {
30
45
  if (range === "ipv4Mapped" && parsed.kind() === "ipv6") return parsed.toIPv4Address().range() === "unicast";
31
46
  return range === "unicast";
32
47
  }
33
- async function resolveHostAddresses(host) {
48
+ async function resolveHostAddresses(host, dnsServers) {
34
49
  try {
35
50
  const resolver = new node_dns_promises.Resolver();
36
- resolver.setServers(["8.8.8.8", "1.1.1.1"]);
51
+ if (Array.isArray(dnsServers) && dnsServers.length > 0) resolver.setServers(dnsServers);
52
+ const [ipv4Result, ipv6Result] = await Promise.allSettled([resolver.resolve4(host), resolver.resolve6(host)]);
37
53
  const addresses = [];
38
- try {
39
- const ipv4Addresses = await resolver.resolve4(host);
40
- addresses.push(...ipv4Addresses);
41
- } catch (error) {
42
- console.warn(`IPv4 resolution failed for ${host}:`, error?.message);
43
- }
44
- if (!addresses.length) try {
45
- const ipv6Addresses = await resolver.resolve6(host);
46
- addresses.push(...ipv6Addresses);
47
- } catch (error) {
48
- console.warn(`IPv6 resolution failed for ${host}:`, error?.message);
49
- }
54
+ if (ipv4Result.status === "fulfilled") addresses.push(...ipv4Result.value);
55
+ else console.warn(`IPv4 resolution failed for ${host}:`, ipv4Result.reason?.message);
56
+ if (ipv6Result.status === "fulfilled") addresses.push(...ipv6Result.value);
57
+ else console.warn(`IPv6 resolution failed for ${host}:`, ipv6Result.reason?.message);
50
58
  return addresses.filter(Boolean);
51
59
  } catch (error) {
52
60
  console.warn(`DNS resolution failed for host: ${host}, error: ${error?.message}`);
@@ -55,11 +63,11 @@ async function resolveHostAddresses(host) {
55
63
  }
56
64
  async function verifyUrl(url$1, options = {}) {
57
65
  if (!url$1) throw new Error("URL is required");
58
- const { maxLength = MAX_URL_LENGTH, protocols = ["https:"], blockedHosts = ["localhost"], blockedSuffixes = [], allowIp = false, checkDns = false } = options;
66
+ const { maxLength = MAX_URL_LENGTH, protocols = ["https:"], blockedHosts = ["localhost"], blockedSuffixes = [], allowIp = false, checkDns = false, dnsServers, resolveHost = resolveHostAddresses } = options;
59
67
  if (url$1.length > maxLength) throw new Error(`URL exceeds maximum length of ${maxLength} characters: ${url$1.length}`);
60
68
  const { hostname, protocol } = new url.URL(url$1);
61
69
  if (!protocols.includes(protocol)) throw new Error(`Protocol '${protocol}' is not allowed. Allowed protocols: ${protocols.join(", ")}`);
62
- const normalizedHost = stripTrailingDots(hostname);
70
+ const normalizedHost = normalizeHostname(hostname);
63
71
  if (isBlockedHostname(normalizedHost, blockedHosts, blockedSuffixes)) throw new Error(`Hostname '${normalizedHost}' is blocked`);
64
72
  const isIP = Boolean(parseIp(normalizedHost));
65
73
  if (isIP) {
@@ -67,7 +75,7 @@ async function verifyUrl(url$1, options = {}) {
67
75
  if (!isUnicastAddress(normalizedHost)) throw new Error(`IP address is not unicast: ${normalizedHost}`);
68
76
  }
69
77
  if (checkDns && !isIP) {
70
- const resolved = await resolveHostAddresses(normalizedHost);
78
+ const resolved = await resolveHost(normalizedHost, dnsServers);
71
79
  if (resolved.length === 0) throw new Error(`DNS resolution failed: no addresses found for ${normalizedHost}`);
72
80
  if (!resolved.every((address) => isUnicastAddress(address))) throw new Error(`DNS resolved to non-unicast addresses for ${normalizedHost}`);
73
81
  }
package/lib/url.d.cts CHANGED
@@ -3,7 +3,7 @@ import ipaddr from "ipaddr.js";
3
3
  //#region src/url.d.ts
4
4
  declare function parseIp(host: string): ipaddr.IPv4 | ipaddr.IPv6 | null;
5
5
  declare function isUnicastAddress(host: string): boolean;
6
- declare function resolveHostAddresses(host: string): Promise<string[]>;
6
+ declare function resolveHostAddresses(host: string, dnsServers?: string[]): Promise<string[]>;
7
7
  interface VerifyUrlOptions {
8
8
  allowIp?: boolean;
9
9
  maxLength?: number;
@@ -11,6 +11,8 @@ interface VerifyUrlOptions {
11
11
  blockedHosts?: string[];
12
12
  blockedSuffixes?: string[];
13
13
  checkDns?: boolean;
14
+ dnsServers?: string[];
15
+ resolveHost?: (host: string, dnsServers?: string[]) => Promise<string[]>;
14
16
  }
15
17
  declare function verifyUrl(url: string, options?: VerifyUrlOptions): Promise<boolean>;
16
18
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocap/util",
3
- "version": "1.30.24",
3
+ "version": "1.30.26",
4
4
  "type": "module",
5
5
  "description": "utils shared across multiple forge js libs, works in both node.js and browser",
6
6
  "keywords": [
@@ -12,7 +12,7 @@
12
12
  "access": "public"
13
13
  },
14
14
  "dependencies": {
15
- "@ocap/types": "1.30.24",
15
+ "@ocap/types": "1.30.26",
16
16
  "@types/bn.js": "^5.2.0",
17
17
  "base64-url": "^2.3.3",
18
18
  "bn.js": "5.2.3",