mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-11 22:43:43 +00:00
refactor(core): share JSON utf8 byte counting helper
This commit is contained in:
16
src/infra/json-utf8-bytes.test.ts
Normal file
16
src/infra/json-utf8-bytes.test.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { jsonUtf8Bytes } from "./json-utf8-bytes.js";
|
||||
|
||||
describe("jsonUtf8Bytes", () => {
|
||||
it("returns utf8 byte length for serializable values", () => {
|
||||
expect(jsonUtf8Bytes({ a: "x", b: [1, 2, 3] })).toBe(
|
||||
Buffer.byteLength(JSON.stringify({ a: "x", b: [1, 2, 3] }), "utf8"),
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to string conversion when JSON serialization throws", () => {
|
||||
const circular: { self?: unknown } = {};
|
||||
circular.self = circular;
|
||||
expect(jsonUtf8Bytes(circular)).toBe(Buffer.byteLength("[object Object]", "utf8"));
|
||||
});
|
||||
});
|
||||
7
src/infra/json-utf8-bytes.ts
Normal file
7
src/infra/json-utf8-bytes.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export function jsonUtf8Bytes(value: unknown): number {
|
||||
try {
|
||||
return Buffer.byteLength(JSON.stringify(value), "utf8");
|
||||
} catch {
|
||||
return Buffer.byteLength(String(value), "utf8");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user