Comparing version 9.0.2 to 10.0.2
@@ -1,11 +0,11 @@ | ||
'use strict' | ||
'use strict'; | ||
const Commented = require('./commented') | ||
const Diagnose = require('./diagnose') | ||
const Decoder = require('./decoder') | ||
const Encoder = require('./encoder') | ||
const Simple = require('./simple') | ||
const Tagged = require('./tagged') | ||
const Map = require('./map') | ||
const SharedValueEncoder = require('./sharedValueEncoder') | ||
const Commented = require('./commented'); | ||
const Diagnose = require('./diagnose'); | ||
const Decoder = require('./decoder'); | ||
const Encoder = require('./encoder'); | ||
const Simple = require('./simple'); | ||
const Tagged = require('./tagged'); | ||
const Map = require('./map'); | ||
const SharedValueEncoder = require('./sharedValueEncoder'); | ||
@@ -111,5 +111,5 @@ module.exports = { | ||
reset() { | ||
Encoder.reset() | ||
Tagged.reset() | ||
Encoder.reset(); | ||
Tagged.reset(); | ||
}, | ||
} | ||
}; |
@@ -1,15 +0,15 @@ | ||
'use strict' | ||
'use strict'; | ||
const stream = require('stream') | ||
const utils = require('./utils') | ||
const Decoder = require('./decoder') | ||
const NoFilter = require('nofilter') | ||
const {MT, NUMBYTES, SYMS} = require('./constants') | ||
const {Buffer} = require('buffer') | ||
const stream = require('stream'); | ||
const utils = require('./utils'); | ||
const Decoder = require('./decoder'); | ||
const NoFilter = require('nofilter'); | ||
const {MT, NUMBYTES, SYMS} = require('./constants'); | ||
const {Buffer} = require('buffer'); | ||
function plural(c) { | ||
if (c > 1) { | ||
return 's' | ||
return 's'; | ||
} | ||
return '' | ||
return ''; | ||
} | ||
@@ -52,11 +52,11 @@ | ||
case 'function': | ||
return {options: {}, cb: /** @type {commentCallback} */ (opts)} | ||
return {options: {}, cb: /** @type {commentCallback} */ (opts)}; | ||
case 'string': | ||
return {options: {encoding: /** @type {BufferEncoding} */ (opts)}, cb} | ||
return {options: {encoding: /** @type {BufferEncoding} */ (opts)}, cb}; | ||
case 'number': | ||
return {options: {max_depth: opts}, cb} | ||
return {options: {max_depth: opts}, cb}; | ||
case 'object': | ||
return {options: opts || {}, cb} | ||
return {options: opts || {}, cb}; | ||
default: | ||
throw new TypeError('Unknown option type') | ||
throw new TypeError('Unknown option type'); | ||
} | ||
@@ -87,3 +87,3 @@ } | ||
...superOpts | ||
} = options | ||
} = options; | ||
@@ -94,10 +94,10 @@ super({ | ||
writableObjectMode: false, | ||
}) | ||
}); | ||
this.depth = depth | ||
this.max_depth = max_depth | ||
this.all = new NoFilter() | ||
this.depth = depth; | ||
this.max_depth = max_depth; | ||
this.all = new NoFilter(); | ||
if (!tags[24]) { | ||
tags[24] = this._tag_24.bind(this) | ||
tags[24] = this._tag_24.bind(this); | ||
} | ||
@@ -109,13 +109,13 @@ this.parser = new Decoder({ | ||
encoding, | ||
}) | ||
this.parser.on('value', this._on_value.bind(this)) | ||
this.parser.on('start', this._on_start.bind(this)) | ||
this.parser.on('start-string', this._on_start_string.bind(this)) | ||
this.parser.on('stop', this._on_stop.bind(this)) | ||
this.parser.on('more-bytes', this._on_more.bind(this)) | ||
this.parser.on('error', this._on_error.bind(this)) | ||
}); | ||
this.parser.on('value', this._on_value.bind(this)); | ||
this.parser.on('start', this._on_start.bind(this)); | ||
this.parser.on('start-string', this._on_start_string.bind(this)); | ||
this.parser.on('stop', this._on_stop.bind(this)); | ||
this.parser.on('more-bytes', this._on_more.bind(this)); | ||
this.parser.on('error', this._on_error.bind(this)); | ||
if (!no_summary) { | ||
this.parser.on('data', this._on_data.bind(this)) | ||
this.parser.on('data', this._on_data.bind(this)); | ||
} | ||
this.parser.bs.on('read', this._on_read.bind(this)) | ||
this.parser.bs.on('read', this._on_read.bind(this)); | ||
} | ||
@@ -128,7 +128,7 @@ | ||
_tag_24(v) { | ||
const c = new Commented({depth: this.depth + 1, no_summary: true}) | ||
const c = new Commented({depth: this.depth + 1, no_summary: true}); | ||
c.on('data', b => this.push(b)) | ||
c.on('error', er => this.emit('error', er)) | ||
c.end(v) | ||
c.on('data', b => this.push(b)); | ||
c.on('error', er => this.emit('error', er)); | ||
c.end(v); | ||
} | ||
@@ -145,3 +145,3 @@ | ||
_transform(fresh, encoding, cb) { | ||
this.parser.write(fresh, encoding, cb) | ||
this.parser.write(fresh, encoding, cb); | ||
} | ||
@@ -157,3 +157,3 @@ | ||
// TODO: find the test that covers this, and look at the return value | ||
return this.parser._flush(cb) | ||
return this.parser._flush(cb); | ||
} | ||
@@ -172,30 +172,29 @@ | ||
* @throws {Error} Input required. | ||
* @static | ||
*/ | ||
static comment(input, options = {}, cb = null) { | ||
if (input == null) { | ||
throw new Error('input required') | ||
throw new Error('input required'); | ||
} | ||
({options, cb} = normalizeOptions(options, cb)) | ||
const bs = new NoFilter() | ||
const {encoding = 'hex', ...opts} = options | ||
const d = new Commented(opts) | ||
let p = null | ||
({options, cb} = normalizeOptions(options, cb)); | ||
const bs = new NoFilter(); | ||
const {encoding = 'hex', ...opts} = options; | ||
const d = new Commented(opts); | ||
let p = null; | ||
if (typeof cb === 'function') { | ||
d.on('end', () => { | ||
cb(null, bs.toString('utf8')) | ||
}) | ||
d.on('error', cb) | ||
cb(null, bs.toString('utf8')); | ||
}); | ||
d.on('error', cb); | ||
} else { | ||
p = new Promise((resolve, reject) => { | ||
d.on('end', () => { | ||
resolve(bs.toString('utf8')) | ||
}) | ||
d.on('error', reject) | ||
}) | ||
resolve(bs.toString('utf8')); | ||
}); | ||
d.on('error', reject); | ||
}); | ||
} | ||
d.pipe(bs) | ||
utils.guessEncoding(input, encoding).pipe(d) | ||
return p | ||
d.pipe(bs); | ||
utils.guessEncoding(input, encoding).pipe(d); | ||
return p; | ||
} | ||
@@ -207,5 +206,5 @@ | ||
_on_error(er) { | ||
this.push('ERROR: ') | ||
this.push(er.toString()) | ||
this.push('\n') | ||
this.push('ERROR: '); | ||
this.push(er.toString()); | ||
this.push('\n'); | ||
} | ||
@@ -217,14 +216,14 @@ | ||
_on_read(buf) { | ||
this.all.write(buf) | ||
const hex = buf.toString('hex') | ||
this.all.write(buf); | ||
const hex = buf.toString('hex'); | ||
this.push(new Array(this.depth + 1).join(' ')) | ||
this.push(hex) | ||
this.push(new Array(this.depth + 1).join(' ')); | ||
this.push(hex); | ||
let ind = ((this.max_depth - this.depth) * 2) - hex.length | ||
let ind = ((this.max_depth - this.depth) * 2) - hex.length; | ||
if (ind < 1) { | ||
ind = 1 | ||
ind = 1; | ||
} | ||
this.push(new Array(ind + 1).join(' ')) | ||
this.push('-- ') | ||
this.push(new Array(ind + 1).join(' ')); | ||
this.push('-- '); | ||
} | ||
@@ -235,34 +234,34 @@ | ||
*/ | ||
_on_more(mt, len, parent_mt, pos) { | ||
let desc = '' | ||
_on_more(mt, len, _parent_mt, _pos) { | ||
let desc = ''; | ||
this.depth++ | ||
this.depth++; | ||
switch (mt) { | ||
case MT.POS_INT: | ||
desc = 'Positive number,' | ||
break | ||
desc = 'Positive number,'; | ||
break; | ||
case MT.NEG_INT: | ||
desc = 'Negative number,' | ||
break | ||
desc = 'Negative number,'; | ||
break; | ||
case MT.ARRAY: | ||
desc = 'Array, length' | ||
break | ||
desc = 'Array, length'; | ||
break; | ||
case MT.MAP: | ||
desc = 'Map, count' | ||
break | ||
desc = 'Map, count'; | ||
break; | ||
case MT.BYTE_STRING: | ||
desc = 'Bytes, length' | ||
break | ||
desc = 'Bytes, length'; | ||
break; | ||
case MT.UTF8_STRING: | ||
desc = 'String, length' | ||
break | ||
desc = 'String, length'; | ||
break; | ||
case MT.SIMPLE_FLOAT: | ||
if (len === 1) { | ||
desc = 'Simple value,' | ||
desc = 'Simple value,'; | ||
} else { | ||
desc = 'Float,' | ||
desc = 'Float,'; | ||
} | ||
break | ||
break; | ||
} | ||
this.push(`${desc} next ${len} byte${plural(len)}\n`) | ||
this.push(`${desc} next ${len} byte${plural(len)}\n`); | ||
} | ||
@@ -273,15 +272,15 @@ | ||
*/ | ||
_on_start_string(mt, len, parent_mt, pos) { | ||
let desc = '' | ||
_on_start_string(mt, len, _parent_mt, _pos) { | ||
let desc = ''; | ||
this.depth++ | ||
this.depth++; | ||
switch (mt) { | ||
case MT.BYTE_STRING: | ||
desc = `Bytes, length: ${len}` | ||
break | ||
desc = `Bytes, length: ${len}`; | ||
break; | ||
case MT.UTF8_STRING: | ||
desc = `String, length: ${len.toString()}` | ||
break | ||
desc = `String, length: ${len.toString()}`; | ||
break; | ||
} | ||
this.push(`${desc}\n`) | ||
this.push(`${desc}\n`); | ||
} | ||
@@ -293,44 +292,44 @@ | ||
_on_start(mt, tag, parent_mt, pos) { | ||
this.depth++ | ||
this.depth++; | ||
switch (parent_mt) { | ||
case MT.ARRAY: | ||
this.push(`[${pos}], `) | ||
break | ||
this.push(`[${pos}], `); | ||
break; | ||
case MT.MAP: | ||
if (pos % 2) { | ||
this.push(`{Val:${Math.floor(pos / 2)}}, `) | ||
this.push(`{Val:${Math.floor(pos / 2)}}, `); | ||
} else { | ||
this.push(`{Key:${Math.floor(pos / 2)}}, `) | ||
this.push(`{Key:${Math.floor(pos / 2)}}, `); | ||
} | ||
break | ||
break; | ||
} | ||
switch (mt) { | ||
case MT.TAG: | ||
this.push(`Tag #${tag}`) | ||
this.push(`Tag #${tag}`); | ||
if (tag === 24) { | ||
this.push(' Encoded CBOR data item') | ||
this.push(' Encoded CBOR data item'); | ||
} | ||
break | ||
break; | ||
case MT.ARRAY: | ||
if (tag === SYMS.STREAM) { | ||
this.push('Array (streaming)') | ||
this.push('Array (streaming)'); | ||
} else { | ||
this.push(`Array, ${tag} item${plural(tag)}`) | ||
this.push(`Array, ${tag} item${plural(tag)}`); | ||
} | ||
break | ||
break; | ||
case MT.MAP: | ||
if (tag === SYMS.STREAM) { | ||
this.push('Map (streaming)') | ||
this.push('Map (streaming)'); | ||
} else { | ||
this.push(`Map, ${tag} pair${plural(tag)}`) | ||
this.push(`Map, ${tag} pair${plural(tag)}`); | ||
} | ||
break | ||
break; | ||
case MT.BYTE_STRING: | ||
this.push('Bytes (streaming)') | ||
break | ||
this.push('Bytes (streaming)'); | ||
break; | ||
case MT.UTF8_STRING: | ||
this.push('String (streaming)') | ||
break | ||
this.push('String (streaming)'); | ||
break; | ||
} | ||
this.push('\n') | ||
this.push('\n'); | ||
} | ||
@@ -341,4 +340,4 @@ | ||
*/ | ||
_on_stop(mt) { | ||
this.depth-- | ||
_on_stop(_mt) { | ||
this.depth--; | ||
} | ||
@@ -353,14 +352,14 @@ | ||
case MT.ARRAY: | ||
this.push(`[${pos}], `) | ||
break | ||
this.push(`[${pos}], `); | ||
break; | ||
case MT.MAP: | ||
if (pos % 2) { | ||
this.push(`{Val:${Math.floor(pos / 2)}}, `) | ||
this.push(`{Val:${Math.floor(pos / 2)}}, `); | ||
} else { | ||
this.push(`{Key:${Math.floor(pos / 2)}}, `) | ||
this.push(`{Key:${Math.floor(pos / 2)}}, `); | ||
} | ||
break | ||
break; | ||
} | ||
} | ||
const str = utils.cborValueToString(val, -Infinity) | ||
const str = utils.cborValueToString(val, -Infinity); | ||
@@ -370,9 +369,9 @@ if ((typeof val === 'string') || | ||
if (val.length > 0) { | ||
this.push(str) | ||
this.push('\n') | ||
this.push(str); | ||
this.push('\n'); | ||
} | ||
this.depth-- | ||
this.depth--; | ||
} else { | ||
this.push(str) | ||
this.push('\n') | ||
this.push(str); | ||
this.push('\n'); | ||
} | ||
@@ -385,3 +384,3 @@ | ||
case NUMBYTES.EIGHT: | ||
this.depth-- | ||
this.depth--; | ||
} | ||
@@ -394,8 +393,8 @@ } | ||
_on_data() { | ||
this.push('0x') | ||
this.push(this.all.read().toString('hex')) | ||
this.push('\n') | ||
this.push('0x'); | ||
this.push(this.all.read().toString('hex')); | ||
this.push('\n'); | ||
} | ||
} | ||
module.exports = Commented | ||
module.exports = Commented; |
@@ -1,2 +0,2 @@ | ||
'use strict' | ||
'use strict'; | ||
@@ -15,3 +15,3 @@ /** | ||
SIMPLE_FLOAT: 7, | ||
} | ||
}; | ||
@@ -39,3 +39,3 @@ /** | ||
SET: 258, | ||
} | ||
}; | ||
@@ -52,3 +52,3 @@ /** | ||
INDEFINITE: 31, | ||
} | ||
}; | ||
@@ -63,3 +63,3 @@ /** | ||
UNDEFINED: 23, | ||
} | ||
}; | ||
@@ -72,5 +72,5 @@ exports.SYMS = { | ||
STREAM: Symbol.for('github.com/hildjj/node-cbor/stream'), | ||
} | ||
}; | ||
exports.SHIFT32 = 0x100000000 | ||
exports.SHIFT32 = 0x100000000; | ||
@@ -83,3 +83,3 @@ exports.BI = { | ||
SHIFT32: BigInt(exports.SHIFT32), | ||
} | ||
}; | ||
@@ -1,34 +0,33 @@ | ||
'use strict' | ||
'use strict'; | ||
const BinaryParseStream = require('../vendor/binary-parse-stream') | ||
const Tagged = require('./tagged') | ||
const Simple = require('./simple') | ||
const utils = require('./utils') | ||
const NoFilter = require('nofilter') | ||
const stream = require('stream') | ||
const constants = require('./constants') | ||
const {MT, NUMBYTES, SYMS, BI} = constants | ||
const {Buffer} = require('buffer') | ||
const BinaryParseStream = require('../vendor/binary-parse-stream'); | ||
const Tagged = require('./tagged'); | ||
const Simple = require('./simple'); | ||
const utils = require('./utils'); | ||
const NoFilter = require('nofilter'); | ||
const constants = require('./constants'); | ||
const {MT, NUMBYTES, SYMS, BI} = constants; | ||
const {Buffer} = require('buffer'); | ||
const COUNT = Symbol('count') | ||
const MAJOR = Symbol('major type') | ||
const ERROR = Symbol('error') | ||
const NOT_FOUND = Symbol('not found') | ||
const COUNT = Symbol('count'); | ||
const MAJOR = Symbol('major type'); | ||
const ERROR = Symbol('error'); | ||
const NOT_FOUND = Symbol('not found'); | ||
function parentArray(parent, typ, count) { | ||
const a = [] | ||
const a = []; | ||
a[COUNT] = count | ||
a[SYMS.PARENT] = parent | ||
a[MAJOR] = typ | ||
return a | ||
a[COUNT] = count; | ||
a[SYMS.PARENT] = parent; | ||
a[MAJOR] = typ; | ||
return a; | ||
} | ||
function parentBufferStream(parent, typ) { | ||
const b = new NoFilter() | ||
const b = new NoFilter(); | ||
b[COUNT] = -1 | ||
b[SYMS.PARENT] = parent | ||
b[MAJOR] = typ | ||
return b | ||
b[COUNT] = -1; | ||
b[SYMS.PARENT] = parent; | ||
b[MAJOR] = typ; | ||
return b; | ||
} | ||
@@ -38,6 +37,6 @@ | ||
constructor(byte, value) { | ||
super(`Unexpected data: 0x${byte.toString(16)}`) | ||
this.name = 'UnexpectedDataError' | ||
this.byte = byte | ||
this.value = value | ||
super(`Unexpected data: 0x${byte.toString(16)}`); | ||
this.name = 'UnexpectedDataError'; | ||
this.byte = byte; | ||
this.value = value; | ||
} | ||
@@ -49,4 +48,4 @@ } | ||
* | ||
* @typedef {string|Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray | ||
* |DataView|stream.Readable} BufferLike | ||
* @typedef {string|Buffer|ArrayBuffer|ArrayBufferView | ||
* |DataView|import('stream').Readable} BufferLike | ||
*/ | ||
@@ -107,9 +106,9 @@ /** | ||
case 'function': | ||
return {options: {}, cb: /** @type {decodeCallback} */ (opts)} | ||
return {options: {}, cb: /** @type {decodeCallback} */ (opts)}; | ||
case 'string': | ||
return {options: {encoding: /** @type {BufferEncoding} */ (opts)}, cb} | ||
return {options: {encoding: /** @type {BufferEncoding} */ (opts)}, cb}; | ||
case 'object': | ||
return {options: opts || {}, cb} | ||
return {options: opts || {}, cb}; | ||
default: | ||
throw new TypeError('Unknown option type') | ||
throw new TypeError('Unknown option type'); | ||
} | ||
@@ -143,18 +142,18 @@ } | ||
...superOpts | ||
} = options | ||
} = options; | ||
super({defaultEncoding: encoding, ...superOpts}) | ||
super({defaultEncoding: encoding, ...superOpts}); | ||
this.running = true | ||
this.max_depth = max_depth | ||
this.tags = tags | ||
this.preferMap = preferMap | ||
this.preferWeb = preferWeb | ||
this.extendedResults = extendedResults | ||
this.required = required | ||
this.preventDuplicateKeys = preventDuplicateKeys | ||
this.running = true; | ||
this.max_depth = max_depth; | ||
this.tags = tags; | ||
this.preferMap = preferMap; | ||
this.preferWeb = preferWeb; | ||
this.extendedResults = extendedResults; | ||
this.required = required; | ||
this.preventDuplicateKeys = preventDuplicateKeys; | ||
if (extendedResults) { | ||
this.bs.on('read', this._onRead.bind(this)) | ||
this.valueBytes = /** @type {NoFilter} */ (new NoFilter()) | ||
this.bs.on('read', this._onRead.bind(this)); | ||
this.valueBytes = /** @type {NoFilter} */ (new NoFilter()); | ||
} | ||
@@ -180,5 +179,5 @@ } | ||
case SYMS.NULL: | ||
return null | ||
return null; | ||
case SYMS.UNDEFINED: | ||
return undefined | ||
return undefined; | ||
// Leaving this in for now as belt-and-suspenders, but I'm pretty sure | ||
@@ -189,5 +188,5 @@ // it can't happen. | ||
/* istanbul ignore next */ | ||
throw new Error('Value not found') | ||
throw new Error('Value not found'); | ||
default: | ||
return val | ||
return val; | ||
} | ||
@@ -208,12 +207,11 @@ } | ||
* @throws {Error} Insufficient data. | ||
* @static | ||
*/ | ||
static decodeFirstSync(input, options = {}) { | ||
if (input == null) { | ||
throw new TypeError('input required') | ||
throw new TypeError('input required'); | ||
} | ||
({options} = normalizeOptions(options)) | ||
const {encoding = 'hex', ...opts} = options | ||
const c = new Decoder(opts) | ||
const s = utils.guessEncoding(input, encoding) | ||
({options} = normalizeOptions(options)); | ||
const {encoding = 'hex', ...opts} = options; | ||
const c = new Decoder(opts); | ||
const s = utils.guessEncoding(input, encoding); | ||
@@ -223,31 +221,31 @@ // For/of doesn't work when you need to call next() with a value | ||
// parser will yield numbers of bytes that it wants | ||
const parser = c._parse() | ||
let state = parser.next() | ||
const parser = c._parse(); | ||
let state = parser.next(); | ||
while (!state.done) { | ||
const b = s.read(state.value) | ||
const b = s.read(state.value); | ||
if ((b == null) || (b.length !== state.value)) { | ||
throw new Error('Insufficient data') | ||
throw new Error('Insufficient data'); | ||
} | ||
if (c.extendedResults) { | ||
c.valueBytes.write(b) | ||
c.valueBytes.write(b); | ||
} | ||
state = parser.next(b) | ||
state = parser.next(b); | ||
} | ||
let val = null | ||
let val = null; | ||
if (c.extendedResults) { | ||
val = state.value | ||
val.unused = s.read() | ||
val = state.value; | ||
val.unused = s.read(); | ||
} else { | ||
val = Decoder.nullcheck(state.value) | ||
val = Decoder.nullcheck(state.value); | ||
if (s.length > 0) { | ||
const nextByte = s.read(1) | ||
const nextByte = s.read(1); | ||
s.unshift(nextByte) | ||
throw new UnexpectedDataError(nextByte[0], val) | ||
s.unshift(nextByte); | ||
throw new UnexpectedDataError(nextByte[0], val); | ||
} | ||
} | ||
return val | ||
return val; | ||
} | ||
@@ -266,32 +264,31 @@ | ||
* @throws {Error} Insufficient data provided. | ||
* @static | ||
*/ | ||
static decodeAllSync(input, options = {}) { | ||
if (input == null) { | ||
throw new TypeError('input required') | ||
throw new TypeError('input required'); | ||
} | ||
({options} = normalizeOptions(options)) | ||
const {encoding = 'hex', ...opts} = options | ||
const c = new Decoder(opts) | ||
const s = utils.guessEncoding(input, encoding) | ||
const res = [] | ||
({options} = normalizeOptions(options)); | ||
const {encoding = 'hex', ...opts} = options; | ||
const c = new Decoder(opts); | ||
const s = utils.guessEncoding(input, encoding); | ||
const res = []; | ||
while (s.length > 0) { | ||
const parser = c._parse() | ||
let state = parser.next() | ||
const parser = c._parse(); | ||
let state = parser.next(); | ||
while (!state.done) { | ||
const b = s.read(state.value) | ||
const b = s.read(state.value); | ||
if ((b == null) || (b.length !== state.value)) { | ||
throw new Error('Insufficient data') | ||
throw new Error('Insufficient data'); | ||
} | ||
if (c.extendedResults) { | ||
c.valueBytes.write(b) | ||
c.valueBytes.write(b); | ||
} | ||
state = parser.next(b) | ||
state = parser.next(b); | ||
} | ||
res.push(Decoder.nullcheck(state.value)) | ||
res.push(Decoder.nullcheck(state.value)); | ||
} | ||
return res | ||
return res; | ||
} | ||
@@ -313,23 +310,22 @@ | ||
* @throws {TypeError} No input provided. | ||
* @static | ||
*/ | ||
static decodeFirst(input, options = {}, cb = null) { | ||
if (input == null) { | ||
throw new TypeError('input required') | ||
throw new TypeError('input required'); | ||
} | ||
({options, cb} = normalizeOptions(options, cb)) | ||
const {encoding = 'hex', required = false, ...opts} = options | ||
({options, cb} = normalizeOptions(options, cb)); | ||
const {encoding = 'hex', required = false, ...opts} = options; | ||
const c = new Decoder(opts) | ||
let v = /** @type {any} */ (NOT_FOUND) | ||
const s = utils.guessEncoding(input, encoding) | ||
const c = new Decoder(opts); | ||
let v = /** @type {any} */ (NOT_FOUND); | ||
const s = utils.guessEncoding(input, encoding); | ||
const p = new Promise((resolve, reject) => { | ||
c.on('data', val => { | ||
v = Decoder.nullcheck(val) | ||
c.close() | ||
}) | ||
v = Decoder.nullcheck(val); | ||
c.close(); | ||
}); | ||
c.once('error', er => { | ||
if (c.extendedResults && (er instanceof UnexpectedDataError)) { | ||
v.unused = c.bs.slice() | ||
return resolve(v) | ||
v.unused = c.bs.slice(); | ||
return resolve(v); | ||
} | ||
@@ -339,8 +335,8 @@ if (v !== NOT_FOUND) { | ||
// eslint-disable-next-line dot-notation | ||
er['value'] = v | ||
er['value'] = v; | ||
} | ||
v = ERROR | ||
c.close() | ||
return reject(er) | ||
}) | ||
v = ERROR; | ||
c.close(); | ||
return reject(er); | ||
}); | ||
c.once('end', () => { | ||
@@ -350,5 +346,5 @@ switch (v) { | ||
if (required) { | ||
return reject(new Error('No CBOR found')) | ||
return reject(new Error('No CBOR found')); | ||
} | ||
return resolve(v) | ||
return resolve(v); | ||
// Pretty sure this can't happen, but not *certain*. | ||
@@ -358,14 +354,14 @@ /* istanbul ignore next */ | ||
/* istanbul ignore next */ | ||
return undefined | ||
return undefined; | ||
default: | ||
return resolve(v) | ||
return resolve(v); | ||
} | ||
}) | ||
}) | ||
}); | ||
}); | ||
if (typeof cb === 'function') { | ||
p.then(val => cb(null, val), cb) | ||
p.then(val => cb(null, val), cb); | ||
} | ||
s.pipe(c) | ||
return p | ||
s.pipe(c); | ||
return p; | ||
} | ||
@@ -391,26 +387,25 @@ | ||
* @throws {TypeError} No input specified. | ||
* @static | ||
*/ | ||
static decodeAll(input, options = {}, cb = null) { | ||
if (input == null) { | ||
throw new TypeError('input required') | ||
throw new TypeError('input required'); | ||
} | ||
({options, cb} = normalizeOptions(options, cb)) | ||
const {encoding = 'hex', ...opts} = options | ||
({options, cb} = normalizeOptions(options, cb)); | ||
const {encoding = 'hex', ...opts} = options; | ||
const c = new Decoder(opts) | ||
const vals = [] | ||
const c = new Decoder(opts); | ||
const vals = []; | ||
c.on('data', val => vals.push(Decoder.nullcheck(val))) | ||
c.on('data', val => vals.push(Decoder.nullcheck(val))); | ||
const p = new Promise((resolve, reject) => { | ||
c.on('error', reject) | ||
c.on('end', () => resolve(vals)) | ||
}) | ||
c.on('error', reject); | ||
c.on('end', () => resolve(vals)); | ||
}); | ||
if (typeof cb === 'function') { | ||
p.then(v => cb(undefined, v), er => cb(er, undefined)) | ||
p.then(v => cb(undefined, v), er => cb(er, undefined)); | ||
} | ||
utils.guessEncoding(input, encoding).pipe(c) | ||
return p | ||
utils.guessEncoding(input, encoding).pipe(c); | ||
return p; | ||
} | ||
@@ -422,4 +417,4 @@ | ||
close() { | ||
this.running = false | ||
this.__fresh = true | ||
this.running = false; | ||
this.__fresh = true; | ||
} | ||
@@ -433,3 +428,3 @@ | ||
_onRead(data) { | ||
this.valueBytes.write(data) | ||
this.valueBytes.write(data); | ||
} | ||
@@ -445,37 +440,37 @@ | ||
*_parse() { | ||
let parent = null | ||
let depth = 0 | ||
let val = null | ||
let parent = null; | ||
let depth = 0; | ||
let val = null; | ||
while (true) { | ||
if ((this.max_depth >= 0) && (depth > this.max_depth)) { | ||
throw new Error(`Maximum depth ${this.max_depth} exceeded`) | ||
throw new Error(`Maximum depth ${this.max_depth} exceeded`); | ||
} | ||
const [octet] = yield 1 | ||
const [octet] = yield 1; | ||
if (!this.running) { | ||
this.bs.unshift(Buffer.from([octet])) | ||
throw new UnexpectedDataError(octet) | ||
this.bs.unshift(Buffer.from([octet])); | ||
throw new UnexpectedDataError(octet); | ||
} | ||
const mt = octet >> 5 | ||
const ai = octet & 0x1f | ||
const parent_major = (parent == null) ? undefined : parent[MAJOR] | ||
const parent_length = (parent == null) ? undefined : parent.length | ||
const mt = octet >> 5; | ||
const ai = octet & 0x1f; | ||
const parent_major = (parent == null) ? undefined : parent[MAJOR]; | ||
const parent_length = (parent == null) ? undefined : parent.length; | ||
switch (ai) { | ||
case NUMBYTES.ONE: | ||
this.emit('more-bytes', mt, 1, parent_major, parent_length) | ||
;[val] = yield 1 | ||
break | ||
this.emit('more-bytes', mt, 1, parent_major, parent_length); | ||
[val] = yield 1; | ||
break; | ||
case NUMBYTES.TWO: | ||
case NUMBYTES.FOUR: | ||
case NUMBYTES.EIGHT: { | ||
const numbytes = 1 << (ai - 24) | ||
const numbytes = 1 << (ai - 24); | ||
this.emit('more-bytes', mt, numbytes, parent_major, parent_length) | ||
const buf = yield numbytes | ||
this.emit('more-bytes', mt, numbytes, parent_major, parent_length); | ||
const buf = yield numbytes; | ||
val = (mt === MT.SIMPLE_FLOAT) ? | ||
buf : | ||
utils.parseCBORint(ai, buf) | ||
break | ||
utils.parseCBORint(ai, buf); | ||
break; | ||
} | ||
@@ -485,4 +480,4 @@ case 28: | ||
case 30: | ||
this.running = false | ||
throw new Error(`Additional info not implemented: ${ai}`) | ||
this.running = false; | ||
throw new Error(`Additional info not implemented: ${ai}`); | ||
case NUMBYTES.INDEFINITE: | ||
@@ -493,8 +488,8 @@ switch (mt) { | ||
case MT.TAG: | ||
throw new Error(`Invalid indefinite encoding for MT ${mt}`) | ||
throw new Error(`Invalid indefinite encoding for MT ${mt}`); | ||
} | ||
val = -1 | ||
break | ||
val = -1; | ||
break; | ||
default: | ||
val = ai | ||
val = ai; | ||
} | ||
@@ -504,10 +499,10 @@ switch (mt) { | ||
// Val already decoded | ||
break | ||
break; | ||
case MT.NEG_INT: | ||
if (val === Number.MAX_SAFE_INTEGER) { | ||
val = BI.NEG_MAX | ||
val = BI.NEG_MAX; | ||
} else { | ||
val = (typeof val === 'bigint') ? BI.MINUS_ONE - val : -1 - val | ||
val = (typeof val === 'bigint') ? BI.MINUS_ONE - val : -1 - val; | ||
} | ||
break | ||
break; | ||
case MT.BYTE_STRING: | ||
@@ -517,24 +512,26 @@ case MT.UTF8_STRING: | ||
case 0: | ||
this.emit('start-string', mt, val, parent_major, parent_length) | ||
this.emit('start-string', mt, val, parent_major, parent_length); | ||
if (mt === MT.UTF8_STRING) { | ||
val = '' | ||
val = ''; | ||
} else { | ||
val = this.preferWeb ? new Uint8Array(0) : Buffer.allocUnsafe(0) | ||
val = this.preferWeb ? | ||
new Uint8Array(0) : | ||
Buffer.allocUnsafe(0); | ||
} | ||
break | ||
break; | ||
case -1: | ||
this.emit('start', mt, SYMS.STREAM, parent_major, parent_length) | ||
parent = parentBufferStream(parent, mt) | ||
depth++ | ||
continue | ||
this.emit('start', mt, SYMS.STREAM, parent_major, parent_length); | ||
parent = parentBufferStream(parent, mt); | ||
depth++; | ||
continue; | ||
default: | ||
this.emit('start-string', mt, val, parent_major, parent_length) | ||
val = yield val | ||
this.emit('start-string', mt, val, parent_major, parent_length); | ||
val = yield val; | ||
if (mt === MT.UTF8_STRING) { | ||
val = utils.utf8(val) | ||
val = utils.utf8(val); | ||
} else if (this.preferWeb) { | ||
val = new Uint8Array(val.buffer, val.byteOffset, val.length) | ||
val = new Uint8Array(val.buffer, val.byteOffset, val.length); | ||
} | ||
} | ||
break | ||
break; | ||
case MT.ARRAY: | ||
@@ -545,25 +542,25 @@ case MT.MAP: | ||
if (mt === MT.MAP) { | ||
val = (this.preferMap) ? new Map() : {} | ||
val = (this.preferMap) ? new Map() : {}; | ||
} else { | ||
val = [] | ||
val = []; | ||
} | ||
break | ||
break; | ||
case -1: | ||
this.emit('start', mt, SYMS.STREAM, parent_major, parent_length) | ||
parent = parentArray(parent, mt, -1) | ||
depth++ | ||
continue | ||
this.emit('start', mt, SYMS.STREAM, parent_major, parent_length); | ||
parent = parentArray(parent, mt, -1); | ||
depth++; | ||
continue; | ||
default: | ||
this.emit('start', mt, val, parent_major, parent_length) | ||
parent = parentArray(parent, mt, val * (mt - 3)) | ||
depth++ | ||
continue | ||
this.emit('start', mt, val, parent_major, parent_length); | ||
parent = parentArray(parent, mt, val * (mt - 3)); | ||
depth++; | ||
continue; | ||
} | ||
break | ||
break; | ||
case MT.TAG: | ||
this.emit('start', mt, val, parent_major, parent_length) | ||
parent = parentArray(parent, mt, 1) | ||
parent.push(val) | ||
depth++ | ||
continue | ||
this.emit('start', mt, val, parent_major, parent_length); | ||
parent = parentArray(parent, mt, 1); | ||
parent.push(val); | ||
depth++; | ||
continue; | ||
case MT.SIMPLE_FLOAT: | ||
@@ -574,5 +571,5 @@ if (typeof val === 'number') { | ||
`Invalid two-byte encoding of simple value ${val}` | ||
) | ||
); | ||
} | ||
const hasParent = (parent != null) | ||
const hasParent = (parent != null); | ||
val = Simple.decode( | ||
@@ -582,31 +579,31 @@ val, | ||
hasParent && (parent[COUNT] < 0) | ||
) | ||
); | ||
} else { | ||
val = utils.parseCBORfloat(val) | ||
val = utils.parseCBORfloat(val); | ||
} | ||
} | ||
this.emit('value', val, parent_major, parent_length, ai) | ||
let again = false | ||
this.emit('value', val, parent_major, parent_length, ai); | ||
let again = false; | ||
while (parent != null) { | ||
if (val === SYMS.BREAK) { | ||
parent[COUNT] = 1 | ||
parent[COUNT] = 1; | ||
} else if (Array.isArray(parent)) { | ||
parent.push(val) | ||
parent.push(val); | ||
} else { | ||
// Assert: parent instanceof NoFilter | ||
const pm = parent[MAJOR] | ||
const pm = parent[MAJOR]; | ||
if ((pm != null) && (pm !== mt)) { | ||
this.running = false | ||
throw new Error('Invalid major type in indefinite encoding') | ||
this.running = false; | ||
throw new Error('Invalid major type in indefinite encoding'); | ||
} | ||
parent.write(val) | ||
parent.write(val); | ||
} | ||
if ((--parent[COUNT]) !== 0) { | ||
again = true | ||
break | ||
again = true; | ||
break; | ||
} | ||
--depth | ||
delete parent[COUNT] | ||
--depth; | ||
delete parent[COUNT]; | ||
@@ -616,9 +613,9 @@ if (Array.isArray(parent)) { | ||
case MT.ARRAY: | ||
val = parent | ||
break | ||
val = parent; | ||
break; | ||
case MT.MAP: { | ||
let allstrings = !this.preferMap | ||
let allstrings = !this.preferMap; | ||
if ((parent.length % 2) !== 0) { | ||
throw new Error(`Invalid map length: ${parent.length}`) | ||
throw new Error(`Invalid map length: ${parent.length}`); | ||
} | ||
@@ -632,31 +629,31 @@ for ( | ||
(parent[i] === '__proto__')) { | ||
allstrings = false | ||
break | ||
allstrings = false; | ||
break; | ||
} | ||
} | ||
if (allstrings) { | ||
val = {} | ||
val = {}; | ||
for (let i = 0, len = parent.length; i < len; i += 2) { | ||
if (this.preventDuplicateKeys && | ||
Object.prototype.hasOwnProperty.call(val, parent[i])) { | ||
throw new Error('Duplicate keys in a map') | ||
throw new Error('Duplicate keys in a map'); | ||
} | ||
val[parent[i]] = parent[i + 1] | ||
val[parent[i]] = parent[i + 1]; | ||
} | ||
} else { | ||
val = new Map() | ||
val = new Map(); | ||
for (let i = 0, len = parent.length; i < len; i += 2) { | ||
if (this.preventDuplicateKeys && val.has(parent[i])) { | ||
throw new Error('Duplicate keys in a map') | ||
throw new Error('Duplicate keys in a map'); | ||
} | ||
val.set(parent[i], parent[i + 1]) | ||
val.set(parent[i], parent[i + 1]); | ||
} | ||
} | ||
break | ||
break; | ||
} | ||
case MT.TAG: { | ||
const t = new Tagged(parent[0], parent[1]) | ||
const t = new Tagged(parent[0], parent[1]); | ||
val = t.convert(this.tags) | ||
break | ||
val = t.convert(this.tags); | ||
break; | ||
} | ||
@@ -669,3 +666,3 @@ } | ||
case MT.BYTE_STRING: | ||
val = parent.slice() | ||
val = parent.slice(); | ||
if (this.preferWeb) { | ||
@@ -676,20 +673,20 @@ val = new Uint8Array( | ||
/** @type {Buffer} */ (val).length | ||
) | ||
); | ||
} | ||
break | ||
break; | ||
case MT.UTF8_STRING: | ||
val = parent.toString('utf-8') | ||
break | ||
val = parent.toString('utf-8'); | ||
break; | ||
} | ||
} | ||
this.emit('stop', parent[MAJOR]) | ||
this.emit('stop', parent[MAJOR]); | ||
const old = parent | ||
parent = parent[SYMS.PARENT] | ||
delete old[SYMS.PARENT] | ||
delete old[MAJOR] | ||
const old = parent; | ||
parent = parent[SYMS.PARENT]; | ||
delete old[SYMS.PARENT]; | ||
delete old[MAJOR]; | ||
} | ||
if (!again) { | ||
if (this.extendedResults) { | ||
const bytes = this.valueBytes.slice() | ||
const bytes = this.valueBytes.slice(); | ||
const ret = { | ||
@@ -699,8 +696,8 @@ value: Decoder.nullcheck(val), | ||
length: bytes.length, | ||
} | ||
}; | ||
this.valueBytes = new NoFilter() | ||
return ret | ||
this.valueBytes = new NoFilter(); | ||
return ret; | ||
} | ||
return val | ||
return val; | ||
} | ||
@@ -711,3 +708,3 @@ } | ||
Decoder.NOT_FOUND = NOT_FOUND | ||
module.exports = Decoder | ||
Decoder.NOT_FOUND = NOT_FOUND; | ||
module.exports = Decoder; |
@@ -1,8 +0,8 @@ | ||
'use strict' | ||
'use strict'; | ||
const stream = require('stream') | ||
const Decoder = require('./decoder') | ||
const utils = require('./utils') | ||
const NoFilter = require('nofilter') | ||
const {MT, SYMS} = require('./constants') | ||
const stream = require('stream'); | ||
const Decoder = require('./decoder'); | ||
const utils = require('./utils'); | ||
const NoFilter = require('nofilter'); | ||
const {MT, SYMS} = require('./constants'); | ||
@@ -12,3 +12,3 @@ /** | ||
* | ||
* @typedef {string|Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray | ||
* @typedef {string|Buffer|ArrayBuffer|ArrayBufferView | ||
* |DataView|stream.Readable} BufferLike | ||
@@ -53,9 +53,9 @@ */ | ||
case 'function': | ||
return {options: {}, cb: /** @type {diagnoseCallback} */ (opts)} | ||
return {options: {}, cb: /** @type {diagnoseCallback} */ (opts)}; | ||
case 'string': | ||
return {options: {encoding: /** @type {BufferEncoding} */ (opts)}, cb} | ||
return {options: {encoding: /** @type {BufferEncoding} */ (opts)}, cb}; | ||
case 'object': | ||
return {options: opts || {}, cb} | ||
return {options: opts || {}, cb}; | ||
default: | ||
throw new TypeError('Unknown option type') | ||
throw new TypeError('Unknown option type'); | ||
} | ||
@@ -86,3 +86,3 @@ } | ||
...superOpts | ||
} = options | ||
} = options; | ||
super({ | ||
@@ -92,7 +92,7 @@ ...superOpts, | ||
writableObjectMode: false, | ||
}) | ||
}); | ||
this.float_bytes = -1 | ||
this.separator = separator | ||
this.stream_errors = stream_errors | ||
this.float_bytes = -1; | ||
this.separator = separator; | ||
this.stream_errors = stream_errors; | ||
this.parser = new Decoder({ | ||
@@ -103,9 +103,9 @@ tags, | ||
encoding, | ||
}) | ||
this.parser.on('more-bytes', this._on_more.bind(this)) | ||
this.parser.on('value', this._on_value.bind(this)) | ||
this.parser.on('start', this._on_start.bind(this)) | ||
this.parser.on('stop', this._on_stop.bind(this)) | ||
this.parser.on('data', this._on_data.bind(this)) | ||
this.parser.on('error', this._on_error.bind(this)) | ||
}); | ||
this.parser.on('more-bytes', this._on_more.bind(this)); | ||
this.parser.on('value', this._on_value.bind(this)); | ||
this.parser.on('start', this._on_start.bind(this)); | ||
this.parser.on('stop', this._on_stop.bind(this)); | ||
this.parser.on('data', this._on_data.bind(this)); | ||
this.parser.on('error', this._on_error.bind(this)); | ||
} | ||
@@ -122,3 +122,3 @@ | ||
_transform(fresh, encoding, cb) { | ||
this.parser.write(fresh, encoding, cb) | ||
this.parser.write(fresh, encoding, cb); | ||
} | ||
@@ -136,8 +136,8 @@ | ||
if (er) { | ||
this._on_error(er) | ||
this._on_error(er); | ||
} | ||
return cb() | ||
return cb(); | ||
} | ||
return cb(er) | ||
}) | ||
return cb(er); | ||
}); | ||
} | ||
@@ -157,22 +157,22 @@ | ||
if (input == null) { | ||
throw new TypeError('input required') | ||
throw new TypeError('input required'); | ||
} | ||
({options, cb} = normalizeOptions(options, cb)) | ||
const {encoding = 'hex', ...opts} = options | ||
({options, cb} = normalizeOptions(options, cb)); | ||
const {encoding = 'hex', ...opts} = options; | ||
const bs = new NoFilter() | ||
const d = new Diagnose(opts) | ||
let p = null | ||
const bs = new NoFilter(); | ||
const d = new Diagnose(opts); | ||
let p = null; | ||
if (typeof cb === 'function') { | ||
d.on('end', () => cb(null, bs.toString('utf8'))) | ||
d.on('error', cb) | ||
d.on('end', () => cb(null, bs.toString('utf8'))); | ||
d.on('error', cb); | ||
} else { | ||
p = new Promise((resolve, reject) => { | ||
d.on('end', () => resolve(bs.toString('utf8'))) | ||
d.on('error', reject) | ||
}) | ||
d.on('end', () => resolve(bs.toString('utf8'))); | ||
d.on('error', reject); | ||
}); | ||
} | ||
d.pipe(bs) | ||
utils.guessEncoding(input, encoding).pipe(d) | ||
return p | ||
d.pipe(bs); | ||
utils.guessEncoding(input, encoding).pipe(d); | ||
return p; | ||
} | ||
@@ -185,5 +185,5 @@ | ||
if (this.stream_errors) { | ||
this.push(er.toString()) | ||
this.push(er.toString()); | ||
} else { | ||
this.emit('error', er) | ||
this.emit('error', er); | ||
} | ||
@@ -193,3 +193,3 @@ } | ||
/** @private */ | ||
_on_more(mt, len, parent_mt, pos) { | ||
_on_more(mt, len, _parent_mt, _pos) { | ||
if (mt === MT.SIMPLE_FLOAT) { | ||
@@ -200,3 +200,3 @@ this.float_bytes = { | ||
8: 3, | ||
}[len] | ||
}[len]; | ||
} | ||
@@ -212,11 +212,11 @@ } | ||
if (pos > 0) { | ||
this.push(', ') | ||
this.push(', '); | ||
} | ||
break | ||
break; | ||
case MT.MAP: | ||
if (pos > 0) { | ||
if (pos % 2) { | ||
this.push(': ') | ||
this.push(': '); | ||
} else { | ||
this.push(', ') | ||
this.push(', '); | ||
} | ||
@@ -230,8 +230,8 @@ } | ||
if (val === SYMS.BREAK) { | ||
return | ||
return; | ||
} | ||
this._fore(parent_mt, pos) | ||
const fb = this.float_bytes | ||
this.float_bytes = -1 | ||
this.push(utils.cborValueToString(val, fb)) | ||
this._fore(parent_mt, pos); | ||
const fb = this.float_bytes; | ||
this.float_bytes = -1; | ||
this.push(utils.cborValueToString(val, fb)); | ||
} | ||
@@ -241,20 +241,20 @@ | ||
_on_start(mt, tag, parent_mt, pos) { | ||
this._fore(parent_mt, pos) | ||
this._fore(parent_mt, pos); | ||
switch (mt) { | ||
case MT.TAG: | ||
this.push(`${tag}(`) | ||
break | ||
this.push(`${tag}(`); | ||
break; | ||
case MT.ARRAY: | ||
this.push('[') | ||
break | ||
this.push('['); | ||
break; | ||
case MT.MAP: | ||
this.push('{') | ||
break | ||
this.push('{'); | ||
break; | ||
case MT.BYTE_STRING: | ||
case MT.UTF8_STRING: | ||
this.push('(') | ||
break | ||
this.push('('); | ||
break; | ||
} | ||
if (tag === SYMS.STREAM) { | ||
this.push('_ ') | ||
this.push('_ '); | ||
} | ||
@@ -267,14 +267,14 @@ } | ||
case MT.TAG: | ||
this.push(')') | ||
break | ||
this.push(')'); | ||
break; | ||
case MT.ARRAY: | ||
this.push(']') | ||
break | ||
this.push(']'); | ||
break; | ||
case MT.MAP: | ||
this.push('}') | ||
break | ||
this.push('}'); | ||
break; | ||
case MT.BYTE_STRING: | ||
case MT.UTF8_STRING: | ||
this.push(')') | ||
break | ||
this.push(')'); | ||
break; | ||
} | ||
@@ -285,6 +285,6 @@ } | ||
_on_data() { | ||
this.push(this.separator) | ||
this.push(this.separator); | ||
} | ||
} | ||
module.exports = Diagnose | ||
module.exports = Diagnose; |
@@ -1,25 +0,25 @@ | ||
'use strict' | ||
'use strict'; | ||
const stream = require('stream') | ||
const NoFilter = require('nofilter') | ||
const utils = require('./utils') | ||
const constants = require('./constants') | ||
const stream = require('stream'); | ||
const NoFilter = require('nofilter'); | ||
const utils = require('./utils'); | ||
const constants = require('./constants'); | ||
const { | ||
MT, NUMBYTES, SHIFT32, SIMPLE, SYMS, TAG, BI, | ||
} = constants | ||
const {Buffer} = require('buffer') | ||
} = constants; | ||
const {Buffer} = require('buffer'); | ||
const HALF = (MT.SIMPLE_FLOAT << 5) | NUMBYTES.TWO | ||
const FLOAT = (MT.SIMPLE_FLOAT << 5) | NUMBYTES.FOUR | ||
const DOUBLE = (MT.SIMPLE_FLOAT << 5) | NUMBYTES.EIGHT | ||
const TRUE = (MT.SIMPLE_FLOAT << 5) | SIMPLE.TRUE | ||
const FALSE = (MT.SIMPLE_FLOAT << 5) | SIMPLE.FALSE | ||
const UNDEFINED = (MT.SIMPLE_FLOAT << 5) | SIMPLE.UNDEFINED | ||
const NULL = (MT.SIMPLE_FLOAT << 5) | SIMPLE.NULL | ||
const HALF = (MT.SIMPLE_FLOAT << 5) | NUMBYTES.TWO; | ||
const FLOAT = (MT.SIMPLE_FLOAT << 5) | NUMBYTES.FOUR; | ||
const DOUBLE = (MT.SIMPLE_FLOAT << 5) | NUMBYTES.EIGHT; | ||
const TRUE = (MT.SIMPLE_FLOAT << 5) | SIMPLE.TRUE; | ||
const FALSE = (MT.SIMPLE_FLOAT << 5) | SIMPLE.FALSE; | ||
const UNDEFINED = (MT.SIMPLE_FLOAT << 5) | SIMPLE.UNDEFINED; | ||
const NULL = (MT.SIMPLE_FLOAT << 5) | SIMPLE.NULL; | ||
const BREAK = Buffer.from([0xff]) | ||
const BUF_NAN = Buffer.from('f97e00', 'hex') | ||
const BUF_INF_NEG = Buffer.from('f9fc00', 'hex') | ||
const BUF_INF_POS = Buffer.from('f97c00', 'hex') | ||
const BUF_NEG_ZERO = Buffer.from('f98000', 'hex') | ||
const BREAK = Buffer.from([0xff]); | ||
const BUF_NAN = Buffer.from('f97e00', 'hex'); | ||
const BUF_INF_NEG = Buffer.from('f9fc00', 'hex'); | ||
const BUF_INF_POS = Buffer.from('f97c00', 'hex'); | ||
const BUF_NEG_ZERO = Buffer.from('f98000', 'hex'); | ||
@@ -37,3 +37,2 @@ /** | ||
/* eslint-disable jsdoc/check-types */ | ||
/** | ||
@@ -44,3 +43,2 @@ * A mapping from tag number to a tag decoding function. | ||
*/ | ||
/* eslint-enable jsdoc/check-types */ | ||
@@ -51,3 +49,3 @@ /** | ||
*/ | ||
const SEMANTIC_TYPES = {} | ||
const SEMANTIC_TYPES = {}; | ||
@@ -58,3 +56,3 @@ /** | ||
*/ | ||
let current_SEMANTIC_TYPES = {} | ||
let current_SEMANTIC_TYPES = {}; | ||
@@ -69,16 +67,16 @@ /** | ||
if (!str) { | ||
return 'number' | ||
return 'number'; | ||
} | ||
switch (str.toLowerCase()) { | ||
case 'number': | ||
return 'number' | ||
return 'number'; | ||
case 'float': | ||
return 'float' | ||
return 'float'; | ||
case 'int': | ||
case 'integer': | ||
return 'int' | ||
return 'int'; | ||
case 'string': | ||
return 'string' | ||
return 'string'; | ||
} | ||
throw new TypeError(`dateType invalid, got "${str}"`) | ||
throw new TypeError(`dateType invalid, got "${str}"`); | ||
} | ||
@@ -157,3 +155,3 @@ | ||
...superOpts | ||
} = options | ||
} = options; | ||
@@ -164,32 +162,32 @@ super({ | ||
writableObjectMode: true, | ||
}) | ||
}); | ||
this.canonical = canonical | ||
this.encodeUndefined = encodeUndefined | ||
this.disallowUndefinedKeys = disallowUndefinedKeys | ||
this.dateType = parseDateType(dateType) | ||
this.collapseBigIntegers = this.canonical ? true : collapseBigIntegers | ||
this.canonical = canonical; | ||
this.encodeUndefined = encodeUndefined; | ||
this.disallowUndefinedKeys = disallowUndefinedKeys; | ||
this.dateType = parseDateType(dateType); | ||
this.collapseBigIntegers = this.canonical ? true : collapseBigIntegers; | ||
/** @type {WeakSet?} */ | ||
this.detectLoops = undefined | ||
this.detectLoops = undefined; | ||
if (typeof detectLoops === 'boolean') { | ||
if (detectLoops) { | ||
this.detectLoops = new WeakSet() | ||
this.detectLoops = new WeakSet(); | ||
} | ||
} else if (detectLoops instanceof WeakSet) { | ||
this.detectLoops = detectLoops | ||
this.detectLoops = detectLoops; | ||
} else { | ||
throw new TypeError('detectLoops must be boolean or WeakSet') | ||
throw new TypeError('detectLoops must be boolean or WeakSet'); | ||
} | ||
this.omitUndefinedProperties = omitUndefinedProperties | ||
this.omitUndefinedProperties = omitUndefinedProperties; | ||
this.semanticTypes = {...Encoder.SEMANTIC_TYPES} | ||
this.semanticTypes = {...Encoder.SEMANTIC_TYPES}; | ||
if (Array.isArray(genTypes)) { | ||
for (let i = 0, len = genTypes.length; i < len; i += 2) { | ||
this.addSemanticType(genTypes[i], genTypes[i + 1]) | ||
this.addSemanticType(genTypes[i], genTypes[i + 1]); | ||
} | ||
} else { | ||
for (const [k, v] of Object.entries(genTypes)) { | ||
this.addSemanticType(k, v) | ||
this.addSemanticType(k, v); | ||
} | ||
@@ -203,10 +201,10 @@ } | ||
* @param {any} fresh Buffer to transcode. | ||
* @param {BufferEncoding} encoding Name of encoding. | ||
* @param {BufferEncoding} _encoding Name of encoding. | ||
* @param {stream.TransformCallback} cb Callback when done. | ||
* @ignore | ||
*/ | ||
_transform(fresh, encoding, cb) { | ||
const ret = this.pushAny(fresh) | ||
_transform(fresh, _encoding, cb) { | ||
const ret = this.pushAny(fresh); | ||
// Old transformers might not return bool. undefined !== false | ||
cb((ret === false) ? new Error('Push Error') : undefined) | ||
cb((ret === false) ? new Error('Push Error') : undefined); | ||
} | ||
@@ -222,3 +220,3 @@ | ||
_flush(cb) { | ||
cb() | ||
cb(); | ||
} | ||
@@ -232,5 +230,5 @@ | ||
_pushUInt8(val) { | ||
const b = Buffer.allocUnsafe(1) | ||
b.writeUInt8(val, 0) | ||
return this.push(b) | ||
const b = Buffer.allocUnsafe(1); | ||
b.writeUInt8(val, 0); | ||
return this.push(b); | ||
} | ||
@@ -244,5 +242,5 @@ | ||
_pushUInt16BE(val) { | ||
const b = Buffer.allocUnsafe(2) | ||
b.writeUInt16BE(val, 0) | ||
return this.push(b) | ||
const b = Buffer.allocUnsafe(2); | ||
b.writeUInt16BE(val, 0); | ||
return this.push(b); | ||
} | ||
@@ -256,5 +254,5 @@ | ||
_pushUInt32BE(val) { | ||
const b = Buffer.allocUnsafe(4) | ||
b.writeUInt32BE(val, 0) | ||
return this.push(b) | ||
const b = Buffer.allocUnsafe(4); | ||
b.writeUInt32BE(val, 0); | ||
return this.push(b); | ||
} | ||
@@ -268,5 +266,5 @@ | ||
_pushFloatBE(val) { | ||
const b = Buffer.allocUnsafe(4) | ||
b.writeFloatBE(val, 0) | ||
return this.push(b) | ||
const b = Buffer.allocUnsafe(4); | ||
b.writeFloatBE(val, 0); | ||
return this.push(b); | ||
} | ||
@@ -280,5 +278,5 @@ | ||
_pushDoubleBE(val) { | ||
const b = Buffer.allocUnsafe(8) | ||
b.writeDoubleBE(val, 0) | ||
return this.push(b) | ||
const b = Buffer.allocUnsafe(8); | ||
b.writeDoubleBE(val, 0); | ||
return this.push(b); | ||
} | ||
@@ -291,3 +289,3 @@ | ||
_pushNaN() { | ||
return this.push(BUF_NAN) | ||
return this.push(BUF_NAN); | ||
} | ||
@@ -301,4 +299,4 @@ | ||
_pushInfinity(obj) { | ||
const half = (obj < 0) ? BUF_INF_NEG : BUF_INF_POS | ||
return this.push(half) | ||
const half = (obj < 0) ? BUF_INF_NEG : BUF_INF_POS; | ||
return this.push(half); | ||
} | ||
@@ -328,14 +326,14 @@ | ||
// which seems pretty much backwards to me. | ||
const b2 = Buffer.allocUnsafe(2) | ||
const b2 = Buffer.allocUnsafe(2); | ||
if (utils.writeHalf(b2, obj)) { | ||
// I have convinced myself that there are no cases where writeHalf | ||
// will return true but `utils.parseHalf(b2) !== obj)` | ||
return this._pushUInt8(HALF) && this.push(b2) | ||
return this._pushUInt8(HALF) && this.push(b2); | ||
} | ||
} | ||
if (Math.fround(obj) === obj) { | ||
return this._pushUInt8(FLOAT) && this._pushFloatBE(obj) | ||
return this._pushUInt8(FLOAT) && this._pushFloatBE(obj); | ||
} | ||
return this._pushUInt8(DOUBLE) && this._pushDoubleBE(obj) | ||
return this._pushUInt8(DOUBLE) && this._pushDoubleBE(obj); | ||
} | ||
@@ -360,20 +358,20 @@ | ||
_pushInt(obj, mt, orig) { | ||
const m = mt << 5 | ||
const m = mt << 5; | ||
if (obj < 24) { | ||
return this._pushUInt8(m | obj) | ||
return this._pushUInt8(m | obj); | ||
} | ||
if (obj <= 0xff) { | ||
return this._pushUInt8(m | NUMBYTES.ONE) && this._pushUInt8(obj) | ||
return this._pushUInt8(m | NUMBYTES.ONE) && this._pushUInt8(obj); | ||
} | ||
if (obj <= 0xffff) { | ||
return this._pushUInt8(m | NUMBYTES.TWO) && this._pushUInt16BE(obj) | ||
return this._pushUInt8(m | NUMBYTES.TWO) && this._pushUInt16BE(obj); | ||
} | ||
if (obj <= 0xffffffff) { | ||
return this._pushUInt8(m | NUMBYTES.FOUR) && this._pushUInt32BE(obj) | ||
return this._pushUInt8(m | NUMBYTES.FOUR) && this._pushUInt32BE(obj); | ||
} | ||
let max = Number.MAX_SAFE_INTEGER | ||
let max = Number.MAX_SAFE_INTEGER; | ||
if (mt === MT.NEG_INT) { | ||
// Special case for Number.MIN_SAFE_INTEGER - 1 | ||
max-- | ||
max--; | ||
} | ||
@@ -383,8 +381,8 @@ if (obj <= max) { | ||
this._pushUInt32BE(Math.floor(obj / SHIFT32)) && | ||
this._pushUInt32BE(obj % SHIFT32) | ||
this._pushUInt32BE(obj % SHIFT32); | ||
} | ||
if (mt === MT.NEG_INT) { | ||
return this._pushFloat(orig) | ||
return this._pushFloat(orig); | ||
} | ||
return this._pushFloat(obj) | ||
return this._pushFloat(obj); | ||
} | ||
@@ -402,9 +400,9 @@ | ||
if (Object.is(obj, -0)) { | ||
return this.push(BUF_NEG_ZERO) | ||
return this.push(BUF_NEG_ZERO); | ||
} | ||
if (obj < 0) { | ||
return this._pushInt(-obj - 1, MT.NEG_INT, obj) | ||
return this._pushInt(-obj - 1, MT.NEG_INT, obj); | ||
} | ||
return this._pushInt(obj, MT.POS_INT) | ||
return this._pushInt(obj, MT.POS_INT); | ||
} | ||
@@ -419,11 +417,11 @@ | ||
if (isNaN(obj)) { | ||
return this._pushNaN() | ||
return this._pushNaN(); | ||
} | ||
if (!isFinite(obj)) { | ||
return this._pushInfinity(obj) | ||
return this._pushInfinity(obj); | ||
} | ||
if (Math.round(obj) === obj) { | ||
return this._pushIntNum(obj) | ||
return this._pushIntNum(obj); | ||
} | ||
return this._pushFloat(obj) | ||
return this._pushFloat(obj); | ||
} | ||
@@ -437,4 +435,4 @@ | ||
_pushString(obj) { | ||
const len = Buffer.byteLength(obj, 'utf8') | ||
return this._pushInt(len, MT.UTF8_STRING) && this.push(obj, 'utf8') | ||
const len = Buffer.byteLength(obj, 'utf8'); | ||
return this._pushInt(len, MT.UTF8_STRING) && this.push(obj, 'utf8'); | ||
} | ||
@@ -448,3 +446,3 @@ | ||
_pushBoolean(obj) { | ||
return this._pushUInt8(obj ? TRUE : FALSE) | ||
return this._pushUInt8(obj ? TRUE : FALSE); | ||
} | ||
@@ -460,22 +458,22 @@ | ||
case 'undefined': | ||
return this._pushUInt8(UNDEFINED) | ||
return this._pushUInt8(UNDEFINED); | ||
case 'function': | ||
return this.pushAny(this.encodeUndefined(obj)) | ||
return this.pushAny(this.encodeUndefined(obj)); | ||
case 'object': { | ||
const buf = utils.bufferishToBuffer(this.encodeUndefined) | ||
const buf = utils.bufferishToBuffer(this.encodeUndefined); | ||
if (buf) { | ||
return this.push(buf) | ||
return this.push(buf); | ||
} | ||
} | ||
} | ||
return this.pushAny(this.encodeUndefined) | ||
return this.pushAny(this.encodeUndefined); | ||
} | ||
/** | ||
* @param {null} obj Ignored. | ||
* @param {null} _obj Ignored. | ||
* @returns {boolean} True on success. | ||
* @ignore | ||
*/ | ||
_pushNull(obj) { | ||
return this._pushUInt8(NULL) | ||
_pushNull(_obj) { | ||
return this._pushUInt8(NULL); | ||
} | ||
@@ -489,3 +487,3 @@ | ||
_pushTag(tag) { | ||
return this._pushInt(tag, MT.TAG) | ||
return this._pushInt(tag, MT.TAG); | ||
} | ||
@@ -499,9 +497,9 @@ | ||
_pushJSBigint(obj) { | ||
let m = MT.POS_INT | ||
let tag = TAG.POS_BIGINT | ||
let m = MT.POS_INT; | ||
let tag = TAG.POS_BIGINT; | ||
// BigInt doesn't have -0 | ||
if (obj < 0) { | ||
obj = -obj + BI.MINUS_ONE | ||
m = MT.NEG_INT | ||
tag = TAG.NEG_BIGINT | ||
obj = -obj + BI.MINUS_ONE; | ||
m = MT.NEG_INT; | ||
tag = TAG.NEG_BIGINT; | ||
} | ||
@@ -513,15 +511,15 @@ | ||
if (obj <= 0xffffffff) { | ||
return this._pushInt(Number(obj), m) | ||
return this._pushInt(Number(obj), m); | ||
} | ||
return this._pushUInt8((m << 5) | NUMBYTES.EIGHT) && | ||
this._pushUInt32BE(Number(obj / BI.SHIFT32)) && | ||
this._pushUInt32BE(Number(obj % BI.SHIFT32)) | ||
this._pushUInt32BE(Number(obj % BI.SHIFT32)); | ||
} | ||
let str = obj.toString(16) | ||
let str = obj.toString(16); | ||
if (str.length % 2) { | ||
str = `0${str}` | ||
str = `0${str}`; | ||
} | ||
const buf = Buffer.from(str, 'hex') | ||
return this._pushTag(tag) && Encoder._pushBuffer(this, buf) | ||
const buf = Buffer.from(str, 'hex'); | ||
return this._pushTag(tag) && Encoder._pushBuffer(this, buf); | ||
} | ||
@@ -538,3 +536,3 @@ | ||
if (!obj) { | ||
return this._pushNull(obj) | ||
return this._pushNull(obj); | ||
} | ||
@@ -545,3 +543,3 @@ opts = { | ||
...opts, | ||
} | ||
}; | ||
if (!opts.indefinite) { | ||
@@ -553,5 +551,5 @@ // This will only happen the first time through for indefinite encoding | ||
Loop detected while CBOR encoding. | ||
Call removeLoopDetectors before resuming.`) | ||
Call removeLoopDetectors before resuming.`); | ||
} else { | ||
this.detectLoops.add(obj) | ||
this.detectLoops.add(obj); | ||
} | ||
@@ -561,17 +559,17 @@ } | ||
if (!opts.skipTypes) { | ||
const f = obj.encodeCBOR | ||
const f = obj.encodeCBOR; | ||
if (typeof f === 'function') { | ||
return f.call(obj, this) | ||
return f.call(obj, this); | ||
} | ||
const converter = this.semanticTypes[obj.constructor.name] | ||
const converter = this.semanticTypes[obj.constructor.name]; | ||
if (converter) { | ||
return converter.call(obj, this, obj) | ||
return converter.call(obj, this, obj); | ||
} | ||
} | ||
const keys = Object.keys(obj).filter(k => { | ||
const tv = typeof obj[k] | ||
const tv = typeof obj[k]; | ||
return (tv !== 'function') && | ||
(!this.omitUndefinedProperties || (tv !== 'undefined')) | ||
}) | ||
const cbor_keys = {} | ||
(!this.omitUndefinedProperties || (tv !== 'undefined')); | ||
}); | ||
const cbor_keys = {}; | ||
if (this.canonical) { | ||
@@ -584,27 +582,27 @@ // Note: this can't be a normal sort, because 'b' needs to sort before | ||
// to encode more than once | ||
const a_cbor = cbor_keys[a] || (cbor_keys[a] = Encoder.encode(a)) | ||
const b_cbor = cbor_keys[b] || (cbor_keys[b] = Encoder.encode(b)) | ||
const a_cbor = cbor_keys[a] || (cbor_keys[a] = Encoder.encode(a)); | ||
const b_cbor = cbor_keys[b] || (cbor_keys[b] = Encoder.encode(b)); | ||
return a_cbor.compare(b_cbor) | ||
}) | ||
return a_cbor.compare(b_cbor); | ||
}); | ||
} | ||
if (opts.indefinite) { | ||
if (!this._pushUInt8((MT.MAP << 5) | NUMBYTES.INDEFINITE)) { | ||
return false | ||
return false; | ||
} | ||
} else if (!this._pushInt(keys.length, MT.MAP)) { | ||
return false | ||
return false; | ||
} | ||
let ck = null | ||
let ck = null; | ||
for (let j = 0, len2 = keys.length; j < len2; j++) { | ||
const k = keys[j] | ||
const k = keys[j]; | ||
if (this.canonical && ((ck = cbor_keys[k]))) { | ||
if (!this.push(ck)) { // Already a Buffer | ||
return false | ||
return false; | ||
} | ||
} else if (!this._pushString(k)) { | ||
return false | ||
return false; | ||
} | ||
if (!this.pushAny(obj[k])) { | ||
return false | ||
return false; | ||
} | ||
@@ -614,8 +612,8 @@ } | ||
if (!this.push(BREAK)) { | ||
return false | ||
return false; | ||
} | ||
} else if (this.detectLoops) { | ||
this.detectLoops.delete(obj) | ||
this.detectLoops.delete(obj); | ||
} | ||
return true | ||
return true; | ||
} | ||
@@ -629,9 +627,9 @@ | ||
_encodeAll(objs) { | ||
const bs = new NoFilter({highWaterMark: this.readableHighWaterMark}) | ||
this.pipe(bs) | ||
const bs = new NoFilter({highWaterMark: this.readableHighWaterMark}); | ||
this.pipe(bs); | ||
for (const o of objs) { | ||
this.pushAny(o) | ||
this.pushAny(o); | ||
} | ||
this.end() | ||
return bs.read() | ||
this.end(); | ||
return bs.read(); | ||
} | ||
@@ -650,14 +648,14 @@ | ||
addSemanticType(type, fun) { | ||
const typeName = (typeof type === 'string') ? type : type.name | ||
const old = this.semanticTypes[typeName] | ||
const typeName = (typeof type === 'string') ? type : type.name; | ||
const old = this.semanticTypes[typeName]; | ||
if (fun) { | ||
if (typeof fun !== 'function') { | ||
throw new TypeError('fun must be of type function') | ||
throw new TypeError('fun must be of type function'); | ||
} | ||
this.semanticTypes[typeName] = fun | ||
this.semanticTypes[typeName] = fun; | ||
} else if (old) { | ||
delete this.semanticTypes[typeName] | ||
delete this.semanticTypes[typeName]; | ||
} | ||
return old | ||
return old; | ||
} | ||
@@ -675,22 +673,22 @@ | ||
case 'number': | ||
return this._pushNumber(obj) | ||
return this._pushNumber(obj); | ||
case 'bigint': | ||
return this._pushJSBigint(obj) | ||
return this._pushJSBigint(obj); | ||
case 'string': | ||
return this._pushString(obj) | ||
return this._pushString(obj); | ||
case 'boolean': | ||
return this._pushBoolean(obj) | ||
return this._pushBoolean(obj); | ||
case 'undefined': | ||
return this._pushUndefined(obj) | ||
return this._pushUndefined(obj); | ||
case 'object': | ||
return this._pushObject(obj) | ||
return this._pushObject(obj); | ||
case 'symbol': | ||
switch (obj) { | ||
case SYMS.NULL: | ||
return this._pushNull(null) | ||
return this._pushNull(null); | ||
case SYMS.UNDEFINED: | ||
return this._pushUndefined(undefined) | ||
return this._pushUndefined(undefined); | ||
// TODO: Add pluggable support for other symbols | ||
default: | ||
throw new TypeError(`Unknown symbol: ${obj.toString()}`) | ||
throw new TypeError(`Unknown symbol: ${obj.toString()}`); | ||
} | ||
@@ -700,3 +698,3 @@ default: | ||
`Unknown type: ${typeof obj}, ${(typeof obj.toString === 'function') ? obj.toString() : ''}` | ||
) | ||
); | ||
} | ||
@@ -718,14 +716,14 @@ } | ||
...opts, | ||
} | ||
const len = obj.length | ||
}; | ||
const len = obj.length; | ||
if (opts.indefinite) { | ||
if (!gen._pushUInt8((MT.ARRAY << 5) | NUMBYTES.INDEFINITE)) { | ||
return false | ||
return false; | ||
} | ||
} else if (!gen._pushInt(len, MT.ARRAY)) { | ||
return false | ||
return false; | ||
} | ||
for (let j = 0; j < len; j++) { | ||
if (!gen.pushAny(obj[j])) { | ||
return false | ||
return false; | ||
} | ||
@@ -735,6 +733,6 @@ } | ||
if (!gen.push(BREAK)) { | ||
return false | ||
return false; | ||
} | ||
} | ||
return true | ||
return true; | ||
} | ||
@@ -749,6 +747,6 @@ | ||
if (!this.detectLoops) { | ||
return false | ||
return false; | ||
} | ||
this.detectLoops = new WeakSet() | ||
return true | ||
this.detectLoops = new WeakSet(); | ||
return true; | ||
} | ||
@@ -766,10 +764,10 @@ | ||
return gen._pushTag(TAG.DATE_STRING) && | ||
gen._pushString(obj.toISOString()) | ||
gen._pushString(obj.toISOString()); | ||
case 'int': | ||
return gen._pushTag(TAG.DATE_EPOCH) && | ||
gen._pushIntNum(Math.round(obj.getTime() / 1000)) | ||
gen._pushIntNum(Math.round(obj.getTime() / 1000)); | ||
case 'float': | ||
// Force float | ||
return gen._pushTag(TAG.DATE_EPOCH) && | ||
gen._pushFloat(obj.getTime() / 1000) | ||
gen._pushFloat(obj.getTime() / 1000); | ||
case 'number': | ||
@@ -780,3 +778,3 @@ default: | ||
return gen._pushTag(TAG.DATE_EPOCH) && | ||
gen.pushAny(obj.getTime() / 1000) | ||
gen.pushAny(obj.getTime() / 1000); | ||
} | ||
@@ -792,3 +790,3 @@ } | ||
static _pushBuffer(gen, obj) { | ||
return gen._pushInt(obj.length, MT.BYTE_STRING) && gen.push(obj) | ||
return gen._pushInt(obj.length, MT.BYTE_STRING) && gen.push(obj); | ||
} | ||
@@ -803,3 +801,3 @@ | ||
static _pushNoFilter(gen, obj) { | ||
return Encoder._pushBuffer(gen, /** @type {Buffer} */ (obj.slice())) | ||
return Encoder._pushBuffer(gen, /** @type {Buffer} */ (obj.slice())); | ||
} | ||
@@ -814,3 +812,3 @@ | ||
static _pushRegexp(gen, obj) { | ||
return gen._pushTag(TAG.REGEXP) && gen.pushAny(obj.source) | ||
return gen._pushTag(TAG.REGEXP) && gen.pushAny(obj.source); | ||
} | ||
@@ -826,13 +824,13 @@ | ||
if (!gen._pushTag(TAG.SET)) { | ||
return false | ||
return false; | ||
} | ||
if (!gen._pushInt(obj.size, MT.ARRAY)) { | ||
return false | ||
return false; | ||
} | ||
for (const x of obj) { | ||
if (!gen.pushAny(x)) { | ||
return false | ||
return false; | ||
} | ||
} | ||
return true | ||
return true; | ||
} | ||
@@ -847,3 +845,3 @@ | ||
static _pushURL(gen, obj) { | ||
return gen._pushTag(TAG.URI) && gen.pushAny(obj.toString()) | ||
return gen._pushTag(TAG.URI) && gen.pushAny(obj.toString()); | ||
} | ||
@@ -858,3 +856,3 @@ | ||
static _pushBoxed(gen, obj) { | ||
return gen.pushAny(obj.valueOf()) | ||
return gen.pushAny(obj.valueOf()); | ||
} | ||
@@ -873,13 +871,13 @@ | ||
...opts, | ||
} | ||
let entries = [...obj.entries()] | ||
}; | ||
let entries = [...obj.entries()]; | ||
if (gen.omitUndefinedProperties) { | ||
entries = entries.filter(([k, v]) => v !== undefined) | ||
entries = entries.filter(([_k, v]) => v !== undefined); | ||
} | ||
if (opts.indefinite) { | ||
if (!gen._pushUInt8((MT.MAP << 5) | NUMBYTES.INDEFINITE)) { | ||
return false | ||
return false; | ||
} | ||
} else if (!gen._pushInt(entries.length, MT.MAP)) { | ||
return false | ||
return false; | ||
} | ||
@@ -898,19 +896,19 @@ // Memoizing the cbor only helps in certain cases, and hurts in most | ||
collapseBigIntegers: gen.collapseBigIntegers, | ||
}) | ||
const bs = new NoFilter({highWaterMark: gen.readableHighWaterMark}) | ||
enc.pipe(bs) | ||
}); | ||
const bs = new NoFilter({highWaterMark: gen.readableHighWaterMark}); | ||
enc.pipe(bs); | ||
entries.sort(([a], [b]) => { | ||
// Both a and b are the keys | ||
enc.pushAny(a) | ||
const a_cbor = bs.read() | ||
enc.pushAny(b) | ||
const b_cbor = bs.read() | ||
return a_cbor.compare(b_cbor) | ||
}) | ||
enc.pushAny(a); | ||
const a_cbor = bs.read(); | ||
enc.pushAny(b); | ||
const b_cbor = bs.read(); | ||
return a_cbor.compare(b_cbor); | ||
}); | ||
for (const [k, v] of entries) { | ||
if (gen.disallowUndefinedKeys && (typeof k === 'undefined')) { | ||
throw new Error('Invalid Map key: undefined') | ||
throw new Error('Invalid Map key: undefined'); | ||
} | ||
if (!(gen.pushAny(k) && gen.pushAny(v))) { | ||
return false | ||
return false; | ||
} | ||
@@ -921,6 +919,6 @@ } | ||
if (gen.disallowUndefinedKeys && (typeof k === 'undefined')) { | ||
throw new Error('Invalid Map key: undefined') | ||
throw new Error('Invalid Map key: undefined'); | ||
} | ||
if (!(gen.pushAny(k) && gen.pushAny(v))) { | ||
return false | ||
return false; | ||
} | ||
@@ -931,6 +929,6 @@ } | ||
if (!gen.push(BREAK)) { | ||
return false | ||
return false; | ||
} | ||
} | ||
return true | ||
return true; | ||
} | ||
@@ -947,14 +945,14 @@ | ||
let typ = 0b01000000 | ||
let sz = obj.BYTES_PER_ELEMENT | ||
const {name} = obj.constructor | ||
let typ = 0b01000000; | ||
let sz = obj.BYTES_PER_ELEMENT; | ||
const {name} = obj.constructor; | ||
if (name.startsWith('Float')) { | ||
typ |= 0b00010000 | ||
sz /= 2 | ||
typ |= 0b00010000; | ||
sz /= 2; | ||
} else if (!name.includes('U')) { | ||
typ |= 0b00001000 | ||
typ |= 0b00001000; | ||
} | ||
if (name.includes('Clamped') || ((sz !== 1) && !utils.isBigEndian())) { | ||
typ |= 0b00000100 | ||
typ |= 0b00000100; | ||
} | ||
@@ -966,5 +964,5 @@ typ |= { | ||
8: 0b11, | ||
}[sz] | ||
}[sz]; | ||
if (!gen._pushTag(typ)) { | ||
return false | ||
return false; | ||
} | ||
@@ -974,3 +972,3 @@ return Encoder._pushBuffer( | ||
Buffer.from(obj.buffer, obj.byteOffset, obj.byteLength) | ||
) | ||
); | ||
} | ||
@@ -985,3 +983,3 @@ | ||
static _pushArrayBuffer(gen, obj) { | ||
return Encoder._pushBuffer(gen, Buffer.from(obj)) | ||
return Encoder._pushBuffer(gen, Buffer.from(obj)); | ||
} | ||
@@ -1013,44 +1011,44 @@ | ||
if (this == null) { | ||
throw new Error('No object to encode') | ||
throw new Error('No object to encode'); | ||
} | ||
obj = this | ||
obj = this; | ||
} | ||
// TODO: consider other options | ||
const {chunkSize = 4096} = options | ||
const {chunkSize = 4096} = options; | ||
let ret = true | ||
const objType = typeof obj | ||
let buf = null | ||
let ret = true; | ||
const objType = typeof obj; | ||
let buf = null; | ||
if (objType === 'string') { | ||
// TODO: make sure not to split surrogate pairs at the edges of chunks, | ||
// since such half-surrogates cannot be legally encoded as UTF-8. | ||
ret = ret && gen._pushUInt8((MT.UTF8_STRING << 5) | NUMBYTES.INDEFINITE) | ||
let offset = 0 | ||
ret = ret && gen._pushUInt8((MT.UTF8_STRING << 5) | NUMBYTES.INDEFINITE); | ||
let offset = 0; | ||
while (offset < obj.length) { | ||
const endIndex = offset + chunkSize | ||
ret = ret && gen._pushString(obj.slice(offset, endIndex)) | ||
offset = endIndex | ||
const endIndex = offset + chunkSize; | ||
ret = ret && gen._pushString(obj.slice(offset, endIndex)); | ||
offset = endIndex; | ||
} | ||
ret = ret && gen.push(BREAK) | ||
ret = ret && gen.push(BREAK); | ||
} else if ((buf = utils.bufferishToBuffer(obj))) { | ||
ret = ret && gen._pushUInt8((MT.BYTE_STRING << 5) | NUMBYTES.INDEFINITE) | ||
let offset = 0 | ||
ret = ret && gen._pushUInt8((MT.BYTE_STRING << 5) | NUMBYTES.INDEFINITE); | ||
let offset = 0; | ||
while (offset < buf.length) { | ||
const endIndex = offset + chunkSize | ||
ret = ret && Encoder._pushBuffer(gen, buf.slice(offset, endIndex)) | ||
offset = endIndex | ||
const endIndex = offset + chunkSize; | ||
ret = ret && Encoder._pushBuffer(gen, buf.slice(offset, endIndex)); | ||
offset = endIndex; | ||
} | ||
ret = ret && gen.push(BREAK) | ||
ret = ret && gen.push(BREAK); | ||
} else if (Array.isArray(obj)) { | ||
ret = ret && Encoder.pushArray(gen, obj, { | ||
indefinite: true, | ||
}) | ||
}); | ||
} else if (obj instanceof Map) { | ||
ret = ret && Encoder._pushMap(gen, obj, { | ||
indefinite: true, | ||
}) | ||
}); | ||
} else { | ||
if (objType !== 'object') { | ||
throw new Error('Invalid indefinite encoding') | ||
throw new Error('Invalid indefinite encoding'); | ||
} | ||
@@ -1060,5 +1058,5 @@ ret = ret && gen._pushObject(obj, { | ||
skipTypes: true, | ||
}) | ||
}); | ||
} | ||
return ret | ||
return ret; | ||
} | ||
@@ -1074,3 +1072,3 @@ | ||
static encode(...objs) { | ||
return new Encoder()._encodeAll(objs) | ||
return new Encoder()._encodeAll(objs); | ||
} | ||
@@ -1088,3 +1086,3 @@ | ||
canonical: true, | ||
})._encodeAll(objs) | ||
})._encodeAll(objs); | ||
} | ||
@@ -1098,6 +1096,5 @@ | ||
* @returns {Buffer} The encoded objects. | ||
* @static | ||
*/ | ||
static encodeOne(obj, options) { | ||
return new Encoder(options)._encodeAll([obj]) | ||
return new Encoder(options)._encodeAll([obj]); | ||
} | ||
@@ -1118,10 +1115,10 @@ | ||
return new Promise((resolve, reject) => { | ||
const bufs = [] | ||
const enc = new Encoder(options) | ||
enc.on('data', buf => bufs.push(buf)) | ||
enc.on('error', reject) | ||
enc.on('finish', () => resolve(Buffer.concat(bufs))) | ||
enc.pushAny(obj) | ||
enc.end() | ||
}) | ||
const bufs = []; | ||
const enc = new Encoder(options); | ||
enc.on('data', buf => bufs.push(buf)); | ||
enc.on('error', reject); | ||
enc.on('finish', () => resolve(Buffer.concat(bufs))); | ||
enc.pushAny(obj); | ||
enc.end(); | ||
}); | ||
} | ||
@@ -1135,7 +1132,7 @@ | ||
static get SEMANTIC_TYPES() { | ||
return current_SEMANTIC_TYPES | ||
return current_SEMANTIC_TYPES; | ||
} | ||
static set SEMANTIC_TYPES(val) { | ||
current_SEMANTIC_TYPES = val | ||
current_SEMANTIC_TYPES = val; | ||
} | ||
@@ -1148,3 +1145,3 @@ | ||
static reset() { | ||
Encoder.SEMANTIC_TYPES = {...SEMANTIC_TYPES} | ||
Encoder.SEMANTIC_TYPES = {...SEMANTIC_TYPES}; | ||
} | ||
@@ -1177,13 +1174,13 @@ } | ||
String: Encoder._pushBoxed, | ||
}) | ||
}); | ||
// Safari needs to get better. | ||
if (typeof BigUint64Array !== 'undefined') { | ||
SEMANTIC_TYPES[BigUint64Array.name] = Encoder._pushTypedArray | ||
SEMANTIC_TYPES[BigUint64Array.name] = Encoder._pushTypedArray; | ||
} | ||
if (typeof BigInt64Array !== 'undefined') { | ||
SEMANTIC_TYPES[BigInt64Array.name] = Encoder._pushTypedArray | ||
SEMANTIC_TYPES[BigInt64Array.name] = Encoder._pushTypedArray; | ||
} | ||
Encoder.reset() | ||
module.exports = Encoder | ||
Encoder.reset(); | ||
module.exports = Encoder; |
@@ -1,7 +0,7 @@ | ||
'use strict' | ||
'use strict'; | ||
const {Buffer} = require('buffer') | ||
const encoder = require('./encoder') | ||
const decoder = require('./decoder') | ||
const {MT} = require('./constants') | ||
const {Buffer} = require('buffer'); | ||
const encoder = require('./encoder'); | ||
const decoder = require('./decoder'); | ||
const {MT} = require('./constants'); | ||
@@ -29,3 +29,3 @@ /** | ||
constructor(iterable) { | ||
super(iterable) | ||
super(iterable); | ||
} | ||
@@ -35,5 +35,7 @@ | ||
* @ignore | ||
* @param {unknown} key | ||
* @returns {string} | ||
*/ | ||
static _encode(key) { | ||
return encoder.encodeCanonical(key).toString('base64') | ||
return encoder.encodeCanonical(key).toString('base64'); | ||
} | ||
@@ -43,5 +45,7 @@ | ||
* @ignore | ||
* @param {string} key | ||
* @returns {unknown} | ||
*/ | ||
static _decode(key) { | ||
return decoder.decodeFirstSync(key, 'base64') | ||
return decoder.decodeFirstSync(key, 'base64'); | ||
} | ||
@@ -58,3 +62,3 @@ | ||
get(key) { | ||
return super.get(CborMap._encode(key)) | ||
return super.get(CborMap._encode(key)); | ||
} | ||
@@ -72,3 +76,3 @@ | ||
set(key, val) { | ||
return super.set(CborMap._encode(key), val) | ||
return super.set(CborMap._encode(key), val); | ||
} | ||
@@ -85,3 +89,3 @@ | ||
delete(key) { | ||
return super.delete(CborMap._encode(key)) | ||
return super.delete(CborMap._encode(key)); | ||
} | ||
@@ -99,3 +103,3 @@ | ||
has(key) { | ||
return super.has(CborMap._encode(key)) | ||
return super.has(CborMap._encode(key)); | ||
} | ||
@@ -108,7 +112,7 @@ | ||
* | ||
* @yields {any} The keys of the map. | ||
* @returns {MapIterator<any>} | ||
*/ | ||
*keys() { | ||
for (const k of super.keys()) { | ||
yield CborMap._decode(k) | ||
yield CborMap._decode(k); | ||
} | ||
@@ -126,3 +130,3 @@ } | ||
for (const kv of super.entries()) { | ||
yield [CborMap._decode(kv[0]), kv[1]] | ||
yield [CborMap._decode(kv[0]), kv[1]]; | ||
} | ||
@@ -135,6 +139,6 @@ } | ||
* | ||
* @returns {IterableIterator} Key value pairs. | ||
* @returns {IterableIterator<any>} Key value pairs. | ||
*/ | ||
[Symbol.iterator]() { | ||
return this.entries() | ||
return this.entries(); | ||
} | ||
@@ -146,13 +150,14 @@ | ||
* | ||
* @param {function(any, any, Map): undefined} fun Function to execute for | ||
* each element, which takes a value, a key, and the Map being traversed. | ||
* @param {function(any, any, Map<any,any>): undefined} fun Function to | ||
* execute for each element, which takes a value, a key, and the Map | ||
* being traversed. | ||
* @param {any} thisArg Value to use as this when executing callback. | ||
* @throws {TypeError} Invalid function. | ||
*/ | ||
forEach(fun, thisArg) { | ||
forEach(fun, thisArg = this) { | ||
if (typeof fun !== 'function') { | ||
throw new TypeError('Must be function') | ||
throw new TypeError('Must be function'); | ||
} | ||
for (const kv of super.entries()) { | ||
fun.call(this, kv[1], CborMap._decode(kv[0]), this) | ||
fun.call(thisArg, kv[1], CborMap._decode(kv[0]), this); | ||
} | ||
@@ -164,3 +169,3 @@ } | ||
* | ||
* @param {object} gen The generator to push onto. | ||
* @param {import('./encoder.js')} gen The generator to push onto. | ||
* @returns {boolean} True on success. | ||
@@ -170,11 +175,11 @@ */ | ||
if (!gen._pushInt(this.size, MT.MAP)) { | ||
return false | ||
return false; | ||
} | ||
if (gen.canonical) { | ||
const entries = Array.from(super.entries()) | ||
.map(kv => [Buffer.from(kv[0], 'base64'), kv[1]]) | ||
entries.sort((a, b) => a[0].compare(b[0])) | ||
.map(kv => [Buffer.from(kv[0], 'base64'), kv[1]]); | ||
entries.sort((a, b) => a[0].compare(b[0])); | ||
for (const kv of entries) { | ||
if (!(gen.push(kv[0]) && gen.pushAny(kv[1]))) { | ||
return false | ||
return false; | ||
} | ||
@@ -185,10 +190,10 @@ } | ||
if (!(gen.push(Buffer.from(kv[0], 'base64')) && gen.pushAny(kv[1]))) { | ||
return false | ||
return false; | ||
} | ||
} | ||
} | ||
return true | ||
return true; | ||
} | ||
} | ||
module.exports = CborMap | ||
module.exports = CborMap; |
@@ -1,2 +0,2 @@ | ||
'use strict' | ||
'use strict'; | ||
@@ -11,3 +11,3 @@ /** | ||
constructor() { | ||
this.clear() | ||
this.clear(); | ||
} | ||
@@ -19,5 +19,5 @@ | ||
clear() { | ||
this.map = new WeakMap() | ||
this.count = 0 | ||
this.recording = true | ||
this.map = new WeakMap(); | ||
this.count = 0; | ||
this.recording = true; | ||
} | ||
@@ -29,3 +29,3 @@ | ||
stop() { | ||
this.recording = false | ||
this.recording = false; | ||
} | ||
@@ -45,31 +45,31 @@ | ||
check(obj) { | ||
const val = this.map.get(obj) | ||
const val = this.map.get(obj); | ||
if (val) { | ||
if (val.length > 1) { | ||
if (val[0] || this.recording) { | ||
return val[1] | ||
return val[1]; | ||
} | ||
val[0] = true | ||
return ObjectRecorder.FIRST | ||
val[0] = true; | ||
return ObjectRecorder.FIRST; | ||
} | ||
if (!this.recording) { | ||
return ObjectRecorder.NEVER | ||
return ObjectRecorder.NEVER; | ||
} | ||
val.push(this.count++) | ||
val.push(this.count++); | ||
// Second use while recording | ||
return val[1] | ||
return val[1]; | ||
} | ||
if (!this.recording) { | ||
throw new Error('New object detected when not recording') | ||
throw new Error('New object detected when not recording'); | ||
} | ||
this.map.set(obj, [false]) | ||
this.map.set(obj, [false]); | ||
// First use while recording | ||
return ObjectRecorder.NEVER | ||
return ObjectRecorder.NEVER; | ||
} | ||
} | ||
ObjectRecorder.NEVER = -1 | ||
ObjectRecorder.FIRST = -2 | ||
ObjectRecorder.NEVER = -1; | ||
ObjectRecorder.FIRST = -2; | ||
module.exports = ObjectRecorder | ||
module.exports = ObjectRecorder; |
@@ -1,6 +0,6 @@ | ||
'use strict' | ||
'use strict'; | ||
const Encoder = require('./encoder') | ||
const ObjectRecorder = require('./objectRecorder') | ||
const {Buffer} = require('buffer') | ||
const Encoder = require('./encoder'); | ||
const ObjectRecorder = require('./objectRecorder'); | ||
const {Buffer} = require('buffer'); | ||
@@ -14,4 +14,4 @@ /** | ||
constructor(opts) { | ||
super(opts) | ||
this.valueSharing = new ObjectRecorder() | ||
super(opts); | ||
this.valueSharing = new ObjectRecorder(); | ||
} | ||
@@ -29,16 +29,16 @@ | ||
if (obj !== null) { | ||
const shared = this.valueSharing.check(obj) | ||
const shared = this.valueSharing.check(obj); | ||
switch (shared) { | ||
case ObjectRecorder.FIRST: | ||
// Prefix with tag 28 | ||
this._pushTag(28) | ||
break | ||
this._pushTag(28); | ||
break; | ||
case ObjectRecorder.NEVER: | ||
// Do nothing | ||
break | ||
break; | ||
default: | ||
return this._pushTag(29) && this._pushIntNum(shared) | ||
return this._pushTag(29) && this._pushIntNum(shared); | ||
} | ||
} | ||
return super._pushObject(obj, opts) | ||
return super._pushObject(obj, opts); | ||
} | ||
@@ -50,3 +50,3 @@ | ||
stopRecording() { | ||
this.valueSharing.stop() | ||
this.valueSharing.stop(); | ||
} | ||
@@ -59,3 +59,3 @@ | ||
clearRecording() { | ||
this.valueSharing.clear() | ||
this.valueSharing.clear(); | ||
} | ||
@@ -71,15 +71,14 @@ | ||
static encode(...objs) { | ||
const enc = new SharedValueEncoder() | ||
const enc = new SharedValueEncoder(); | ||
// eslint-disable-next-line no-empty-function | ||
enc.on('data', () => {}) // Sink all writes | ||
enc.on('data', () => {}); // Sink all writes | ||
for (const o of objs) { | ||
enc.pushAny(o) | ||
enc.pushAny(o); | ||
} | ||
enc.stopRecording() | ||
enc.removeAllListeners('data') | ||
return enc._encodeAll(objs) | ||
enc.stopRecording(); | ||
enc.removeAllListeners('data'); | ||
return enc._encodeAll(objs); | ||
} | ||
// eslint-disable-next-line jsdoc/require-returns-check | ||
/** | ||
@@ -89,8 +88,8 @@ * Encode one or more JavaScript objects canonically (slower!), and return | ||
* | ||
* @param {...any} objs The objects to encode. | ||
* @param {...any} _objs The objects to encode. | ||
* @returns {Buffer} Never. | ||
* @throws {Error} Always. This combination doesn't work at the moment. | ||
*/ | ||
static encodeCanonical(...objs) { | ||
throw new Error('Cannot encode canonically in a SharedValueEncoder, which serializes objects multiple times.') | ||
static encodeCanonical(..._objs) { | ||
throw new Error('Cannot encode canonically in a SharedValueEncoder, which serializes objects multiple times.'); | ||
} | ||
@@ -108,9 +107,9 @@ | ||
static encodeOne(obj, options) { | ||
const enc = new SharedValueEncoder(options) | ||
const enc = new SharedValueEncoder(options); | ||
// eslint-disable-next-line no-empty-function | ||
enc.on('data', () => {}) // Sink all writes | ||
enc.pushAny(obj) | ||
enc.stopRecording() | ||
enc.removeAllListeners('data') | ||
return enc._encodeAll([obj]) | ||
enc.on('data', () => {}); // Sink all writes | ||
enc.pushAny(obj); | ||
enc.stopRecording(); | ||
enc.removeAllListeners('data'); | ||
return enc._encodeAll([obj]); | ||
} | ||
@@ -133,18 +132,18 @@ | ||
/** @type {Buffer[]} */ | ||
const bufs = [] | ||
const enc = new SharedValueEncoder(options) | ||
const bufs = []; | ||
const enc = new SharedValueEncoder(options); | ||
// eslint-disable-next-line no-empty-function | ||
enc.on('data', () => {}) | ||
enc.on('error', reject) | ||
enc.on('finish', () => resolve(Buffer.concat(bufs))) | ||
enc.pushAny(obj) | ||
enc.stopRecording() | ||
enc.removeAllListeners('data') | ||
enc.on('data', buf => bufs.push(buf)) | ||
enc.pushAny(obj) | ||
enc.end() | ||
}) | ||
enc.on('data', () => {}); | ||
enc.on('error', reject); | ||
enc.on('finish', () => resolve(Buffer.concat(bufs))); | ||
enc.pushAny(obj); | ||
enc.stopRecording(); | ||
enc.removeAllListeners('data'); | ||
enc.on('data', buf => bufs.push(buf)); | ||
enc.pushAny(obj); | ||
enc.end(); | ||
}); | ||
} | ||
} | ||
module.exports = SharedValueEncoder | ||
module.exports = SharedValueEncoder; |
@@ -1,4 +0,4 @@ | ||
'use strict' | ||
'use strict'; | ||
const {MT, SIMPLE, SYMS} = require('./constants') | ||
const {MT, SIMPLE, SYMS} = require('./constants'); | ||
@@ -16,8 +16,8 @@ /** | ||
if (typeof value !== 'number') { | ||
throw new Error(`Invalid Simple type: ${typeof value}`) | ||
throw new Error(`Invalid Simple type: ${typeof value}`); | ||
} | ||
if ((value < 0) || (value > 255) || ((value | 0) !== value)) { | ||
throw new Error(`value must be a small positive integer: ${value}`) | ||
throw new Error(`value must be a small positive integer: ${value}`); | ||
} | ||
this.value = value | ||
this.value = value; | ||
} | ||
@@ -31,3 +31,3 @@ | ||
toString() { | ||
return `simple(${this.value})` | ||
return `simple(${this.value})`; | ||
} | ||
@@ -38,8 +38,8 @@ | ||
* | ||
* @param {number} depth How deep are we? | ||
* @param {object} opts Options. | ||
* @param {number} _depth How deep are we? | ||
* @param {object} _opts Options. | ||
* @returns {string} Formatted string of `simple(value)`. | ||
*/ | ||
[Symbol.for('nodejs.util.inspect.custom')](depth, opts) { | ||
return `simple(${this.value})` | ||
[Symbol.for('nodejs.util.inspect.custom')](_depth, _opts) { | ||
return `simple(${this.value})`; | ||
} | ||
@@ -54,3 +54,3 @@ | ||
encodeCBOR(gen) { | ||
return gen._pushInt(this.value, MT.SIMPLE_FLOAT) | ||
return gen._pushInt(this.value, MT.SIMPLE_FLOAT); | ||
} | ||
@@ -65,3 +65,3 @@ | ||
static isSimple(obj) { | ||
return obj instanceof Simple | ||
return obj instanceof Simple; | ||
} | ||
@@ -85,22 +85,22 @@ | ||
case SIMPLE.FALSE: | ||
return false | ||
return false; | ||
case SIMPLE.TRUE: | ||
return true | ||
return true; | ||
case SIMPLE.NULL: | ||
if (has_parent) { | ||
return null | ||
return null; | ||
} | ||
return SYMS.NULL | ||
return SYMS.NULL; | ||
case SIMPLE.UNDEFINED: | ||
if (has_parent) { | ||
return undefined | ||
return undefined; | ||
} | ||
return SYMS.UNDEFINED | ||
return SYMS.UNDEFINED; | ||
case -1: | ||
if (!has_parent || !parent_indefinite) { | ||
throw new Error('Invalid BREAK') | ||
throw new Error('Invalid BREAK'); | ||
} | ||
return SYMS.BREAK | ||
return SYMS.BREAK; | ||
default: | ||
return new Simple(val) | ||
return new Simple(val); | ||
} | ||
@@ -110,2 +110,2 @@ } | ||
module.exports = Simple | ||
module.exports = Simple; |
@@ -1,6 +0,6 @@ | ||
'use strict' | ||
'use strict'; | ||
const constants = require('./constants') | ||
const utils = require('./utils') | ||
const INTERNAL_JSON = Symbol('INTERNAL_JSON') | ||
const constants = require('./constants'); | ||
const utils = require('./utils'); | ||
const INTERNAL_JSON = Symbol('INTERNAL_JSON'); | ||
@@ -13,6 +13,6 @@ function setBuffersToJSON(obj, fn) { | ||
if (utils.isBufferish(obj)) { | ||
obj.toJSON = fn | ||
obj.toJSON = fn; | ||
} else if (Array.isArray(obj)) { | ||
for (const v of obj) { | ||
setBuffersToJSON(v, fn) | ||
setBuffersToJSON(v, fn); | ||
} | ||
@@ -26,3 +26,3 @@ } else if (obj && (typeof obj === 'object')) { | ||
for (const v of Object.values(obj)) { | ||
setBuffersToJSON(v, fn) | ||
setBuffersToJSON(v, fn); | ||
} | ||
@@ -35,3 +35,3 @@ } | ||
// eslint-disable-next-line no-invalid-this | ||
return utils.base64(this) | ||
return utils.base64(this); | ||
} | ||
@@ -41,3 +41,3 @@ | ||
// eslint-disable-next-line no-invalid-this | ||
return utils.base64url(this) | ||
return utils.base64url(this); | ||
} | ||
@@ -47,7 +47,7 @@ | ||
// eslint-disable-next-line no-invalid-this | ||
return this.toString('hex') | ||
return this.toString('hex'); | ||
} | ||
function swapEndian(ab, size, byteOffset, byteLength) { | ||
const dv = new DataView(ab) | ||
const dv = new DataView(ab); | ||
const [getter, setter] = { | ||
@@ -57,7 +57,7 @@ 2: [dv.getUint16, dv.setUint16], | ||
8: [dv.getBigUint64, dv.setBigUint64], | ||
}[size] | ||
}[size]; | ||
const end = byteOffset + byteLength | ||
const end = byteOffset + byteLength; | ||
for (let offset = byteOffset; offset < end; offset += size) { | ||
setter.call(dv, offset, getter.call(dv, offset, true)) | ||
setter.call(dv, offset, getter.call(dv, offset, true)); | ||
} | ||
@@ -78,3 +78,2 @@ } | ||
/* eslint-disable jsdoc/check-types */ | ||
/** | ||
@@ -85,3 +84,2 @@ * A mapping from tag number to a tag decoding function. | ||
*/ | ||
/* eslint-enable jsdoc/check-types */ | ||
@@ -104,7 +102,7 @@ /** | ||
if (utils.isBufferish(v)) { | ||
tag[INTERNAL_JSON] = b64urlThis | ||
tag[INTERNAL_JSON] = b64urlThis; | ||
} else { | ||
setBuffersToJSON(v, b64urlThis) | ||
setBuffersToJSON(v, b64urlThis); | ||
} | ||
return tag | ||
return tag; | ||
}, | ||
@@ -114,7 +112,7 @@ // Expected conversion to base64 encoding; see Section 3.4.5.2 | ||
if (utils.isBufferish(v)) { | ||
tag[INTERNAL_JSON] = b64this | ||
tag[INTERNAL_JSON] = b64this; | ||
} else { | ||
setBuffersToJSON(v, b64this) | ||
setBuffersToJSON(v, b64this); | ||
} | ||
return tag | ||
return tag; | ||
}, | ||
@@ -124,7 +122,7 @@ // Expected conversion to base16 encoding; see Section Section 3.4.5.2 | ||
if (utils.isBufferish(v)) { | ||
tag[INTERNAL_JSON] = hexThis | ||
tag[INTERNAL_JSON] = hexThis; | ||
} else { | ||
setBuffersToJSON(v, hexThis) | ||
setBuffersToJSON(v, hexThis); | ||
} | ||
return tag | ||
return tag; | ||
}, | ||
@@ -141,7 +139,7 @@ // URI; see Section 3.4.5.3 | ||
if (!v.match(/^[a-zA-Z0-9_-]+$/)) { | ||
throw new Error('Invalid base64url characters') | ||
throw new Error('Invalid base64url characters'); | ||
} | ||
const last = v.length % 4 | ||
const last = v.length % 4; | ||
if (last === 1) { | ||
throw new Error('Invalid base64url length') | ||
throw new Error('Invalid base64url length'); | ||
} | ||
@@ -152,3 +150,3 @@ // - the padding bits in a 2- or 3-character block are not 0, or | ||
if ('AQgw'.indexOf(v[v.length - 1]) === -1) { | ||
throw new Error('Invalid base64 padding') | ||
throw new Error('Invalid base64 padding'); | ||
} | ||
@@ -158,3 +156,3 @@ } else if (last === 3) { | ||
if ('AEIMQUYcgkosw048'.indexOf(v[v.length - 1]) === -1) { | ||
throw new Error('Invalid base64 padding') | ||
throw new Error('Invalid base64 padding'); | ||
} | ||
@@ -168,3 +166,3 @@ } | ||
// the string is invalid. | ||
return tag | ||
return tag; | ||
}, | ||
@@ -178,8 +176,8 @@ // Base64; see Section 3.4.5.3 | ||
// and Section 4 of [RFC4648] for tag number 34), or | ||
const m = v.match(/^[a-zA-Z0-9+/]+(?<padding>={0,2})$/) | ||
const m = v.match(/^[a-zA-Z0-9+/]+(?<padding>={0,2})$/); | ||
if (!m) { | ||
throw new Error('Invalid base64 characters') | ||
throw new Error('Invalid base64 characters'); | ||
} | ||
if ((v.length % 4) !== 0) { | ||
throw new Error('Invalid base64 length') | ||
throw new Error('Invalid base64 length'); | ||
} | ||
@@ -190,3 +188,3 @@ // - the padding bits in a 2- or 3-character block are not 0, or | ||
if ('AQgw'.indexOf(v[v.length - 2]) === -1) { | ||
throw new Error('Invalid base64 padding') | ||
throw new Error('Invalid base64 padding'); | ||
} | ||
@@ -196,3 +194,3 @@ } else if (m.groups.padding === '==') { | ||
if ('AEIMQUYcgkosw048'.indexOf(v[v.length - 3]) === -1) { | ||
throw new Error('Invalid base64 padding') | ||
throw new Error('Invalid base64 padding'); | ||
} | ||
@@ -204,3 +202,3 @@ } | ||
// the string is invalid. | ||
return tag | ||
return tag; | ||
}, | ||
@@ -211,3 +209,3 @@ // Regular expression; see Section 2.4.4.3 | ||
258: v => new Set(v), | ||
} | ||
}; | ||
@@ -239,38 +237,38 @@ const TYPED_ARRAY_TAGS = { | ||
// 87: not implemented, float128 array | ||
} | ||
}; | ||
// Safari | ||
if (typeof BigUint64Array !== 'undefined') { | ||
TYPED_ARRAY_TAGS[67] = BigUint64Array | ||
TYPED_ARRAY_TAGS[71] = BigUint64Array | ||
TYPED_ARRAY_TAGS[67] = BigUint64Array; | ||
TYPED_ARRAY_TAGS[71] = BigUint64Array; | ||
} | ||
if (typeof BigInt64Array !== 'undefined') { | ||
TYPED_ARRAY_TAGS[75] = BigInt64Array | ||
TYPED_ARRAY_TAGS[79] = BigInt64Array | ||
TYPED_ARRAY_TAGS[75] = BigInt64Array; | ||
TYPED_ARRAY_TAGS[79] = BigInt64Array; | ||
} | ||
function _toTypedArray(val, tagged) { | ||
function toTypedArray(val, tagged) { | ||
if (!utils.isBufferish(val)) { | ||
throw new TypeError('val not a buffer') | ||
throw new TypeError('val not a buffer'); | ||
} | ||
const {tag} = tagged | ||
const {tag} = tagged; | ||
// See https://tools.ietf.org/html/rfc8746 | ||
const TypedClass = TYPED_ARRAY_TAGS[tag] | ||
const TypedClass = TYPED_ARRAY_TAGS[tag]; | ||
if (!TypedClass) { | ||
throw new Error(`Invalid typed array tag: ${tag}`) | ||
throw new Error(`Invalid typed array tag: ${tag}`); | ||
} | ||
const little = tag & 0b00000100 | ||
const float = (tag & 0b00010000) >> 4 | ||
const sz = 2 ** (float + (tag & 0b00000011)) | ||
const little = tag & 0b00000100; | ||
const float = (tag & 0b00010000) >> 4; | ||
const sz = 2 ** (float + (tag & 0b00000011)); | ||
if ((!little !== utils.isBigEndian()) && (sz > 1)) { | ||
swapEndian(val.buffer, sz, val.byteOffset, val.byteLength) | ||
swapEndian(val.buffer, sz, val.byteOffset, val.byteLength); | ||
} | ||
const ab = val.buffer.slice(val.byteOffset, val.byteOffset + val.byteLength) | ||
return new TypedClass(ab) | ||
const ab = val.buffer.slice(val.byteOffset, val.byteOffset + val.byteLength); | ||
return new TypedClass(ab); | ||
} | ||
for (const n of Object.keys(TYPED_ARRAY_TAGS)) { | ||
TAGS[n] = _toTypedArray | ||
TAGS[n] = toTypedArray; | ||
} | ||
@@ -282,3 +280,3 @@ | ||
*/ | ||
let current_TAGS = {} | ||
let current_TAGS = {}; | ||
@@ -299,10 +297,10 @@ /** | ||
constructor(tag, value, err) { | ||
this.tag = tag | ||
this.value = value | ||
this.err = err | ||
this.tag = tag; | ||
this.value = value; | ||
this.err = err; | ||
if (typeof this.tag !== 'number') { | ||
throw new Error(`Invalid tag type (${typeof this.tag})`) | ||
throw new Error(`Invalid tag type (${typeof this.tag})`); | ||
} | ||
if ((this.tag < 0) || ((this.tag | 0) !== this.tag)) { | ||
throw new Error(`Tag must be a positive integer: ${this.tag}`) | ||
throw new Error(`Tag must be a positive integer: ${this.tag}`); | ||
} | ||
@@ -313,3 +311,3 @@ } | ||
if (this[INTERNAL_JSON]) { | ||
return this[INTERNAL_JSON].call(this.value) | ||
return this[INTERNAL_JSON].call(this.value); | ||
} | ||
@@ -319,7 +317,7 @@ const ret = { | ||
value: this.value, | ||
} | ||
}; | ||
if (this.err) { | ||
ret.err = this.err | ||
ret.err = this.err; | ||
} | ||
return ret | ||
return ret; | ||
} | ||
@@ -333,3 +331,3 @@ | ||
toString() { | ||
return `${this.tag}(${JSON.stringify(this.value)})` | ||
return `${this.tag}(${JSON.stringify(this.value)})`; | ||
} | ||
@@ -344,4 +342,4 @@ | ||
encodeCBOR(gen) { | ||
gen._pushTag(this.tag) | ||
return gen.pushAny(this.value) | ||
gen._pushTag(this.tag); | ||
return gen.pushAny(this.value); | ||
} | ||
@@ -361,21 +359,21 @@ | ||
convert(converters) { | ||
let f = (converters == null) ? undefined : converters[this.tag] | ||
let f = (converters == null) ? undefined : converters[this.tag]; | ||
if (f === null) { // === is intentional. null has semantic meaning as above | ||
return this | ||
return this; | ||
} | ||
if (typeof f !== 'function') { | ||
f = Tagged.TAGS[this.tag] | ||
f = Tagged.TAGS[this.tag]; | ||
if (typeof f !== 'function') { | ||
return this | ||
return this; | ||
} | ||
} | ||
try { | ||
return f.call(this, this.value, this) | ||
return f.call(this, this.value, this); | ||
} catch (error) { | ||
if (error && error.message && (error.message.length > 0)) { | ||
this.err = error.message | ||
this.err = error.message; | ||
} else { | ||
this.err = error | ||
this.err = error; | ||
} | ||
return this | ||
return this; | ||
} | ||
@@ -391,7 +389,7 @@ } | ||
static get TAGS() { | ||
return current_TAGS | ||
return current_TAGS; | ||
} | ||
static set TAGS(val) { | ||
current_TAGS = val | ||
current_TAGS = val; | ||
} | ||
@@ -404,7 +402,7 @@ | ||
static reset() { | ||
Tagged.TAGS = {...TAGS} | ||
Tagged.TAGS = {...TAGS}; | ||
} | ||
} | ||
Tagged.INTERNAL_JSON = INTERNAL_JSON | ||
Tagged.reset() | ||
module.exports = Tagged | ||
Tagged.INTERNAL_JSON = INTERNAL_JSON; | ||
Tagged.reset(); | ||
module.exports = Tagged; |
214
lib/utils.js
@@ -1,9 +0,9 @@ | ||
'use strict' | ||
'use strict'; | ||
const {Buffer} = require('buffer') | ||
const NoFilter = require('nofilter') | ||
const stream = require('stream') | ||
const constants = require('./constants') | ||
const {NUMBYTES, SHIFT32, BI, SYMS} = constants | ||
const MAX_SAFE_HIGH = 0x1fffff | ||
const {Buffer} = require('buffer'); | ||
const NoFilter = require('nofilter'); | ||
const stream = require('stream'); | ||
const constants = require('./constants'); | ||
const {NUMBYTES, SHIFT32, BI, SYMS} = constants; | ||
const MAX_SAFE_HIGH = 0x1fffff; | ||
@@ -16,5 +16,5 @@ /** | ||
*/ | ||
const td = new TextDecoder('utf8', {fatal: true, ignoreBOM: true}) | ||
exports.utf8 = buf => td.decode(buf) | ||
exports.utf8.checksUTF8 = true | ||
const td = new TextDecoder('utf8', {fatal: true, ignoreBOM: true}); | ||
exports.utf8 = buf => td.decode(buf); | ||
exports.utf8.checksUTF8 = true; | ||
@@ -25,5 +25,5 @@ function isReadable(s) { | ||
if (s instanceof stream.Readable) { | ||
return true | ||
return true; | ||
} | ||
return ['read', 'on', 'pipe'].every(f => typeof s[f] === 'function') | ||
return ['read', 'on', 'pipe'].every(f => typeof s[f] === 'function'); | ||
} | ||
@@ -38,15 +38,15 @@ | ||
(b instanceof ArrayBuffer) || | ||
(b instanceof DataView)) | ||
} | ||
(b instanceof DataView)); | ||
}; | ||
exports.bufferishToBuffer = function bufferishToBuffer(b) { | ||
if (Buffer.isBuffer(b)) { | ||
return b | ||
return b; | ||
} else if (ArrayBuffer.isView(b)) { | ||
return Buffer.from(b.buffer, b.byteOffset, b.byteLength) | ||
return Buffer.from(b.buffer, b.byteOffset, b.byteLength); | ||
} else if (b instanceof ArrayBuffer) { | ||
return Buffer.from(b) | ||
return Buffer.from(b); | ||
} | ||
return null | ||
} | ||
return null; | ||
}; | ||
@@ -56,19 +56,19 @@ exports.parseCBORint = function parseCBORint(ai, buf) { | ||
case NUMBYTES.ONE: | ||
return buf.readUInt8(0) | ||
return buf.readUInt8(0); | ||
case NUMBYTES.TWO: | ||
return buf.readUInt16BE(0) | ||
return buf.readUInt16BE(0); | ||
case NUMBYTES.FOUR: | ||
return buf.readUInt32BE(0) | ||
return buf.readUInt32BE(0); | ||
case NUMBYTES.EIGHT: { | ||
const f = buf.readUInt32BE(0) | ||
const g = buf.readUInt32BE(4) | ||
const f = buf.readUInt32BE(0); | ||
const g = buf.readUInt32BE(4); | ||
if (f > MAX_SAFE_HIGH) { | ||
return (BigInt(f) * BI.SHIFT32) + BigInt(g) | ||
return (BigInt(f) * BI.SHIFT32) + BigInt(g); | ||
} | ||
return (f * SHIFT32) + g | ||
return (f * SHIFT32) + g; | ||
} | ||
default: | ||
throw new Error(`Invalid additional info for int: ${ai}`) | ||
throw new Error(`Invalid additional info for int: ${ai}`); | ||
} | ||
} | ||
}; | ||
@@ -89,5 +89,5 @@ exports.writeHalf = function writeHalf(buf, half) { | ||
const u32 = Buffer.allocUnsafe(4) | ||
u32.writeFloatBE(half, 0) | ||
const u = u32.readUInt32BE(0) | ||
const u32 = Buffer.allocUnsafe(4); | ||
u32.writeFloatBE(half, 0); | ||
const u = u32.readUInt32BE(0); | ||
@@ -100,3 +100,3 @@ // If ((u32.u & 0x1FFF) == 0) { /* worth trying half */ | ||
if ((u & 0x1FFF) !== 0) { | ||
return false | ||
return false; | ||
} | ||
@@ -109,5 +109,5 @@ | ||
let s16 = (u >> 16) & 0x8000 // Top bit is sign | ||
const exp = (u >> 23) & 0xff // Then 5 bits of exponent | ||
const mant = u & 0x7fffff | ||
let s16 = (u >> 16) & 0x8000; // Top bit is sign | ||
const exp = (u >> 23) & 0xff; // Then 5 bits of exponent | ||
const mant = u & 0x7fffff; | ||
@@ -122,3 +122,3 @@ // Hildjj: zeros already handled. Assert if you don't believe me. | ||
if ((exp >= 113) && (exp <= 142)) { | ||
s16 += ((exp - 112) << 10) + (mant >> 13) | ||
s16 += ((exp - 112) << 10) + (mant >> 13); | ||
} else if ((exp >= 103) && (exp < 113)) { | ||
@@ -132,5 +132,5 @@ // Denormalized numbers | ||
if (mant & ((1 << (126 - exp)) - 1)) { | ||
return false | ||
return false; | ||
} | ||
s16 += ((mant + 0x800000) >> (126 - exp)) | ||
s16 += ((mant + 0x800000) >> (126 - exp)); | ||
} else { | ||
@@ -145,3 +145,3 @@ // } else if (exp == 255 && mant == 0) { /* Inf */ | ||
return false | ||
return false; | ||
} | ||
@@ -153,17 +153,17 @@ | ||
// be16 = hton16p((const uint8_t*)&u16); | ||
buf.writeUInt16BE(s16) | ||
return true | ||
} | ||
buf.writeUInt16BE(s16); | ||
return true; | ||
}; | ||
exports.parseHalf = function parseHalf(buf) { | ||
const sign = buf[0] & 0x80 ? -1 : 1 | ||
const exp = (buf[0] & 0x7C) >> 2 | ||
const mant = ((buf[0] & 0x03) << 8) | buf[1] | ||
const sign = buf[0] & 0x80 ? -1 : 1; | ||
const exp = (buf[0] & 0x7C) >> 2; | ||
const mant = ((buf[0] & 0x03) << 8) | buf[1]; | ||
if (!exp) { | ||
return sign * 5.9604644775390625e-8 * mant | ||
return sign * 5.9604644775390625e-8 * mant; | ||
} else if (exp === 0x1f) { | ||
return sign * (mant ? NaN : Infinity) | ||
return sign * (mant ? NaN : Infinity); | ||
} | ||
return sign * (2 ** (exp - 25)) * (1024 + mant) | ||
} | ||
return sign * (2 ** (exp - 25)) * (1024 + mant); | ||
}; | ||
@@ -173,42 +173,42 @@ exports.parseCBORfloat = function parseCBORfloat(buf) { | ||
case 2: | ||
return exports.parseHalf(buf) | ||
return exports.parseHalf(buf); | ||
case 4: | ||
return buf.readFloatBE(0) | ||
return buf.readFloatBE(0); | ||
case 8: | ||
return buf.readDoubleBE(0) | ||
return buf.readDoubleBE(0); | ||
default: | ||
throw new Error(`Invalid float size: ${buf.length}`) | ||
throw new Error(`Invalid float size: ${buf.length}`); | ||
} | ||
} | ||
}; | ||
exports.hex = function hex(s) { | ||
return Buffer.from(s.replace(/^0x/, ''), 'hex') | ||
} | ||
return Buffer.from(s.replace(/^0x/, ''), 'hex'); | ||
}; | ||
exports.bin = function bin(s) { | ||
s = s.replace(/\s/g, '') | ||
let start = 0 | ||
let end = (s.length % 8) || 8 | ||
const chunks = [] | ||
s = s.replace(/\s/g, ''); | ||
let start = 0; | ||
let end = (s.length % 8) || 8; | ||
const chunks = []; | ||
while (end <= s.length) { | ||
chunks.push(parseInt(s.slice(start, end), 2)) | ||
start = end | ||
end += 8 | ||
chunks.push(parseInt(s.slice(start, end), 2)); | ||
start = end; | ||
end += 8; | ||
} | ||
return Buffer.from(chunks) | ||
} | ||
return Buffer.from(chunks); | ||
}; | ||
exports.arrayEqual = function arrayEqual(a, b) { | ||
if ((a == null) && (b == null)) { | ||
return true | ||
return true; | ||
} | ||
if ((a == null) || (b == null)) { | ||
return false | ||
return false; | ||
} | ||
return (a.length === b.length) && a.every((elem, i) => elem === b[i]) | ||
} | ||
return (a.length === b.length) && a.every((elem, i) => elem === b[i]); | ||
}; | ||
exports.bufferToBigInt = function bufferToBigInt(buf) { | ||
return BigInt(`0x${buf.toString('hex')}`) | ||
} | ||
return BigInt(`0x${buf.toString('hex')}`); | ||
}; | ||
@@ -220,7 +220,7 @@ exports.cborValueToString = function cborValueToString(val, float_bytes = -1) { | ||
case SYMS.NULL: | ||
return 'null' | ||
return 'null'; | ||
case SYMS.UNDEFINED: | ||
return 'undefined' | ||
return 'undefined'; | ||
case SYMS.BREAK: | ||
return 'BREAK' | ||
return 'BREAK'; | ||
} | ||
@@ -230,8 +230,8 @@ // Impossible in node 10 | ||
if (val.description) { | ||
return val.description | ||
return val.description; | ||
} | ||
// On node10, Symbol doesn't have description. Parse it out of the | ||
// toString value, which looks like `Symbol(foo)`. | ||
const s = val.toString() | ||
const m = s.match(/^Symbol\((?<name>.*)\)/) | ||
const s = val.toString(); | ||
const m = s.match(/^Symbol\((?<name>.*)\)/); | ||
/* istanbul ignore if */ | ||
@@ -241,50 +241,50 @@ if (m && m.groups.name) { | ||
/* istanbul ignore next */ | ||
return m.groups.name | ||
return m.groups.name; | ||
} | ||
return 'Symbol' | ||
return 'Symbol'; | ||
} | ||
case 'string': | ||
return JSON.stringify(val) | ||
return JSON.stringify(val); | ||
case 'bigint': | ||
return val.toString() | ||
return val.toString(); | ||
case 'number': { | ||
const s = Object.is(val, -0) ? '-0' : String(val) | ||
return (float_bytes > 0) ? `${s}_${float_bytes}` : s | ||
const s = Object.is(val, -0) ? '-0' : String(val); | ||
return (float_bytes > 0) ? `${s}_${float_bytes}` : s; | ||
} | ||
case 'object': { | ||
if (!val) { | ||
return 'null' | ||
return 'null'; | ||
} | ||
const buf = exports.bufferishToBuffer(val) | ||
const buf = exports.bufferishToBuffer(val); | ||
if (buf) { | ||
const hex = buf.toString('hex') | ||
return (float_bytes === -Infinity) ? hex : `h'${hex}'` | ||
const hex = buf.toString('hex'); | ||
return (float_bytes === -Infinity) ? hex : `h'${hex}'`; | ||
} | ||
if (val && typeof val[Symbol.for('nodejs.util.inspect.custom')] === 'function') { | ||
return val[Symbol.for('nodejs.util.inspect.custom')]() | ||
return val[Symbol.for('nodejs.util.inspect.custom')](); | ||
} | ||
// Shouldn't get non-empty arrays here | ||
if (Array.isArray(val)) { | ||
return '[]' | ||
return '[]'; | ||
} | ||
// This should be all that is left | ||
return '{}' | ||
return '{}'; | ||
} | ||
} | ||
return String(val) | ||
} | ||
return String(val); | ||
}; | ||
exports.guessEncoding = function guessEncoding(input, encoding) { | ||
if (typeof input === 'string') { | ||
return new NoFilter(input, (encoding == null) ? 'hex' : encoding) | ||
return new NoFilter(input, (encoding == null) ? 'hex' : encoding); | ||
} | ||
const buf = exports.bufferishToBuffer(input) | ||
const buf = exports.bufferishToBuffer(input); | ||
if (buf) { | ||
return new NoFilter(buf) | ||
return new NoFilter(buf); | ||
} | ||
if (isReadable(input)) { | ||
return input | ||
return input; | ||
} | ||
throw new Error('Unknown input type') | ||
} | ||
throw new Error('Unknown input type'); | ||
}; | ||
@@ -295,3 +295,3 @@ const B64URL_SWAPS = { | ||
'/': '_', | ||
} | ||
}; | ||
@@ -307,4 +307,4 @@ /** | ||
.toString('base64') | ||
.replace(/[=+/]/g, c => B64URL_SWAPS[c]) | ||
} | ||
.replace(/[=+/]/g, c => B64URL_SWAPS[c]); | ||
}; | ||
@@ -318,9 +318,9 @@ /** | ||
exports.base64 = function base64(buf) { | ||
return exports.bufferishToBuffer(buf).toString('base64') | ||
} | ||
return exports.bufferishToBuffer(buf).toString('base64'); | ||
}; | ||
exports.isBigEndian = function isBigEndian() { | ||
const array = new Uint8Array(4) | ||
const view = new Uint32Array(array.buffer) | ||
return !((view[0] = 1) & array[0]) | ||
} | ||
const array = new Uint8Array(4); | ||
const view = new Uint32Array(array.buffer); | ||
return !((view[0] = 1) & array[0]); | ||
}; |
{ | ||
"name": "cbor", | ||
"version": "9.0.2", | ||
"version": "10.0.2", | ||
"description": "Encode and parse data in the Concise Binary Object Representation (CBOR) data format (RFC8949).", | ||
@@ -8,3 +8,3 @@ "main": "./lib/cbor.js", | ||
"type": "git", | ||
"url": "http://github.com/hildjj/node-cbor.git", | ||
"url": "git+ssh://git@github.com/hildjj/node-cbor.git", | ||
"directory": "packages/cbor" | ||
@@ -19,13 +19,2 @@ }, | ||
}, | ||
"scripts": { | ||
"clean": "rimraf coverage .nyc_output/ docs", | ||
"lint": "eslint lib/*.js test/*.js", | ||
"coverage": "nyc -r lcov npm test", | ||
"test": "ava test/*.ava.js", | ||
"release": "npm version patch && git push --follow-tags && npm publish", | ||
"predev": "npm run coverage", | ||
"dev": "light-server -q -s. -w 'lib/*.js,test/*.js # npm run coverage' -o /coverage/lcov-report/index.html", | ||
"types": "tsc && npm run copy-types", | ||
"copy-types": "copyfiles \"./types/**\" \"../cbor-web/\"" | ||
}, | ||
"keywords": [ | ||
@@ -53,17 +42,9 @@ "coap", | ||
"dependencies": { | ||
"nofilter": "^3.1.0" | ||
"nofilter": "^3.0.2" | ||
}, | ||
"devDependencies": { | ||
"@types/node": "^20", | ||
"bignumber.js": "^9.1.1", | ||
"garbage": "~0.0.0", | ||
"p-event": "^4.2.0", | ||
"rimraf": "^5.0.0" | ||
}, | ||
"license": "MIT", | ||
"readmeFilename": "README.md", | ||
"engines": { | ||
"node": ">=16" | ||
}, | ||
"gitHead": "1967cd4540e9aab60093fcd711cd97edee542043" | ||
"node": ">=18" | ||
} | ||
} |
@@ -36,16 +36,16 @@ # cbor | ||
```js | ||
const cbor = require('cbor') | ||
const assert = require('assert') | ||
const cbor = require('cbor'); | ||
const assert = require('node:assert'); | ||
let encoded = cbor.encode(true) // Returns <Buffer f5> | ||
let encoded = cbor.encode(true); // Returns <Buffer f5> | ||
cbor.decodeFirst(encoded, (error, obj) => { | ||
// If there was an error, error != null | ||
// obj is the unpacked object | ||
assert.ok(obj === true) | ||
}) | ||
assert.ok(obj === true); | ||
}); | ||
// Use integers as keys? | ||
const m = new Map() | ||
m.set(1, 2) | ||
encoded = cbor.encode(m) // <Buffer a1 01 02> | ||
const m = new Map(); | ||
m.set(1, 2); | ||
encoded = cbor.encode(m); // <Buffer a1 01 02> | ||
``` | ||
@@ -56,17 +56,17 @@ | ||
```js | ||
const cbor = require('cbor') | ||
const fs = require('fs') | ||
const cbor = require('cbor'); | ||
const fs = require('node:fs'); | ||
const d = new cbor.Decoder() | ||
const d = new cbor.Decoder(); | ||
d.on('data', obj => { | ||
console.log(obj) | ||
}) | ||
console.log(obj); | ||
}); | ||
const s = fs.createReadStream('foo') | ||
s.pipe(d) | ||
const s = fs.createReadStream('foo'); | ||
s.pipe(d); | ||
const d2 = new cbor.Decoder({input: '00', encoding: 'hex'}) | ||
const d2 = new cbor.Decoder({input: '00', encoding: 'hex'}); | ||
d.on('data', obj => { | ||
console.log(obj) | ||
}) | ||
console.log(obj); | ||
}); | ||
``` | ||
@@ -78,4 +78,4 @@ | ||
try { | ||
console.log(cbor.decodeFirstSync('02')) // 2 | ||
console.log(cbor.decodeAllSync('0202')) // [2, 2] | ||
console.log(cbor.decodeFirstSync('02')); // 2 | ||
console.log(cbor.decodeAllSync('0202')); // [2, 2] | ||
} catch (e) { | ||
@@ -99,3 +99,3 @@ // Throws on invalid input | ||
```js | ||
cbor.encodeOne(new ArrayBuffer(40000), {highWaterMark: 65535}) | ||
cbor.encodeOne(new ArrayBuffer(40000), {highWaterMark: 65535}); | ||
``` | ||
@@ -106,8 +106,8 @@ | ||
```js | ||
const enc = new cbor.Encoder() | ||
enc.on('data', buf => /* Send the data somewhere */ null) | ||
enc.on('error', console.error) | ||
enc.on('finish', () => /* Tell the consumer we are finished */ null) | ||
const enc = new cbor.Encoder(); | ||
enc.on('data', buf => /* Send the data somewhere */ null); | ||
enc.on('error', console.error); | ||
enc.on('finish', () => /* Tell the consumer we are finished */ null); | ||
enc.end(['foo', 1, false]) | ||
enc.end(['foo', 1, false]); | ||
``` | ||
@@ -187,9 +187,9 @@ | ||
constructor() { | ||
this.one = 1 | ||
this.two = 2 | ||
this.one = 1; | ||
this.two = 2; | ||
} | ||
encodeCBOR(encoder) { | ||
const tagged = new Tagged(64000, [this.one, this.two]) | ||
return encoder.pushAny(tagged) | ||
const tagged = new Tagged(64000, [this.one, this.two]); | ||
return encoder.pushAny(tagged); | ||
} | ||
@@ -212,9 +212,9 @@ } | ||
constructor() { | ||
this.three = 3 | ||
this.three = 3; | ||
} | ||
} | ||
const enc = new Encoder() | ||
const enc = new Encoder(); | ||
enc.addSemanticType(Bar, (encoder, b) => { | ||
encoder.pushAny(b.three) | ||
}) | ||
encoder.pushAny(b.three); | ||
}); | ||
``` | ||
@@ -237,8 +237,8 @@ | ||
// Check val to make sure it's an Array as expected, etc. | ||
const foo = new Foo() | ||
;[foo.one, foo.two] = val | ||
return foo | ||
const foo = new Foo(); | ||
[foo.one, foo.two] = val; | ||
return foo; | ||
}, | ||
}, | ||
}) | ||
}); | ||
``` | ||
@@ -257,3 +257,3 @@ | ||
}, | ||
}) | ||
}); | ||
``` | ||
@@ -281,2 +281,2 @@ | ||
[![Build Status](https://github.com/hildjj/node-cbor/workflows/Tests/badge.svg)](https://github.com/hildjj/node-cbor/actions?query=workflow%3ATests) | ||
[![Coverage Status](https://coveralls.io/repos/hildjj/node-cbor/badge.svg?branch=main)](https://coveralls.io/r/hildjj/node-cbor?branch=main) | ||
[![codecov](https://codecov.io/github/hildjj/node-cbor/graph/badge.svg?token=HEGszEFpTc)](https://codecov.io/github/hildjj/node-cbor) |
@@ -9,20 +9,20 @@ import Commented = require("./commented"); | ||
import SharedValueEncoder = require("./sharedValueEncoder"); | ||
export declare const comment: typeof import("./commented").comment; | ||
export declare const decodeAll: typeof import("./decoder").decodeAll; | ||
export declare const decodeFirst: typeof import("./decoder").decodeFirst; | ||
export declare const decodeAllSync: typeof import("./decoder").decodeAllSync; | ||
export declare const decodeFirstSync: any; | ||
export declare const diagnose: typeof import("./diagnose").diagnose; | ||
export declare const encode: typeof import("./encoder").encode; | ||
export declare const encodeCanonical: typeof import("./encoder").encodeCanonical; | ||
export declare const encodeOne: typeof import("./encoder").encodeOne; | ||
export declare const encodeAsync: typeof import("./encoder").encodeAsync; | ||
export declare const decode: typeof import("./decoder").decodeFirstSync; | ||
export declare let comment: typeof import("./commented").comment; | ||
export declare let decodeAll: typeof import("./decoder").decodeAll; | ||
export declare let decodeFirst: typeof import("./decoder").decodeFirst; | ||
export declare let decodeAllSync: typeof import("./decoder").decodeAllSync; | ||
export declare let decodeFirstSync: typeof import("./decoder").decodeFirstSync; | ||
export declare let diagnose: typeof import("./diagnose").diagnose; | ||
export declare let encode: typeof import("./encoder").encode; | ||
export declare let encodeCanonical: typeof import("./encoder").encodeCanonical; | ||
export declare let encodeOne: typeof import("./encoder").encodeOne; | ||
export declare let encodeAsync: typeof import("./encoder").encodeAsync; | ||
export declare let decode: typeof import("./decoder").decodeFirstSync; | ||
export declare namespace leveldb { | ||
const decode_1: typeof Decoder.decodeFirstSync; | ||
let decode_1: typeof Decoder.decodeFirstSync; | ||
export { decode_1 as decode }; | ||
const encode_1: typeof Encoder.encode; | ||
let encode_1: typeof Encoder.encode; | ||
export { encode_1 as encode }; | ||
export const buffer: boolean; | ||
export const name: string; | ||
export let buffer: boolean; | ||
export let name: string; | ||
} | ||
@@ -29,0 +29,0 @@ /** |
@@ -1,2 +0,1 @@ | ||
/// <reference types="node" /> | ||
export = Commented; | ||
@@ -3,0 +2,0 @@ /** |
export namespace MT { | ||
const POS_INT: number; | ||
const NEG_INT: number; | ||
const BYTE_STRING: number; | ||
const UTF8_STRING: number; | ||
const ARRAY: number; | ||
const MAP: number; | ||
const TAG: number; | ||
const SIMPLE_FLOAT: number; | ||
let POS_INT: number; | ||
let NEG_INT: number; | ||
let BYTE_STRING: number; | ||
let UTF8_STRING: number; | ||
let ARRAY: number; | ||
let MAP: number; | ||
let TAG: number; | ||
let SIMPLE_FLOAT: number; | ||
} | ||
export type MT = number; | ||
export namespace TAG { | ||
const DATE_STRING: number; | ||
const DATE_EPOCH: number; | ||
const POS_BIGINT: number; | ||
const NEG_BIGINT: number; | ||
const DECIMAL_FRAC: number; | ||
const BIGFLOAT: number; | ||
const BASE64URL_EXPECTED: number; | ||
const BASE64_EXPECTED: number; | ||
const BASE16_EXPECTED: number; | ||
const CBOR: number; | ||
const URI: number; | ||
const BASE64URL: number; | ||
const BASE64: number; | ||
const REGEXP: number; | ||
const MIME: number; | ||
const SET: number; | ||
let DATE_STRING: number; | ||
let DATE_EPOCH: number; | ||
let POS_BIGINT: number; | ||
let NEG_BIGINT: number; | ||
let DECIMAL_FRAC: number; | ||
let BIGFLOAT: number; | ||
let BASE64URL_EXPECTED: number; | ||
let BASE64_EXPECTED: number; | ||
let BASE16_EXPECTED: number; | ||
let CBOR: number; | ||
let URI: number; | ||
let BASE64URL: number; | ||
let BASE64: number; | ||
let REGEXP: number; | ||
let MIME: number; | ||
let SET: number; | ||
} | ||
export type TAG = number; | ||
export namespace NUMBYTES { | ||
const ZERO: number; | ||
const ONE: number; | ||
const TWO: number; | ||
const FOUR: number; | ||
const EIGHT: number; | ||
const INDEFINITE: number; | ||
let ZERO: number; | ||
let ONE: number; | ||
let TWO: number; | ||
let FOUR: number; | ||
let EIGHT: number; | ||
let INDEFINITE: number; | ||
} | ||
export type NUMBYTES = number; | ||
export namespace SIMPLE { | ||
const FALSE: number; | ||
const TRUE: number; | ||
const NULL: number; | ||
const UNDEFINED: number; | ||
let FALSE: number; | ||
let TRUE: number; | ||
let NULL: number; | ||
let UNDEFINED: number; | ||
} | ||
export type SIMPLE = number; | ||
export namespace SYMS { | ||
const NULL_1: symbol; | ||
let NULL_1: symbol; | ||
export { NULL_1 as NULL }; | ||
const UNDEFINED_1: symbol; | ||
let UNDEFINED_1: symbol; | ||
export { UNDEFINED_1 as UNDEFINED }; | ||
export const PARENT: symbol; | ||
export const BREAK: symbol; | ||
export const STREAM: symbol; | ||
export let PARENT: symbol; | ||
export let BREAK: symbol; | ||
export let STREAM: symbol; | ||
} | ||
export const SHIFT32: 4294967296; | ||
export namespace BI { | ||
const MINUS_ONE: bigint; | ||
const NEG_MAX: bigint; | ||
const MAXINT32: bigint; | ||
const MAXINT64: bigint; | ||
const SHIFT32: bigint; | ||
let MINUS_ONE: bigint; | ||
let NEG_MAX: bigint; | ||
let MAXINT32: bigint; | ||
let MAXINT64: bigint; | ||
let SHIFT32: bigint; | ||
} |
@@ -1,2 +0,1 @@ | ||
/// <reference types="node" /> | ||
export = Decoder; | ||
@@ -92,3 +91,3 @@ /** | ||
*/ | ||
static decodeAll(input: BufferLike, options?: string | DecoderOptions | ((error: Error, value: Array<ExtendedResults> | Array<any>) => any), cb?: (error: Error, value: Array<ExtendedResults> | Array<any>) => any): Promise<Array<ExtendedResults> | Array<any>>; | ||
static decodeAll(input: BufferLike, options?: DecoderOptions | ((error: Error, value: Array<ExtendedResults> | Array<any>) => any) | string, cb?: (error: Error, value: Array<ExtendedResults> | Array<any>) => any): Promise<Array<ExtendedResults> | Array<any>>; | ||
/** | ||
@@ -105,2 +104,3 @@ * Create a parsing stream. | ||
}; | ||
preferMap: boolean; | ||
preferWeb: boolean; | ||
@@ -128,6 +128,29 @@ extendedResults: boolean; | ||
import NoFilter = require("nofilter"); | ||
declare const NOT_FOUND: unique symbol; | ||
/** | ||
* Things that can act as inputs, from which a NoFilter can be created. | ||
*/ | ||
type BufferLike = string | Buffer | ArrayBuffer | Uint8Array | Uint8ClampedArray | DataView | stream.Readable; | ||
type BufferLike = string | Buffer | ArrayBuffer | ArrayBufferView | DataView | import("stream").Readable; | ||
type ExtendedResults = { | ||
/** | ||
* The value that was found. | ||
*/ | ||
value: any; | ||
/** | ||
* The number of bytes of the original input that | ||
* were read. | ||
*/ | ||
length: number; | ||
/** | ||
* The bytes of the original input that were used | ||
* to produce the value. | ||
*/ | ||
bytes: Buffer; | ||
/** | ||
* The bytes that were left over from the original | ||
* input. This property only exists if {@linkcode Decoder.decodeFirst} or | ||
* {@linkcode Decoder.decodeFirstSync} was called. | ||
*/ | ||
unused?: Buffer; | ||
}; | ||
type DecoderOptions = { | ||
@@ -149,2 +172,8 @@ /** | ||
/** | ||
* If true, prefer to generate Map | ||
* instances to plain objects, even if there are no entries in the map | ||
* or if all of the keys are strings. | ||
*/ | ||
preferMap?: boolean; | ||
/** | ||
* If true, prefer Uint8Arrays to | ||
@@ -167,3 +196,3 @@ * be generated instead of node Buffers. This might turn on some more | ||
* If true, emit extended | ||
* results, which will be an object with shape {@link ExtendedResults }. | ||
* results, which will be an object with shape {@link ExtendedResults}. | ||
* The value will already have been null-checked. | ||
@@ -178,27 +207,3 @@ */ | ||
}; | ||
type ExtendedResults = { | ||
/** | ||
* The value that was found. | ||
*/ | ||
value: any; | ||
/** | ||
* The number of bytes of the original input that | ||
* were read. | ||
*/ | ||
length: number; | ||
/** | ||
* The bytes of the original input that were used | ||
* to produce the value. | ||
*/ | ||
bytes: Buffer; | ||
/** | ||
* The bytes that were left over from the original | ||
* input. This property only exists if {@linkcode Decoder.decodeFirst } or | ||
* {@linkcode Decoder.decodeFirstSync } was called. | ||
*/ | ||
unused?: Buffer; | ||
}; | ||
type decodeCallback = (error?: Error, value?: any) => void; | ||
declare const NOT_FOUND: unique symbol; | ||
import { Buffer } from "buffer"; | ||
import stream = require("stream"); |
@@ -1,2 +0,1 @@ | ||
/// <reference types="node" /> | ||
export = Encoder; | ||
@@ -198,3 +197,3 @@ /** | ||
static encodeAsync(obj: any, options?: EncodingOptions): Promise<Buffer>; | ||
static set SEMANTIC_TYPES(arg: { | ||
static set SEMANTIC_TYPES(val: { | ||
[x: string]: EncodeFunction; | ||
@@ -394,8 +393,16 @@ }); | ||
import stream = require("stream"); | ||
import { Buffer } from "buffer"; | ||
import NoFilter = require("nofilter"); | ||
/** | ||
* Generate the CBOR for a value. If you are using this, you'll either need | ||
* to call {@link Encoder.write } with a Buffer, or look into the internals of | ||
* to call {@link Encoder.write} with a Buffer, or look into the internals of | ||
* Encoder to reuse existing non-documented behavior. | ||
*/ | ||
type EncodeFunction = (enc: Encoder, val: any) => boolean; | ||
/** | ||
* A mapping from tag number to a tag decoding function. | ||
*/ | ||
type SemanticMap = { | ||
[x: string]: EncodeFunction; | ||
}; | ||
type ObjectOptions = { | ||
@@ -413,4 +420,2 @@ /** | ||
}; | ||
import { Buffer } from "buffer"; | ||
import NoFilter = require("nofilter"); | ||
type EncodingOptions = { | ||
@@ -481,7 +486,1 @@ /** | ||
}; | ||
/** | ||
* A mapping from tag number to a tag decoding function. | ||
*/ | ||
type SemanticMap = { | ||
[x: string]: EncodeFunction; | ||
}; |
@@ -16,8 +16,12 @@ export = CborMap; | ||
* @ignore | ||
* @param {unknown} key | ||
* @returns {string} | ||
*/ | ||
static _encode(key: any): string; | ||
static _encode(key: unknown): string; | ||
/** | ||
* @ignore | ||
* @param {string} key | ||
* @returns {unknown} | ||
*/ | ||
static _decode(key: any): any; | ||
static _decode(key: string): unknown; | ||
/** | ||
@@ -43,10 +47,2 @@ * Creates an instance of CborMap. | ||
/** | ||
* Returns a new Iterator object that contains the keys for each element | ||
* in the Map object in insertion order. The keys are decoded into their | ||
* original format. | ||
* | ||
* @yields {any} The keys of the map. | ||
*/ | ||
keys(): Generator<any, void, unknown>; | ||
/** | ||
* Returns a new Iterator object that contains the [key, value] pairs for | ||
@@ -63,15 +59,16 @@ * each element in the Map object in insertion order. | ||
* | ||
* @param {function(any, any, Map): undefined} fun Function to execute for | ||
* each element, which takes a value, a key, and the Map being traversed. | ||
* @param {function(any, any, Map<any,any>): undefined} fun Function to | ||
* execute for each element, which takes a value, a key, and the Map | ||
* being traversed. | ||
* @param {any} thisArg Value to use as this when executing callback. | ||
* @throws {TypeError} Invalid function. | ||
*/ | ||
forEach(fun: (arg0: any, arg1: any, arg2: Map<any, any>) => undefined, thisArg: any): void; | ||
forEach(fun: (arg0: any, arg1: any, arg2: Map<any, any>) => undefined, thisArg?: any): void; | ||
/** | ||
* Push the simple value onto the CBOR stream. | ||
* | ||
* @param {object} gen The generator to push onto. | ||
* @param {import('./encoder.js')} gen The generator to push onto. | ||
* @returns {boolean} True on success. | ||
*/ | ||
encodeCBOR(gen: object): boolean; | ||
encodeCBOR(gen: import("./encoder.js")): boolean; | ||
/** | ||
@@ -81,5 +78,5 @@ * Returns a new Iterator object that contains the [key, value] pairs for | ||
* | ||
* @returns {IterableIterator} Key value pairs. | ||
* @returns {IterableIterator<any>} Key value pairs. | ||
*/ | ||
[Symbol.iterator](): IterableIterator<any>; | ||
} |
@@ -34,4 +34,4 @@ export = ObjectRecorder; | ||
declare namespace ObjectRecorder { | ||
const NEVER: number; | ||
const FIRST: number; | ||
let NEVER: number; | ||
let FIRST: number; | ||
} |
@@ -8,3 +8,3 @@ export = Tagged; | ||
declare class Tagged { | ||
static set TAGS(arg: { | ||
static set TAGS(val: { | ||
[x: string]: TagFunction; | ||
@@ -67,2 +67,3 @@ }); | ||
} | ||
declare const INTERNAL_JSON: unique symbol; | ||
/** | ||
@@ -74,3 +75,2 @@ * Convert a tagged value to a more interesting JavaScript type. Errors | ||
type TagFunction = (value: any, tag: Tagged) => any; | ||
declare const INTERNAL_JSON: unique symbol; | ||
/** | ||
@@ -77,0 +77,0 @@ * A mapping from tag number to a tag decoding function. |
@@ -1,5 +0,4 @@ | ||
/// <reference types="node" /> | ||
export function utf8(buf: any): string; | ||
export namespace utf8 { | ||
const checksUTF8: boolean; | ||
let checksUTF8: boolean; | ||
} | ||
@@ -6,0 +5,0 @@ export function isBufferish(b: any): boolean; |
@@ -10,5 +10,6 @@ // Tweaked version of nathan7's binary-parse-stream | ||
'use strict' | ||
const stream = require('stream') | ||
const NoFilter = require('nofilter') | ||
'use strict'; | ||
// eslint-disable-next-line n/prefer-node-protocol | ||
const stream = require('stream'); | ||
const NoFilter = require('nofilter'); | ||
@@ -32,12 +33,12 @@ /** | ||
constructor(options) { | ||
super(options) | ||
super(options); | ||
// Doesn't work to pass these in as opts, for some reason | ||
// also, work around typescript not knowing TransformStream internals | ||
// eslint-disable-next-line dot-notation | ||
this['_writableState'].objectMode = false | ||
this['_writableState'].objectMode = false; | ||
// eslint-disable-next-line dot-notation | ||
this['_readableState'].objectMode = true | ||
this['_readableState'].objectMode = true; | ||
this.bs = new NoFilter() | ||
this.__restart() | ||
this.bs = new NoFilter(); | ||
this.__restart(); | ||
} | ||
@@ -49,34 +50,34 @@ | ||
* @param {any} fresh Buffer to transcode. | ||
* @param {BufferEncoding} encoding Name of encoding. | ||
* @param {BufferEncoding} _encoding Name of encoding. | ||
* @param {stream.TransformCallback} cb Callback when done. | ||
* @ignore | ||
*/ | ||
_transform(fresh, encoding, cb) { | ||
this.bs.write(fresh) | ||
_transform(fresh, _encoding, cb) { | ||
this.bs.write(fresh); | ||
while (this.bs.length >= this.__needed) { | ||
let ret = null | ||
let ret = null; | ||
const chunk = (this.__needed === null) ? | ||
undefined : | ||
this.bs.read(this.__needed) | ||
this.bs.read(this.__needed); | ||
try { | ||
ret = this.__parser.next(chunk) | ||
ret = this.__parser.next(chunk); | ||
} catch (e) { | ||
return cb(e) | ||
return cb(e); | ||
} | ||
if (this.__needed) { | ||
this.__fresh = false | ||
this.__fresh = false; | ||
} | ||
if (ret.done) { | ||
this.push(ret.value) | ||
this.__restart() | ||
this.push(ret.value); | ||
this.__restart(); | ||
} else { | ||
this.__needed = ret.value || Infinity | ||
this.__needed = ret.value || Infinity; | ||
} | ||
} | ||
return cb() | ||
return cb(); | ||
} | ||
@@ -93,9 +94,9 @@ | ||
*_parse() { // eslint-disable-line class-methods-use-this, require-yield | ||
throw new Error('Must be implemented in subclass') | ||
throw new Error('Must be implemented in subclass'); | ||
} | ||
__restart() { | ||
this.__needed = null | ||
this.__parser = this._parse() | ||
this.__fresh = true | ||
this.__needed = null; | ||
this.__parser = this._parse(); | ||
this.__fresh = true; | ||
} | ||
@@ -110,6 +111,6 @@ | ||
_flush(cb) { | ||
cb(this.__fresh ? null : new Error('unexpected end of input')) | ||
cb(this.__fresh ? null : new Error('unexpected end of input')); | ||
} | ||
} | ||
module.exports = BinaryParseStream | ||
module.exports = BinaryParseStream; |
@@ -16,4 +16,4 @@ # binary-parse-stream | ||
```js | ||
const BinaryParseStream = require('binary-parse-stream') | ||
const {One} = BinaryParseStream // -1 | ||
const BinaryParseStream = require('binary-parse-stream'); | ||
const {One} = BinaryParseStream; // -1 | ||
``` | ||
@@ -35,12 +35,12 @@ | ||
constructor(options) { | ||
super(options) | ||
this.count = 0 | ||
super(options); | ||
this.count = 0; | ||
} | ||
*_parse() { | ||
const type = (yield 4).readUInt32BE(0, true) | ||
const length = yield -1 | ||
const buf = yield length | ||
this.count++ | ||
return {type, buf} | ||
const type = (yield 4).readUInt32BE(0, true); | ||
const length = yield -1; | ||
const buf = yield length; | ||
this.count++; | ||
return {type, buf}; | ||
} | ||
@@ -47,0 +47,0 @@ } |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
166513
0
4938
Updatednofilter@^3.0.2