openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2 lines • 1.76 kB
JavaScript
function jsonUtf8Bytes(e){try{return Buffer.byteLength(JSON.stringify(e),`utf8`)}catch{return Buffer.byteLength(String(e),`utf8`)}}function jsonUtf8BytesOrInfinity(e){try{let t=JSON.stringify(e);return typeof t==`string`?Buffer.byteLength(t,`utf8`):1/0}catch{return 1/0}}const e=/["\\\u0000-\u001f\ud800-\udfff]/gu;function jsonStringByteLengthUpToLimit(t,n){if(t.length+2>n)return n+1;let r=Buffer.byteLength(t,`utf8`)+2;if(r>n)return n+1;for(let n of t.match(e)??[]){let e=n.charCodeAt(0);r+=e>=55296?3:e<32&&!`\b
\f\r`.includes(n)?5:1}return r}function boundedJsonUtf8Bytes(e,t){let n=0,r,add=e=>{if(n+=e,n>t)throw Error(`json_byte_limit_exceeded`)},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`:i&&add(4);return;case`bigint`:throw Error(`json_byte_length_unsupported`)}let a=e;if((r??=/* @__PURE__ */ new WeakSet).has(a))throw Error(`json_byte_length_circular`);if(typeof a.toJSON==`function`&&!(a instanceof Date))throw Error(`json_byte_length_custom_to_json`);r.add(a);try{if(a instanceof Date){visit(a.toJSON(),i);return}let e=Array.isArray(a);if(add(1),e)for(let e=0;e<a.length;e+=1)e>0&&add(1),visit(a[e],!0);else{let e=!1,r=a;for(let i in r){if(!Object.prototype.propertyIsEnumerable.call(r,i))continue;let a=r[i];a!==void 0&&typeof a!=`function`&&typeof a!=`symbol`&&(e&&add(1),e=!0,add(jsonStringByteLengthUpToLimit(i,t-n)),add(1),visit(a,!1))}}add(1)}finally{r.delete(a)}};try{return visit(e,!1),{bytes:n,complete:!0}}catch{return{bytes:Math.max(n,t+1),complete:!1}}}export{jsonUtf8Bytes as n,boundedJsonUtf8Bytes as t};