UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 2.72 kB
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{serialize}from"node:v8"; //!src/infra/json-field-transfer.ts const JSON_FIELD_TRANSFER_BYTES=65536;const STRING_CHARS=8192;function*jsonFieldBatches(e){let t=[];let n=16;for(const r of fields(e)){const e=serialize(r).byteLength+16;if(n+e>65536){yield t;t=[];n=16}t.push(r);n+=e}if(t.length)yield t}function*textFields(e,t){yield{kind:e,value:t.slice(0,STRING_CHARS)};for(let n=STRING_CHARS;n<t.length;n+=STRING_CHARS)yield{kind:e,value:t.slice(n,n+STRING_CHARS),append:true}}function*fields(e){if(e===void 0)return;if(typeof e===`string`)yield*textFields(`value`,e);else if(e===null||typeof e===`boolean`||typeof e===`number`)yield{kind:`value`,value:typeof e===`number`&&!Number.isFinite(e)?null:e};else if(typeof e===`object`){yield{kind:Array.isArray(e)?`array`:`object`};for(const[t,n]of Object.entries(e))if(n!==void 0){yield*textFields(`key`,t);yield*fields(n)}yield{kind:`end`}}else throw new TypeError(`JSON document contains non-JSON value: ${typeof e}`)}function isJsonTransferField(e){if(!isRecord(e))return false;if(e.kind===`object`||e.kind===`array`||e.kind===`end`)return true;return(e.kind===`key`||e.kind===`value`)&&(e.append===void 0||e.append===true&&typeof e.value===`string`)&&(typeof e.value===`string`||e.kind===`value`&&(e.value===null||typeof e.value===`boolean`||typeof e.value===`number`))}function createJsonFieldReceiver(){let e;let t=false;const n=[];let r;const write=r=>{const i=n.at(-1);if(i){if(i.key===void 0)throw new Error(`JSON field has no property key`);Object.defineProperty(i.container,i.key,{value:r,writable:true,enumerable:true,configurable:true});i.key=void 0}else{if(t)throw new Error(`JSON transfer has more than one root`);e=r;t=true}};const flush=()=>{if(!r)return;const e=r.chunks.join(``);if(r.kind===`key`){const t=n.at(-1);if(!t||t.key!==void 0)throw new Error(`JSON property key has no value or container`);t.key=e}else write(e);r=void 0};return{accept(e){if(!isJsonTransferField(e))throw new Error(`Invalid JSON transfer field`);if(e.kind===`key`||e.kind===`value`){if(e.append){if(!r||r.kind!==e.kind||typeof e.value!==`string`)throw new Error(`Invalid JSON string continuation`);r.chunks.push(e.value);return}flush();if(typeof e.value===`string`)r={kind:e.kind,chunks:[e.value]};else write(e.value)}else{flush();if(e.kind===`end`){const e=n.pop();if(!e||e.key!==void 0)throw new Error(`JSON container ended with an incomplete field`)}else{const t=e.kind===`array`?[]:{};write(t);n.push({container:t})}}},finish(){flush();if(n.length)throw new Error(`JSON transfer ended with an incomplete container`);return e}}}export{createJsonFieldReceiver as n,jsonFieldBatches as r,JSON_FIELD_TRANSFER_BYTES as t};