diff --git a/src/WABinary/encode.ts b/src/WABinary/encode.ts index f1168a6..39f7881 100644 --- a/src/WABinary/encode.ts +++ b/src/WABinary/encode.ts @@ -149,8 +149,8 @@ const encodeBinaryNodeInner = ( } } - const isNibble = (str: string) => { - if(str.length > TAGS.PACKED_MAX) { + const isNibble = (str?: string) => { + if(!str || str.length > TAGS.PACKED_MAX) { return false } @@ -164,8 +164,8 @@ const encodeBinaryNodeInner = ( return true } - const isHex = (str: string) => { - if(str.length > TAGS.PACKED_MAX) { + const isHex = (str?: string) => { + if(!str || str.length > TAGS.PACKED_MAX) { return false } @@ -179,7 +179,12 @@ const encodeBinaryNodeInner = ( return true } - const writeString = (str: string) => { + const writeString = (str?: string) => { + if(str === undefined || str === null) { + pushByte(TAGS.LIST_EMPTY) + return + } + const tokenIndex = TOKEN_MAP[str] if(tokenIndex) { if(typeof tokenIndex.dict === 'number') { @@ -212,7 +217,11 @@ const encodeBinaryNodeInner = ( } } - const validAttributes = Object.keys(attrs).filter(k => ( + if(!tag) { + throw new Error('Invalid node: tag cannot be undefined') + } + + const validAttributes = Object.keys(attrs || {}).filter(k => ( typeof attrs[k] !== 'undefined' && attrs[k] !== null )) @@ -232,8 +241,10 @@ const encodeBinaryNodeInner = ( writeByteLength(content.length) pushBytes(content) } else if(Array.isArray(content)) { - writeListStart(content.length) - for(const item of content) { + const validContent = content.filter(item => item && (item.tag || Buffer.isBuffer(item) || item instanceof Uint8Array || typeof item === 'string') + ) + writeListStart(validContent.length) + for(const item of validContent) { encodeBinaryNodeInner(item, opts, buffer) } } else if(typeof content === 'undefined') {