openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
112 lines (111 loc) • 2.96 kB
JavaScript
//#region src/infra/json-utf8-bytes.ts
/** Returns the UTF-8 byte length of JSON.stringify(value), falling back to String(value). */
function jsonUtf8Bytes(e) {
try {
return Buffer.byteLength(JSON.stringify(e), "utf8");
} catch {
return Buffer.byteLength(String(e), "utf8");
}
}
/** Returns JSON UTF-8 byte length, or Infinity when the value cannot serialize safely. */
function jsonUtf8BytesOrInfinity(e) {
try {
const t = JSON.stringify(e);
return typeof t === "string" ? Buffer.byteLength(t, "utf8") : Number.POSITIVE_INFINITY;
} catch {
return Number.POSITIVE_INFINITY;
}
}
function jsonStringByteLengthUpToLimit(e, t) {
if (e.length + 2 > t || e.length * 3 + 2 > t && Buffer.byteLength(e, "utf8") + 2 > t) return t + 1;
return jsonUtf8BytesOrInfinity(e);
}
/** Returns the first enumerable own keys in JavaScript enumeration order. */
function firstEnumerableOwnKeys(e, t) {
const n = [];
for (const r in e) {
if (!Object.prototype.propertyIsEnumerable.call(e, r)) continue;
n.push(r);
if (n.length >= t) break;
}
return n;
}
/** Counts JSON UTF-8 bytes up to a hard limit without fully serializing large objects. */
function boundedJsonUtf8Bytes(e, t) {
let n = 0;
let r;
const add = (e) => {
n += e;
if (n > t) throw new Error("json_byte_limit_exceeded");
};
const visit = (e, i) => {
if (e === null) {
add(4);
return;
}
switch (typeof e) {
case "string":
add(jsonStringByteLengthUpToLimit(e, t - n));
return;
case "number":
add(jsonUtf8BytesOrInfinity(Number.isFinite(e) ? e : null));
return;
case "boolean":
add(e ? 4 : 5);
return;
case "undefined":
case "function":
case "symbol":
if (i) add(4);
return;
case "bigint": throw new Error("json_byte_length_unsupported");
}
const a = e;
if ((r ??= /* @__PURE__ */ new WeakSet()).has(a)) throw new Error("json_byte_length_circular");
if (typeof a.toJSON === "function" && !(a instanceof Date)) throw new Error("json_byte_length_custom_to_json");
r.add(a);
try {
if (a instanceof Date) {
visit(a.toJSON(), i);
return;
}
const e = Array.isArray(a);
add(1);
if (e) for (let e = 0; e < a.length; e += 1) {
if (e > 0) add(1);
visit(a[e], true);
}
else {
let e = false;
const r = a;
for (const i in r) {
if (!Object.prototype.propertyIsEnumerable.call(r, i)) continue;
const a = r[i];
if (a === void 0 || typeof a === "function" || typeof a === "symbol") continue;
if (e) add(1);
e = true;
add(jsonStringByteLengthUpToLimit(i, t - n));
add(1);
visit(a, false);
}
}
add(1);
} finally {
r.delete(a);
}
};
try {
visit(e, false);
return {
bytes: n,
complete: true
};
} catch {
return {
bytes: Math.max(n, t + 1),
complete: false
};
}
}
//#endregion
export { jsonUtf8BytesOrInfinity as i, firstEnumerableOwnKeys as n, jsonUtf8Bytes as r, boundedJsonUtf8Bytes as t };