From 212e0787b4823a92f83f9858866418cf49a9dd1a Mon Sep 17 00:00:00 2001 From: Stephen Cresswell Date: Wed, 3 Sep 2025 21:46:33 +0100 Subject: [PATCH 1/2] Add code formatting implementation plan MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Documents comprehensive plan for introducing Biome formatter with: - Node.js v16 engine requirement update - Biome installation and configuration - Staged formatting rollout (lib/ first, then all files) - Test suite validation at each stage - Lefthook pre-commit hooks for automated formatting 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- todo.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 todo.md diff --git a/todo.md b/todo.md new file mode 100644 index 00000000..dcf29159 --- /dev/null +++ b/todo.md @@ -0,0 +1,16 @@ +# Code Formatting Implementation Plan + +## Implementation Steps +1. Update Node.js engine requirement to v16 (preparation for future test harness updates) +2. Install Biome as development dependency +3. Generate lib/defs.js using existing make target to ensure it is properly formatted +4. Apply Biome formatting to all source code in lib/ directory +5. Execute complete test suite to verify code changes maintain functionality +6. Add npm format script to package.json for formatting lib/ directory +7. Install and configure Lefthook with pre-commit hook to auto-format staged files +8. Widen formatting scope to include all files and folders (not restricted to lib/) +9. Apply Biome formatting to all files +10. Execute complete test suite to verify all changes maintain functionality + +## Pull Request Structure + From 8f9a402ebb64eb0a41e73a4fafebeee3ad6677f0 Mon Sep 17 00:00:00 2001 From: Stephen Cresswell <229672+cressie176@users.noreply.github.com> Date: Wed, 3 Sep 2025 22:01:24 +0100 Subject: [PATCH 2/2] Implement comprehensive code formatting with Biome MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Update Node.js engine requirement from >=10 to >=16 - Add @biomejs/biome as development dependency with strict formatting rules - Configure Biome with 2-space indents, 140-char lines, single quotes, trailing commas - Install Lefthook for automated pre-commit formatting hooks - Add npm format script for manual code formatting - Format entire codebase (63 files) with consistent styling - Update changelog for v1.0.0 major release - All tests pass with formatted code 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- CHANGELOG.md | 7 + bin/generate-defs.js | 600 +-- biome.json | 29 + callback_api.js | 10 +- channel_api.js | 7 +- examples/direct_reply_to_client.js | 16 +- examples/direct_reply_to_server.js | 17 +- examples/headers.js | 27 +- examples/receive_generator.js | 11 +- examples/send_generators.js | 9 +- examples/ssl.js | 3 +- examples/stream_queues/receive_stream.js | 75 +- examples/stream_queues/send_stream.js | 55 +- examples/tutorials/callback_api/emit_log.js | 9 +- .../tutorials/callback_api/emit_log_direct.js | 11 +- .../tutorials/callback_api/emit_log_topic.js | 11 +- examples/tutorials/callback_api/new_task.js | 13 +- examples/tutorials/callback_api/receive.js | 28 +- .../tutorials/callback_api/receive_logs.js | 30 +- .../callback_api/receive_logs_direct.js | 36 +- .../callback_api/receive_logs_topic.js | 37 +- examples/tutorials/callback_api/rpc_client.js | 42 +- examples/tutorials/callback_api/rpc_server.js | 48 +- examples/tutorials/callback_api/send.js | 9 +- examples/tutorials/callback_api/worker.js | 33 +- examples/tutorials/emit_log.js | 12 +- examples/tutorials/emit_log_direct.js | 14 +- examples/tutorials/emit_log_topic.js | 14 +- examples/tutorials/new_task.js | 14 +- examples/tutorials/receive.js | 14 +- examples/tutorials/receive_logs.js | 20 +- examples/tutorials/receive_logs_direct.js | 30 +- examples/tutorials/receive_logs_topic.js | 31 +- examples/tutorials/rpc_client.js | 38 +- examples/tutorials/rpc_server.js | 17 +- examples/tutorials/send.js | 12 +- examples/tutorials/worker.js | 33 +- examples/waitForConfirms.js | 4 +- lefthook.yml | 6 + lib/api_args.js | 117 +- lib/bitset.js | 38 +- lib/callback_model.js | 254 +- lib/channel.js | 310 +- lib/channel_model.js | 105 +- lib/codec.js | 467 +- lib/connect.js | 81 +- lib/connection.js | 271 +- lib/credentials.js | 36 +- lib/defs.js | 4486 ++++++++++------- lib/error.js | 3 +- lib/format.js | 28 +- lib/frame.js | 114 +- lib/heartbeat.js | 25 +- lib/mux.js | 31 +- package-lock.json | 490 +- package.json | 7 +- test/bitset.js | 132 +- test/callback_api.js | 329 +- test/channel.js | 1237 +++-- test/channel_api.js | 604 +-- test/codec.js | 215 +- test/connect.js | 164 +- test/connection.js | 688 +-- test/data.js | 364 +- test/frame.js | 256 +- test/mux.js | 138 +- test/util.js | 99 +- todo.md | 41 +- 68 files changed, 7120 insertions(+), 5442 deletions(-) create mode 100644 biome.json create mode 100644 lefthook.yml diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e861b97..435cc0c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Change log for amqplib +## v1.0.0 +- **BREAKING**: Update minimum Node.js requirement to v16 +- Introduce Biome formatter for consistent code formatting +- Add automated formatting via pre-commit hooks using Lefthook +- Format entire codebase with standardised formatting rules +- Add npm format script for manual code formatting + ## v0.10.9 - Add support for IPv6 urls diff --git a/bin/generate-defs.js b/bin/generate-defs.js index 2e87fd40..6f8937f2 100644 --- a/bin/generate-defs.js +++ b/bin/generate-defs.js @@ -11,24 +11,26 @@ var METHOD_OVERHEAD = FRAME_OVERHEAD + 4; var PROPERTIES_OVERHEAD = FRAME_OVERHEAD + 4 + 8 + 2; // F_O + classId + weight + content size + flags - var out = process.stdout; function printf() { out.write(format.apply(format, arguments), 'utf8'); } -function nl() { out.write('\n'); } -function println() { printf.apply(printf, arguments); nl(); } +function nl() { + out.write('\n'); +} +function println() { + printf.apply(printf, arguments); + nl(); +} function isEmptyObject(val) { - return (val != null && typeof val === 'object' && - Object.keys(val).length === 0); + return val != null && typeof val === 'object' && Object.keys(val).length === 0; } function stringifyValue(val) { - return (isEmptyObject(val)) ? 'EMPTY_OBJECT' : - JSON.stringify(val); + return isEmptyObject(val) ? 'EMPTY_OBJECT' : JSON.stringify(val); } var constants = {}; @@ -64,7 +66,7 @@ function argument(a) { } var domains = {}; -for (var i=0, len = defs.domains.length; i < len; i++) { +for (var i = 0, len = defs.domains.length; i < len; i++) { var dom = defs.domains[i]; domains[dom[0]] = dom[1]; } @@ -89,7 +91,7 @@ for (var i = 0, len = defs.classes.length; i < len; i++) { isReply: method.answer, encoder: 'encode' + name, decoder: 'decode' + name, - info: info + info: info, }; } if (clazz.properties && clazz.properties.length > 0) { @@ -109,14 +111,16 @@ for (var i = 0, len = defs.classes.length; i < len; i++) { // OK let's get emitting println( -'/** @preserve This file is generated by the script\n', -'* ../bin/generate-defs.js, which is not in general included in a\n', -'* distribution, but is available in the source repository e.g. at\n', -'* https://github.com/amqp-node/amqplib/\n', -'*/'); - -println("'use strict';"); nl(); -nl() + '/** @preserve This file is generated by the script\n', + '* ../bin/generate-defs.js, which is not in general included in a\n', + '* distribution, but is available in the source repository e.g. at\n', + '* https://github.com/amqp-node/amqplib/\n', + '*/', +); + +println("'use strict';"); +nl(); +nl(); println('var codec = require("./codec");'); println('var ints = require("buffer-more-ints");'); println('var encodeTable = codec.encodeTable;'); @@ -126,11 +130,9 @@ nl(); println('var SCRATCH = Buffer.alloc(65536);'); println('var EMPTY_OBJECT = Object.freeze({});'); -println('module.exports.constants = %s', - JSON.stringify(constants)); +println('module.exports.constants = %s', JSON.stringify(constants)); nl(); -println('module.exports.constant_strs = %s', - JSON.stringify(constant_strs)); +println('module.exports.constant_strs = %s', JSON.stringify(constant_strs)); nl(); println('module.exports.FRAME_OVERHEAD = %d;', FRAME_OVERHEAD); nl(); @@ -143,32 +145,31 @@ for (var m in methods) { } for (var p in propertieses) { var props = propertieses[p]; - println('case %d: return %s(buf);', props.id, props.decoder); + println('case %d: return %s(buf);', props.id, props.decoder); } println('default: throw new Error("Unknown class/method ID");'); -println('}}'); nl(); +println('}}'); +nl(); -println('module.exports.encodeMethod =', - 'function(id, channel, fields) {'); +println('module.exports.encodeMethod =', 'function(id, channel, fields) {'); println('switch (id) {'); for (var m in methods) { var method = methods[m]; - println('case %d: return %s(channel, fields);', - method.id, method.encoder); + println('case %d: return %s(channel, fields);', method.id, method.encoder); } println('default: throw new Error("Unknown class/method ID");'); -println('}}'); nl(); +println('}}'); +nl(); -println('module.exports.encodeProperties =' - , 'function(id, channel, size, fields) {'); +println('module.exports.encodeProperties =', 'function(id, channel, size, fields) {'); println('switch (id) {'); for (var p in propertieses) { var props = propertieses[p]; - println('case %d: return %s(channel, size, fields);', - props.id, props.encoder); + println('case %d: return %s(channel, size, fields);', props.id, props.encoder); } println('default: throw new Error("Unknown class/properties ID");'); -println('}}'); nl(); +println('}}'); +nl(); println('module.exports.info = function(id) {'); println('switch(id) {'); @@ -181,22 +182,29 @@ for (var p in propertieses) { println('case %d: return %s', properties.id, properties.info); } println('default: throw new Error("Unknown class/method ID");'); -println('}}'); nl(); +println('}}'); +nl(); for (var m in methods) { var method = methods[m]; println('module.exports.%s = %d;', m, method.id); - decoderFn(method); nl(); - encoderFn(method); nl(); - infoObj(method); nl(); + decoderFn(method); + nl(); + encoderFn(method); + nl(); + infoObj(method); + nl(); } for (var p in propertieses) { var properties = propertieses[p]; println('module.exports.%s = %d;', p, properties.id); - encodePropsFn(properties); nl(); - decodePropsFn(properties); nl(); - infoObj(properties); nl(); + encodePropsFn(properties); + nl(); + decodePropsFn(properties); + nl(); + infoObj(properties); + nl(); } function methodId(clazz, method) { @@ -209,41 +217,50 @@ function propertiesName(clazz) { function valTypeTest(arg) { switch (arg.type) { - // everything is booleany - case 'bit': return 'true' - case 'octet': - case 'short': - case 'long': - case 'longlong': - case 'timestamp': return "typeof val === 'number' && !isNaN(val)"; - case 'shortstr': return "typeof val === 'string' &&" + - " Buffer.byteLength(val) < 256"; - case 'longstr': return "Buffer.isBuffer(val)"; - case 'table': return "typeof val === 'object'"; + // everything is booleany + case 'bit': + return 'true'; + case 'octet': + case 'short': + case 'long': + case 'longlong': + case 'timestamp': + return "typeof val === 'number' && !isNaN(val)"; + case 'shortstr': + return "typeof val === 'string' &&" + ' Buffer.byteLength(val) < 256'; + case 'longstr': + return 'Buffer.isBuffer(val)'; + case 'table': + return "typeof val === 'object'"; } } function typeDesc(t) { switch (t) { - case 'bit': return 'booleany'; - case 'octet': - case 'short': - case 'long': - case 'longlong': - case 'timestamp': return "a number (but not NaN)"; - case 'shortstr': return "a string (up to 255 chars)"; - case 'longstr': return "a Buffer"; - case 'table': return "an object"; + case 'bit': + return 'booleany'; + case 'octet': + case 'short': + case 'long': + case 'longlong': + case 'timestamp': + return 'a number (but not NaN)'; + case 'shortstr': + return 'a string (up to 255 chars)'; + case 'longstr': + return 'a Buffer'; + case 'table': + return 'an object'; } } function defaultValueRepr(arg) { switch (arg.type) { - case 'longstr': - return format("Buffer.from(%s)", JSON.stringify(arg.default)); - default: - // assumes no tables as defaults - return JSON.stringify(arg.default); + case 'longstr': + return format('Buffer.from(%s)', JSON.stringify(arg.default)); + default: + // assumes no tables as defaults + return JSON.stringify(arg.default); } } @@ -254,7 +271,7 @@ function assignArg(a) { function assignOrDefault(a) { println("val = fields['%s'];", a.name); - println("if (val === undefined) val = %s;", defaultValueRepr(a)); + println('if (val === undefined) val = %s;', defaultValueRepr(a)); } // Emit code for assigning an argument value to `val`, checking that @@ -265,15 +282,13 @@ function checkAssignArg(a) { println('if (val === undefined) {'); if (a.default !== undefined) { println('val = %s;', defaultValueRepr(a)); - } - else { + } else { println('throw new Error("Missing value for mandatory field \'%s\'");', a.name); } println('}'); // undefined test println('else if (!(%s)) {', valTypeTest(a)); println('throw new TypeError('); - println('"Field \'%s\' is the wrong type; must be %s");', - a.name, typeDesc(a.type)); + println('"Field \'%s\' is the wrong type; must be %s");', a.name, typeDesc(a.type)); println('}'); // type test } @@ -286,8 +301,7 @@ function checkAssignArg(a) { // expected to have been declared. function assignTable(a) { var varname = tableVar(a); - println( - "len = encodeTable(SCRATCH, val, scratchOffset);"); + println('len = encodeTable(SCRATCH, val, scratchOffset);'); println('var %s = SCRATCH.slice(scratchOffset, scratchOffset + len);', varname); println('scratchOffset += len;'); } @@ -306,7 +320,6 @@ function assignStringLen(a) { println("var %s = Buffer.byteLength(val, 'utf8');", v); } - function encoderFn(method) { var args = method['args']; println('function %s(channel, fields) {', method.encoder); @@ -323,46 +336,53 @@ function encoderFn(method) { var bitsInARow = 0; - for (var i=0, len = args.length; i < len; i++) { + for (var i = 0, len = args.length; i < len; i++) { var arg = args[i]; if (arg.type != 'bit') bitsInARow = 0; switch (arg.type) { - // varying size - case 'shortstr': - checkAssignArg(arg); - assignStringLen(arg); - println("varyingSize += %s;", stringLenVar(arg)); - fixedSize += 1; - break; - case 'longstr': - checkAssignArg(arg); - println("varyingSize += val.length;"); - fixedSize += 4; - break; - case 'table': - // For a table we have to encode the table before we can see its - // length. - checkAssignArg(arg); - assignTable(arg); - println('varyingSize += %s.length;', tableVar(arg)); - break; - - // fixed size - case 'octet': fixedSize += 1; break; - case 'short': fixedSize += 2; break; - case 'long': fixedSize += 4; break; - case 'longlong': //fall through - case 'timestamp': - fixedSize += 8; break; - case 'bit': - bitsInARow ++; - // open a fresh pack o' bits - if (bitsInARow === 1) fixedSize += 1; - // just used a pack; reset - else if (bitsInARow === 8) bitsInARow = 0; - break; + // varying size + case 'shortstr': + checkAssignArg(arg); + assignStringLen(arg); + println('varyingSize += %s;', stringLenVar(arg)); + fixedSize += 1; + break; + case 'longstr': + checkAssignArg(arg); + println('varyingSize += val.length;'); + fixedSize += 4; + break; + case 'table': + // For a table we have to encode the table before we can see its + // length. + checkAssignArg(arg); + assignTable(arg); + println('varyingSize += %s.length;', tableVar(arg)); + break; + + // fixed size + case 'octet': + fixedSize += 1; + break; + case 'short': + fixedSize += 2; + break; + case 'long': + fixedSize += 4; + break; + case 'longlong': //fall through + case 'timestamp': + fixedSize += 8; + break; + case 'bit': + bitsInARow++; + // open a fresh pack o' bits + if (bitsInARow === 1) fixedSize += 1; + // just used a pack; reset + else if (bitsInARow === 8) bitsInARow = 0; + break; } } @@ -386,48 +406,48 @@ function encoderFn(method) { } switch (a.type) { - case 'octet': - checkAssignArg(a); - println('buffer.writeUInt8(val, offset); offset++;'); - break; - case 'short': - checkAssignArg(a); - println('buffer.writeUInt16BE(val, offset); offset += 2;'); - break; - case 'long': - checkAssignArg(a); - println('buffer.writeUInt32BE(val, offset); offset += 4;'); - break; - case 'longlong': - case 'timestamp': - checkAssignArg(a); - println('ints.writeUInt64BE(buffer, val, offset); offset += 8;'); - break; - case 'bit': - checkAssignArg(a); - println('if (val) bits += %d;', 1 << bitsInARow); - if (bitsInARow === 7) { // I don't think this ever happens, but whatever - println('buffer[offset] = bits; offset++; bits = 0;'); - bitsInARow = 0; - } - else bitsInARow++; - break; - case 'shortstr': - assignOrDefault(a); - println('buffer[offset] = %s; offset++;', stringLenVar(a)); - println('buffer.write(val, offset, "utf8"); offset += %s;', - stringLenVar(a)); - break; - case 'longstr': - assignOrDefault(a); - println('len = val.length;'); - println('buffer.writeUInt32BE(len, offset); offset += 4;'); - println('val.copy(buffer, offset); offset += len;'); - break; - case 'table': - println('offset += %s.copy(buffer, offset);', tableVar(a)); - break; - default: throw new Error("Unexpected argument type: " + a.type); + case 'octet': + checkAssignArg(a); + println('buffer.writeUInt8(val, offset); offset++;'); + break; + case 'short': + checkAssignArg(a); + println('buffer.writeUInt16BE(val, offset); offset += 2;'); + break; + case 'long': + checkAssignArg(a); + println('buffer.writeUInt32BE(val, offset); offset += 4;'); + break; + case 'longlong': + case 'timestamp': + checkAssignArg(a); + println('ints.writeUInt64BE(buffer, val, offset); offset += 8;'); + break; + case 'bit': + checkAssignArg(a); + println('if (val) bits += %d;', 1 << bitsInARow); + if (bitsInARow === 7) { + // I don't think this ever happens, but whatever + println('buffer[offset] = bits; offset++; bits = 0;'); + bitsInARow = 0; + } else bitsInARow++; + break; + case 'shortstr': + assignOrDefault(a); + println('buffer[offset] = %s; offset++;', stringLenVar(a)); + println('buffer.write(val, offset, "utf8"); offset += %s;', stringLenVar(a)); + break; + case 'longstr': + assignOrDefault(a); + println('len = val.length;'); + println('buffer.writeUInt32BE(len, offset); offset += 4;'); + println('val.copy(buffer, offset); offset += len;'); + break; + case 'table': + println('offset += %s.copy(buffer, offset);', tableVar(a)); + break; + default: + throw new Error('Unexpected argument type: ' + a.type); } } @@ -446,7 +466,7 @@ function encoderFn(method) { function fieldsDecl(args) { println('var fields = {'); - for (var i=0, num=args.length; i < num; i++) { + for (var i = 0, num = args.length; i < num; i++) { println('%s: undefined,', args[i].name); } println('};'); @@ -460,7 +480,7 @@ function decoderFn(method) { var bitsInARow = 0; - for (var i=0, num=args.length; i < num; i++) { + for (var i = 0, num = args.length; i < num; i++) { var a = args[i]; var field = "fields['" + a.name + "']"; @@ -471,45 +491,44 @@ function decoderFn(method) { } switch (a.type) { - case 'octet': - println('val = buffer[offset]; offset++;'); - break; - case 'short': - println('val = buffer.readUInt16BE(offset); offset += 2;'); - break; - case 'long': - println('val = buffer.readUInt32BE(offset); offset += 4;'); - break; - case 'longlong': - case 'timestamp': - println('val = ints.readUInt64BE(buffer, offset); offset += 8;'); - break; - case 'bit': - var bit = 1 << bitsInARow; - println('val = !!(buffer[offset] & %d);', bit); - if (bitsInARow === 7) { - println('offset++;'); - bitsInARow = 0; - } - else bitsInARow++; - break; - case 'longstr': - println('len = buffer.readUInt32BE(offset); offset += 4;'); - println('val = buffer.subarray(offset, offset + len);'); - println('offset += len;'); - break; - case 'shortstr': - println('len = buffer.readUInt8(offset); offset++;'); - println('val = buffer.toString("utf8", offset, offset + len);'); - println('offset += len;'); - break; - case 'table': - println('len = buffer.readUInt32BE(offset); offset += 4;'); - println('val = decodeFields(buffer.subarray(offset, offset + len));'); - println('offset += len;'); - break; - default: - throw new TypeError("Unexpected type in argument list: " + a.type); + case 'octet': + println('val = buffer[offset]; offset++;'); + break; + case 'short': + println('val = buffer.readUInt16BE(offset); offset += 2;'); + break; + case 'long': + println('val = buffer.readUInt32BE(offset); offset += 4;'); + break; + case 'longlong': + case 'timestamp': + println('val = ints.readUInt64BE(buffer, offset); offset += 8;'); + break; + case 'bit': + var bit = 1 << bitsInARow; + println('val = !!(buffer[offset] & %d);', bit); + if (bitsInARow === 7) { + println('offset++;'); + bitsInARow = 0; + } else bitsInARow++; + break; + case 'longstr': + println('len = buffer.readUInt32BE(offset); offset += 4;'); + println('val = buffer.subarray(offset, offset + len);'); + println('offset += len;'); + break; + case 'shortstr': + println('len = buffer.readUInt8(offset); offset++;'); + println('val = buffer.toString("utf8", offset, offset + len);'); + println('offset += len;'); + break; + case 'table': + println('len = buffer.readUInt32BE(offset); offset += 4;'); + println('val = decodeFields(buffer.subarray(offset, offset + len));'); + println('offset += len;'); + break; + default: + throw new TypeError('Unexpected type in argument list: ' + a.type); } println('%s = val;', field); } @@ -518,13 +537,8 @@ function decoderFn(method) { } function infoObj(thing) { - var info = JSON.stringify({id: thing.id, - classId: thing.clazzId, - methodId: thing.methodId, - name: thing.name, - args: thing.args}); - println('var %s = module.exports.%s = %s;', - thing.info, thing.info, info); + var info = JSON.stringify({id: thing.id, classId: thing.clazzId, methodId: thing.methodId, name: thing.name, args: thing.args}); + println('var %s = module.exports.%s = %s;', thing.info, thing.info, info); } // The flags are laid out in groups of fifteen in a short (high to @@ -551,42 +565,48 @@ function encodePropsFn(props) { var args = props.args; function incVarying(by) { - println("varyingSize += %d;", by); + println('varyingSize += %d;', by); } - for (var i=0, num=args.length; i < num; i++) { + for (var i = 0, num = args.length; i < num; i++) { var p = args[i]; assignArg(p); - println("if (val != undefined) {"); + println('if (val != undefined) {'); - println("if (%s) {", valTypeTest(p)); + println('if (%s) {', valTypeTest(p)); switch (p.type) { - case 'shortstr': - assignStringLen(p); - incVarying(1); - println('varyingSize += %s;', stringLenVar(p)); - break; - case 'longstr': - incVarying(4); - println('varyingSize += val.length;'); - break; - case 'table': - assignTable(p); - println('varyingSize += %s.length;', tableVar(p)); - break; - case 'octet': incVarying(1); break; - case 'short': incVarying(2); break; - case 'long': incVarying(4); break; - case 'longlong': // fall through - case 'timestamp': - incVarying(8); break; + case 'shortstr': + assignStringLen(p); + incVarying(1); + println('varyingSize += %s;', stringLenVar(p)); + break; + case 'longstr': + incVarying(4); + println('varyingSize += val.length;'); + break; + case 'table': + assignTable(p); + println('varyingSize += %s.length;', tableVar(p)); + break; + case 'octet': + incVarying(1); + break; + case 'short': + incVarying(2); + break; + case 'long': + incVarying(4); + break; + case 'longlong': // fall through + case 'timestamp': + incVarying(8); + break; // no case for bit, as they are accounted for in the flags } println('} else {'); println('throw new TypeError('); - println('"Field \'%s\' is the wrong type; must be %s");', - p.name, typeDesc(p.type)); + println('"Field \'%s\' is the wrong type; must be %s");', p.name, typeDesc(p.type)); println('}'); println('}'); } @@ -606,48 +626,49 @@ function encodePropsFn(props) { // we'll write the flags later too println('offset = 21;'); - for (var i=0, num=args.length; i < num; i++) { + for (var i = 0, num = args.length; i < num; i++) { var p = args[i]; var flag = flagAt(i); assignArg(p); - println("if (val != undefined) {"); - if (p.type === 'bit') { // which none of them are .. + println('if (val != undefined) {'); + if (p.type === 'bit') { + // which none of them are .. println('if (val) flags += %d;', flag); - } - else { + } else { println('flags += %d;', flag); // %%% FIXME only slightly different to the method args encoding switch (p.type) { - case 'octet': - println('buffer.writeUInt8(val, offset); offset++;'); - break; - case 'short': - println('buffer.writeUInt16BE(val, offset); offset += 2;'); - break; - case 'long': - println('buffer.writeUInt32BE(val, offset); offset += 4;'); - break; - case 'longlong': - case 'timestamp': - println('ints.writeUInt64BE(buffer, val, offset);'); - println('offset += 8;'); - break; - case 'shortstr': - var v = stringLenVar(p); - println('buffer[offset] = %s; offset++;', v); - println("buffer.write(val, offset, 'utf8');"); - println("offset += %s;", v); - break; - case 'longstr': - println('buffer.writeUInt32BE(val.length, offset);'); - println('offset += 4;'); - println('offset += val.copy(buffer, offset);'); - break; - case 'table': - println('offset += %s.copy(buffer, offset);', tableVar(p)); - break; - default: throw new Error("Unexpected argument type: " + p.type); + case 'octet': + println('buffer.writeUInt8(val, offset); offset++;'); + break; + case 'short': + println('buffer.writeUInt16BE(val, offset); offset += 2;'); + break; + case 'long': + println('buffer.writeUInt32BE(val, offset); offset += 4;'); + break; + case 'longlong': + case 'timestamp': + println('ints.writeUInt64BE(buffer, val, offset);'); + println('offset += 8;'); + break; + case 'shortstr': + var v = stringLenVar(p); + println('buffer[offset] = %s; offset++;', v); + println("buffer.write(val, offset, 'utf8');"); + println('offset += %s;', v); + break; + case 'longstr': + println('buffer.writeUInt32BE(val.length, offset);'); + println('offset += 4;'); + println('offset += val.copy(buffer, offset);'); + break; + case 'table': + println('offset += %s.copy(buffer, offset);', tableVar(p)); + break; + default: + throw new Error('Unexpected argument type: ' + p.type); } } println('}'); // != undefined @@ -672,46 +693,45 @@ function decodePropsFn(props) { fieldsDecl(args); - for (var i=0, num=args.length; i < num; i++) { + for (var i = 0, num = args.length; i < num; i++) { var p = argument(args[i]); var field = "fields['" + p.name + "']"; println('if (flags & %d) {', flagAt(i)); if (p.type === 'bit') { println('%d = true;', field); - } - else { + } else { switch (p.type) { - case 'octet': - println('val = buffer[offset]; offset++;'); - break; - case 'short': - println('val = buffer.readUInt16BE(offset); offset += 2;'); - break; - case 'long': - println('val = buffer.readUInt32BE(offset); offset += 4;'); - break; - case 'longlong': - case 'timestamp': - println('val = ints.readUInt64BE(buffer, offset); offset += 8;'); - break; - case 'longstr': - println('len = buffer.readUInt32BE(offset); offset += 4;'); - println('val = buffer.subarray(offset, offset + len);'); - println('offset += len;'); - break; - case 'shortstr': - println('len = buffer.readUInt8(offset); offset++;'); - println('val = buffer.toString("utf8", offset, offset + len);'); - println('offset += len;'); - break; - case 'table': - println('len = buffer.readUInt32BE(offset); offset += 4;'); - println('val = decodeFields(buffer.subarray(offset, offset + len));'); - println('offset += len;'); - break; - default: - throw new TypeError("Unexpected type in argument list: " + p.type); + case 'octet': + println('val = buffer[offset]; offset++;'); + break; + case 'short': + println('val = buffer.readUInt16BE(offset); offset += 2;'); + break; + case 'long': + println('val = buffer.readUInt32BE(offset); offset += 4;'); + break; + case 'longlong': + case 'timestamp': + println('val = ints.readUInt64BE(buffer, offset); offset += 8;'); + break; + case 'longstr': + println('len = buffer.readUInt32BE(offset); offset += 4;'); + println('val = buffer.subarray(offset, offset + len);'); + println('offset += len;'); + break; + case 'shortstr': + println('len = buffer.readUInt8(offset); offset++;'); + println('val = buffer.toString("utf8", offset, offset + len);'); + println('offset += len;'); + break; + case 'table': + println('len = buffer.readUInt32BE(offset); offset += 4;'); + println('val = decodeFields(buffer.subarray(offset, offset + len));'); + println('offset += len;'); + break; + default: + throw new TypeError('Unexpected type in argument list: ' + p.type); } println('%s = val;', field); } diff --git a/biome.json b/biome.json new file mode 100644 index 00000000..f7436caf --- /dev/null +++ b/biome.json @@ -0,0 +1,29 @@ +{ + "formatter": { + "enabled": true, + "formatWithErrors": false, + "indentStyle": "space", + "indentWidth": 2, + "lineWidth": 140, + "lineEnding": "lf", + "attributePosition": "auto" + }, + "linter": { + "enabled": false + }, + "javascript": { + "formatter": { + "arrowParentheses": "always", + "bracketSameLine": false, + "bracketSpacing": false, + "jsxQuoteStyle": "double", + "quoteProperties": "asNeeded", + "quoteStyle": "single", + "semicolons": "always", + "trailingCommas": "all" + } + }, + "files": { + "includes": ["**/*.js"] + } +} diff --git a/callback_api.js b/callback_api.js index 19553128..0005d95d 100644 --- a/callback_api.js +++ b/callback_api.js @@ -6,16 +6,14 @@ var CallbackModel = require('./lib/callback_model').CallbackModel; // connect(url, callback) // connect(callback) function connect(url, options, cb) { - if (typeof url === 'function') - cb = url, url = false, options = false; - else if (typeof options === 'function') - cb = options, options = false; + if (typeof url === 'function') (cb = url), (url = false), (options = false); + else if (typeof options === 'function') (cb = options), (options = false); - raw_connect(url, options, function(err, c) { + raw_connect(url, options, function (err, c) { if (err === null) cb(null, new CallbackModel(c)); else cb(err); }); -}; +} module.exports.connect = connect; module.exports.credentials = require('./lib/credentials'); diff --git a/channel_api.js b/channel_api.js index 4fe67f68..0688f8df 100644 --- a/channel_api.js +++ b/channel_api.js @@ -3,13 +3,12 @@ var ChannelModel = require('./lib/channel_model').ChannelModel; var promisify = require('util').promisify; function connect(url, connOptions) { - return promisify(function(cb) { + return promisify(function (cb) { return raw_connect(url, connOptions, cb); - })() - .then(function(conn) { + })().then(function (conn) { return new ChannelModel(conn); }); -}; +} module.exports.connect = connect; module.exports.credentials = require('./lib/credentials'); diff --git a/examples/direct_reply_to_client.js b/examples/direct_reply_to_client.js index 4c7027c6..53fdfdb0 100644 --- a/examples/direct_reply_to_client.js +++ b/examples/direct_reply_to_client.js @@ -8,13 +8,17 @@ const queue = 'rpc_queue'; const connection = await amqp.connect(); const channel = await connection.createChannel(); - await channel.consume('amq.rabbitmq.reply-to', async (message) => { - console.log(message.content.toString()); - await channel.close(); - await connection.close(); - }, { noAck: true }); + await channel.consume( + 'amq.rabbitmq.reply-to', + async (message) => { + console.log(message.content.toString()); + await channel.close(); + await connection.close(); + }, + {noAck: true}, + ); - await channel.assertQueue(queue, { durable: false }); + await channel.assertQueue(queue, {durable: false}); channel.sendToQueue(queue, Buffer.from(' [X] ping'), { replyTo: 'amq.rabbitmq.reply-to', diff --git a/examples/direct_reply_to_server.js b/examples/direct_reply_to_server.js index 394890ec..e65e4ad0 100644 --- a/examples/direct_reply_to_server.js +++ b/examples/direct_reply_to_server.js @@ -1,7 +1,7 @@ #!/usr/bin/env node const amqp = require('../'); -const { v4: uuid } = require('uuid'); +const {v4: uuid} = require('uuid'); const queue = 'rpc_queue'; @@ -14,12 +14,15 @@ const queue = 'rpc_queue'; await connection.close(); }); - await channel.assertQueue(queue, { durable: false }); - await channel.consume(queue, (message) => { - console.log(message.content.toString()); - channel.sendToQueue(message.properties.replyTo, Buffer.from(' [.] pong')); - }, { noAck: true }); + await channel.assertQueue(queue, {durable: false}); + await channel.consume( + queue, + (message) => { + console.log(message.content.toString()); + channel.sendToQueue(message.properties.replyTo, Buffer.from(' [.] pong')); + }, + {noAck: true}, + ); console.log(' [x] To exit press CTRL+C.'); - })(); diff --git a/examples/headers.js b/examples/headers.js index dce178c4..0f6ff7b9 100755 --- a/examples/headers.js +++ b/examples/headers.js @@ -3,7 +3,6 @@ const amqp = require('../'); (async () => { - const connection = await amqp.connect(); const channel = await connection.createChannel(); @@ -12,8 +11,8 @@ const amqp = require('../'); await connection.close(); }); - const { exchange } = await channel.assertExchange('matching exchange', 'headers'); - const { queue } = await channel.assertQueue(); + const {exchange} = await channel.assertExchange('matching exchange', 'headers'); + const {queue} = await channel.assertQueue(); // When using a headers exchange, the headers to be matched go in // the binding arguments. The routing key is ignore, so best left @@ -24,17 +23,21 @@ const amqp = require('../'); // matched go in subsequent fields. await channel.bindQueue(queue, exchange, '', { 'x-match': 'any', - 'foo': 'bar', - 'baz': 'boo' + foo: 'bar', + baz: 'boo', }); - await channel.consume(queue, (message) => { - console.log(message.content.toString()); - }, { noAck: true }); - - channel.publish(exchange, '', Buffer.from('hello'), { headers: { baz: 'boo' }}); - channel.publish(exchange, '', Buffer.from('hello'), { headers: { foo: 'bar' }}); - channel.publish(exchange, '', Buffer.from('lost'), { headers: { meh: 'nah' }}); + await channel.consume( + queue, + (message) => { + console.log(message.content.toString()); + }, + {noAck: true}, + ); + + channel.publish(exchange, '', Buffer.from('hello'), {headers: {baz: 'boo'}}); + channel.publish(exchange, '', Buffer.from('hello'), {headers: {foo: 'bar'}}); + channel.publish(exchange, '', Buffer.from('lost'), {headers: {meh: 'nah'}}); console.log(' [x] To exit press CTRL+C.'); })(); diff --git a/examples/receive_generator.js b/examples/receive_generator.js index 8146de0c..e9c86684 100644 --- a/examples/receive_generator.js +++ b/examples/receive_generator.js @@ -21,19 +21,18 @@ co(function* () { channel.sendToQueue(q, Buffer.from(msg)); console.log(" [x] Sent '%s'", msg); // consume the message - yield channel.consume(q, myConsumer, { noAck: true }); - } - catch (e) { + yield channel.consume(q, myConsumer, {noAck: true}); + } catch (e) { throw e; } -}).catch(err => { +}).catch((err) => { console.warn('Error:', err); }); const rl = readline.createInterface({ input: process.stdin, - output: process.stdout + output: process.stdout, }); // pend until message is consumed -rl.question('newline to exit', () => process.exit()); \ No newline at end of file +rl.question('newline to exit', () => process.exit()); diff --git a/examples/send_generators.js b/examples/send_generators.js index 171778e9..e1ca1978 100755 --- a/examples/send_generators.js +++ b/examples/send_generators.js @@ -29,14 +29,11 @@ co(function* () { console.log(" [x] Sent '%s'", msg); channel.close(); - } - catch (e) { + } catch (e) { throw e; - } - finally { + } finally { conn.close(); } - -}).catch(err => { +}).catch((err) => { console.warn('Error:', err); }); diff --git a/examples/ssl.js b/examples/ssl.js index a0a3cd5a..0974fc1a 100644 --- a/examples/ssl.js +++ b/examples/ssl.js @@ -40,7 +40,7 @@ const opts = { // cert and key or // pfx: fs.readFileSync('../etc/client/keycert.p12'), passphrase: 'MySecretPassword', - ca: [fs.readFileSync('../etc/testca/cacert.pem')] + ca: [fs.readFileSync('../etc/testca/cacert.pem')], }; // Options for just confidentiality. This requires RabbitMQ's SSL @@ -67,4 +67,3 @@ const opts = { console.log(' [x] To exit press CTRL+C.'); })(); - diff --git a/examples/stream_queues/receive_stream.js b/examples/stream_queues/receive_stream.js index 6144a4d1..90af5479 100755 --- a/examples/stream_queues/receive_stream.js +++ b/examples/stream_queues/receive_stream.js @@ -1,34 +1,37 @@ const amqp = require('amqplib'); (async () => { - try { - const connection = await amqp.connect('amqp://localhost'); - process.once('SIGINT', connection.close); - - const channel = await connection.createChannel(); - const queue = 'my_first_stream'; - - // Define the queue stream - // Mandatory: exclusive: false, durable: true autoDelete: false - await channel.assertQueue(queue, { - exclusive: false, - durable: true, - autoDelete: false, - arguments: { - 'x-queue-type': 'stream', // Mandatory to define stream queue - 'x-max-length-bytes': 2_000_000_000 // Set the queue retention to 2GB else the stream doesn't have any limit - } - }); - - channel.qos(100); // This is mandatory - - channel.consume(queue, (msg) => { - console.log(" [x] Received '%s'", msg.content.toString()); - channel.ack(msg); // Mandatory - }, { - noAck: false, - arguments: { - /* + try { + const connection = await amqp.connect('amqp://localhost'); + process.once('SIGINT', connection.close); + + const channel = await connection.createChannel(); + const queue = 'my_first_stream'; + + // Define the queue stream + // Mandatory: exclusive: false, durable: true autoDelete: false + await channel.assertQueue(queue, { + exclusive: false, + durable: true, + autoDelete: false, + arguments: { + 'x-queue-type': 'stream', // Mandatory to define stream queue + 'x-max-length-bytes': 2_000_000_000, // Set the queue retention to 2GB else the stream doesn't have any limit + }, + }); + + channel.qos(100); // This is mandatory + + channel.consume( + queue, + (msg) => { + console.log(" [x] Received '%s'", msg.content.toString()); + channel.ack(msg); // Mandatory + }, + { + noAck: false, + arguments: { + /* Here you can specify the offset: : first, last, next, offset, timestamp and interval, i.e. 'x-stream-offset': 'first' @@ -42,14 +45,14 @@ const amqp = require('amqplib'); The interval units can be Y, M, D, h, m, s */ - 'x-stream-offset': 'first' - } - }); + 'x-stream-offset': 'first', + }, + }, + ); - console.log(' [*] Waiting for messages. To exit press CTRL+C'); - } + console.log(' [*] Waiting for messages. To exit press CTRL+C'); + } catch (e) { // Catch and display any errors in the console - catch(e) { - console.log(e) - } + console.log(e); + } })(); diff --git a/examples/stream_queues/send_stream.js b/examples/stream_queues/send_stream.js index 3d6991db..33cf1dcb 100755 --- a/examples/stream_queues/send_stream.js +++ b/examples/stream_queues/send_stream.js @@ -1,38 +1,35 @@ const amqp = require('amqplib'); - (async () => { - try { - const connection = await amqp.connect('amqp://localhost'); - process.once('SIGINT', connection.close); + try { + const connection = await amqp.connect('amqp://localhost'); + process.once('SIGINT', connection.close); - const channel = await connection.createChannel(); - const queue = 'my_first_stream'; - const msg = `Hello World! ${Date.now()}`; + const channel = await connection.createChannel(); + const queue = 'my_first_stream'; + const msg = `Hello World! ${Date.now()}`; - // Define the queue stream - // Mandatory: exclusive: false, durable: true autoDelete: false - await channel.assertQueue(queue, { - exclusive: false, - durable: true, - autoDelete: false, - arguments: { - 'x-queue-type': 'stream', // Mandatory to define stream queue - 'x-max-length-bytes': 2_000_000_000 // Set the queue retention to 2GB else the stream doesn't have any limit - } - }); + // Define the queue stream + // Mandatory: exclusive: false, durable: true autoDelete: false + await channel.assertQueue(queue, { + exclusive: false, + durable: true, + autoDelete: false, + arguments: { + 'x-queue-type': 'stream', // Mandatory to define stream queue + 'x-max-length-bytes': 2_000_000_000, // Set the queue retention to 2GB else the stream doesn't have any limit + }, + }); - // Send the message to the stream queue - await channel.sendToQueue(queue, Buffer.from(msg)); - console.log(" [x] Sent '%s'", msg); - await channel.close(); + // Send the message to the stream queue + await channel.sendToQueue(queue, Buffer.from(msg)); + console.log(" [x] Sent '%s'", msg); + await channel.close(); - // Close connection - connection.close(); - } + // Close connection + connection.close(); + } catch (e) { // Catch and display any errors in the console - catch(e) { - console.log(e) - } + console.log(e); + } })(); - diff --git a/examples/tutorials/callback_api/emit_log.js b/examples/tutorials/callback_api/emit_log.js index e79cae38..71d4533e 100755 --- a/examples/tutorials/callback_api/emit_log.js +++ b/examples/tutorials/callback_api/emit_log.js @@ -9,7 +9,7 @@ amqp.connect((err, connection) => { if (err) return bail(err); connection.createChannel((err, channel) => { if (err) return bail(err, connection); - channel.assertExchange(exchange, 'fanout', { durable: false }, (err) => { + channel.assertExchange(exchange, 'fanout', {durable: false}, (err) => { if (err) return bail(err, connection); channel.publish(exchange, '', Buffer.from(text)); console.log(" [x] Sent '%s'", text); @@ -22,7 +22,8 @@ amqp.connect((err, connection) => { function bail(err, connection) { console.error(err); - if (connection) connection.close(() => { - process.exit(1); - }); + if (connection) + connection.close(() => { + process.exit(1); + }); } diff --git a/examples/tutorials/callback_api/emit_log_direct.js b/examples/tutorials/callback_api/emit_log_direct.js index 911f1fb2..0d2b243e 100755 --- a/examples/tutorials/callback_api/emit_log_direct.js +++ b/examples/tutorials/callback_api/emit_log_direct.js @@ -4,14 +4,14 @@ const amqp = require('amqplib/callback_api'); const exchange = 'direct_logs'; const args = process.argv.slice(2); -const routingKey = (args.length > 0) ? args[0] : 'info'; +const routingKey = args.length > 0 ? args[0] : 'info'; const text = args.slice(1).join(' ') || 'Hello World!'; amqp.connect((err, connection) => { if (err) return bail(err); connection.createChannel((err, channel) => { if (err) return bail(err, connection); - channel.assertExchange(exchange, 'direct', { durable: false }, (err) => { + channel.assertExchange(exchange, 'direct', {durable: false}, (err) => { if (err) return bail(err, connection); channel.publish(exchange, routingKey, Buffer.from(text)); console.log(" [x] Sent '%s'", text); @@ -24,7 +24,8 @@ amqp.connect((err, connection) => { function bail(err, connection) { console.error(err); - if (connection) connection.close(() => { - process.exit(1); - }); + if (connection) + connection.close(() => { + process.exit(1); + }); } diff --git a/examples/tutorials/callback_api/emit_log_topic.js b/examples/tutorials/callback_api/emit_log_topic.js index 830b6149..8c427b2f 100755 --- a/examples/tutorials/callback_api/emit_log_topic.js +++ b/examples/tutorials/callback_api/emit_log_topic.js @@ -4,14 +4,14 @@ const amqp = require('amqplib/callback_api'); const exchange = 'topic_logs'; const args = process.argv.slice(2); -const routingKey = (args.length > 0) ? args[0] : 'info'; +const routingKey = args.length > 0 ? args[0] : 'info'; const text = args.slice(1).join(' ') || 'Hello World!'; amqp.connect((err, connection) => { if (err) return bail(err); connection.createChannel((err, channel) => { if (err) return bail(err, connection); - channel.assertExchange(exchange, 'topic', { durable: false }, (err) => { + channel.assertExchange(exchange, 'topic', {durable: false}, (err) => { if (err) return bail(err, connection); channel.publish(exchange, routingKey, Buffer.from(text)); console.log(" [x] Sent '%s'", text); @@ -24,7 +24,8 @@ amqp.connect((err, connection) => { function bail(err, connection) { console.error(err); - if (connection) connection.close(() => { - process.exit(1); - }); + if (connection) + connection.close(() => { + process.exit(1); + }); } diff --git a/examples/tutorials/callback_api/new_task.js b/examples/tutorials/callback_api/new_task.js index 4f33f258..d1d725bf 100755 --- a/examples/tutorials/callback_api/new_task.js +++ b/examples/tutorials/callback_api/new_task.js @@ -3,15 +3,15 @@ const amqp = require('amqplib/callback_api'); const queue = 'task_queue'; -const text = process.argv.slice(2).join(' ') || "Hello World!"; +const text = process.argv.slice(2).join(' ') || 'Hello World!'; amqp.connect((err, connection) => { if (err) return bail(err); connection.createChannel((err, channel) => { if (err) return bail(err, connection); - channel.assertQueue(queue, { durable: true }, (err) => { + channel.assertQueue(queue, {durable: true}, (err) => { if (err) return bails(err, connection); - channel.sendToQueue(queue, Buffer.from(text), { persistent: true }); + channel.sendToQueue(queue, Buffer.from(text), {persistent: true}); console.log(" [x] Sent '%s'", text); channel.close(() => { connection.close(); @@ -22,7 +22,8 @@ amqp.connect((err, connection) => { function bail(err, connection) { console.error(err); - if (connection) connection.close(() => { - process.exit(1); - }); + if (connection) + connection.close(() => { + process.exit(1); + }); } diff --git a/examples/tutorials/callback_api/receive.js b/examples/tutorials/callback_api/receive.js index 0da9b168..5c8f9503 100755 --- a/examples/tutorials/callback_api/receive.js +++ b/examples/tutorials/callback_api/receive.js @@ -15,22 +15,28 @@ amqp.connect((err, connection) => { }); }); - channel.assertQueue(queue, { durable: false }, (err) => { + channel.assertQueue(queue, {durable: false}, (err) => { if (err) return bail(err, connection); - channel.consume(queue, (message) => { - if (message) console.log(" [x] Received '%s'", message.content.toString()); - else console.warn(' [x] Consumer cancelled'); - }, { noAck: true }, (err) => { - if (err) return bail(err, connection); - console.log(" [*] Waiting for logs. To exit press CTRL+C."); - }); + channel.consume( + queue, + (message) => { + if (message) console.log(" [x] Received '%s'", message.content.toString()); + else console.warn(' [x] Consumer cancelled'); + }, + {noAck: true}, + (err) => { + if (err) return bail(err, connection); + console.log(' [*] Waiting for logs. To exit press CTRL+C.'); + }, + ); }); }); }); function bail(err, connection) { console.error(err); - if (connection) connection.close(() => { - process.exit(1); - }); + if (connection) + connection.close(() => { + process.exit(1); + }); } diff --git a/examples/tutorials/callback_api/receive_logs.js b/examples/tutorials/callback_api/receive_logs.js index 09564080..15f736b5 100755 --- a/examples/tutorials/callback_api/receive_logs.js +++ b/examples/tutorials/callback_api/receive_logs.js @@ -15,19 +15,24 @@ amqp.connect((err, connection) => { }); }); - channel.assertExchange(exchange, 'fanout', { durable: false }, (err, { queue }) => { + channel.assertExchange(exchange, 'fanout', {durable: false}, (err, {queue}) => { if (err) return bail(err, connection); - channel.assertQueue('', { exclusive: true }, (err, { queue }) => { + channel.assertQueue('', {exclusive: true}, (err, {queue}) => { if (err) return bail(err, connection); channel.bindQueue(queue, exchange, '', {}, (err) => { if (err) return bail(err, connection); - channel.consume(queue, (message) => { - if (message) console.log(" [x] '%s'", message.content.toString()); - else console.warn(' [x] Consumer cancelled'); - }, { noAck: true }, (err) => { - if (err) return bail(err, connection); - console.log(" [*] Waiting for logs. To exit press CTRL+C."); - }); + channel.consume( + queue, + (message) => { + if (message) console.log(" [x] '%s'", message.content.toString()); + else console.warn(' [x] Consumer cancelled'); + }, + {noAck: true}, + (err) => { + if (err) return bail(err, connection); + console.log(' [*] Waiting for logs. To exit press CTRL+C.'); + }, + ); }); }); }); @@ -36,7 +41,8 @@ amqp.connect((err, connection) => { function bail(err, connection) { console.error(err); - if (connection) connection.close(() => { - process.exit(1); - }); + if (connection) + connection.close(() => { + process.exit(1); + }); } diff --git a/examples/tutorials/callback_api/receive_logs_direct.js b/examples/tutorials/callback_api/receive_logs_direct.js index 0257452e..7e0d414f 100755 --- a/examples/tutorials/callback_api/receive_logs_direct.js +++ b/examples/tutorials/callback_api/receive_logs_direct.js @@ -1,7 +1,7 @@ #!/usr/bin/env node const amqp = require('amqplib/callback_api'); -const { basename } = require('path'); +const {basename} = require('path'); const exchange = 'direct_logs'; const severities = process.argv.slice(2); @@ -21,20 +21,25 @@ amqp.connect((err, connection) => { }); }); - channel.assertExchange(exchange, 'direct', { durable: false }, (err) => { + channel.assertExchange(exchange, 'direct', {durable: false}, (err) => { if (err) return bail(err, connection); - channel.assertQueue('', { exclusive: true }, (err, { queue }) => { + channel.assertQueue('', {exclusive: true}, (err, {queue}) => { if (err) return bail(err, connection); - channel.consume(queue, (message) => { - if (message) console.log(" [x] %s:'%s'", message.fields.routingKey, message.content.toString()); - else console.warn(' [x] Consumer cancelled'); - }, {noAck: true}, function(err) { - if (err) return bail(err, connection); - console.log(' [*] Waiting for logs. To exit press CTRL+C.'); - subscribeAll(channel, queue, severities, (err) => { + channel.consume( + queue, + (message) => { + if (message) console.log(" [x] %s:'%s'", message.fields.routingKey, message.content.toString()); + else console.warn(' [x] Consumer cancelled'); + }, + {noAck: true}, + function (err) { if (err) return bail(err, connection); - }); - }); + console.log(' [*] Waiting for logs. To exit press CTRL+C.'); + subscribeAll(channel, queue, severities, (err) => { + if (err) return bail(err, connection); + }); + }, + ); }); }); }); @@ -51,7 +56,8 @@ function subscribeAll(channel, queue, bindingKeys, cb) { function bail(err, connection) { console.error(err); - if (connection) connection.close(() => { - process.exit(1); - }); + if (connection) + connection.close(() => { + process.exit(1); + }); } diff --git a/examples/tutorials/callback_api/receive_logs_topic.js b/examples/tutorials/callback_api/receive_logs_topic.js index 0c95b197..33175d7f 100755 --- a/examples/tutorials/callback_api/receive_logs_topic.js +++ b/examples/tutorials/callback_api/receive_logs_topic.js @@ -1,7 +1,7 @@ #!/usr/bin/env node const amqp = require('amqplib/callback_api'); -const { basename } = require('path'); +const {basename} = require('path'); const exchange = 'topic_logs'; const severities = process.argv.slice(2); @@ -21,20 +21,25 @@ amqp.connect((err, connection) => { }); }); - channel.assertExchange(exchange, 'topic', { durable: false }, (err) => { + channel.assertExchange(exchange, 'topic', {durable: false}, (err) => { if (err) return bail(err, connection); - channel.assertQueue('', { exclusive: true }, (err, { queue }) => { + channel.assertQueue('', {exclusive: true}, (err, {queue}) => { if (err) return bail(err, connection); - channel.consume(queue, (message) => { - if (message) console.log(" [x] %s:'%s'", message.fields.routingKey, message.content.toString()); - else console.warn(' [x] Consumer cancelled'); - }, {noAck: true}, function(err) { - if (err) return bail(err, connection); - console.log(' [*] Waiting for logs. To exit press CTRL+C.'); - subscribeAll(channel, queue, severities, (err) => { + channel.consume( + queue, + (message) => { + if (message) console.log(" [x] %s:'%s'", message.fields.routingKey, message.content.toString()); + else console.warn(' [x] Consumer cancelled'); + }, + {noAck: true}, + function (err) { if (err) return bail(err, connection); - }); - }); + console.log(' [*] Waiting for logs. To exit press CTRL+C.'); + subscribeAll(channel, queue, severities, (err) => { + if (err) return bail(err, connection); + }); + }, + ); }); }); }); @@ -51,8 +56,8 @@ function subscribeAll(channel, queue, bindingKeys, cb) { function bail(err, connection) { console.error(err); - if (connection) connection.close(() => { - process.exit(1); - }); + if (connection) + connection.close(() => { + process.exit(1); + }); } - diff --git a/examples/tutorials/callback_api/rpc_client.js b/examples/tutorials/callback_api/rpc_client.js index 85e1630c..8f623125 100755 --- a/examples/tutorials/callback_api/rpc_client.js +++ b/examples/tutorials/callback_api/rpc_client.js @@ -1,8 +1,8 @@ #!/usr/bin/env node const amqp = require('amqplib/callback_api'); -const { basename } = require('path'); -const { v4: uuid } = require('uuid'); +const {basename} = require('path'); +const {v4: uuid} = require('uuid'); const queue = 'rpc_queue'; @@ -16,26 +16,30 @@ amqp.connect((err, connection) => { if (err) return bail(err); connection.createChannel((err, channel) => { if (err) return bail(err, connection); - channel.assertQueue('', { exclusive: true }, (err, { queue: replyTo }) => { + channel.assertQueue('', {exclusive: true}, (err, {queue: replyTo}) => { if (err) return bail(err, connection); const correlationId = uuid(); - channel.consume(replyTo, (message) => { - if (!message) console.warn(' [x] Consumer cancelled'); - else if (message.properties.correlationId === correlationId) { - console.log(' [.] Got %d', message.content.toString()); - channel.close(() => { - connection.close(); - }) - } - }, { noAck: true }); - - channel.assertQueue(queue, { durable: false }, (err) => { + channel.consume( + replyTo, + (message) => { + if (!message) console.warn(' [x] Consumer cancelled'); + else if (message.properties.correlationId === correlationId) { + console.log(' [.] Got %d', message.content.toString()); + channel.close(() => { + connection.close(); + }); + } + }, + {noAck: true}, + ); + + channel.assertQueue(queue, {durable: false}, (err) => { if (err) return bail(err, connection); console.log(' [x] Requesting fib(%d)', n); channel.sendToQueue(queue, Buffer.from(n.toString()), { correlationId, - replyTo + replyTo, }); }); }); @@ -44,8 +48,8 @@ amqp.connect((err, connection) => { function bail(err, connection) { console.error(err); - if (connection) connection.close(() => { - process.exit(1); - }); + if (connection) + connection.close(() => { + process.exit(1); + }); } - diff --git a/examples/tutorials/callback_api/rpc_server.js b/examples/tutorials/callback_api/rpc_server.js index 208bff4e..dc939640 100755 --- a/examples/tutorials/callback_api/rpc_server.js +++ b/examples/tutorials/callback_api/rpc_server.js @@ -15,21 +15,26 @@ amqp.connect((err, connection) => { }); }); - channel.assertQueue(queue, { durable: false }, (err) => { + channel.assertQueue(queue, {durable: false}, (err) => { if (err) return bail(err, connection); channel.prefetch(1); - channel.consume(queue, (message) => { - const n = parseInt(message.content.toString(), 10); - console.log(' [.] fib(%d)', n); - const response = fib(n); - channel.sendToQueue(message.properties.replyTo, Buffer.from(response.toString()), { - correlationId: message.properties.correlationId - }); - channel.ack(message); - }, { noAck: false }, function(err) { - if (err) return bail(err, conn); - console.log(' [x] Awaiting RPC requests. To exit press CTRL+C.'); - }); + channel.consume( + queue, + (message) => { + const n = parseInt(message.content.toString(), 10); + console.log(' [.] fib(%d)', n); + const response = fib(n); + channel.sendToQueue(message.properties.replyTo, Buffer.from(response.toString()), { + correlationId: message.properties.correlationId, + }); + channel.ack(message); + }, + {noAck: false}, + function (err) { + if (err) return bail(err, conn); + console.log(' [x] Awaiting RPC requests. To exit press CTRL+C.'); + }, + ); }); }); }); @@ -37,19 +42,20 @@ amqp.connect((err, connection) => { function fib(n) { // Do it the ridiculous, but not most ridiculous, way. For better, // see http://nayuki.eigenstate.org/page/fast-fibonacci-algorithms - let a = 0, b = 1; - for (let i=0; i < n; i++) { + let a = 0, + b = 1; + for (let i = 0; i < n; i++) { let c = a + b; - a = b; b = c; + a = b; + b = c; } return a; } - function bail(err, connection) { console.error(err); - if (connection) connection.close(() => { - process.exit(1); - }); + if (connection) + connection.close(() => { + process.exit(1); + }); } - diff --git a/examples/tutorials/callback_api/send.js b/examples/tutorials/callback_api/send.js index 1a371e0e..27d8b645 100755 --- a/examples/tutorials/callback_api/send.js +++ b/examples/tutorials/callback_api/send.js @@ -9,7 +9,7 @@ amqp.connect((err, connection) => { if (err) return bail(err); connection.createChannel((err, channel) => { if (err) return bail(err, connection); - channel.assertQueue(queue, { durable: false }, (err) => { + channel.assertQueue(queue, {durable: false}, (err) => { if (err) return bail(err, connection); channel.sendToQueue(queue, Buffer.from(text)); console.log(" [x] Sent '%s'", text); @@ -22,7 +22,8 @@ amqp.connect((err, connection) => { function bail(err, connection) { console.error(err); - if (connection) connection.close(() => { - process.exit(1); - }); + if (connection) + connection.close(() => { + process.exit(1); + }); } diff --git a/examples/tutorials/callback_api/worker.js b/examples/tutorials/callback_api/worker.js index 52c33d83..3116837d 100755 --- a/examples/tutorials/callback_api/worker.js +++ b/examples/tutorials/callback_api/worker.js @@ -15,25 +15,30 @@ amqp.connect((err, connection) => { }); }); - channel.assertQueue(queue, { durable: true }, (err, { queue }) => { + channel.assertQueue(queue, {durable: true}, (err, {queue}) => { if (err) return bail(err, connection); - channel.consume(queue, (message) => { - const text = message.content.toString(); - console.log(" [x] Received '%s'", text); - const seconds = text.split('.').length - 1; - setTimeout(() => { - console.log(" [x] Done"); - channel.ack(message); - }, seconds * 1000); - }, { noAck: false }); - console.log(" [*] Waiting for messages. To exit press CTRL+C"); + channel.consume( + queue, + (message) => { + const text = message.content.toString(); + console.log(" [x] Received '%s'", text); + const seconds = text.split('.').length - 1; + setTimeout(() => { + console.log(' [x] Done'); + channel.ack(message); + }, seconds * 1000); + }, + {noAck: false}, + ); + console.log(' [*] Waiting for messages. To exit press CTRL+C'); }); }); }); function bail(err, connection) { console.error(err); - if (connection) connection.close(() => { - process.exit(1); - }); + if (connection) + connection.close(() => { + process.exit(1); + }); } diff --git a/examples/tutorials/emit_log.js b/examples/tutorials/emit_log.js index 9cb71d38..93d68683 100755 --- a/examples/tutorials/emit_log.js +++ b/examples/tutorials/emit_log.js @@ -10,15 +10,13 @@ const text = process.argv.slice(2).join(' ') || 'info: Hello World!'; try { connection = await amqp.connect('amqp://localhost'); const channel = await connection.createChannel(); - await channel.assertExchange(exchange, 'fanout', { durable: false }); + await channel.assertExchange(exchange, 'fanout', {durable: false}); channel.publish(exchange, '', Buffer.from(text)); console.log(" [x] Sent '%s'", text); await channel.close(); - } - catch (err) { + } catch (err) { console.warn(err); - } - finally { + } finally { if (connection) await connection.close(); - }; -})(); + } +})(); diff --git a/examples/tutorials/emit_log_direct.js b/examples/tutorials/emit_log_direct.js index 8f593e39..7b39ed03 100755 --- a/examples/tutorials/emit_log_direct.js +++ b/examples/tutorials/emit_log_direct.js @@ -4,7 +4,7 @@ const amqp = require('amqplib'); const exchange = 'direct_logs'; const args = process.argv.slice(2); -const routingKey = (args.length > 0) ? args[0] : 'info'; +const routingKey = args.length > 0 ? args[0] : 'info'; const text = args.slice(1).join(' ') || 'Hello World!'; (async () => { @@ -12,15 +12,13 @@ const text = args.slice(1).join(' ') || 'Hello World!'; try { connection = await amqp.connect('amqp://localhost'); const channel = await connection.createChannel(); - await channel.assertExchange(exchange, 'direct', { durable: false }); + await channel.assertExchange(exchange, 'direct', {durable: false}); channel.publish(exchange, routingKey, Buffer.from(text)); console.log(" [x] Sent %s:'%s'", routingKey, text); await channel.close(); - } - catch (err) { + } catch (err) { console.warn(err); - } - finally { + } finally { if (connection) await connection.close(); - }; -})(); + } +})(); diff --git a/examples/tutorials/emit_log_topic.js b/examples/tutorials/emit_log_topic.js index 484010ee..a2604bb4 100755 --- a/examples/tutorials/emit_log_topic.js +++ b/examples/tutorials/emit_log_topic.js @@ -4,7 +4,7 @@ const amqp = require('amqplib'); const exchange = 'topic_logs'; const args = process.argv.slice(2); -const routingKeys = (args.length > 0) ? args[0] : 'info'; +const routingKeys = args.length > 0 ? args[0] : 'info'; const text = args.slice(1).join(' ') || 'Hello World!'; (async () => { @@ -12,15 +12,13 @@ const text = args.slice(1).join(' ') || 'Hello World!'; try { connection = await amqp.connect('amqp://localhost'); const channel = await connection.createChannel(); - await channel.assertExchange(exchange, 'topic', { durable: false }); + await channel.assertExchange(exchange, 'topic', {durable: false}); channel.publish(exchange, routingKeys, Buffer.from(text)); console.log(" [x] Sent %s:'%s'", routingKeys, text); await channel.close(); - } - catch (err) { + } catch (err) { console.warn(err); - } - finally { + } finally { if (connection) await connection.close(); - }; -})(); + } +})(); diff --git a/examples/tutorials/new_task.js b/examples/tutorials/new_task.js index 0c6a5e67..43bc5283 100755 --- a/examples/tutorials/new_task.js +++ b/examples/tutorials/new_task.js @@ -4,22 +4,20 @@ const amqp = require('amqplib'); const queue = 'task_queue'; -const text = process.argv.slice(2).join(' ') || "Hello World!"; +const text = process.argv.slice(2).join(' ') || 'Hello World!'; (async () => { let connection; try { connection = await amqp.connect('amqp://localhost'); const channel = await connection.createChannel(); - await channel.assertQueue(queue, { durable: true }); - channel.sendToQueue(queue, Buffer.from(text), { persistent: true }); + await channel.assertQueue(queue, {durable: true}); + channel.sendToQueue(queue, Buffer.from(text), {persistent: true}); console.log(" [x] Sent '%s'", text); await channel.close(); - } - catch (err) { + } catch (err) { console.warn(err); - } - finally { + } finally { await connection.close(); - }; + } })(); diff --git a/examples/tutorials/receive.js b/examples/tutorials/receive.js index 8716e3f0..9da42598 100755 --- a/examples/tutorials/receive.js +++ b/examples/tutorials/receive.js @@ -9,15 +9,19 @@ const queue = 'hello'; const connection = await amqp.connect('amqp://localhost'); const channel = await connection.createChannel(); - process.once('SIGINT', async () => { + process.once('SIGINT', async () => { await channel.close(); await connection.close(); }); - await channel.assertQueue(queue, { durable: false }); - await channel.consume(queue, (message) => { - console.log(" [x] Received '%s'", message.content.toString()); - }, { noAck: true }); + await channel.assertQueue(queue, {durable: false}); + await channel.consume( + queue, + (message) => { + console.log(" [x] Received '%s'", message.content.toString()); + }, + {noAck: true}, + ); console.log(' [*] Waiting for messages. To exit press CTRL+C'); } catch (err) { diff --git a/examples/tutorials/receive_logs.js b/examples/tutorials/receive_logs.js index 14abc9a2..6f2f5251 100755 --- a/examples/tutorials/receive_logs.js +++ b/examples/tutorials/receive_logs.js @@ -9,19 +9,23 @@ const exchange = 'logs'; const connection = await amqp.connect('amqp://localhost'); const channel = await connection.createChannel(); - process.once('SIGINT', async () => { + process.once('SIGINT', async () => { await channel.close(); await connection.close(); }); - await channel.assertExchange(exchange, 'fanout', { durable: false }); - const { queue } = await channel.assertQueue('', { exclusive: true }); - await channel.bindQueue(queue, exchange, '') + await channel.assertExchange(exchange, 'fanout', {durable: false}); + const {queue} = await channel.assertQueue('', {exclusive: true}); + await channel.bindQueue(queue, exchange, ''); - await channel.consume(queue, (message) => { - if (message) console.log(" [x] '%s'", message.content.toString()); - else console.warn(' [x] Consumer cancelled'); - }, { noAck: true }); + await channel.consume( + queue, + (message) => { + if (message) console.log(" [x] '%s'", message.content.toString()); + else console.warn(' [x] Consumer cancelled'); + }, + {noAck: true}, + ); console.log(' [*] Waiting for logs. To exit press CTRL+C'); } catch (err) { diff --git a/examples/tutorials/receive_logs_direct.js b/examples/tutorials/receive_logs_direct.js index 116fffc4..f5877b5a 100755 --- a/examples/tutorials/receive_logs_direct.js +++ b/examples/tutorials/receive_logs_direct.js @@ -1,7 +1,7 @@ #!/usr/bin/env node const amqp = require('../..'); -const { basename } = require('path'); +const {basename} = require('path'); const exchange = 'direct_logs'; const bindingKeys = process.argv.slice(2); @@ -15,24 +15,30 @@ if (bindingKeys.length < 1) { const connection = await amqp.connect('amqp://localhost'); const channel = await connection.createChannel(); - process.once('SIGINT', async () => { + process.once('SIGINT', async () => { await channel.close(); await connection.close(); }); - await channel.assertExchange(exchange, 'direct', { durable: false }); - const { queue } = await channel.assertQueue('', { exclusive: true }); - await Promise.all(bindingKeys.map(async (bindingKey) => { - await channel.bindQueue(queue, exchange, bindingKey); - })); + await channel.assertExchange(exchange, 'direct', {durable: false}); + const {queue} = await channel.assertQueue('', {exclusive: true}); + await Promise.all( + bindingKeys.map(async (bindingKey) => { + await channel.bindQueue(queue, exchange, bindingKey); + }), + ); - await channel.consume(queue, (message) => { - if (message) console.log(" [x] %s:'%s'", message.fields.routingKey, message.content.toString()); - else console.warn(' [x] Consumer cancelled'); - }, { noAck: true }); + await channel.consume( + queue, + (message) => { + if (message) console.log(" [x] %s:'%s'", message.fields.routingKey, message.content.toString()); + else console.warn(' [x] Consumer cancelled'); + }, + {noAck: true}, + ); console.log(' [*] Waiting for logs. To exit press CTRL+C.'); - } catch(err) { + } catch (err) { console.warn(err); } })(); diff --git a/examples/tutorials/receive_logs_topic.js b/examples/tutorials/receive_logs_topic.js index f99aa4ca..ad41bcd9 100755 --- a/examples/tutorials/receive_logs_topic.js +++ b/examples/tutorials/receive_logs_topic.js @@ -1,7 +1,7 @@ #!/usr/bin/env node const amqp = require('../..'); -const { basename } = require('path'); +const {basename} = require('path'); const exchange = 'topic_logs'; const bindingKeys = process.argv.slice(2); @@ -15,25 +15,30 @@ if (bindingKeys.length < 1) { const connection = await amqp.connect('amqp://localhost'); const channel = await connection.createChannel(); - process.once('SIGINT', async () => { + process.once('SIGINT', async () => { await channel.close(); await connection.close(); }); - await channel.assertExchange(exchange, 'topic', { durable: false }); - const { queue } = await channel.assertQueue('', { exclusive: true }); - await Promise.all(bindingKeys.map(async (bindingKey) => { - await channel.bindQueue(queue, exchange, bindingKey); - })); + await channel.assertExchange(exchange, 'topic', {durable: false}); + const {queue} = await channel.assertQueue('', {exclusive: true}); + await Promise.all( + bindingKeys.map(async (bindingKey) => { + await channel.bindQueue(queue, exchange, bindingKey); + }), + ); - await channel.consume(queue, (message) => { - if (message) console.log(" [x] %s:'%s'", message.fields.routingKey, message.content.toString()); - else console.warn(' [x] Consumer cancelled'); - }, { noAck: true }); + await channel.consume( + queue, + (message) => { + if (message) console.log(" [x] %s:'%s'", message.fields.routingKey, message.content.toString()); + else console.warn(' [x] Consumer cancelled'); + }, + {noAck: true}, + ); console.log(' [*] Waiting for logs. To exit press CTRL+C.'); - } - catch (err) { + } catch (err) { console.warn(err); } })(); diff --git a/examples/tutorials/rpc_client.js b/examples/tutorials/rpc_client.js index be9ceeb9..3aba2b03 100755 --- a/examples/tutorials/rpc_client.js +++ b/examples/tutorials/rpc_client.js @@ -1,8 +1,8 @@ #!/usr/bin/env node const amqp = require('amqplib'); -const { basename } = require('path'); -const { v4: uuid } = require('uuid'); +const {basename} = require('path'); +const {v4: uuid} = require('uuid'); const queue = 'rpc_queue'; @@ -20,18 +20,22 @@ if (isNaN(n)) { const correlationId = uuid(); const requestFib = new Promise(async (resolve) => { - const { queue: replyTo } = await channel.assertQueue('', { exclusive: true }); + const {queue: replyTo} = await channel.assertQueue('', {exclusive: true}); - await channel.consume(replyTo, (message) => { - if (!message) console.warn(' [x] Consumer cancelled'); - else if (message.properties.correlationId === correlationId) { - resolve(message.content.toString()); - } - }, { noAck: true }); - - await channel.assertQueue(queue, { durable: false }); + await channel.consume( + replyTo, + (message) => { + if (!message) console.warn(' [x] Consumer cancelled'); + else if (message.properties.correlationId === correlationId) { + resolve(message.content.toString()); + } + }, + {noAck: true}, + ); + + await channel.assertQueue(queue, {durable: false}); console.log(' [x] Requesting fib(%d)', n); - channel.sendToQueue(queue, Buffer.from(n.toString()), { + channel.sendToQueue(queue, Buffer.from(n.toString()), { correlationId, replyTo, }); @@ -39,11 +43,9 @@ if (isNaN(n)) { const fibN = await requestFib; console.log(' [.] Got %d', fibN); - } - catch (err) { + } catch (err) { console.warn(err); - } - finally { + } finally { if (connection) await connection.close(); - }; -})(); + } +})(); diff --git a/examples/tutorials/rpc_server.js b/examples/tutorials/rpc_server.js index 13be3a71..7fa32996 100755 --- a/examples/tutorials/rpc_server.js +++ b/examples/tutorials/rpc_server.js @@ -9,12 +9,12 @@ const queue = 'rpc_queue'; const connection = await amqp.connect('amqp://localhost'); const channel = await connection.createChannel(); - process.once('SIGINT', async () => { + process.once('SIGINT', async () => { await channel.close(); await connection.close(); }); - await channel.assertQueue(queue, { durable: false }); + await channel.assertQueue(queue, {durable: false}); channel.prefetch(1); await channel.consume(queue, (message) => { @@ -22,14 +22,13 @@ const queue = 'rpc_queue'; console.log(' [.] fib(%d)', n); const response = fib(n); channel.sendToQueue(message.properties.replyTo, Buffer.from(response.toString()), { - correlationId: message.properties.correlationId + correlationId: message.properties.correlationId, }); channel.ack(message); }); console.log(' [x] Awaiting RPC requests. To exit press CTRL+C.'); - } - catch (err) { + } catch (err) { console.warn(err); } })(); @@ -37,10 +36,12 @@ const queue = 'rpc_queue'; function fib(n) { // Do it the ridiculous, but not most ridiculous, way. For better, // see http://nayuki.eigenstate.org/page/fast-fibonacci-algorithms - let a = 0, b = 1; - for (let i=0; i < n; i++) { + let a = 0, + b = 1; + for (let i = 0; i < n; i++) { let c = a + b; - a = b; b = c; + a = b; + b = c; } return a; } diff --git a/examples/tutorials/send.js b/examples/tutorials/send.js index 159cd593..ef6052a8 100755 --- a/examples/tutorials/send.js +++ b/examples/tutorials/send.js @@ -11,7 +11,7 @@ const text = 'Hello World!'; connection = await amqp.connect('amqp://localhost'); const channel = await connection.createChannel(); - await channel.assertQueue(queue, { durable: false }); + await channel.assertQueue(queue, {durable: false}); // NB: `sentToQueue` and `publish` both return a boolean // indicating whether it's OK to send again straight away, or @@ -21,11 +21,9 @@ const text = 'Hello World!'; channel.sendToQueue(queue, Buffer.from(text)); console.log(" [x] Sent '%s'", text); await channel.close(); - } - catch (err) { + } catch (err) { console.warn(err); - } - finally { + } finally { if (connection) await connection.close(); - }; -})(); + } +})(); diff --git a/examples/tutorials/worker.js b/examples/tutorials/worker.js index 8807f578..acd4d834 100755 --- a/examples/tutorials/worker.js +++ b/examples/tutorials/worker.js @@ -8,27 +8,30 @@ const queue = 'task_queue'; (async () => { try { const connection = await amqp.connect('amqp://localhost'); - process.once('SIGINT', async () => { + process.once('SIGINT', async () => { await connection.close(); }); const channel = await connection.createChannel(); - await channel.assertQueue(queue, { durable: true }); + await channel.assertQueue(queue, {durable: true}); channel.prefetch(1); - await channel.consume(queue, (message) => { - const text = message.content.toString(); - console.log(" [x] Received '%s'", text); - const seconds = text.split('.').length - 1; - setTimeout(() => { - console.log(" [x] Done"); - channel.ack(message); - }, seconds * 1000); - }, { noAck: false }); - - console.log(" [*] Waiting for messages. To exit press CTRL+C"); - } - catch (err) { + await channel.consume( + queue, + (message) => { + const text = message.content.toString(); + console.log(" [x] Received '%s'", text); + const seconds = text.split('.').length - 1; + setTimeout(() => { + console.log(' [x] Done'); + channel.ack(message); + }, seconds * 1000); + }, + {noAck: false}, + ); + + console.log(' [*] Waiting for messages. To exit press CTRL+C'); + } catch (err) { console.warn(err); } })(); diff --git a/examples/waitForConfirms.js b/examples/waitForConfirms.js index a7fdbb06..ab9c2297 100644 --- a/examples/waitForConfirms.js +++ b/examples/waitForConfirms.js @@ -6,9 +6,9 @@ const amqp = require('../'); connection = await amqp.connect(); const channel = await connection.createConfirmChannel(); - for (var i=0; i < 20; i++) { + for (var i = 0; i < 20; i++) { channel.publish('amq.topic', 'whatever', Buffer.from('blah')); - }; + } await channel.waitForConfirms(); console.log('All messages done'); diff --git a/lefthook.yml b/lefthook.yml new file mode 100644 index 00000000..84d7fd29 --- /dev/null +++ b/lefthook.yml @@ -0,0 +1,6 @@ +pre-commit: + commands: + format: + glob: "**/*.js" + run: npx biome format {staged_files} --write + stage_fixed: true \ No newline at end of file diff --git a/lib/api_args.js b/lib/api_args.js index 740fe870..abfbed8b 100644 --- a/lib/api_args.js +++ b/lib/api_args.js @@ -45,17 +45,15 @@ var EMPTY_OPTIONS = Object.freeze({}); var Args = {}; -Args.assertQueue = function(queue, options) { +Args.assertQueue = function (queue, options) { queue = queue || ''; options = options || EMPTY_OPTIONS; var argt = Object.create(options.arguments || null); setIfDefined(argt, 'x-expires', options.expires); setIfDefined(argt, 'x-message-ttl', options.messageTtl); - setIfDefined(argt, 'x-dead-letter-exchange', - options.deadLetterExchange); - setIfDefined(argt, 'x-dead-letter-routing-key', - options.deadLetterRoutingKey); + setIfDefined(argt, 'x-dead-letter-exchange', options.deadLetterExchange); + setIfDefined(argt, 'x-dead-letter-routing-key', options.deadLetterRoutingKey); setIfDefined(argt, 'x-max-length', options.maxLength); setIfDefined(argt, 'x-max-priority', options.maxPriority); setIfDefined(argt, 'x-overflow', options.overflow); @@ -64,64 +62,70 @@ Args.assertQueue = function(queue, options) { return { queue: queue, exclusive: !!options.exclusive, - durable: (options.durable === undefined) ? true : options.durable, + durable: options.durable === undefined ? true : options.durable, autoDelete: !!options.autoDelete, arguments: argt, passive: false, // deprecated but we have to include it ticket: 0, - nowait: false + nowait: false, }; }; -Args.checkQueue = function(queue) { +Args.checkQueue = function (queue) { return { queue: queue, passive: true, // switch to "completely different" mode nowait: false, - durable: true, autoDelete: false, exclusive: false, // ignored + durable: true, + autoDelete: false, + exclusive: false, // ignored ticket: 0, }; }; -Args.deleteQueue = function(queue, options) { +Args.deleteQueue = function (queue, options) { options = options || EMPTY_OPTIONS; return { queue: queue, ifUnused: !!options.ifUnused, ifEmpty: !!options.ifEmpty, - ticket: 0, nowait: false + ticket: 0, + nowait: false, }; }; -Args.purgeQueue = function(queue) { +Args.purgeQueue = function (queue) { return { queue: queue, - ticket: 0, nowait: false + ticket: 0, + nowait: false, }; }; -Args.bindQueue = function(queue, source, pattern, argt) { +Args.bindQueue = function (queue, source, pattern, argt) { return { queue: queue, exchange: source, routingKey: pattern, arguments: argt, - ticket: 0, nowait: false + ticket: 0, + nowait: false, }; }; -Args.unbindQueue = function(queue, source, pattern, argt) { +Args.unbindQueue = function (queue, source, pattern, argt) { return { queue: queue, exchange: source, routingKey: pattern, arguments: argt, - ticket: 0, nowait: false + ticket: 0, + nowait: false, }; }; -Args.assertExchange = function(exchange, type, options) { +Args.assertExchange = function (exchange, type, options) { options = options || EMPTY_OPTIONS; var argt = Object.create(options.arguments || null); setIfDefined(argt, 'alternate-exchange', options.alternateExchange); @@ -130,51 +134,57 @@ Args.assertExchange = function(exchange, type, options) { ticket: 0, type: type, passive: false, - durable: (options.durable === undefined) ? true : options.durable, + durable: options.durable === undefined ? true : options.durable, autoDelete: !!options.autoDelete, internal: !!options.internal, nowait: false, - arguments: argt + arguments: argt, }; }; -Args.checkExchange = function(exchange) { +Args.checkExchange = function (exchange) { return { exchange: exchange, passive: true, // switch to 'may as well be another method' mode nowait: false, // ff are ignored - durable: true, internal: false, type: '', autoDelete: false, - ticket: 0 + durable: true, + internal: false, + type: '', + autoDelete: false, + ticket: 0, }; }; -Args.deleteExchange = function(exchange, options) { +Args.deleteExchange = function (exchange, options) { options = options || EMPTY_OPTIONS; return { exchange: exchange, ifUnused: !!options.ifUnused, - ticket: 0, nowait: false + ticket: 0, + nowait: false, }; }; -Args.bindExchange = function(dest, source, pattern, argt) { +Args.bindExchange = function (dest, source, pattern, argt) { return { source: source, destination: dest, routingKey: pattern, arguments: argt, - ticket: 0, nowait: false + ticket: 0, + nowait: false, }; }; -Args.unbindExchange = function(dest, source, pattern, argt) { +Args.unbindExchange = function (dest, source, pattern, argt) { return { source: source, destination: dest, routingKey: pattern, arguments: argt, - ticket: 0, nowait: false + ticket: 0, + nowait: false, }; }; @@ -183,7 +193,7 @@ Args.unbindExchange = function(dest, source, pattern, argt) { // `options`. Since the property or mthod field names don't overlap, I // just return one big object that can be used for both purposes, and // the encoder will pick out what it wants. -Args.publish = function(exchange, routingKey, options) { +Args.publish = function (exchange, routingKey, options) { options = options || EMPTY_OPTIONS; // The CC and BCC fields expect an array of "longstr", which would @@ -193,11 +203,9 @@ Args.publish = function(exchange, routingKey, options) { function convertCC(cc) { if (cc === undefined) { return undefined; - } - else if (Array.isArray(cc)) { + } else if (Array.isArray(cc)) { return cc.map(String); - } - else return [String(cc)]; + } else return [String(cc)]; } var headers = Object.create(options.headers || null); @@ -210,11 +218,10 @@ Args.publish = function(exchange, routingKey, options) { // 'persistent or not'; better is to name this option for what it // is, but I need to have backwards compatibility for applications // that either supply a numeric or boolean value. - if (options.persistent !== undefined) - deliveryMode = (options.persistent) ? 2 : 1; - else if (typeof options.deliveryMode === 'number') - deliveryMode = options.deliveryMode; - else if (options.deliveryMode) // is supplied and truthy + if (options.persistent !== undefined) deliveryMode = options.persistent ? 2 : 1; + else if (typeof options.deliveryMode === 'number') deliveryMode = options.deliveryMode; + else if (options.deliveryMode) + // is supplied and truthy deliveryMode = 2; var expiration = options.expiration; @@ -241,11 +248,11 @@ Args.publish = function(exchange, routingKey, options) { type: options.type, userId: options.userId, appId: options.appId, - clusterId: undefined + clusterId: undefined, }; }; -Args.consume = function(queue, options) { +Args.consume = function (queue, options) { options = options || EMPTY_OPTIONS; var argt = Object.create(options.arguments || null); setIfDefined(argt, 'x-priority', options.priority); @@ -257,57 +264,57 @@ Args.consume = function(queue, options) { noAck: !!options.noAck, exclusive: !!options.exclusive, nowait: false, - arguments: argt + arguments: argt, }; }; -Args.cancel = function(consumerTag) { +Args.cancel = function (consumerTag) { return { consumerTag: consumerTag, - nowait: false + nowait: false, }; }; -Args.get = function(queue, options) { +Args.get = function (queue, options) { options = options || EMPTY_OPTIONS; return { ticket: 0, queue: queue, - noAck: !!options.noAck + noAck: !!options.noAck, }; }; -Args.ack = function(tag, allUpTo) { +Args.ack = function (tag, allUpTo) { return { deliveryTag: tag, - multiple: !!allUpTo + multiple: !!allUpTo, }; }; -Args.nack = function(tag, allUpTo, requeue) { +Args.nack = function (tag, allUpTo, requeue) { return { deliveryTag: tag, multiple: !!allUpTo, - requeue: (requeue === undefined) ? true : requeue + requeue: requeue === undefined ? true : requeue, }; }; -Args.reject = function(tag, requeue) { +Args.reject = function (tag, requeue) { return { deliveryTag: tag, - requeue: (requeue === undefined) ? true : requeue + requeue: requeue === undefined ? true : requeue, }; }; -Args.prefetch = function(count, global) { +Args.prefetch = function (count, global) { return { prefetchCount: count || 0, prefetchSize: 0, - global: !!global + global: !!global, }; }; -Args.recover = function() { +Args.recover = function () { return {requeue: true}; }; diff --git a/lib/bitset.js b/lib/bitset.js index 4ab6787b..aa396ab0 100644 --- a/lib/bitset.js +++ b/lib/bitset.js @@ -17,8 +17,7 @@ class BitSet { if (size) { const numWords = Math.ceil(size / 32); this.words = new Array(numWords); - } - else { + } else { this.words = []; } this.wordsInUse = 0; // = number, not index @@ -80,7 +79,7 @@ class BitSet { // word that are > fromIndex let word = this.words[w] & (0xffffffff << fromIndex); while (true) { - if (word) return (w * 32) + trailingZeros(word); + if (word) return w * 32 + trailingZeros(word); w++; if (w === this.wordsInUse) return -1; word = this.words[w]; @@ -94,12 +93,12 @@ class BitSet { let w = wordIndex(fromIndex); if (w >= this.wordsInUse) return fromIndex; - let word = ~(this.words[w]) & (0xffffffff << fromIndex); + let word = ~this.words[w] & (0xffffffff << fromIndex); while (true) { - if (word) return (w * 32) + trailingZeros(word); + if (word) return w * 32 + trailingZeros(word); w++; if (w == this.wordsInUse) return w * 32; - word = ~(this.words[w]); + word = ~this.words[w]; } } } @@ -119,11 +118,28 @@ function trailingZeros(i) { // since bit ops are not necessarily the quick way to do things in // JS. if (i === 0) return 32; - let y, n = 31; - y = i << 16; if (y != 0) { n = n -16; i = y; } - y = i << 8; if (y != 0) { n = n - 8; i = y; } - y = i << 4; if (y != 0) { n = n - 4; i = y; } - y = i << 2; if (y != 0) { n = n - 2; i = y; } + let y, + n = 31; + y = i << 16; + if (y != 0) { + n = n - 16; + i = y; + } + y = i << 8; + if (y != 0) { + n = n - 8; + i = y; + } + y = i << 4; + if (y != 0) { + n = n - 4; + i = y; + } + y = i << 2; + if (y != 0) { + n = n - 2; + i = y; + } return n - ((i << 1) >>> 31); } diff --git a/lib/callback_model.js b/lib/callback_model.js index 084244c8..19b20287 100644 --- a/lib/callback_model.js +++ b/lib/callback_model.js @@ -11,7 +11,7 @@ var acceptMessage = require('./channel').acceptMessage; var Args = require('./api_args'); class CallbackModel extends EventEmitter { - constructor (connection) { + constructor(connection) { super(); this.connection = connection; var self = this; @@ -20,7 +20,7 @@ class CallbackModel extends EventEmitter { }); } - close (cb) { + close(cb) { this.connection.close(cb); } @@ -28,7 +28,7 @@ class CallbackModel extends EventEmitter { this.connection._updateSecret(newSecret, reason, cb); } - createChannel (options, cb) { + createChannel(options, cb) { if (arguments.length === 1) { cb = options; options = undefined; @@ -36,15 +36,13 @@ class CallbackModel extends EventEmitter { var ch = new Channel(this.connection); ch.setOptions(options); ch.open(function (err, ok) { - if (err === null) - cb && cb(null, ch); - else - cb && cb(err); + if (err === null) cb && cb(null, ch); + else cb && cb(err); }); return ch; } - createConfirmChannel (options, cb) { + createConfirmChannel(options, cb) { if (arguments.length === 1) { cb = options; options = undefined; @@ -52,16 +50,12 @@ class CallbackModel extends EventEmitter { var ch = new ConfirmChannel(this.connection); ch.setOptions(options); ch.open(function (err) { - if (err !== null) - return cb && cb(err); + if (err !== null) return cb && cb(err); else { - ch.rpc(defs.ConfirmSelect, { nowait: false }, - defs.ConfirmSelectOk, function (err, _ok) { - if (err !== null) - return cb && cb(err); - else - cb && cb(null, ch); - }); + ch.rpc(defs.ConfirmSelect, {nowait: false}, defs.ConfirmSelectOk, function (err, _ok) { + if (err !== null) return cb && cb(err); + else cb && cb(null, ch); + }); } }); return ch; @@ -69,7 +63,7 @@ class CallbackModel extends EventEmitter { } class Channel extends BaseChannel { - constructor (connection) { + constructor(connection) { super(connection); this.on('delivery', this.handleDelivery.bind(this)); this.on('cancel', this.handleCancel.bind(this)); @@ -81,7 +75,7 @@ class Channel extends BaseChannel { // needs to have side-effects, or needs to change the server response, // use `#_rpc(...)` and remember to dereference `.fields` of the // server response. - rpc (method, fields, expect, cb0) { + rpc(method, fields, expect, cb0) { var cb = callbackWrapper(this, cb0); this._rpc(method, fields, expect, function (err, ok) { cb(err, ok && ok.fields); // in case of an error, ok will be @@ -92,131 +86,105 @@ class Channel extends BaseChannel { } // === Public API === - open (cb) { - try { this.allocate(); } - catch (e) { return cb(e); } + open(cb) { + try { + this.allocate(); + } catch (e) { + return cb(e); + } - return this.rpc(defs.ChannelOpen, { outOfBand: "" }, - defs.ChannelOpenOk, cb); + return this.rpc(defs.ChannelOpen, {outOfBand: ''}, defs.ChannelOpenOk, cb); } - close (cb) { - return this.closeBecause("Goodbye", defs.constants.REPLY_SUCCESS, - function () { cb && cb(null); }); + close(cb) { + return this.closeBecause('Goodbye', defs.constants.REPLY_SUCCESS, function () { + cb && cb(null); + }); } - assertQueue (queue, options, cb) { - return this.rpc(defs.QueueDeclare, - Args.assertQueue(queue, options), - defs.QueueDeclareOk, cb); + assertQueue(queue, options, cb) { + return this.rpc(defs.QueueDeclare, Args.assertQueue(queue, options), defs.QueueDeclareOk, cb); } - checkQueue (queue, cb) { - return this.rpc(defs.QueueDeclare, - Args.checkQueue(queue), - defs.QueueDeclareOk, cb); + checkQueue(queue, cb) { + return this.rpc(defs.QueueDeclare, Args.checkQueue(queue), defs.QueueDeclareOk, cb); } - deleteQueue (queue, options, cb) { - return this.rpc(defs.QueueDelete, - Args.deleteQueue(queue, options), - defs.QueueDeleteOk, cb); + deleteQueue(queue, options, cb) { + return this.rpc(defs.QueueDelete, Args.deleteQueue(queue, options), defs.QueueDeleteOk, cb); } - purgeQueue (queue, cb) { - return this.rpc(defs.QueuePurge, - Args.purgeQueue(queue), - defs.QueuePurgeOk, cb); + purgeQueue(queue, cb) { + return this.rpc(defs.QueuePurge, Args.purgeQueue(queue), defs.QueuePurgeOk, cb); } - bindQueue (queue, source, pattern, argt, cb) { - return this.rpc(defs.QueueBind, - Args.bindQueue(queue, source, pattern, argt), - defs.QueueBindOk, cb); + bindQueue(queue, source, pattern, argt, cb) { + return this.rpc(defs.QueueBind, Args.bindQueue(queue, source, pattern, argt), defs.QueueBindOk, cb); } - unbindQueue (queue, source, pattern, argt, cb) { - return this.rpc(defs.QueueUnbind, - Args.unbindQueue(queue, source, pattern, argt), - defs.QueueUnbindOk, cb); + unbindQueue(queue, source, pattern, argt, cb) { + return this.rpc(defs.QueueUnbind, Args.unbindQueue(queue, source, pattern, argt), defs.QueueUnbindOk, cb); } - assertExchange (ex, type, options, cb0) { + assertExchange(ex, type, options, cb0) { var cb = callbackWrapper(this, cb0); - this._rpc(defs.ExchangeDeclare, - Args.assertExchange(ex, type, options), - defs.ExchangeDeclareOk, - function (e, _) { cb(e, { exchange: ex }); }); + this._rpc(defs.ExchangeDeclare, Args.assertExchange(ex, type, options), defs.ExchangeDeclareOk, function (e, _) { + cb(e, {exchange: ex}); + }); return this; } - checkExchange (exchange, cb) { - return this.rpc(defs.ExchangeDeclare, - Args.checkExchange(exchange), - defs.ExchangeDeclareOk, cb); + checkExchange(exchange, cb) { + return this.rpc(defs.ExchangeDeclare, Args.checkExchange(exchange), defs.ExchangeDeclareOk, cb); } - deleteExchange (exchange, options, cb) { - return this.rpc(defs.ExchangeDelete, - Args.deleteExchange(exchange, options), - defs.ExchangeDeleteOk, cb); + deleteExchange(exchange, options, cb) { + return this.rpc(defs.ExchangeDelete, Args.deleteExchange(exchange, options), defs.ExchangeDeleteOk, cb); } - bindExchange (dest, source, pattern, argt, cb) { - return this.rpc(defs.ExchangeBind, - Args.bindExchange(dest, source, pattern, argt), - defs.ExchangeBindOk, cb); + bindExchange(dest, source, pattern, argt, cb) { + return this.rpc(defs.ExchangeBind, Args.bindExchange(dest, source, pattern, argt), defs.ExchangeBindOk, cb); } - unbindExchange (dest, source, pattern, argt, cb) { - return this.rpc(defs.ExchangeUnbind, - Args.unbindExchange(dest, source, pattern, argt), - defs.ExchangeUnbindOk, cb); + unbindExchange(dest, source, pattern, argt, cb) { + return this.rpc(defs.ExchangeUnbind, Args.unbindExchange(dest, source, pattern, argt), defs.ExchangeUnbindOk, cb); } - publish (exchange, routingKey, content, options) { + publish(exchange, routingKey, content, options) { var fieldsAndProps = Args.publish(exchange, routingKey, options); return this.sendMessage(fieldsAndProps, fieldsAndProps, content); } - sendToQueue (queue, content, options) { + sendToQueue(queue, content, options) { return this.publish('', queue, content, options); } - consume (queue, callback, options, cb0) { + consume(queue, callback, options, cb0) { var cb = callbackWrapper(this, cb0); var fields = Args.consume(queue, options); var self = this; - this._rpc( - defs.BasicConsume, fields, defs.BasicConsumeOk, - function (err, ok) { - if (err === null) { - self.registerConsumer(ok.fields.consumerTag, callback); - cb(null, ok.fields); - } - else - cb(err); - }); + this._rpc(defs.BasicConsume, fields, defs.BasicConsumeOk, function (err, ok) { + if (err === null) { + self.registerConsumer(ok.fields.consumerTag, callback); + cb(null, ok.fields); + } else cb(err); + }); return this; } - cancel (consumerTag, cb0) { + cancel(consumerTag, cb0) { var cb = callbackWrapper(this, cb0); var self = this; - this._rpc( - defs.BasicCancel, Args.cancel(consumerTag), defs.BasicCancelOk, - function (err, ok) { - if (err === null) { - self.unregisterConsumer(consumerTag); - cb(null, ok.fields); - } - else - cb(err); - }); + this._rpc(defs.BasicCancel, Args.cancel(consumerTag), defs.BasicCancelOk, function (err, ok) { + if (err === null) { + self.unregisterConsumer(consumerTag); + cb(null, ok.fields); + } else cb(err); + }); return this; } - get (queue, options, cb0) { + get(queue, options, cb0) { var self = this; var fields = Args.get(queue, options); var cb = callbackWrapper(this, cb0); @@ -224,116 +192,102 @@ class Channel extends BaseChannel { if (err === null) { if (f.id === defs.BasicGetEmpty) { cb(null, false); - } - else if (f.id === defs.BasicGetOk) { + } else if (f.id === defs.BasicGetOk) { self.handleMessage = acceptMessage(function (m) { m.fields = f.fields; cb(null, m); }); - } - else { - cb(new Error("Unexpected response to BasicGet: " + - inspect(f))); + } else { + cb(new Error('Unexpected response to BasicGet: ' + inspect(f))); } } }); return this; } - ack (message, allUpTo) { - this.sendImmediately( - defs.BasicAck, Args.ack(message.fields.deliveryTag, allUpTo)); + ack(message, allUpTo) { + this.sendImmediately(defs.BasicAck, Args.ack(message.fields.deliveryTag, allUpTo)); return this; } - ackAll () { + ackAll() { this.sendImmediately(defs.BasicAck, Args.ack(0, true)); return this; } - nack (message, allUpTo, requeue) { - this.sendImmediately( - defs.BasicNack, - Args.nack(message.fields.deliveryTag, allUpTo, requeue)); + nack(message, allUpTo, requeue) { + this.sendImmediately(defs.BasicNack, Args.nack(message.fields.deliveryTag, allUpTo, requeue)); return this; } - nackAll (requeue) { - this.sendImmediately( - defs.BasicNack, Args.nack(0, true, requeue)); + nackAll(requeue) { + this.sendImmediately(defs.BasicNack, Args.nack(0, true, requeue)); return this; } - reject (message, requeue) { - this.sendImmediately( - defs.BasicReject, - Args.reject(message.fields.deliveryTag, requeue)); + reject(message, requeue) { + this.sendImmediately(defs.BasicReject, Args.reject(message.fields.deliveryTag, requeue)); return this; } - prefetch (count, global, cb) { - return this.rpc(defs.BasicQos, - Args.prefetch(count, global), - defs.BasicQosOk, cb); + prefetch(count, global, cb) { + return this.rpc(defs.BasicQos, Args.prefetch(count, global), defs.BasicQosOk, cb); } - recover (cb) { - return this.rpc(defs.BasicRecover, - Args.recover(), - defs.BasicRecoverOk, cb); + recover(cb) { + return this.rpc(defs.BasicRecover, Args.recover(), defs.BasicRecoverOk, cb); } } - // Wrap an RPC callback to make sure the callback is invoked with // either `(null, value)` or `(error)`, i.e., never two non-null // values. Also substitutes a stub if the callback is `undefined` or // otherwise falsey, for convenience in methods for which the callback // is optional (that is, most of them). function callbackWrapper(ch, cb) { - return (cb) ? function(err, ok) { - if (err === null) { - cb(null, ok); - } - else cb(err); - } : function() {}; + return cb + ? function (err, ok) { + if (err === null) { + cb(null, ok); + } else cb(err); + } + : function () {}; } class ConfirmChannel extends Channel { - publish (exchange, routingKey, - content, options, cb) { + publish(exchange, routingKey, content, options, cb) { this.pushConfirmCallback(cb); - return Channel.prototype.publish.call( - this, exchange, routingKey, content, options); + return Channel.prototype.publish.call(this, exchange, routingKey, content, options); } - sendToQueue (queue, content, - options, cb) { + sendToQueue(queue, content, options, cb) { return this.publish('', queue, content, options, cb); } - waitForConfirms (k) { + waitForConfirms(k) { var awaiting = []; var unconfirmed = this.unconfirmed; unconfirmed.forEach(function (val, index) { - if (val === null) - ; // already confirmed + if (val === null); // already confirmed else { var confirmed = new Promise(function (resolve, reject) { unconfirmed[index] = function (err) { - if (val) - val(err); - if (err === null) - resolve(); - else - reject(err); + if (val) val(err); + if (err === null) resolve(); + else reject(err); }; }); awaiting.push(confirmed); } }); - return Promise.all(awaiting).then(function () { k(); }, - function (err) { k(err); }); + return Promise.all(awaiting).then( + function () { + k(); + }, + function (err) { + k(err); + }, + ); } } diff --git a/lib/channel.js b/lib/channel.js index 0feadca9..c5fd9aec 100644 --- a/lib/channel.js +++ b/lib/channel.js @@ -17,7 +17,7 @@ var IllegalOperationError = require('./error').IllegalOperationError; var stackCapture = require('./error').stackCapture; class Channel extends EventEmitter { - constructor (connection) { + constructor(connection) { super(); this.connection = connection; @@ -28,19 +28,22 @@ class Channel extends EventEmitter { // for unconfirmed messages this.lwm = 1; // the least, unconfirmed deliveryTag this.unconfirmed = []; // rolling window of delivery callbacks - this.on('ack', this.handleConfirm.bind(this, function (cb) { - if (cb) - cb(null); - })); - this.on('nack', this.handleConfirm.bind(this, function (cb) { - if (cb) - cb(new Error('message nacked')); - })); + this.on( + 'ack', + this.handleConfirm.bind(this, function (cb) { + if (cb) cb(null); + }), + ); + this.on( + 'nack', + this.handleConfirm.bind(this, function (cb) { + if (cb) cb(new Error('message nacked')); + }), + ); this.on('close', function () { var cb; - while (cb = this.unconfirmed.shift()) { - if (cb) - cb(new Error('channel closed')); + while ((cb = this.unconfirmed.shift())) { + if (cb) cb(new Error('channel closed')); } }); // message frame state machine @@ -51,7 +54,7 @@ class Channel extends EventEmitter { this.options = options; } - allocate () { + allocate() { this.ch = this.connection.freshChannel(this, this.options); return this; } @@ -67,7 +70,7 @@ class Channel extends EventEmitter { // this reason, I buffer RPCs if the channel is already waiting for a // reply. // Just send the damn frame. - sendImmediately (method, fields) { + sendImmediately(method, fields) { return this.connection.sendMethod(this.ch, method, fields); } @@ -75,69 +78,57 @@ class Channel extends EventEmitter { // clear a reply, we must send another RPC (and thereby fill // this.reply) if there is one waiting. The invariant relevant here // and in `accept`. - sendOrEnqueue (method, fields, reply) { - if (!this.reply) { // if no reply waiting, we can go + sendOrEnqueue(method, fields, reply) { + if (!this.reply) { + // if no reply waiting, we can go assert(this.pending.length === 0); this.reply = reply; this.sendImmediately(method, fields); - } - else { + } else { this.pending.push({ method: method, fields: fields, - reply: reply + reply: reply, }); } } - sendMessage (fields, properties, content) { - return this.connection.sendMessage( - this.ch, - defs.BasicPublish, fields, - defs.BasicProperties, properties, - content); + sendMessage(fields, properties, content) { + return this.connection.sendMessage(this.ch, defs.BasicPublish, fields, defs.BasicProperties, properties, content); } // Internal, synchronously resolved RPC; the return value is resolved // with the whole frame. - _rpc (method, fields, expect, cb) { + _rpc(method, fields, expect, cb) { var self = this; - function reply (err, f) { + function reply(err, f) { if (err === null) { if (f.id === expect) { return cb(null, f); - } - else { + } else { // We have detected a problem, so it's up to us to close the // channel var expectedName = methodName(expect); - var e = new Error(fmt("Expected %s; got %s", - expectedName, inspect(f, false))); - self.closeWithError(f.id, fmt('Expected %s; got %s', - expectedName, methodName(f.id)), - defs.constants.UNEXPECTED_FRAME, e); + var e = new Error(fmt('Expected %s; got %s', expectedName, inspect(f, false))); + self.closeWithError(f.id, fmt('Expected %s; got %s', expectedName, methodName(f.id)), defs.constants.UNEXPECTED_FRAME, e); return cb(e); } } - // An error will be given if, for example, this is waiting to be // sent and the connection closes - else if (err instanceof Error) - return cb(err); - - + else if (err instanceof Error) return cb(err); // A close frame will be given if this is the RPC awaiting reply // and the channel is closed by the server else { // otherwise, it's a close frame var closeReason = (err.fields.classId << 16) + err.fields.methodId; - var e = (method === closeReason) - ? fmt("Operation failed: %s; %s", - methodName(method), closeMsg(err)) - : fmt("Channel closed by server: %s", closeMsg(err)); + var e = + method === closeReason + ? fmt('Operation failed: %s; %s', methodName(method), closeMsg(err)) + : fmt('Channel closed by server: %s', closeMsg(err)); var closeFrameError = new Error(e); closeFrameError.code = err.fields.replyCode; closeFrameError.classId = err.fields.classId; @@ -150,7 +141,7 @@ class Channel extends EventEmitter { } // Move to entirely closed state. - toClosed (capturedStack) { + toClosed(capturedStack) { this._rejectPending(); invalidateSend(this, 'Channel closed', capturedStack); this.accept = invalidOp('Channel closed', capturedStack); @@ -162,43 +153,40 @@ class Channel extends EventEmitter { // we close the channel. Invokes the continuation once the server has // acknowledged the close, but before the channel is moved to the // closed state. - toClosing (capturedStack, k) { + toClosing(capturedStack, k) { var send = this.sendImmediately.bind(this); invalidateSend(this, 'Channel closing', capturedStack); this.accept = function (f) { if (f.id === defs.ChannelCloseOk) { - if (k) - k(); + if (k) k(); var s = stackCapture('ChannelCloseOk frame received'); this.toClosed(s); - } - else if (f.id === defs.ChannelClose) { + } else if (f.id === defs.ChannelClose) { send(defs.ChannelCloseOk, {}); } // else ignore frame }; } - _rejectPending () { - function rej (r) { - r(new Error("Channel ended, no reply will be forthcoming")); + _rejectPending() { + function rej(r) { + r(new Error('Channel ended, no reply will be forthcoming')); } - if (this.reply !== null) - rej(this.reply); + if (this.reply !== null) rej(this.reply); this.reply = null; var discard; - while (discard = this.pending.shift()) - rej(discard.reply); + while ((discard = this.pending.shift())) rej(discard.reply); this.pending = null; // so pushes will break } - closeBecause (reason, code, k) { + closeBecause(reason, code, k) { this.sendImmediately(defs.ChannelClose, { replyText: reason, replyCode: code, - methodId: 0, classId: 0 + methodId: 0, + classId: 0, }); var s = stackCapture('closeBecause called: ' + reason); this.toClosing(s, k); @@ -207,7 +195,7 @@ class Channel extends EventEmitter { // If we close because there's been an error, we need to distinguish // between what we tell the server (`reason`) and what we report as // the cause in the client (`error`). - closeWithError (id, reason, code, error) { + closeWithError(id, reason, code, error) { var self = this; this.closeBecause(reason, code, function () { error.code = code; @@ -227,28 +215,21 @@ class Channel extends EventEmitter { // frames. // Keep the try/catch localised, in an attempt to avoid disabling // optimisation - acceptMessageFrame (f) { + acceptMessageFrame(f) { try { this.handleMessage = this.handleMessage(f); - } - catch (msg) { + } catch (msg) { if (typeof msg === 'string') { - this.closeWithError(f.id, msg, defs.constants.UNEXPECTED_FRAME, - new Error(msg)); - } - else if (msg instanceof Error) { - this.closeWithError(f.id, 'Error while processing message', - defs.constants.INTERNAL_ERROR, msg); - } - else { - this.closeWithError(f.id, 'Internal error while processing message', - defs.constants.INTERNAL_ERROR, - new Error(msg.toString())); + this.closeWithError(f.id, msg, defs.constants.UNEXPECTED_FRAME, new Error(msg)); + } else if (msg instanceof Error) { + this.closeWithError(f.id, 'Error while processing message', defs.constants.INTERNAL_ERROR, msg); + } else { + this.closeWithError(f.id, 'Internal error while processing message', defs.constants.INTERNAL_ERROR, new Error(msg.toString())); } } } - handleConfirm (handle, f) { + handleConfirm(handle, f) { var tag = f.deliveryTag; var multi = f.multiple; @@ -256,8 +237,7 @@ class Channel extends EventEmitter { var confirmed = this.unconfirmed.splice(0, tag - this.lwm + 1); this.lwm = tag + 1; confirmed.forEach(handle); - } - else { + } else { var c; if (tag === this.lwm) { c = this.unconfirmed.shift(); @@ -268,8 +248,7 @@ class Channel extends EventEmitter { this.unconfirmed.shift(); this.lwm++; } - } - else { + } else { c = this.unconfirmed[tag - this.lwm]; this.unconfirmed[tag - this.lwm] = null; } @@ -279,78 +258,76 @@ class Channel extends EventEmitter { } } - pushConfirmCallback (cb) { + pushConfirmCallback(cb) { // `null` is used specifically for marking already confirmed slots, // so I coerce `undefined` and `null` to false; functions are never // falsey. this.unconfirmed.push(cb || false); } - onBufferDrain () { + onBufferDrain() { this.emit('drain'); } accept(f) { - switch (f.id) { - // Message frames - case undefined: // content frame! - case defs.BasicDeliver: - case defs.BasicReturn: - case defs.BasicProperties: - return this.acceptMessageFrame(f); + case undefined: // content frame! + case defs.BasicDeliver: + case defs.BasicReturn: + case defs.BasicProperties: + return this.acceptMessageFrame(f); // confirmations, need to do confirm.select first - case defs.BasicAck: - return this.emit('ack', f.fields); - case defs.BasicNack: - return this.emit('nack', f.fields); - case defs.BasicCancel: - // The broker can send this if e.g., the queue is deleted. - return this.emit('cancel', f.fields); - - case defs.ChannelClose: - // Any remote closure is an error to us. Reject the pending reply - // with the close frame, so it can see whether it was that - // operation that caused it to close. - if (this.reply) { - var reply = this.reply; this.reply = null; - reply(f); - } - var emsg = "Channel closed by server: " + closeMsg(f); - this.sendImmediately(defs.ChannelCloseOk, {}); - - var error = new Error(emsg); - error.code = f.fields.replyCode; - error.classId = f.fields.classId; - error.methodId = f.fields.methodId; - this.emit('error', error); - - var s = stackCapture(emsg); - this.toClosed(s); - return; - - case defs.BasicFlow: - // RabbitMQ doesn't send this, it just blocks the TCP socket - return this.closeWithError(f.id, "Flow not implemented", - defs.constants.NOT_IMPLEMENTED, - new Error('Flow not implemented')); - - default: // assume all other things are replies - // Resolving the reply may lead to another RPC; to make sure we - // don't hold that up, clear this.reply - var reply = this.reply; this.reply = null; - // however, maybe there's an RPC waiting to go? If so, that'll - // fill this.reply again, restoring the invariant. This does rely - // on any response being recv'ed after resolving the promise, - // below; hence, I use synchronous defer. - if (this.pending.length > 0) { - var send = this.pending.shift(); - this.reply = send.reply; - this.sendImmediately(send.method, send.fields); - } - return reply(null, f); + case defs.BasicAck: + return this.emit('ack', f.fields); + case defs.BasicNack: + return this.emit('nack', f.fields); + case defs.BasicCancel: + // The broker can send this if e.g., the queue is deleted. + return this.emit('cancel', f.fields); + + case defs.ChannelClose: + // Any remote closure is an error to us. Reject the pending reply + // with the close frame, so it can see whether it was that + // operation that caused it to close. + if (this.reply) { + var reply = this.reply; + this.reply = null; + reply(f); + } + var emsg = 'Channel closed by server: ' + closeMsg(f); + this.sendImmediately(defs.ChannelCloseOk, {}); + + var error = new Error(emsg); + error.code = f.fields.replyCode; + error.classId = f.fields.classId; + error.methodId = f.fields.methodId; + this.emit('error', error); + + var s = stackCapture(emsg); + this.toClosed(s); + return; + + case defs.BasicFlow: + // RabbitMQ doesn't send this, it just blocks the TCP socket + return this.closeWithError(f.id, 'Flow not implemented', defs.constants.NOT_IMPLEMENTED, new Error('Flow not implemented')); + + default: // assume all other things are replies + // Resolving the reply may lead to another RPC; to make sure we + // don't hold that up, clear this.reply + var reply = this.reply; + this.reply = null; + // however, maybe there's an RPC waiting to go? If so, that'll + // fill this.reply again, restoring the invariant. This does rely + // on any response being recv'ed after resolving the promise, + // below; hence, I use synchronous defer. + if (this.pending.length > 0) { + var send = this.pending.shift(); + this.reply = send.reply; + this.sendImmediately(send.method, send.fields); + } + return reply(null, f); } } } @@ -369,14 +346,13 @@ class Channel extends EventEmitter { // the exchange. function invalidOp(msg, stack) { - return function() { + return function () { throw new IllegalOperationError(msg, stack); }; } function invalidateSend(ch, msg, stack) { - ch.sendImmediately = ch.sendOrEnqueue = ch.sendMessage = - invalidOp(msg, stack); + ch.sendImmediately = ch.sendOrEnqueue = ch.sendMessage = invalidOp(msg, stack); } // Kick off a message delivery given a BasicDeliver or BasicReturn @@ -385,12 +361,11 @@ function acceptDeliveryOrReturn(f) { var event; if (f.id === defs.BasicDeliver) event = 'delivery'; else if (f.id === defs.BasicReturn) event = 'return'; - else throw fmt("Expected BasicDeliver or BasicReturn; got %s", - inspect(f)); + else throw fmt('Expected BasicDeliver or BasicReturn; got %s', inspect(f)); var self = this; var fields = f.fields; - return acceptMessage(function(message) { + return acceptMessage(function (message) { message.fields = fields; self.emit(event, message); }); @@ -399,13 +374,14 @@ function acceptDeliveryOrReturn(f) { // Move to the state of waiting for message frames (headers, then // one or more content frames) function acceptMessage(continuation) { - var totalSize = 0, remaining = 0; + var totalSize = 0, + remaining = 0; var buffers = null; var message = { fields: null, properties: null, - content: null + content: null, }; return headers; @@ -421,13 +397,11 @@ function acceptMessage(continuation) { message.content = Buffer.alloc(0); continuation(message); return acceptDeliveryOrReturn; - } - else { + } else { return content; } - } - else { - throw "Expected headers frame after delivery"; + } else { + throw 'Expected headers frame after delivery'; } } @@ -441,64 +415,56 @@ function acceptMessage(continuation) { if (buffers !== null) { buffers.push(f.content); message.content = Buffer.concat(buffers); - } - else { + } else { message.content = f.content; } continuation(message); return acceptDeliveryOrReturn; - } - else if (remaining < 0) { - throw fmt("Too much content sent! Expected %d bytes", - totalSize); - } - else { - if (buffers !== null) - buffers.push(f.content); - else - buffers = [f.content]; + } else if (remaining < 0) { + throw fmt('Too much content sent! Expected %d bytes', totalSize); + } else { + if (buffers !== null) buffers.push(f.content); + else buffers = [f.content]; return content; } - } - else throw "Expected content frame after headers" + } else throw 'Expected content frame after headers'; } } // This adds just a bit more stuff useful for the APIs, but not // low-level machinery. class BaseChannel extends Channel { - constructor (connection) { + constructor(connection) { super(connection); this.consumers = new Map(); } // Not sure I like the ff, it's going to be changing hidden classes // all over the place. On the other hand, whaddya do. - registerConsumer (tag, callback) { + registerConsumer(tag, callback) { this.consumers.set(tag, callback); } - unregisterConsumer (tag) { + unregisterConsumer(tag) { this.consumers.delete(tag); } - dispatchMessage (fields, message) { + dispatchMessage(fields, message) { var consumerTag = fields.consumerTag; var consumer = this.consumers.get(consumerTag); if (consumer) { return consumer(message); - } - else { + } else { // %%% Surely a race here - throw new Error("Unknown consumer: " + consumerTag); + throw new Error('Unknown consumer: ' + consumerTag); } } - handleDelivery (message) { + handleDelivery(message) { return this.dispatchMessage(message.fields, message); } - handleCancel (fields) { + handleCancel(fields) { var result = this.dispatchMessage(fields, null); this.unregisterConsumer(fields.consumerTag); return result; diff --git a/lib/channel_model.js b/lib/channel_model.js index f3cfffd3..65c64262 100644 --- a/lib/channel_model.js +++ b/lib/channel_model.js @@ -17,7 +17,7 @@ class ChannelModel extends EventEmitter { super(); this.connection = connection; - ['error', 'close', 'blocked', 'unblocked'].forEach(ev => { + ['error', 'close', 'blocked', 'unblocked'].forEach((ev) => { connection.on(ev, this.emit.bind(this, ev)); }); } @@ -59,7 +59,7 @@ class Channel extends BaseChannel { // response's fields; this is intended to be suitable for implementing // API procedures. async rpc(method, fields, expect) { - const f = await promisify(cb => { + const f = await promisify((cb) => { return this._rpc(method, fields, expect, cb); })(); @@ -69,86 +69,63 @@ class Channel extends BaseChannel { // Do the remarkably simple channel open handshake async open() { const ch = await this.allocate.bind(this)(); - return ch.rpc(defs.ChannelOpen, {outOfBand: ""}, - defs.ChannelOpenOk); + return ch.rpc(defs.ChannelOpen, {outOfBand: ''}, defs.ChannelOpenOk); } close() { - return promisify(cb => { - return this.closeBecause("Goodbye", defs.constants.REPLY_SUCCESS, - cb); + return promisify((cb) => { + return this.closeBecause('Goodbye', defs.constants.REPLY_SUCCESS, cb); })(); } // === Public API, declaring queues and stuff === assertQueue(queue, options) { - return this.rpc(defs.QueueDeclare, - Args.assertQueue(queue, options), - defs.QueueDeclareOk); + return this.rpc(defs.QueueDeclare, Args.assertQueue(queue, options), defs.QueueDeclareOk); } checkQueue(queue) { - return this.rpc(defs.QueueDeclare, - Args.checkQueue(queue), - defs.QueueDeclareOk); + return this.rpc(defs.QueueDeclare, Args.checkQueue(queue), defs.QueueDeclareOk); } deleteQueue(queue, options) { - return this.rpc(defs.QueueDelete, - Args.deleteQueue(queue, options), - defs.QueueDeleteOk); + return this.rpc(defs.QueueDelete, Args.deleteQueue(queue, options), defs.QueueDeleteOk); } purgeQueue(queue) { - return this.rpc(defs.QueuePurge, - Args.purgeQueue(queue), - defs.QueuePurgeOk); + return this.rpc(defs.QueuePurge, Args.purgeQueue(queue), defs.QueuePurgeOk); } bindQueue(queue, source, pattern, argt) { - return this.rpc(defs.QueueBind, - Args.bindQueue(queue, source, pattern, argt), - defs.QueueBindOk); + return this.rpc(defs.QueueBind, Args.bindQueue(queue, source, pattern, argt), defs.QueueBindOk); } unbindQueue(queue, source, pattern, argt) { - return this.rpc(defs.QueueUnbind, - Args.unbindQueue(queue, source, pattern, argt), - defs.QueueUnbindOk); + return this.rpc(defs.QueueUnbind, Args.unbindQueue(queue, source, pattern, argt), defs.QueueUnbindOk); } assertExchange(exchange, type, options) { // The server reply is an empty set of fields, but it's convenient // to have the exchange name handed to the continuation. - return this.rpc(defs.ExchangeDeclare, - Args.assertExchange(exchange, type, options), - defs.ExchangeDeclareOk) - .then(_ok => { return { exchange }; }); + return this.rpc(defs.ExchangeDeclare, Args.assertExchange(exchange, type, options), defs.ExchangeDeclareOk).then((_ok) => { + return {exchange}; + }); } checkExchange(exchange) { - return this.rpc(defs.ExchangeDeclare, - Args.checkExchange(exchange), - defs.ExchangeDeclareOk); + return this.rpc(defs.ExchangeDeclare, Args.checkExchange(exchange), defs.ExchangeDeclareOk); } deleteExchange(name, options) { - return this.rpc(defs.ExchangeDelete, - Args.deleteExchange(name, options), - defs.ExchangeDeleteOk); + return this.rpc(defs.ExchangeDelete, Args.deleteExchange(name, options), defs.ExchangeDeleteOk); } bindExchange(dest, source, pattern, argt) { - return this.rpc(defs.ExchangeBind, - Args.bindExchange(dest, source, pattern, argt), - defs.ExchangeBindOk); + return this.rpc(defs.ExchangeBind, Args.bindExchange(dest, source, pattern, argt), defs.ExchangeBindOk); } unbindExchange(dest, source, pattern, argt) { - return this.rpc(defs.ExchangeUnbind, - Args.unbindExchange(dest, source, pattern, argt), - defs.ExchangeUnbindOk); + return this.rpc(defs.ExchangeUnbind, Args.unbindExchange(dest, source, pattern, argt), defs.ExchangeUnbindOk); } // Working with messages @@ -176,12 +153,9 @@ class Channel extends BaseChannel { } async cancel(consumerTag) { - const ok = await promisify(cb => { - this._rpc(defs.BasicCancel, Args.cancel(consumerTag), - defs.BasicCancelOk, - cb); - })() - .then(ok => { + const ok = await promisify((cb) => { + this._rpc(defs.BasicCancel, Args.cancel(consumerTag), defs.BasicCancelOk, cb); + })().then((ok) => { this.unregisterConsumer(consumerTag); return ok.fields; }); @@ -194,15 +168,13 @@ class Channel extends BaseChannel { if (err) return reject(err); if (f.id === defs.BasicGetEmpty) { return resolve(false); - } - else if (f.id === defs.BasicGetOk) { + } else if (f.id === defs.BasicGetOk) { const fields = f.fields; - this.handleMessage = acceptMessage(m => { + this.handleMessage = acceptMessage((m) => { m.fields = fields; resolve(m); }); - } - else { + } else { reject(new Error(`Unexpected response to BasicGet: ${inspect(f)}`)); } }); @@ -210,9 +182,7 @@ class Channel extends BaseChannel { } ack(message, allUpTo) { - this.sendImmediately( - defs.BasicAck, - Args.ack(message.fields.deliveryTag, allUpTo)); + this.sendImmediately(defs.BasicAck, Args.ack(message.fields.deliveryTag, allUpTo)); } ackAll() { @@ -220,14 +190,11 @@ class Channel extends BaseChannel { } nack(message, allUpTo, requeue) { - this.sendImmediately( - defs.BasicNack, - Args.nack(message.fields.deliveryTag, allUpTo, requeue)); + this.sendImmediately(defs.BasicNack, Args.nack(message.fields.deliveryTag, allUpTo, requeue)); } nackAll(requeue) { - this.sendImmediately(defs.BasicNack, - Args.nack(0, true, requeue)); + this.sendImmediately(defs.BasicNack, Args.nack(0, true, requeue)); } // `Basic.Nack` is not available in older RabbitMQ versions (or in the @@ -235,21 +202,15 @@ class Channel extends BaseChannel { // `Basic.Reject`. This is otherwise synonymous with // `#nack(message, false, requeue)`. reject(message, requeue) { - this.sendImmediately( - defs.BasicReject, - Args.reject(message.fields.deliveryTag, requeue)); + this.sendImmediately(defs.BasicReject, Args.reject(message.fields.deliveryTag, requeue)); } recover() { - return this.rpc(defs.BasicRecover, - Args.recover(), - defs.BasicRecoverOk); + return this.rpc(defs.BasicRecover, Args.recover(), defs.BasicRecoverOk); } qos(count, global) { - return this.rpc(defs.BasicQos, - Args.prefetch(count, global), - defs.BasicQosOk); + return this.rpc(defs.BasicQos, Args.prefetch(count, global), defs.BasicQosOk); } } @@ -258,7 +219,7 @@ class Channel extends BaseChannel { // channels or consumers. RabbitMQ v3.3.0 and after treat prefetch // (without `global` set) as per-consumer (for consumers following), // and prefetch with `global` set as per-channel. -Channel.prototype.prefetch = Channel.prototype.qos +Channel.prototype.prefetch = Channel.prototype.qos; // Confirm channel. This is a channel with confirms 'switched on', // meaning sent messages will provoke a responding 'ack' or 'nack' @@ -283,7 +244,7 @@ class ConfirmChannel extends Channel { unconfirmed.forEach((val, index) => { if (val !== null) { const confirmed = new Promise((resolve, reject) => { - unconfirmed[index] = err => { + unconfirmed[index] = (err) => { if (val) val(err); if (err === null) resolve(); else reject(err); @@ -295,7 +256,7 @@ class ConfirmChannel extends Channel { // Channel closed if (!this.pending) { var cb; - while (cb = this.unconfirmed.shift()) { + while ((cb = this.unconfirmed.shift())) { if (cb) cb(new Error('channel closed')); } } diff --git a/lib/codec.js b/lib/codec.js index bb9f5594..d0488720 100644 --- a/lib/codec.js +++ b/lib/codec.js @@ -69,276 +69,307 @@ var ints = require('buffer-more-ints'); // as a 64-bit integer. Except that only signed integers are supported // by RabbitMQ, so anything above 2^63 - 1 must be a double. function isFloatingPoint(n) { - return n >= 0x8000000000000000 || - (Math.abs(n) < 0x4000000000000 - && Math.floor(n) !== n); + return n >= 0x8000000000000000 || (Math.abs(n) < 0x4000000000000 && Math.floor(n) !== n); } function encodeTable(buffer, val, offset) { - var start = offset; - offset += 4; // leave room for the table length - for (var key in val) { - if (val[key] !== undefined) { - var len = Buffer.byteLength(key); - buffer.writeUInt8(len, offset); offset++; - buffer.write(key, offset, 'utf8'); offset += len; - offset += encodeFieldValue(buffer, val[key], offset); - } + var start = offset; + offset += 4; // leave room for the table length + for (var key in val) { + if (val[key] !== undefined) { + var len = Buffer.byteLength(key); + buffer.writeUInt8(len, offset); + offset++; + buffer.write(key, offset, 'utf8'); + offset += len; + offset += encodeFieldValue(buffer, val[key], offset); } - var size = offset - start; - buffer.writeUInt32BE(size - 4, start); - return size; + } + var size = offset - start; + buffer.writeUInt32BE(size - 4, start); + return size; } function encodeArray(buffer, val, offset) { - var start = offset; - offset += 4; - for (var i=0, num=val.length; i < num; i++) { - offset += encodeFieldValue(buffer, val[i], offset); - } - var size = offset - start; - buffer.writeUInt32BE(size - 4, start); - return size; + var start = offset; + offset += 4; + for (var i = 0, num = val.length; i < num; i++) { + offset += encodeFieldValue(buffer, val[i], offset); + } + var size = offset - start; + buffer.writeUInt32BE(size - 4, start); + return size; } function encodeFieldValue(buffer, value, offset) { - var start = offset; - var type = typeof value, val = value; - // A trapdoor for specifying a type, e.g., timestamp - if (value && type === 'object' && value.hasOwnProperty('!')) { - val = value.value; - type = value['!']; - } + var start = offset; + var type = typeof value, + val = value; + // A trapdoor for specifying a type, e.g., timestamp + if (value && type === 'object' && value.hasOwnProperty('!')) { + val = value.value; + type = value['!']; + } - // If it's a JS number, we'll have to guess what type to encode it - // as. - if (type == 'number') { - // Making assumptions about the kind of number (floating point - // v integer, signed, unsigned, size) desired is dangerous in - // general; however, in practice RabbitMQ uses only - // longstrings and unsigned integers in its arguments, and - // other clients generally conflate number types anyway. So - // the only distinction we care about is floating point vs - // integers, preferring integers since those can be promoted - // if necessary. If floating point is required, we may as well - // use double precision. - if (isFloatingPoint(val)) { - type = 'double'; - } - else { // only signed values are used in tables by - // RabbitMQ. It *used* to (< v3.3.0) treat the byte 'b' - // type as unsigned, but most clients (and the spec) - // think it's signed, and now RabbitMQ does too. - if (val < 128 && val >= -128) { - type = 'byte'; - } - else if (val >= -0x8000 && val < 0x8000) { - type = 'short' - } - else if (val >= -0x80000000 && val < 0x80000000) { - type = 'int'; - } - else { - type = 'long'; - } - } + // If it's a JS number, we'll have to guess what type to encode it + // as. + if (type == 'number') { + // Making assumptions about the kind of number (floating point + // v integer, signed, unsigned, size) desired is dangerous in + // general; however, in practice RabbitMQ uses only + // longstrings and unsigned integers in its arguments, and + // other clients generally conflate number types anyway. So + // the only distinction we care about is floating point vs + // integers, preferring integers since those can be promoted + // if necessary. If floating point is required, we may as well + // use double precision. + if (isFloatingPoint(val)) { + type = 'double'; + } else { + // only signed values are used in tables by + // RabbitMQ. It *used* to (< v3.3.0) treat the byte 'b' + // type as unsigned, but most clients (and the spec) + // think it's signed, and now RabbitMQ does too. + if (val < 128 && val >= -128) { + type = 'byte'; + } else if (val >= -0x8000 && val < 0x8000) { + type = 'short'; + } else if (val >= -0x80000000 && val < 0x80000000) { + type = 'int'; + } else { + type = 'long'; + } } + } - function tag(t) { buffer.write(t, offset); offset++; } + function tag(t) { + buffer.write(t, offset); + offset++; + } - switch (type) { + switch (type) { case 'string': // no shortstr in field tables - var len = Buffer.byteLength(val, 'utf8'); - tag('S'); - buffer.writeUInt32BE(len, offset); offset += 4; - buffer.write(val, offset, 'utf8'); offset += len; - break; + var len = Buffer.byteLength(val, 'utf8'); + tag('S'); + buffer.writeUInt32BE(len, offset); + offset += 4; + buffer.write(val, offset, 'utf8'); + offset += len; + break; case 'object': - if (val === null) { - tag('V'); - } - else if (Array.isArray(val)) { - tag('A'); - offset += encodeArray(buffer, val, offset); - } - else if (Buffer.isBuffer(val)) { - tag('x'); - buffer.writeUInt32BE(val.length, offset); offset += 4; - val.copy(buffer, offset); offset += val.length; - } - else { - tag('F'); - offset += encodeTable(buffer, val, offset); - } - break; + if (val === null) { + tag('V'); + } else if (Array.isArray(val)) { + tag('A'); + offset += encodeArray(buffer, val, offset); + } else if (Buffer.isBuffer(val)) { + tag('x'); + buffer.writeUInt32BE(val.length, offset); + offset += 4; + val.copy(buffer, offset); + offset += val.length; + } else { + tag('F'); + offset += encodeTable(buffer, val, offset); + } + break; case 'boolean': - tag('t'); - buffer.writeUInt8((val) ? 1 : 0, offset); offset++; - break; + tag('t'); + buffer.writeUInt8(val ? 1 : 0, offset); + offset++; + break; // These are the types that are either guessed above, or // explicitly given using the {'!': type} notation. case 'double': case 'float64': - tag('d'); - buffer.writeDoubleBE(val, offset); - offset += 8; - break; + tag('d'); + buffer.writeDoubleBE(val, offset); + offset += 8; + break; case 'byte': case 'int8': - tag('b'); - buffer.writeInt8(val, offset); offset++; - break; + tag('b'); + buffer.writeInt8(val, offset); + offset++; + break; case 'unsignedbyte': case 'uint8': - tag('B'); - buffer.writeUInt8(val, offset); offset++; - break; + tag('B'); + buffer.writeUInt8(val, offset); + offset++; + break; case 'short': case 'int16': - tag('s'); - buffer.writeInt16BE(val, offset); offset += 2; - break; + tag('s'); + buffer.writeInt16BE(val, offset); + offset += 2; + break; case 'unsignedshort': case 'uint16': - tag('u'); - buffer.writeUInt16BE(val, offset); offset += 2; - break; + tag('u'); + buffer.writeUInt16BE(val, offset); + offset += 2; + break; case 'int': case 'int32': - tag('I'); - buffer.writeInt32BE(val, offset); offset += 4; - break; + tag('I'); + buffer.writeInt32BE(val, offset); + offset += 4; + break; case 'unsignedint': case 'uint32': - tag('i'); - buffer.writeUInt32BE(val, offset); offset += 4; - break; + tag('i'); + buffer.writeUInt32BE(val, offset); + offset += 4; + break; case 'long': case 'int64': - tag('l'); - ints.writeInt64BE(buffer, val, offset); offset += 8; - break; + tag('l'); + ints.writeInt64BE(buffer, val, offset); + offset += 8; + break; // Now for exotic types, those can _only_ be denoted by using // `{'!': type, value: val} case 'timestamp': - tag('T'); - ints.writeUInt64BE(buffer, val, offset); offset += 8; - break; + tag('T'); + ints.writeUInt64BE(buffer, val, offset); + offset += 8; + break; case 'float': - tag('f'); - buffer.writeFloatBE(val, offset); offset += 4; - break; + tag('f'); + buffer.writeFloatBE(val, offset); + offset += 4; + break; case 'decimal': - tag('D'); - if (val.hasOwnProperty('places') && val.hasOwnProperty('digits') - && val.places >= 0 && val.places < 256) { - buffer[offset] = val.places; offset++; - buffer.writeUInt32BE(val.digits, offset); offset += 4; - } - else throw new TypeError( - "Decimal value must be {'places': 0..255, 'digits': uint32}, " + - "got " + JSON.stringify(val)); - break; + tag('D'); + if (val.hasOwnProperty('places') && val.hasOwnProperty('digits') && val.places >= 0 && val.places < 256) { + buffer[offset] = val.places; + offset++; + buffer.writeUInt32BE(val.digits, offset); + offset += 4; + } else throw new TypeError("Decimal value must be {'places': 0..255, 'digits': uint32}, " + 'got ' + JSON.stringify(val)); + break; default: - throw new TypeError('Unknown type to encode: ' + type); - } - return offset - start; + throw new TypeError('Unknown type to encode: ' + type); + } + return offset - start; } // Assume we're given a slice of the buffer that contains just the // fields. function decodeFields(slice) { - var fields = {}, offset = 0, size = slice.length; - var len, key, val; + var fields = {}, + offset = 0, + size = slice.length; + var len, key, val; - function decodeFieldValue() { - var tag = String.fromCharCode(slice[offset]); offset++; - switch (tag) { - case 'b': - val = slice.readInt8(offset); offset++; - break; - case 'B': - val = slice.readUInt8(offset); offset++; - break; - case 'S': - len = slice.readUInt32BE(offset); offset += 4; - val = slice.toString('utf8', offset, offset + len); - offset += len; - break; - case 'I': - val = slice.readInt32BE(offset); offset += 4; - break; - case 'i': - val = slice.readUInt32BE(offset); offset += 4; - break; - case 'D': // only positive decimals, apparently. - var places = slice[offset]; offset++; - var digits = slice.readUInt32BE(offset); offset += 4; - val = {'!': 'decimal', value: {places: places, digits: digits}}; - break; - case 'T': - val = ints.readUInt64BE(slice, offset); offset += 8; - val = {'!': 'timestamp', value: val}; - break; - case 'F': - len = slice.readUInt32BE(offset); offset += 4; - val = decodeFields(slice.subarray(offset, offset + len)); - offset += len; - break; - case 'A': - len = slice.readUInt32BE(offset); offset += 4; - decodeArray(offset + len); - // NB decodeArray will itself update offset and val - break; - case 'd': - val = slice.readDoubleBE(offset); offset += 8; - break; - case 'f': - val = slice.readFloatBE(offset); offset += 4; - break; - case 'l': - val = ints.readInt64BE(slice, offset); offset += 8; - break; - case 's': - val = slice.readInt16BE(offset); offset += 2; - break; - case 'u': - val = slice.readUInt16BE(offset); offset += 2; - break; - case 't': - val = slice[offset] != 0; offset++; - break; - case 'V': - val = null; - break; - case 'x': - len = slice.readUInt32BE(offset); offset += 4; - val = slice.subarray(offset, offset + len); - offset += len; - break; - default: - throw new TypeError('Unexpected type tag "' + tag +'"'); - } + function decodeFieldValue() { + var tag = String.fromCharCode(slice[offset]); + offset++; + switch (tag) { + case 'b': + val = slice.readInt8(offset); + offset++; + break; + case 'B': + val = slice.readUInt8(offset); + offset++; + break; + case 'S': + len = slice.readUInt32BE(offset); + offset += 4; + val = slice.toString('utf8', offset, offset + len); + offset += len; + break; + case 'I': + val = slice.readInt32BE(offset); + offset += 4; + break; + case 'i': + val = slice.readUInt32BE(offset); + offset += 4; + break; + case 'D': // only positive decimals, apparently. + var places = slice[offset]; + offset++; + var digits = slice.readUInt32BE(offset); + offset += 4; + val = {'!': 'decimal', value: {places: places, digits: digits}}; + break; + case 'T': + val = ints.readUInt64BE(slice, offset); + offset += 8; + val = {'!': 'timestamp', value: val}; + break; + case 'F': + len = slice.readUInt32BE(offset); + offset += 4; + val = decodeFields(slice.subarray(offset, offset + len)); + offset += len; + break; + case 'A': + len = slice.readUInt32BE(offset); + offset += 4; + decodeArray(offset + len); + // NB decodeArray will itself update offset and val + break; + case 'd': + val = slice.readDoubleBE(offset); + offset += 8; + break; + case 'f': + val = slice.readFloatBE(offset); + offset += 4; + break; + case 'l': + val = ints.readInt64BE(slice, offset); + offset += 8; + break; + case 's': + val = slice.readInt16BE(offset); + offset += 2; + break; + case 'u': + val = slice.readUInt16BE(offset); + offset += 2; + break; + case 't': + val = slice[offset] != 0; + offset++; + break; + case 'V': + val = null; + break; + case 'x': + len = slice.readUInt32BE(offset); + offset += 4; + val = slice.subarray(offset, offset + len); + offset += len; + break; + default: + throw new TypeError('Unexpected type tag "' + tag + '"'); } + } - function decodeArray(until) { - var vals = []; - while (offset < until) { - decodeFieldValue(); - vals.push(val); - } - val = vals; + function decodeArray(until) { + var vals = []; + while (offset < until) { + decodeFieldValue(); + vals.push(val); } + val = vals; + } - while (offset < size) { - len = slice.readUInt8(offset); offset++; - key = slice.toString('utf8', offset, offset + len); - offset += len; - decodeFieldValue(); - fields[key] = val; - } - return fields; + while (offset < size) { + len = slice.readUInt8(offset); + offset++; + key = slice.toString('utf8', offset, offset + len); + offset += len; + decodeFieldValue(); + fields[key] = val; + } + return fields; } module.exports.encodeTable = encodeTable; diff --git a/lib/connect.js b/lib/connect.js index 4cde5d90..38352d18 100644 --- a/lib/connect.js +++ b/lib/connect.js @@ -28,60 +28,59 @@ function clone(obj) { } var CLIENT_PROPERTIES = { - "product": "amqplib", - "version": require('../package.json').version, - "platform": fmt('Node.JS %s', process.version), - "information": "https://amqp-node.github.io/amqplib/", - "capabilities": { - "publisher_confirms": true, - "exchange_exchange_bindings": true, - "basic.nack": true, - "consumer_cancel_notify": true, - "connection.blocked": true, - "authentication_failure_close": true - } + product: 'amqplib', + version: require('../package.json').version, + platform: fmt('Node.JS %s', process.version), + information: 'https://amqp-node.github.io/amqplib/', + capabilities: { + publisher_confirms: true, + exchange_exchange_bindings: true, + 'basic.nack': true, + consumer_cancel_notify: true, + 'connection.blocked': true, + authentication_failure_close: true, + }, }; // Construct the main frames used in the opening handshake function openFrames(vhost, query, credentials, extraClientProperties) { - if (!vhost) - vhost = '/'; - else - vhost = QS.unescape(vhost); + if (!vhost) vhost = '/'; + else vhost = QS.unescape(vhost); var query = query || {}; function intOrDefault(val, def) { - return (val === undefined) ? def : parseInt(val); + return val === undefined ? def : parseInt(val); } var clientProperties = Object.create(CLIENT_PROPERTIES); return { // start-ok - 'clientProperties': copyInto(extraClientProperties, clientProperties), - 'mechanism': credentials.mechanism, - 'response': credentials.response(), - 'locale': query.locale || 'en_US', + clientProperties: copyInto(extraClientProperties, clientProperties), + mechanism: credentials.mechanism, + response: credentials.response(), + locale: query.locale || 'en_US', // tune-ok - 'channelMax': intOrDefault(query.channelMax, 0), - 'frameMax': intOrDefault(query.frameMax, 131072), - 'heartbeat': intOrDefault(query.heartbeat, 0), + channelMax: intOrDefault(query.channelMax, 0), + frameMax: intOrDefault(query.frameMax, 131072), + heartbeat: intOrDefault(query.heartbeat, 0), // open - 'virtualHost': vhost, - 'capabilities': '', - 'insist': 0 + virtualHost: vhost, + capabilities: '', + insist: 0, }; } // Decide on credentials based on what we're supplied. function credentialsFromUrl(parts) { - var user = 'guest', passwd = 'guest'; + var user = 'guest', + passwd = 'guest'; if (parts.username != '' || parts.password != '') { - user = (parts.username) ? unescape(parts.username) : ''; - passwd = (parts.password) ? unescape(parts.password) : ''; + user = parts.username ? unescape(parts.username) : ''; + passwd = parts.password ? unescape(parts.password) : ''; } return credentials.plain(user, passwd); } @@ -107,13 +106,14 @@ function connect(url, socketOptions, openCallback) { protocol = (url.protocol || 'amqp') + ':'; sockopts.host = url.hostname; sockopts.servername = sockopts.servername || url.hostname; - sockopts.port = url.port || ((protocol === 'amqp:') ? 5672 : 5671); + sockopts.port = url.port || (protocol === 'amqp:' ? 5672 : 5671); var user, pass; // Only default if both are missing, to have the same behaviour as // the stringly URL. if (url.username == undefined && url.password == undefined) { - user = 'guest'; pass = 'guest'; + user = 'guest'; + pass = 'guest'; } else { user = url.username || ''; pass = url.password || ''; @@ -133,7 +133,7 @@ function connect(url, socketOptions, openCallback) { protocol = parts.protocol; sockopts.host = host; sockopts.servername = sockopts.servername || host; - sockopts.port = parseInt(parts.port) || ((protocol === 'amqp:') ? 5672 : 5671); + sockopts.port = parseInt(parts.port) || (protocol === 'amqp:' ? 5672 : 5671); var vhost = parts.pathname ? parts.pathname.substr(1) : null; fields = openFrames(vhost, parts.query, sockopts.credentials || credentialsFromUrl(parts), extraClientProperties); } @@ -147,7 +147,7 @@ function connect(url, socketOptions, openCallback) { if (keepAlive) sock.setKeepAlive(keepAlive, keepAliveDelay); var c = new Connection(sock); - c.open(fields, function(err, ok) { + c.open(fields, function (err, ok) { // disable timeout once the connection is open, we don't want // it fouling things if (timeout) sock.setTimeout(0); @@ -164,26 +164,23 @@ function connect(url, socketOptions, openCallback) { if (protocol === 'amqp:') { sock = require('net').connect(sockopts, onConnect); - } - else if (protocol === 'amqps:') { + } else if (protocol === 'amqps:') { sock = require('tls').connect(sockopts, onConnect); - } - else { - throw new Error("Expected amqp: or amqps: as the protocol; got " + protocol); + } else { + throw new Error('Expected amqp: or amqps: as the protocol; got ' + protocol); } if (timeout) { - sock.setTimeout(timeout, function() { + sock.setTimeout(timeout, function () { sock.end(); sock.destroy(); openCallback(new Error('connect ETIMEDOUT')); }); } - sock.once('error', function(err) { + sock.once('error', function (err) { if (!sockok) openCallback(err); }); - } module.exports.connect = connect; diff --git a/lib/connection.js b/lib/connection.js index aa68885e..2e59a9d8 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -34,10 +34,10 @@ var DEFAULT_WRITE_HWM = 1024; var SINGLE_CHUNK_THRESHOLD = 2048; class Connection extends EventEmitter { - constructor (underlying) { + constructor(underlying) { super(); - var stream = this.stream = wrapStream(underlying); + var stream = (this.stream = wrapStream(underlying)); this.muxer = new Mux(stream); // frames @@ -48,17 +48,19 @@ class Connection extends EventEmitter { this.expectSocketClose = false; this.freeChannels = new BitSet(); - this.channels = [{ - channel: { accept: channel0(this) }, - buffer: underlying - }]; + this.channels = [ + { + channel: {accept: channel0(this)}, + buffer: underlying, + }, + ]; } // This changed between versions, as did the codec, methods, etc. AMQP // 0-9-1 is fairly similar to 0.8, but better, and nothing implements // 0.8 that doesn't implement 0-9-1. In other words, it doesn't make // much sense to generalise here. - sendProtocolHeader () { + sendProtocolHeader() { this.sendBytes(frame.PROTOCOL_HEADER); } @@ -84,50 +86,42 @@ class Connection extends EventEmitter { (SASL PLAIN: http://tools.ietf.org/html/rfc4616) */ - open (allFields, openCallback0) { + open(allFields, openCallback0) { var self = this; - var openCallback = openCallback0 || function () { }; + var openCallback = openCallback0 || function () {}; // This is where we'll put our negotiated values var tunedOptions = Object.create(allFields); - function wait (k) { + function wait(k) { self.step(function (err, frame) { - if (err !== null) - bail(err); + if (err !== null) bail(err); else if (frame.channel !== 0) { - bail(new Error( - fmt("Frame on channel != 0 during handshake: %s", - inspect(frame, false)))); - } - else - k(frame); + bail(new Error(fmt('Frame on channel != 0 during handshake: %s', inspect(frame, false)))); + } else k(frame); }); } - function expect (Method, k) { + function expect(Method, k) { wait(function (frame) { - if (frame.id === Method) - k(frame); + if (frame.id === Method) k(frame); else { - bail(new Error( - fmt("Expected %s; got %s", - methodName(Method), inspect(frame, false)))); + bail(new Error(fmt('Expected %s; got %s', methodName(Method), inspect(frame, false)))); } }); } - function bail (err) { + function bail(err) { openCallback(err); } - function send (Method) { + function send(Method) { // This can throw an exception if there's some problem with the // options; e.g., something is a string instead of a number. self.sendMethod(0, Method, tunedOptions); } - function negotiate (server, desired) { + function negotiate(server, desired) { // We get sent values for channelMax, frameMax and heartbeat, // which we may accept or lower (subject to a minimum for // frameMax, but we'll leave that to the server to enforce). In @@ -136,17 +130,15 @@ class Connection extends EventEmitter { if (server === 0 || desired === 0) { // i.e., whichever places a limit, if either return Math.max(server, desired); - } - else { + } else { return Math.min(server, desired); } } - function onStart (start) { + function onStart(start) { var mechanisms = start.fields.mechanisms.toString().split(' '); if (mechanisms.indexOf(allFields.mechanism) < 0) { - bail(new Error(fmt('SASL mechanism %s is not provided by the server', - allFields.mechanism))); + bail(new Error(fmt('SASL mechanism %s is not provided by the server', allFields.mechanism))); return; } self.serverProperties = start.fields.serverProperties; @@ -159,24 +151,19 @@ class Connection extends EventEmitter { wait(afterStartOk); } - function afterStartOk (reply) { + function afterStartOk(reply) { switch (reply.id) { case defs.ConnectionSecure: - bail(new Error( - "Wasn't expecting to have to go through secure")); + bail(new Error("Wasn't expecting to have to go through secure")); break; case defs.ConnectionClose: - bail(new Error(fmt("Handshake terminated by server: %s", - closeMsg(reply)))); + bail(new Error(fmt('Handshake terminated by server: %s', closeMsg(reply)))); break; case defs.ConnectionTune: var fields = reply.fields; - tunedOptions.frameMax = - negotiate(fields.frameMax, allFields.frameMax); - tunedOptions.channelMax = - negotiate(fields.channelMax, allFields.channelMax); - tunedOptions.heartbeat = - negotiate(fields.heartbeat, allFields.heartbeat); + tunedOptions.frameMax = negotiate(fields.frameMax, allFields.frameMax); + tunedOptions.channelMax = negotiate(fields.channelMax, allFields.channelMax); + tunedOptions.heartbeat = negotiate(fields.heartbeat, allFields.heartbeat); try { send(defs.ConnectionTuneOk); send(defs.ConnectionOpen); @@ -187,15 +174,16 @@ class Connection extends EventEmitter { expect(defs.ConnectionOpenOk, onOpenOk); break; default: - bail(new Error( - fmt("Expected connection.secure, connection.close, " + - "or connection.tune during handshake; got %s", - inspect(reply, false)))); + bail( + new Error( + fmt('Expected connection.secure, connection.close, ' + 'or connection.tune during handshake; got %s', inspect(reply, false)), + ), + ); break; } } - function onOpenOk (openOk) { + function onOpenOk(openOk) { // Impose the maximum of the encoded value, if the negotiated // value is zero, meaning "no, no limits" self.channelMax = tunedOptions.channelMax || 0xffff; @@ -210,20 +198,18 @@ class Connection extends EventEmitter { // If the server closes the connection, it's probably because of // something we did - function endWhileOpening (err) { - bail(err || new Error('Socket closed abruptly ' + - 'during opening handshake')); + function endWhileOpening(err) { + bail(err || new Error('Socket closed abruptly ' + 'during opening handshake')); } this.stream.on('end', endWhileOpening); this.stream.on('error', endWhileOpening); - function succeed (ok) { + function succeed(ok) { self.stream.removeListener('end', endWhileOpening); self.stream.removeListener('error', endWhileOpening); self.stream.on('error', self.onSocketError.bind(self)); - self.stream.on('end', self.onSocketError.bind( - self, new Error('Unexpected close'))); + self.stream.on('end', self.onSocketError.bind(self, new Error('Unexpected close'))); self.on('frameError', self.onSocketError.bind(self)); self.acceptLoop(); openCallback(null, ok); @@ -275,30 +261,35 @@ class Connection extends EventEmitter { // emitted as above. The events will fire *before* promises are // resolved. // Close the connection without even giving a reason. Typical. - close (closeCallback) { - var k = closeCallback && function () { closeCallback(null); }; - this.closeBecause("Cheers, thanks", constants.REPLY_SUCCESS, k); + close(closeCallback) { + var k = + closeCallback && + function () { + closeCallback(null); + }; + this.closeBecause('Cheers, thanks', constants.REPLY_SUCCESS, k); } // Close with a reason and a 'code'. I'm pretty sure RabbitMQ totally // ignores these; maybe it logs them. The continuation will be invoked // when the CloseOk has been received, and before the 'close' event. - closeBecause (reason, code, k) { + closeBecause(reason, code, k) { this.sendMethod(0, defs.ConnectionClose, { replyText: reason, replyCode: code, - methodId: 0, classId: 0 + methodId: 0, + classId: 0, }); var s = stackCapture('closeBecause called: ' + reason); this.toClosing(s, k); } - closeWithError (reason, code, error) { + closeWithError(reason, code, error) { this.emit('error', error); this.closeBecause(reason, code); } - onSocketError (err) { + onSocketError(err) { if (!this.expectSocketClose) { // forestall any more calls to onSocketError, since we're signed // up for `'error'` *and* `'end'` @@ -312,17 +303,15 @@ class Connection extends EventEmitter { // A close has been initiated. Repeat: a close has been initiated. // This means we should not send more frames, anyway they will be // ignored. We also have to shut down all the channels. - toClosing (capturedStack, k) { + toClosing(capturedStack, k) { var send = this.sendMethod.bind(this); this.accept = function (f) { if (f.id === defs.ConnectionCloseOk) { - if (k) - k(); + if (k) k(); var s = stackCapture('ConnectionCloseOk received'); this.toClosed(s, undefined); - } - else if (f.id === defs.ConnectionClose) { + } else if (f.id === defs.ConnectionClose) { send(0, defs.ConnectionCloseOk, {}); } // else ignore frame @@ -330,7 +319,7 @@ class Connection extends EventEmitter { invalidateSend(this, 'Connection closing', capturedStack); } - _closeChannels (capturedStack) { + _closeChannels(capturedStack) { for (var i = 1; i < this.channels.length; i++) { var ch = this.channels[i]; if (ch !== null) { @@ -340,18 +329,16 @@ class Connection extends EventEmitter { } // A close has been confirmed. Cease all communication. - toClosed (capturedStack, maybeErr) { + toClosed(capturedStack, maybeErr) { this._closeChannels(capturedStack); - var info = fmt('Connection closed (%s)', - (maybeErr) ? maybeErr.toString() : 'by client'); + var info = fmt('Connection closed (%s)', maybeErr ? maybeErr.toString() : 'by client'); // Tidy up, invalidate enverything, dynamite the bridges. invalidateSend(this, info, capturedStack); this.accept = invalidOp(info, capturedStack); this.close = function (cb) { cb && cb(new IllegalOperationError(info, capturedStack)); }; - if (this.heartbeater) - this.heartbeater.clear(); + if (this.heartbeater) this.heartbeater.clear(); // This is certainly true now, if it wasn't before this.expectSocketClose = true; this.stream.end(); @@ -361,22 +348,19 @@ class Connection extends EventEmitter { _updateSecret(newSecret, reason, cb) { this.sendMethod(0, defs.ConnectionUpdateSecret, { newSecret, - reason + reason, }); this.once('update-secret-ok', cb); } // === - startHeartbeater () { - if (this.heartbeat === 0) - return null; + startHeartbeater() { + if (this.heartbeat === 0) return null; else { var self = this; - var hb = new Heart(this.heartbeat, - this.checkSend.bind(this), - this.checkRecv.bind(this)); + var hb = new Heart(this.heartbeat, this.checkSend.bind(this), this.checkRecv.bind(this)); hb.on('timeout', function () { - var hberr = new Error("Heartbeat timeout"); + var hberr = new Error('Heartbeat timeout'); self.emit('error', hberr); var s = stackCapture('Heartbeat timeout'); self.toClosed(s, hberr); @@ -397,17 +381,17 @@ class Connection extends EventEmitter { // the expectation that the next channel allocation will fill the slot // again rather than growing the array. See // http://www.html5rocks.com/en/tutorials/speed/v8/ - freshChannel (channel, options) { + freshChannel(channel, options) { var next = this.freeChannels.nextClearBit(1); - if (next < 0 || next > this.channelMax) - throw new Error("No channels left to allocate"); + if (next < 0 || next > this.channelMax) throw new Error('No channels left to allocate'); this.freeChannels.set(next); var hwm = (options && options.highWaterMark) || DEFAULT_WRITE_HWM; var writeBuffer = new PassThrough({ - objectMode: true, highWaterMark: hwm + objectMode: true, + highWaterMark: hwm, }); - this.channels[next] = { channel: channel, buffer: writeBuffer }; + this.channels[next] = {channel: channel, buffer: writeBuffer}; writeBuffer.on('drain', function () { channel.onBufferDrain(); }); @@ -415,22 +399,21 @@ class Connection extends EventEmitter { return next; } - releaseChannel (channel) { + releaseChannel(channel) { this.freeChannels.clear(channel); var buffer = this.channels[channel].buffer; buffer.end(); // will also cause it to be unpiped this.channels[channel] = null; } - acceptLoop () { + acceptLoop() { var self = this; - function go () { + function go() { try { - var f; while (f = self.recvFrame()) - self.accept(f); - } - catch (e) { + var f; + while ((f = self.recvFrame())) self.accept(f); + } catch (e) { self.emit('frameError', e); } } @@ -438,66 +421,60 @@ class Connection extends EventEmitter { go(); } - step (cb) { + step(cb) { var self = this; - function recv () { + function recv() { var f; try { f = self.recvFrame(); - } - catch (e) { + } catch (e) { cb(e, null); return; } - if (f) - cb(null, f); - else - self.stream.once('readable', recv); + if (f) cb(null, f); + else self.stream.once('readable', recv); } recv(); } - checkSend () { + checkSend() { var check = this.sentSinceLastCheck; this.sentSinceLastCheck = false; return check; } - checkRecv () { + checkRecv() { var check = this.recvSinceLastCheck; this.recvSinceLastCheck = false; return check; } - sendBytes (bytes) { + sendBytes(bytes) { this.sentSinceLastCheck = true; this.stream.write(bytes); } - sendHeartbeat () { + sendHeartbeat() { return this.sendBytes(frame.HEARTBEAT_BUF); } - sendMethod (channel, Method, fields) { + sendMethod(channel, Method, fields) { var frame = encodeMethod(Method, channel, fields); this.sentSinceLastCheck = true; var buffer = this.channels[channel].buffer; return buffer.write(frame); } - sendMessage (channel, Method, fields, Properties, props, content) { - if (!Buffer.isBuffer(content)) - throw new TypeError('content is not a buffer'); + sendMessage(channel, Method, fields, Properties, props, content) { + if (!Buffer.isBuffer(content)) throw new TypeError('content is not a buffer'); var mframe = encodeMethod(Method, channel, fields); - var pframe = encodeProperties(Properties, channel, - content.length, props); + var pframe = encodeProperties(Properties, channel, content.length, props); var buffer = this.channels[channel].buffer; this.sentSinceLastCheck = true; var methodHeaderLen = mframe.length + pframe.length; - var bodyLen = (content.length > 0) ? - content.length + FRAME_OVERHEAD : 0; + var bodyLen = content.length > 0 ? content.length + FRAME_OVERHEAD : 0; var allLen = methodHeaderLen + bodyLen; if (allLen < SINGLE_CHUNK_THRESHOLD) { @@ -509,11 +486,9 @@ class Connection extends EventEmitter { var offset = mframe.copy(all, 0); offset += pframe.copy(all, offset); - if (bodyLen > 0) - makeBodyFrame(channel, content).copy(all, offset); + if (bodyLen > 0) makeBodyFrame(channel, content).copy(all, offset); return buffer.write(all); - } - else { + } else { if (methodHeaderLen < SINGLE_CHUNK_THRESHOLD) { // Use `allocUnsafe` to avoid excessive allocations and CPU usage // from zeroing. The returned Buffer is not zeroed and so must be @@ -523,8 +498,7 @@ class Connection extends EventEmitter { var offset = mframe.copy(both, 0); pframe.copy(both, offset); buffer.write(both); - } - else { + } else { buffer.write(mframe); buffer.write(pframe); } @@ -532,9 +506,9 @@ class Connection extends EventEmitter { } } - sendContent (channel, body) { + sendContent(channel, body) { if (!Buffer.isBuffer(body)) { - throw new TypeError(fmt("Expected buffer; got %s", body)); + throw new TypeError(fmt('Expected buffer; got %s', body)); } var writeResult = true; var buffer = this.channels[channel].buffer; @@ -543,7 +517,7 @@ class Connection extends EventEmitter { for (var offset = 0; offset < body.length; offset += maxBody) { var end = offset + maxBody; - var slice = (end > body.length) ? body.subarray(offset) : body.subarray(offset, end); + var slice = end > body.length ? body.subarray(offset) : body.subarray(offset, end); var bodyFrame = makeBodyFrame(channel, slice); writeResult = buffer.write(bodyFrame); } @@ -551,7 +525,7 @@ class Connection extends EventEmitter { return writeResult; } - recvFrame () { + recvFrame() { // %%% identifying invariants might help here? var frame = parseFrame(this.rest); @@ -559,14 +533,12 @@ class Connection extends EventEmitter { var incoming = this.stream.read(); if (incoming === null) { return false; - } - else { + } else { this.recvSinceLastCheck = true; this.rest = Buffer.concat([this.rest, incoming]); return this.recvFrame(); } - } - else { + } else { this.rest = frame.rest; return decodeFrame(frame); } @@ -576,28 +548,30 @@ class Connection extends EventEmitter { // Usual frame accept mode function mainAccept(frame) { var rec = this.channels[frame.channel]; - if (rec) { return rec.channel.accept(frame); } + if (rec) { + return rec.channel.accept(frame); + } // NB CHANNEL_ERROR may not be right, but I don't know what is .. else this.closeWithError( fmt('Frame on unknown channel %d', frame.channel), constants.CHANNEL_ERROR, - new Error(fmt("Frame on unknown channel: %s", - inspect(frame, false)))); + new Error(fmt('Frame on unknown channel: %s', inspect(frame, false))), + ); } // Handle anything that comes through on channel 0, that's the // connection control channel. This is only used once mainAccept is // installed as the frame handler, after the opening handshake. function channel0(connection) { - return function(f) { + return function (f) { // Once we get a 'close', we know 1. we'll get no more frames, and // 2. anything we send except close, or close-ok, will be // ignored. If we already sent 'close', this won't be invoked since // we're already in closing mode; if we didn't well we're not going // to send it now are we. if (f === HEARTBEAT); // ignore; it's already counted as activity - // on the socket, which is its purpose + // on the socket, which is its purpose else if (f.id === defs.ConnectionClose) { // Oh. OK. I guess we're done here then. connection.sendMethod(0, defs.ConnectionCloseOk, {}); @@ -609,35 +583,30 @@ function channel0(connection) { connection.emit('error', e); } connection.toClosed(s, e); - } - else if (f.id === defs.ConnectionBlocked) { + } else if (f.id === defs.ConnectionBlocked) { connection.emit('blocked', f.fields.reason); - } - else if (f.id === defs.ConnectionUnblocked) { + } else if (f.id === defs.ConnectionUnblocked) { connection.emit('unblocked'); - } - else if (f.id === defs.ConnectionUpdateSecretOk) { + } else if (f.id === defs.ConnectionUpdateSecretOk) { connection.emit('update-secret-ok'); - } - else { + } else { connection.closeWithError( - fmt("Unexpected frame on channel 0"), + fmt('Unexpected frame on channel 0'), constants.UNEXPECTED_FRAME, - new Error(fmt("Unexpected frame on channel 0: %s", - inspect(f, false)))); + new Error(fmt('Unexpected frame on channel 0: %s', inspect(f, false))), + ); } }; } function invalidOp(msg, stack) { - return function() { + return function () { throw new IllegalOperationError(msg, stack); }; } function invalidateSend(conn, msg, stack) { - conn.sendMethod = conn.sendContent = conn.sendMessage = - invalidOp(msg, stack); + conn.sendMethod = conn.sendContent = conn.sendMessage = invalidOp(msg, stack); } var encodeMethod = defs.encodeMethod; @@ -654,7 +623,7 @@ function wrapStream(s) { else { var ws = new Duplex(); ws.wrap(s); //wraps the readable side of things - ws._write = function(chunk, encoding, callback) { + ws._write = function (chunk, encoding, callback) { return s.write(chunk, encoding, callback); }; return ws; @@ -663,11 +632,11 @@ function wrapStream(s) { function isFatalError(error) { switch (error && error.code) { - case defs.constants.CONNECTION_FORCED: - case defs.constants.REPLY_SUCCESS: - return false; - default: - return true; + case defs.constants.CONNECTION_FORCED: + case defs.constants.REPLY_SUCCESS: + return false; + default: + return true; } } diff --git a/lib/credentials.js b/lib/credentials.js index a9452845..42416144 100644 --- a/lib/credentials.js +++ b/lib/credentials.js @@ -8,35 +8,37 @@ // * PLAIN (send username and password in the plain) // * EXTERNAL (assume the server will figure out who you are from // context, i.e., your SSL certificate) -var codec = require('./codec') +var codec = require('./codec'); -module.exports.plain = function(user, passwd) { +module.exports.plain = function (user, passwd) { return { mechanism: 'PLAIN', - response: function() { - return Buffer.from(['', user, passwd].join(String.fromCharCode(0))) + response: function () { + return Buffer.from(['', user, passwd].join(String.fromCharCode(0))); }, username: user, - password: passwd - } -} + password: passwd, + }; +}; -module.exports.amqplain = function(user, passwd) { +module.exports.amqplain = function (user, passwd) { return { mechanism: 'AMQPLAIN', - response: function() { + response: function () { const buffer = Buffer.alloc(16384); - const size = codec.encodeTable(buffer, { LOGIN: user, PASSWORD: passwd}, 0); + const size = codec.encodeTable(buffer, {LOGIN: user, PASSWORD: passwd}, 0); return buffer.subarray(4, size); }, username: user, - password: passwd - } -} + password: passwd, + }; +}; -module.exports.external = function() { +module.exports.external = function () { return { mechanism: 'EXTERNAL', - response: function() { return Buffer.from(''); } - } -} + response: function () { + return Buffer.from(''); + }, + }; +}; diff --git a/lib/defs.js b/lib/defs.js index 6b3102dc..d9143663 100644 --- a/lib/defs.js +++ b/lib/defs.js @@ -1,16 +1,18 @@ /** @preserve This file is generated by the script * ../bin/generate-defs.js, which is not in general included in a * distribution, but is available in the source repository e.g. at - * https://github.com/squaremo/amqp.node/ + * https://github.com/amqp-node/amqplib/ */ -"use strict"; +'use strict'; function decodeBasicQos(buffer) { - var val, offset = 0, fields = { - prefetchSize: void 0, - prefetchCount: void 0, - global: void 0 - }; + var val, + offset = 0, + fields = { + prefetchSize: void 0, + prefetchCount: void 0, + global: void 0, + }; val = buffer.readUInt32BE(offset); offset += 4; fields.prefetchSize = val; @@ -23,17 +25,24 @@ function decodeBasicQos(buffer) { } function encodeBasicQos(channel, fields) { - var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(19); + var offset = 0, + val = null, + bits = 0, + buffer = Buffer.alloc(19); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(3932170, 7); offset = 11; val = fields.prefetchSize; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'prefetchSize' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) + throw new TypeError("Field 'prefetchSize' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt32BE(val, offset); offset += 4; val = fields.prefetchCount; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'prefetchCount' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) + throw new TypeError("Field 'prefetchCount' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.global; @@ -51,7 +60,8 @@ function decodeBasicQosOk(buffer) { } function encodeBasicQosOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(3932171, 7); @@ -62,27 +72,30 @@ function encodeBasicQosOk(channel, fields) { } function decodeBasicConsume(buffer) { - var val, len, offset = 0, fields = { - ticket: void 0, - queue: void 0, - consumerTag: void 0, - noLocal: void 0, - noAck: void 0, - exclusive: void 0, - nowait: void 0, - arguments: void 0 - }; + var val, + len, + offset = 0, + fields = { + ticket: void 0, + queue: void 0, + consumerTag: void 0, + noLocal: void 0, + noAck: void 0, + exclusive: void 0, + nowait: void 0, + arguments: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.queue = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.consumerTag = val; val = !!(1 & buffer[offset]); @@ -103,17 +116,27 @@ function decodeBasicConsume(buffer) { } function encodeBasicConsume(channel, fields) { - var len, offset = 0, val = null, bits = 0, varyingSize = 0, scratchOffset = 0; + var len, + offset = 0, + val = null, + bits = 0, + varyingSize = 0, + scratchOffset = 0; val = fields.queue; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); - var queue_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, 'utf8'); varyingSize += queue_len; val = fields.consumerTag; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); - var consumerTag_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); + var consumerTag_len = Buffer.byteLength(val, 'utf8'); varyingSize += consumerTag_len; val = fields.arguments; - if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + if (void 0 === val) val = {}; + else if ('object' != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); len = encodeTable(SCRATCH, val, scratchOffset); var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); scratchOffset += len; @@ -124,20 +147,21 @@ function encodeBasicConsume(channel, fields) { buffer.writeUInt32BE(3932180, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.queue; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = queue_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += queue_len; val = fields.consumerTag; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = consumerTag_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += consumerTag_len; val = fields.noLocal; void 0 === val && (val = !1); @@ -161,23 +185,29 @@ function encodeBasicConsume(channel, fields) { } function decodeBasicConsumeOk(buffer) { - var val, len, offset = 0, fields = { - consumerTag: void 0 - }; + var val, + len, + offset = 0, + fields = { + consumerTag: void 0, + }; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.consumerTag = val; return fields; } function encodeBasicConsumeOk(channel, fields) { - var offset = 0, val = null, varyingSize = 0; + var offset = 0, + val = null, + varyingSize = 0; val = fields.consumerTag; if (void 0 === val) throw new Error("Missing value for mandatory field 'consumerTag'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); - var consumerTag_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); + var consumerTag_len = Buffer.byteLength(val, 'utf8'); varyingSize += consumerTag_len; var buffer = Buffer.alloc(13 + varyingSize); buffer[0] = 1; @@ -188,7 +218,7 @@ function encodeBasicConsumeOk(channel, fields) { void 0 === val && (val = void 0); buffer[offset] = consumerTag_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += consumerTag_len; buffer[offset] = 206; buffer.writeUInt32BE(offset - 7, 3); @@ -196,13 +226,16 @@ function encodeBasicConsumeOk(channel, fields) { } function decodeBasicCancel(buffer) { - var val, len, offset = 0, fields = { - consumerTag: void 0, - nowait: void 0 - }; + var val, + len, + offset = 0, + fields = { + consumerTag: void 0, + nowait: void 0, + }; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.consumerTag = val; val = !!(1 & buffer[offset]); @@ -211,11 +244,15 @@ function decodeBasicCancel(buffer) { } function encodeBasicCancel(channel, fields) { - var offset = 0, val = null, bits = 0, varyingSize = 0; + var offset = 0, + val = null, + bits = 0, + varyingSize = 0; val = fields.consumerTag; if (void 0 === val) throw new Error("Missing value for mandatory field 'consumerTag'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); - var consumerTag_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); + var consumerTag_len = Buffer.byteLength(val, 'utf8'); varyingSize += consumerTag_len; var buffer = Buffer.alloc(14 + varyingSize); buffer[0] = 1; @@ -226,7 +263,7 @@ function encodeBasicCancel(channel, fields) { void 0 === val && (val = void 0); buffer[offset] = consumerTag_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += consumerTag_len; val = fields.nowait; void 0 === val && (val = !1); @@ -239,23 +276,29 @@ function encodeBasicCancel(channel, fields) { } function decodeBasicCancelOk(buffer) { - var val, len, offset = 0, fields = { - consumerTag: void 0 - }; + var val, + len, + offset = 0, + fields = { + consumerTag: void 0, + }; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.consumerTag = val; return fields; } function encodeBasicCancelOk(channel, fields) { - var offset = 0, val = null, varyingSize = 0; + var offset = 0, + val = null, + varyingSize = 0; val = fields.consumerTag; if (void 0 === val) throw new Error("Missing value for mandatory field 'consumerTag'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); - var consumerTag_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); + var consumerTag_len = Buffer.byteLength(val, 'utf8'); varyingSize += consumerTag_len; var buffer = Buffer.alloc(13 + varyingSize); buffer[0] = 1; @@ -266,7 +309,7 @@ function encodeBasicCancelOk(channel, fields) { void 0 === val && (val = void 0); buffer[offset] = consumerTag_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += consumerTag_len; buffer[offset] = 206; buffer.writeUInt32BE(offset - 7, 3); @@ -274,24 +317,27 @@ function encodeBasicCancelOk(channel, fields) { } function decodeBasicPublish(buffer) { - var val, len, offset = 0, fields = { - ticket: void 0, - exchange: void 0, - routingKey: void 0, - mandatory: void 0, - immediate: void 0 - }; + var val, + len, + offset = 0, + fields = { + ticket: void 0, + exchange: void 0, + routingKey: void 0, + mandatory: void 0, + immediate: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.exchange = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.routingKey = val; val = !!(1 & buffer[offset]); @@ -302,14 +348,21 @@ function decodeBasicPublish(buffer) { } function encodeBasicPublish(channel, fields) { - var offset = 0, val = null, bits = 0, varyingSize = 0; + var offset = 0, + val = null, + bits = 0, + varyingSize = 0; val = fields.exchange; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); - var exchange_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, 'utf8'); varyingSize += exchange_len; val = fields.routingKey; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); - var routingKey_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, 'utf8'); varyingSize += routingKey_len; var buffer = Buffer.alloc(17 + varyingSize); buffer[0] = 1; @@ -317,20 +370,21 @@ function encodeBasicPublish(channel, fields) { buffer.writeUInt32BE(3932200, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.exchange; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = exchange_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += exchange_len; val = fields.routingKey; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = routingKey_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += routingKey_len; val = fields.mandatory; void 0 === val && (val = !1); @@ -346,48 +400,57 @@ function encodeBasicPublish(channel, fields) { } function decodeBasicReturn(buffer) { - var val, len, offset = 0, fields = { - replyCode: void 0, - replyText: void 0, - exchange: void 0, - routingKey: void 0 - }; + var val, + len, + offset = 0, + fields = { + replyCode: void 0, + replyText: void 0, + exchange: void 0, + routingKey: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.replyCode = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.replyText = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.exchange = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.routingKey = val; return fields; } function encodeBasicReturn(channel, fields) { - var offset = 0, val = null, varyingSize = 0; + var offset = 0, + val = null, + varyingSize = 0; val = fields.replyText; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'replyText' is the wrong type; must be a string (up to 255 chars)"); - var replyText_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'replyText' is the wrong type; must be a string (up to 255 chars)"); + var replyText_len = Buffer.byteLength(val, 'utf8'); varyingSize += replyText_len; val = fields.exchange; if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); - var exchange_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, 'utf8'); varyingSize += exchange_len; val = fields.routingKey; if (void 0 === val) throw new Error("Missing value for mandatory field 'routingKey'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); - var routingKey_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, 'utf8'); varyingSize += routingKey_len; var buffer = Buffer.alloc(17 + varyingSize); buffer[0] = 1; @@ -396,26 +459,26 @@ function encodeBasicReturn(channel, fields) { offset = 11; val = fields.replyCode; if (void 0 === val) throw new Error("Missing value for mandatory field 'replyCode'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'replyCode' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'replyCode' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.replyText; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = replyText_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += replyText_len; val = fields.exchange; void 0 === val && (val = void 0); buffer[offset] = exchange_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += exchange_len; val = fields.routingKey; void 0 === val && (val = void 0); buffer[offset] = routingKey_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += routingKey_len; buffer[offset] = 206; buffer.writeUInt32BE(offset - 7, 3); @@ -423,16 +486,19 @@ function encodeBasicReturn(channel, fields) { } function decodeBasicDeliver(buffer) { - var val, len, offset = 0, fields = { - consumerTag: void 0, - deliveryTag: void 0, - redelivered: void 0, - exchange: void 0, - routingKey: void 0 - }; + var val, + len, + offset = 0, + fields = { + consumerTag: void 0, + deliveryTag: void 0, + redelivered: void 0, + exchange: void 0, + routingKey: void 0, + }; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.consumerTag = val; val = ints.readUInt64BE(buffer, offset); @@ -443,33 +509,39 @@ function decodeBasicDeliver(buffer) { offset++; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.exchange = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.routingKey = val; return fields; } function encodeBasicDeliver(channel, fields) { - var offset = 0, val = null, bits = 0, varyingSize = 0; + var offset = 0, + val = null, + bits = 0, + varyingSize = 0; val = fields.consumerTag; if (void 0 === val) throw new Error("Missing value for mandatory field 'consumerTag'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); - var consumerTag_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); + var consumerTag_len = Buffer.byteLength(val, 'utf8'); varyingSize += consumerTag_len; val = fields.exchange; if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); - var exchange_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, 'utf8'); varyingSize += exchange_len; val = fields.routingKey; if (void 0 === val) throw new Error("Missing value for mandatory field 'routingKey'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); - var routingKey_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, 'utf8'); varyingSize += routingKey_len; var buffer = Buffer.alloc(24 + varyingSize); buffer[0] = 1; @@ -480,11 +552,11 @@ function encodeBasicDeliver(channel, fields) { void 0 === val && (val = void 0); buffer[offset] = consumerTag_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += consumerTag_len; val = fields.deliveryTag; if (void 0 === val) throw new Error("Missing value for mandatory field 'deliveryTag'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); ints.writeUInt64BE(buffer, val, offset); offset += 8; val = fields.redelivered; @@ -497,13 +569,13 @@ function encodeBasicDeliver(channel, fields) { void 0 === val && (val = void 0); buffer[offset] = exchange_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += exchange_len; val = fields.routingKey; void 0 === val && (val = void 0); buffer[offset] = routingKey_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += routingKey_len; buffer[offset] = 206; buffer.writeUInt32BE(offset - 7, 3); @@ -511,17 +583,20 @@ function encodeBasicDeliver(channel, fields) { } function decodeBasicGet(buffer) { - var val, len, offset = 0, fields = { - ticket: void 0, - queue: void 0, - noAck: void 0 - }; + var val, + len, + offset = 0, + fields = { + ticket: void 0, + queue: void 0, + noAck: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.queue = val; val = !!(1 & buffer[offset]); @@ -530,10 +605,15 @@ function decodeBasicGet(buffer) { } function encodeBasicGet(channel, fields) { - var offset = 0, val = null, bits = 0, varyingSize = 0; + var offset = 0, + val = null, + bits = 0, + varyingSize = 0; val = fields.queue; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); - var queue_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, 'utf8'); varyingSize += queue_len; var buffer = Buffer.alloc(16 + varyingSize); buffer[0] = 1; @@ -541,14 +621,15 @@ function encodeBasicGet(channel, fields) { buffer.writeUInt32BE(3932230, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.queue; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = queue_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += queue_len; val = fields.noAck; void 0 === val && (val = !1); @@ -561,13 +642,16 @@ function encodeBasicGet(channel, fields) { } function decodeBasicGetOk(buffer) { - var val, len, offset = 0, fields = { - deliveryTag: void 0, - redelivered: void 0, - exchange: void 0, - routingKey: void 0, - messageCount: void 0 - }; + var val, + len, + offset = 0, + fields = { + deliveryTag: void 0, + redelivered: void 0, + exchange: void 0, + routingKey: void 0, + messageCount: void 0, + }; val = ints.readUInt64BE(buffer, offset); offset += 8; fields.deliveryTag = val; @@ -576,12 +660,12 @@ function decodeBasicGetOk(buffer) { offset++; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.exchange = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.routingKey = val; val = buffer.readUInt32BE(offset); @@ -591,16 +675,21 @@ function decodeBasicGetOk(buffer) { } function encodeBasicGetOk(channel, fields) { - var offset = 0, val = null, bits = 0, varyingSize = 0; + var offset = 0, + val = null, + bits = 0, + varyingSize = 0; val = fields.exchange; if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); - var exchange_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, 'utf8'); varyingSize += exchange_len; val = fields.routingKey; if (void 0 === val) throw new Error("Missing value for mandatory field 'routingKey'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); - var routingKey_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, 'utf8'); varyingSize += routingKey_len; var buffer = Buffer.alloc(27 + varyingSize); buffer[0] = 1; @@ -609,7 +698,7 @@ function encodeBasicGetOk(channel, fields) { offset = 11; val = fields.deliveryTag; if (void 0 === val) throw new Error("Missing value for mandatory field 'deliveryTag'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); ints.writeUInt64BE(buffer, val, offset); offset += 8; val = fields.redelivered; @@ -622,17 +711,17 @@ function encodeBasicGetOk(channel, fields) { void 0 === val && (val = void 0); buffer[offset] = exchange_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += exchange_len; val = fields.routingKey; void 0 === val && (val = void 0); buffer[offset] = routingKey_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += routingKey_len; val = fields.messageCount; if (void 0 === val) throw new Error("Missing value for mandatory field 'messageCount'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt32BE(val, offset); offset += 4; buffer[offset] = 206; @@ -641,22 +730,29 @@ function encodeBasicGetOk(channel, fields) { } function decodeBasicGetEmpty(buffer) { - var val, len, offset = 0, fields = { - clusterId: void 0 - }; + var val, + len, + offset = 0, + fields = { + clusterId: void 0, + }; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.clusterId = val; return fields; } function encodeBasicGetEmpty(channel, fields) { - var offset = 0, val = null, varyingSize = 0; + var offset = 0, + val = null, + varyingSize = 0; val = fields.clusterId; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'clusterId' is the wrong type; must be a string (up to 255 chars)"); - var clusterId_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'clusterId' is the wrong type; must be a string (up to 255 chars)"); + var clusterId_len = Buffer.byteLength(val, 'utf8'); varyingSize += clusterId_len; var buffer = Buffer.alloc(13 + varyingSize); buffer[0] = 1; @@ -664,10 +760,10 @@ function encodeBasicGetEmpty(channel, fields) { buffer.writeUInt32BE(3932232, 7); offset = 11; val = fields.clusterId; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = clusterId_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += clusterId_len; buffer[offset] = 206; buffer.writeUInt32BE(offset - 7, 3); @@ -675,10 +771,12 @@ function encodeBasicGetEmpty(channel, fields) { } function decodeBasicAck(buffer) { - var val, offset = 0, fields = { - deliveryTag: void 0, - multiple: void 0 - }; + var val, + offset = 0, + fields = { + deliveryTag: void 0, + multiple: void 0, + }; val = ints.readUInt64BE(buffer, offset); offset += 8; fields.deliveryTag = val; @@ -688,13 +786,18 @@ function decodeBasicAck(buffer) { } function encodeBasicAck(channel, fields) { - var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(21); + var offset = 0, + val = null, + bits = 0, + buffer = Buffer.alloc(21); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(3932240, 7); offset = 11; val = fields.deliveryTag; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) + throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); ints.writeUInt64BE(buffer, val, offset); offset += 8; val = fields.multiple; @@ -708,10 +811,12 @@ function encodeBasicAck(channel, fields) { } function decodeBasicReject(buffer) { - var val, offset = 0, fields = { - deliveryTag: void 0, - requeue: void 0 - }; + var val, + offset = 0, + fields = { + deliveryTag: void 0, + requeue: void 0, + }; val = ints.readUInt64BE(buffer, offset); offset += 8; fields.deliveryTag = val; @@ -721,14 +826,17 @@ function decodeBasicReject(buffer) { } function encodeBasicReject(channel, fields) { - var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(21); + var offset = 0, + val = null, + bits = 0, + buffer = Buffer.alloc(21); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(3932250, 7); offset = 11; val = fields.deliveryTag; if (void 0 === val) throw new Error("Missing value for mandatory field 'deliveryTag'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); ints.writeUInt64BE(buffer, val, offset); offset += 8; val = fields.requeue; @@ -742,16 +850,20 @@ function encodeBasicReject(channel, fields) { } function decodeBasicRecoverAsync(buffer) { - var val, fields = { - requeue: void 0 - }; + var val, + fields = { + requeue: void 0, + }; val = !!(1 & buffer[0]); fields.requeue = val; return fields; } function encodeBasicRecoverAsync(channel, fields) { - var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(13); + var offset = 0, + val = null, + bits = 0, + buffer = Buffer.alloc(13); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(3932260, 7); @@ -767,16 +879,20 @@ function encodeBasicRecoverAsync(channel, fields) { } function decodeBasicRecover(buffer) { - var val, fields = { - requeue: void 0 - }; + var val, + fields = { + requeue: void 0, + }; val = !!(1 & buffer[0]); fields.requeue = val; return fields; } function encodeBasicRecover(channel, fields) { - var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(13); + var offset = 0, + val = null, + bits = 0, + buffer = Buffer.alloc(13); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(3932270, 7); @@ -796,7 +912,8 @@ function decodeBasicRecoverOk(buffer) { } function encodeBasicRecoverOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(3932271, 7); @@ -807,11 +924,13 @@ function encodeBasicRecoverOk(channel, fields) { } function decodeBasicNack(buffer) { - var val, offset = 0, fields = { - deliveryTag: void 0, - multiple: void 0, - requeue: void 0 - }; + var val, + offset = 0, + fields = { + deliveryTag: void 0, + multiple: void 0, + requeue: void 0, + }; val = ints.readUInt64BE(buffer, offset); offset += 8; fields.deliveryTag = val; @@ -823,13 +942,18 @@ function decodeBasicNack(buffer) { } function encodeBasicNack(channel, fields) { - var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(21); + var offset = 0, + val = null, + bits = 0, + buffer = Buffer.alloc(21); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(3932280, 7); offset = 11; val = fields.deliveryTag; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) + throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); ints.writeUInt64BE(buffer, val, offset); offset += 8; val = fields.multiple; @@ -846,13 +970,16 @@ function encodeBasicNack(channel, fields) { } function decodeConnectionStart(buffer) { - var val, len, offset = 0, fields = { - versionMajor: void 0, - versionMinor: void 0, - serverProperties: void 0, - mechanisms: void 0, - locales: void 0 - }; + var val, + len, + offset = 0, + fields = { + versionMajor: void 0, + versionMinor: void 0, + serverProperties: void 0, + mechanisms: void 0, + locales: void 0, + }; val = buffer[offset]; offset++; fields.versionMajor = val; @@ -878,19 +1005,25 @@ function decodeConnectionStart(buffer) { } function encodeConnectionStart(channel, fields) { - var len, offset = 0, val = null, varyingSize = 0, scratchOffset = 0; + var len, + offset = 0, + val = null, + varyingSize = 0, + scratchOffset = 0; val = fields.serverProperties; if (void 0 === val) throw new Error("Missing value for mandatory field 'serverProperties'"); - if ("object" != typeof val) throw new TypeError("Field 'serverProperties' is the wrong type; must be an object"); + if ('object' != typeof val) throw new TypeError("Field 'serverProperties' is the wrong type; must be an object"); len = encodeTable(SCRATCH, val, scratchOffset); var serverProperties_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); scratchOffset += len; varyingSize += serverProperties_encoded.length; val = fields.mechanisms; - if (void 0 === val) val = Buffer.from("PLAIN"); else if (!Buffer.isBuffer(val)) throw new TypeError("Field 'mechanisms' is the wrong type; must be a Buffer"); + if (void 0 === val) val = Buffer.from('PLAIN'); + else if (!Buffer.isBuffer(val)) throw new TypeError("Field 'mechanisms' is the wrong type; must be a Buffer"); varyingSize += val.length; val = fields.locales; - if (void 0 === val) val = Buffer.from("en_US"); else if (!Buffer.isBuffer(val)) throw new TypeError("Field 'locales' is the wrong type; must be a Buffer"); + if (void 0 === val) val = Buffer.from('en_US'); + else if (!Buffer.isBuffer(val)) throw new TypeError("Field 'locales' is the wrong type; must be a Buffer"); varyingSize += val.length; var buffer = Buffer.alloc(22 + varyingSize); buffer[0] = 1; @@ -898,23 +1031,27 @@ function encodeConnectionStart(channel, fields) { buffer.writeUInt32BE(655370, 7); offset = 11; val = fields.versionMajor; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'versionMajor' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) + throw new TypeError("Field 'versionMajor' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt8(val, offset); offset++; val = fields.versionMinor; - if (void 0 === val) val = 9; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'versionMinor' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 9; + else if ('number' != typeof val || isNaN(val)) + throw new TypeError("Field 'versionMinor' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt8(val, offset); offset++; offset += serverProperties_encoded.copy(buffer, offset); val = fields.mechanisms; - void 0 === val && (val = Buffer.from("PLAIN")); + void 0 === val && (val = Buffer.from('PLAIN')); len = val.length; buffer.writeUInt32BE(len, offset); offset += 4; val.copy(buffer, offset); offset += len; val = fields.locales; - void 0 === val && (val = Buffer.from("en_US")); + void 0 === val && (val = Buffer.from('en_US')); len = val.length; buffer.writeUInt32BE(len, offset); offset += 4; @@ -926,12 +1063,15 @@ function encodeConnectionStart(channel, fields) { } function decodeConnectionStartOk(buffer) { - var val, len, offset = 0, fields = { - clientProperties: void 0, - mechanism: void 0, - response: void 0, - locale: void 0 - }; + var val, + len, + offset = 0, + fields = { + clientProperties: void 0, + mechanism: void 0, + response: void 0, + locale: void 0, + }; len = buffer.readUInt32BE(offset); offset += 4; val = decodeFields(buffer.subarray(offset, offset + len)); @@ -939,7 +1079,7 @@ function decodeConnectionStartOk(buffer) { fields.clientProperties = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.mechanism = val; len = buffer.readUInt32BE(offset); @@ -949,32 +1089,40 @@ function decodeConnectionStartOk(buffer) { fields.response = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.locale = val; return fields; } function encodeConnectionStartOk(channel, fields) { - var len, offset = 0, val = null, varyingSize = 0, scratchOffset = 0; + var len, + offset = 0, + val = null, + varyingSize = 0, + scratchOffset = 0; val = fields.clientProperties; if (void 0 === val) throw new Error("Missing value for mandatory field 'clientProperties'"); - if ("object" != typeof val) throw new TypeError("Field 'clientProperties' is the wrong type; must be an object"); + if ('object' != typeof val) throw new TypeError("Field 'clientProperties' is the wrong type; must be an object"); len = encodeTable(SCRATCH, val, scratchOffset); var clientProperties_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); scratchOffset += len; varyingSize += clientProperties_encoded.length; val = fields.mechanism; - if (void 0 === val) val = "PLAIN"; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'mechanism' is the wrong type; must be a string (up to 255 chars)"); - var mechanism_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = 'PLAIN'; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'mechanism' is the wrong type; must be a string (up to 255 chars)"); + var mechanism_len = Buffer.byteLength(val, 'utf8'); varyingSize += mechanism_len; val = fields.response; if (void 0 === val) throw new Error("Missing value for mandatory field 'response'"); if (!Buffer.isBuffer(val)) throw new TypeError("Field 'response' is the wrong type; must be a Buffer"); varyingSize += val.length; val = fields.locale; - if (void 0 === val) val = "en_US"; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'locale' is the wrong type; must be a string (up to 255 chars)"); - var locale_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = 'en_US'; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'locale' is the wrong type; must be a string (up to 255 chars)"); + var locale_len = Buffer.byteLength(val, 'utf8'); varyingSize += locale_len; var buffer = Buffer.alloc(18 + varyingSize); buffer[0] = 1; @@ -983,10 +1131,10 @@ function encodeConnectionStartOk(channel, fields) { offset = 11; offset += clientProperties_encoded.copy(buffer, offset); val = fields.mechanism; - void 0 === val && (val = "PLAIN"); + void 0 === val && (val = 'PLAIN'); buffer[offset] = mechanism_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += mechanism_len; val = fields.response; void 0 === val && (val = Buffer.from(void 0)); @@ -996,10 +1144,10 @@ function encodeConnectionStartOk(channel, fields) { val.copy(buffer, offset); offset += len; val = fields.locale; - void 0 === val && (val = "en_US"); + void 0 === val && (val = 'en_US'); buffer[offset] = locale_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += locale_len; buffer[offset] = 206; buffer.writeUInt32BE(offset - 7, 3); @@ -1007,9 +1155,12 @@ function encodeConnectionStartOk(channel, fields) { } function decodeConnectionSecure(buffer) { - var val, len, offset = 0, fields = { - challenge: void 0 - }; + var val, + len, + offset = 0, + fields = { + challenge: void 0, + }; len = buffer.readUInt32BE(offset); offset += 4; val = buffer.subarray(offset, offset + len); @@ -1019,7 +1170,10 @@ function decodeConnectionSecure(buffer) { } function encodeConnectionSecure(channel, fields) { - var len, offset = 0, val = null, varyingSize = 0; + var len, + offset = 0, + val = null, + varyingSize = 0; val = fields.challenge; if (void 0 === val) throw new Error("Missing value for mandatory field 'challenge'"); if (!Buffer.isBuffer(val)) throw new TypeError("Field 'challenge' is the wrong type; must be a Buffer"); @@ -1042,9 +1196,12 @@ function encodeConnectionSecure(channel, fields) { } function decodeConnectionSecureOk(buffer) { - var val, len, offset = 0, fields = { - response: void 0 - }; + var val, + len, + offset = 0, + fields = { + response: void 0, + }; len = buffer.readUInt32BE(offset); offset += 4; val = buffer.subarray(offset, offset + len); @@ -1054,7 +1211,10 @@ function decodeConnectionSecureOk(buffer) { } function encodeConnectionSecureOk(channel, fields) { - var len, offset = 0, val = null, varyingSize = 0; + var len, + offset = 0, + val = null, + varyingSize = 0; val = fields.response; if (void 0 === val) throw new Error("Missing value for mandatory field 'response'"); if (!Buffer.isBuffer(val)) throw new TypeError("Field 'response' is the wrong type; must be a Buffer"); @@ -1077,11 +1237,13 @@ function encodeConnectionSecureOk(channel, fields) { } function decodeConnectionTune(buffer) { - var val, offset = 0, fields = { - channelMax: void 0, - frameMax: void 0, - heartbeat: void 0 - }; + var val, + offset = 0, + fields = { + channelMax: void 0, + frameMax: void 0, + heartbeat: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.channelMax = val; @@ -1095,21 +1257,27 @@ function decodeConnectionTune(buffer) { } function encodeConnectionTune(channel, fields) { - var offset = 0, val = null, buffer = Buffer.alloc(20); + var offset = 0, + val = null, + buffer = Buffer.alloc(20); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(655390, 7); offset = 11; val = fields.channelMax; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'channelMax' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) + throw new TypeError("Field 'channelMax' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.frameMax; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'frameMax' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'frameMax' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt32BE(val, offset); offset += 4; val = fields.heartbeat; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'heartbeat' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'heartbeat' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; buffer[offset] = 206; @@ -1118,11 +1286,13 @@ function encodeConnectionTune(channel, fields) { } function decodeConnectionTuneOk(buffer) { - var val, offset = 0, fields = { - channelMax: void 0, - frameMax: void 0, - heartbeat: void 0 - }; + var val, + offset = 0, + fields = { + channelMax: void 0, + frameMax: void 0, + heartbeat: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.channelMax = val; @@ -1136,21 +1306,27 @@ function decodeConnectionTuneOk(buffer) { } function encodeConnectionTuneOk(channel, fields) { - var offset = 0, val = null, buffer = Buffer.alloc(20); + var offset = 0, + val = null, + buffer = Buffer.alloc(20); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(655391, 7); offset = 11; val = fields.channelMax; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'channelMax' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) + throw new TypeError("Field 'channelMax' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.frameMax; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'frameMax' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'frameMax' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt32BE(val, offset); offset += 4; val = fields.heartbeat; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'heartbeat' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'heartbeat' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; buffer[offset] = 206; @@ -1159,19 +1335,22 @@ function encodeConnectionTuneOk(channel, fields) { } function decodeConnectionOpen(buffer) { - var val, len, offset = 0, fields = { - virtualHost: void 0, - capabilities: void 0, - insist: void 0 - }; + var val, + len, + offset = 0, + fields = { + virtualHost: void 0, + capabilities: void 0, + insist: void 0, + }; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.virtualHost = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.capabilities = val; val = !!(1 & buffer[offset]); @@ -1180,14 +1359,21 @@ function decodeConnectionOpen(buffer) { } function encodeConnectionOpen(channel, fields) { - var offset = 0, val = null, bits = 0, varyingSize = 0; + var offset = 0, + val = null, + bits = 0, + varyingSize = 0; val = fields.virtualHost; - if (void 0 === val) val = "/"; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'virtualHost' is the wrong type; must be a string (up to 255 chars)"); - var virtualHost_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = '/'; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'virtualHost' is the wrong type; must be a string (up to 255 chars)"); + var virtualHost_len = Buffer.byteLength(val, 'utf8'); varyingSize += virtualHost_len; val = fields.capabilities; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'capabilities' is the wrong type; must be a string (up to 255 chars)"); - var capabilities_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'capabilities' is the wrong type; must be a string (up to 255 chars)"); + var capabilities_len = Buffer.byteLength(val, 'utf8'); varyingSize += capabilities_len; var buffer = Buffer.alloc(15 + varyingSize); buffer[0] = 1; @@ -1195,16 +1381,16 @@ function encodeConnectionOpen(channel, fields) { buffer.writeUInt32BE(655400, 7); offset = 11; val = fields.virtualHost; - void 0 === val && (val = "/"); + void 0 === val && (val = '/'); buffer[offset] = virtualHost_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += virtualHost_len; val = fields.capabilities; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = capabilities_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += capabilities_len; val = fields.insist; void 0 === val && (val = !1); @@ -1217,22 +1403,29 @@ function encodeConnectionOpen(channel, fields) { } function decodeConnectionOpenOk(buffer) { - var val, len, offset = 0, fields = { - knownHosts: void 0 - }; + var val, + len, + offset = 0, + fields = { + knownHosts: void 0, + }; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.knownHosts = val; return fields; } function encodeConnectionOpenOk(channel, fields) { - var offset = 0, val = null, varyingSize = 0; + var offset = 0, + val = null, + varyingSize = 0; val = fields.knownHosts; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'knownHosts' is the wrong type; must be a string (up to 255 chars)"); - var knownHosts_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'knownHosts' is the wrong type; must be a string (up to 255 chars)"); + var knownHosts_len = Buffer.byteLength(val, 'utf8'); varyingSize += knownHosts_len; var buffer = Buffer.alloc(13 + varyingSize); buffer[0] = 1; @@ -1240,10 +1433,10 @@ function encodeConnectionOpenOk(channel, fields) { buffer.writeUInt32BE(655401, 7); offset = 11; val = fields.knownHosts; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = knownHosts_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += knownHosts_len; buffer[offset] = 206; buffer.writeUInt32BE(offset - 7, 3); @@ -1251,18 +1444,21 @@ function encodeConnectionOpenOk(channel, fields) { } function decodeConnectionClose(buffer) { - var val, len, offset = 0, fields = { - replyCode: void 0, - replyText: void 0, - classId: void 0, - methodId: void 0 - }; + var val, + len, + offset = 0, + fields = { + replyCode: void 0, + replyText: void 0, + classId: void 0, + methodId: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.replyCode = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.replyText = val; val = buffer.readUInt16BE(offset); @@ -1275,10 +1471,14 @@ function decodeConnectionClose(buffer) { } function encodeConnectionClose(channel, fields) { - var offset = 0, val = null, varyingSize = 0; + var offset = 0, + val = null, + varyingSize = 0; val = fields.replyText; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'replyText' is the wrong type; must be a string (up to 255 chars)"); - var replyText_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'replyText' is the wrong type; must be a string (up to 255 chars)"); + var replyText_len = Buffer.byteLength(val, 'utf8'); varyingSize += replyText_len; var buffer = Buffer.alloc(19 + varyingSize); buffer[0] = 1; @@ -1287,23 +1487,23 @@ function encodeConnectionClose(channel, fields) { offset = 11; val = fields.replyCode; if (void 0 === val) throw new Error("Missing value for mandatory field 'replyCode'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'replyCode' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'replyCode' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.replyText; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = replyText_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += replyText_len; val = fields.classId; if (void 0 === val) throw new Error("Missing value for mandatory field 'classId'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'classId' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'classId' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.methodId; if (void 0 === val) throw new Error("Missing value for mandatory field 'methodId'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'methodId' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'methodId' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; buffer[offset] = 206; @@ -1316,7 +1516,8 @@ function decodeConnectionCloseOk(buffer) { } function encodeConnectionCloseOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(655411, 7); @@ -1327,22 +1528,29 @@ function encodeConnectionCloseOk(channel, fields) { } function decodeConnectionBlocked(buffer) { - var val, len, offset = 0, fields = { - reason: void 0 - }; + var val, + len, + offset = 0, + fields = { + reason: void 0, + }; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.reason = val; return fields; } function encodeConnectionBlocked(channel, fields) { - var offset = 0, val = null, varyingSize = 0; + var offset = 0, + val = null, + varyingSize = 0; val = fields.reason; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'reason' is the wrong type; must be a string (up to 255 chars)"); - var reason_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'reason' is the wrong type; must be a string (up to 255 chars)"); + var reason_len = Buffer.byteLength(val, 'utf8'); varyingSize += reason_len; var buffer = Buffer.alloc(13 + varyingSize); buffer[0] = 1; @@ -1350,10 +1558,10 @@ function encodeConnectionBlocked(channel, fields) { buffer.writeUInt32BE(655420, 7); offset = 11; val = fields.reason; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = reason_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += reason_len; buffer[offset] = 206; buffer.writeUInt32BE(offset - 7, 3); @@ -1365,7 +1573,8 @@ function decodeConnectionUnblocked(buffer) { } function encodeConnectionUnblocked(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(655421, 7); @@ -1376,10 +1585,13 @@ function encodeConnectionUnblocked(channel, fields) { } function decodeConnectionUpdateSecret(buffer) { - var val, len, offset = 0, fields = { - newSecret: void 0, - reason: void 0 - }; + var val, + len, + offset = 0, + fields = { + newSecret: void 0, + reason: void 0, + }; len = buffer.readUInt32BE(offset); offset += 4; val = buffer.subarray(offset, offset + len); @@ -1387,22 +1599,26 @@ function decodeConnectionUpdateSecret(buffer) { fields.newSecret = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.reason = val; return fields; } function encodeConnectionUpdateSecret(channel, fields) { - var len, offset = 0, val = null, varyingSize = 0; + var len, + offset = 0, + val = null, + varyingSize = 0; val = fields.newSecret; if (void 0 === val) throw new Error("Missing value for mandatory field 'newSecret'"); if (!Buffer.isBuffer(val)) throw new TypeError("Field 'newSecret' is the wrong type; must be a Buffer"); varyingSize += val.length; val = fields.reason; if (void 0 === val) throw new Error("Missing value for mandatory field 'reason'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'reason' is the wrong type; must be a string (up to 255 chars)"); - var reason_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'reason' is the wrong type; must be a string (up to 255 chars)"); + var reason_len = Buffer.byteLength(val, 'utf8'); varyingSize += reason_len; var buffer = Buffer.alloc(17 + varyingSize); buffer[0] = 1; @@ -1420,7 +1636,7 @@ function encodeConnectionUpdateSecret(channel, fields) { void 0 === val && (val = void 0); buffer[offset] = reason_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += reason_len; buffer[offset] = 206; buffer.writeUInt32BE(offset - 7, 3); @@ -1432,7 +1648,8 @@ function decodeConnectionUpdateSecretOk(buffer) { } function encodeConnectionUpdateSecretOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(655431, 7); @@ -1443,22 +1660,29 @@ function encodeConnectionUpdateSecretOk(channel, fields) { } function decodeChannelOpen(buffer) { - var val, len, offset = 0, fields = { - outOfBand: void 0 - }; + var val, + len, + offset = 0, + fields = { + outOfBand: void 0, + }; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.outOfBand = val; return fields; } function encodeChannelOpen(channel, fields) { - var offset = 0, val = null, varyingSize = 0; + var offset = 0, + val = null, + varyingSize = 0; val = fields.outOfBand; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'outOfBand' is the wrong type; must be a string (up to 255 chars)"); - var outOfBand_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'outOfBand' is the wrong type; must be a string (up to 255 chars)"); + var outOfBand_len = Buffer.byteLength(val, 'utf8'); varyingSize += outOfBand_len; var buffer = Buffer.alloc(13 + varyingSize); buffer[0] = 1; @@ -1466,10 +1690,10 @@ function encodeChannelOpen(channel, fields) { buffer.writeUInt32BE(1310730, 7); offset = 11; val = fields.outOfBand; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = outOfBand_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += outOfBand_len; buffer[offset] = 206; buffer.writeUInt32BE(offset - 7, 3); @@ -1477,9 +1701,12 @@ function encodeChannelOpen(channel, fields) { } function decodeChannelOpenOk(buffer) { - var val, len, offset = 0, fields = { - channelId: void 0 - }; + var val, + len, + offset = 0, + fields = { + channelId: void 0, + }; len = buffer.readUInt32BE(offset); offset += 4; val = buffer.subarray(offset, offset + len); @@ -1489,9 +1716,13 @@ function decodeChannelOpenOk(buffer) { } function encodeChannelOpenOk(channel, fields) { - var len, offset = 0, val = null, varyingSize = 0; + var len, + offset = 0, + val = null, + varyingSize = 0; val = fields.channelId; - if (void 0 === val) val = Buffer.from(""); else if (!Buffer.isBuffer(val)) throw new TypeError("Field 'channelId' is the wrong type; must be a Buffer"); + if (void 0 === val) val = Buffer.from(''); + else if (!Buffer.isBuffer(val)) throw new TypeError("Field 'channelId' is the wrong type; must be a Buffer"); varyingSize += val.length; var buffer = Buffer.alloc(16 + varyingSize); buffer[0] = 1; @@ -1499,7 +1730,7 @@ function encodeChannelOpenOk(channel, fields) { buffer.writeUInt32BE(1310731, 7); offset = 11; val = fields.channelId; - void 0 === val && (val = Buffer.from("")); + void 0 === val && (val = Buffer.from('')); len = val.length; buffer.writeUInt32BE(len, offset); offset += 4; @@ -1511,16 +1742,20 @@ function encodeChannelOpenOk(channel, fields) { } function decodeChannelFlow(buffer) { - var val, fields = { - active: void 0 - }; + var val, + fields = { + active: void 0, + }; val = !!(1 & buffer[0]); fields.active = val; return fields; } function encodeChannelFlow(channel, fields) { - var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(13); + var offset = 0, + val = null, + bits = 0, + buffer = Buffer.alloc(13); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(1310740, 7); @@ -1536,16 +1771,20 @@ function encodeChannelFlow(channel, fields) { } function decodeChannelFlowOk(buffer) { - var val, fields = { - active: void 0 - }; + var val, + fields = { + active: void 0, + }; val = !!(1 & buffer[0]); fields.active = val; return fields; } function encodeChannelFlowOk(channel, fields) { - var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(13); + var offset = 0, + val = null, + bits = 0, + buffer = Buffer.alloc(13); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(1310741, 7); @@ -1561,18 +1800,21 @@ function encodeChannelFlowOk(channel, fields) { } function decodeChannelClose(buffer) { - var val, len, offset = 0, fields = { - replyCode: void 0, - replyText: void 0, - classId: void 0, - methodId: void 0 - }; + var val, + len, + offset = 0, + fields = { + replyCode: void 0, + replyText: void 0, + classId: void 0, + methodId: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.replyCode = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.replyText = val; val = buffer.readUInt16BE(offset); @@ -1585,10 +1827,14 @@ function decodeChannelClose(buffer) { } function encodeChannelClose(channel, fields) { - var offset = 0, val = null, varyingSize = 0; + var offset = 0, + val = null, + varyingSize = 0; val = fields.replyText; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'replyText' is the wrong type; must be a string (up to 255 chars)"); - var replyText_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'replyText' is the wrong type; must be a string (up to 255 chars)"); + var replyText_len = Buffer.byteLength(val, 'utf8'); varyingSize += replyText_len; var buffer = Buffer.alloc(19 + varyingSize); buffer[0] = 1; @@ -1597,23 +1843,23 @@ function encodeChannelClose(channel, fields) { offset = 11; val = fields.replyCode; if (void 0 === val) throw new Error("Missing value for mandatory field 'replyCode'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'replyCode' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'replyCode' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.replyText; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = replyText_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += replyText_len; val = fields.classId; if (void 0 === val) throw new Error("Missing value for mandatory field 'classId'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'classId' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'classId' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.methodId; if (void 0 === val) throw new Error("Missing value for mandatory field 'methodId'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'methodId' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'methodId' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; buffer[offset] = 206; @@ -1626,7 +1872,8 @@ function decodeChannelCloseOk(buffer) { } function encodeChannelCloseOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(1310761, 7); @@ -1637,17 +1884,20 @@ function encodeChannelCloseOk(channel, fields) { } function decodeAccessRequest(buffer) { - var val, len, offset = 0, fields = { - realm: void 0, - exclusive: void 0, - passive: void 0, - active: void 0, - write: void 0, - read: void 0 - }; + var val, + len, + offset = 0, + fields = { + realm: void 0, + exclusive: void 0, + passive: void 0, + active: void 0, + write: void 0, + read: void 0, + }; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.realm = val; val = !!(1 & buffer[offset]); @@ -1664,10 +1914,15 @@ function decodeAccessRequest(buffer) { } function encodeAccessRequest(channel, fields) { - var offset = 0, val = null, bits = 0, varyingSize = 0; + var offset = 0, + val = null, + bits = 0, + varyingSize = 0; val = fields.realm; - if (void 0 === val) val = "/data"; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'realm' is the wrong type; must be a string (up to 255 chars)"); - var realm_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = '/data'; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'realm' is the wrong type; must be a string (up to 255 chars)"); + var realm_len = Buffer.byteLength(val, 'utf8'); varyingSize += realm_len; var buffer = Buffer.alloc(14 + varyingSize); buffer[0] = 1; @@ -1675,10 +1930,10 @@ function encodeAccessRequest(channel, fields) { buffer.writeUInt32BE(1966090, 7); offset = 11; val = fields.realm; - void 0 === val && (val = "/data"); + void 0 === val && (val = '/data'); buffer[offset] = realm_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += realm_len; val = fields.exclusive; void 0 === val && (val = !1); @@ -1703,9 +1958,11 @@ function encodeAccessRequest(channel, fields) { } function decodeAccessRequestOk(buffer) { - var val, offset = 0, fields = { - ticket: void 0 - }; + var val, + offset = 0, + fields = { + ticket: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; @@ -1713,13 +1970,16 @@ function decodeAccessRequestOk(buffer) { } function encodeAccessRequestOk(channel, fields) { - var offset = 0, val = null, buffer = Buffer.alloc(14); + var offset = 0, + val = null, + buffer = Buffer.alloc(14); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(1966091, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 1; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 1; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; buffer[offset] = 206; @@ -1728,28 +1988,31 @@ function encodeAccessRequestOk(channel, fields) { } function decodeExchangeDeclare(buffer) { - var val, len, offset = 0, fields = { - ticket: void 0, - exchange: void 0, - type: void 0, - passive: void 0, - durable: void 0, - autoDelete: void 0, - internal: void 0, - nowait: void 0, - arguments: void 0 - }; + var val, + len, + offset = 0, + fields = { + ticket: void 0, + exchange: void 0, + type: void 0, + passive: void 0, + durable: void 0, + autoDelete: void 0, + internal: void 0, + nowait: void 0, + arguments: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.exchange = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.type = val; val = !!(1 & buffer[offset]); @@ -1772,18 +2035,27 @@ function decodeExchangeDeclare(buffer) { } function encodeExchangeDeclare(channel, fields) { - var len, offset = 0, val = null, bits = 0, varyingSize = 0, scratchOffset = 0; + var len, + offset = 0, + val = null, + bits = 0, + varyingSize = 0, + scratchOffset = 0; val = fields.exchange; if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); - var exchange_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, 'utf8'); varyingSize += exchange_len; val = fields.type; - if (void 0 === val) val = "direct"; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'type' is the wrong type; must be a string (up to 255 chars)"); - var type_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = 'direct'; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'type' is the wrong type; must be a string (up to 255 chars)"); + var type_len = Buffer.byteLength(val, 'utf8'); varyingSize += type_len; val = fields.arguments; - if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + if (void 0 === val) val = {}; + else if ('object' != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); len = encodeTable(SCRATCH, val, scratchOffset); var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); scratchOffset += len; @@ -1794,20 +2066,21 @@ function encodeExchangeDeclare(channel, fields) { buffer.writeUInt32BE(2621450, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.exchange; void 0 === val && (val = void 0); buffer[offset] = exchange_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += exchange_len; val = fields.type; - void 0 === val && (val = "direct"); + void 0 === val && (val = 'direct'); buffer[offset] = type_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += type_len; val = fields.passive; void 0 === val && (val = !1); @@ -1838,7 +2111,8 @@ function decodeExchangeDeclareOk(buffer) { } function encodeExchangeDeclareOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(2621451, 7); @@ -1849,18 +2123,21 @@ function encodeExchangeDeclareOk(channel, fields) { } function decodeExchangeDelete(buffer) { - var val, len, offset = 0, fields = { - ticket: void 0, - exchange: void 0, - ifUnused: void 0, - nowait: void 0 - }; + var val, + len, + offset = 0, + fields = { + ticket: void 0, + exchange: void 0, + ifUnused: void 0, + nowait: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.exchange = val; val = !!(1 & buffer[offset]); @@ -1871,11 +2148,15 @@ function decodeExchangeDelete(buffer) { } function encodeExchangeDelete(channel, fields) { - var offset = 0, val = null, bits = 0, varyingSize = 0; + var offset = 0, + val = null, + bits = 0, + varyingSize = 0; val = fields.exchange; if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); - var exchange_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, 'utf8'); varyingSize += exchange_len; var buffer = Buffer.alloc(16 + varyingSize); buffer[0] = 1; @@ -1883,14 +2164,15 @@ function encodeExchangeDelete(channel, fields) { buffer.writeUInt32BE(2621460, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.exchange; void 0 === val && (val = void 0); buffer[offset] = exchange_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += exchange_len; val = fields.ifUnused; void 0 === val && (val = !1); @@ -1910,7 +2192,8 @@ function decodeExchangeDeleteOk(buffer) { } function encodeExchangeDeleteOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(2621461, 7); @@ -1921,30 +2204,33 @@ function encodeExchangeDeleteOk(channel, fields) { } function decodeExchangeBind(buffer) { - var val, len, offset = 0, fields = { - ticket: void 0, - destination: void 0, - source: void 0, - routingKey: void 0, - nowait: void 0, - arguments: void 0 - }; + var val, + len, + offset = 0, + fields = { + ticket: void 0, + destination: void 0, + source: void 0, + routingKey: void 0, + nowait: void 0, + arguments: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.destination = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.source = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.routingKey = val; val = !!(1 & buffer[offset]); @@ -1959,23 +2245,33 @@ function decodeExchangeBind(buffer) { } function encodeExchangeBind(channel, fields) { - var len, offset = 0, val = null, bits = 0, varyingSize = 0, scratchOffset = 0; + var len, + offset = 0, + val = null, + bits = 0, + varyingSize = 0, + scratchOffset = 0; val = fields.destination; if (void 0 === val) throw new Error("Missing value for mandatory field 'destination'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'destination' is the wrong type; must be a string (up to 255 chars)"); - var destination_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'destination' is the wrong type; must be a string (up to 255 chars)"); + var destination_len = Buffer.byteLength(val, 'utf8'); varyingSize += destination_len; val = fields.source; if (void 0 === val) throw new Error("Missing value for mandatory field 'source'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'source' is the wrong type; must be a string (up to 255 chars)"); - var source_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'source' is the wrong type; must be a string (up to 255 chars)"); + var source_len = Buffer.byteLength(val, 'utf8'); varyingSize += source_len; val = fields.routingKey; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); - var routingKey_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, 'utf8'); varyingSize += routingKey_len; val = fields.arguments; - if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + if (void 0 === val) val = {}; + else if ('object' != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); len = encodeTable(SCRATCH, val, scratchOffset); var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); scratchOffset += len; @@ -1986,26 +2282,27 @@ function encodeExchangeBind(channel, fields) { buffer.writeUInt32BE(2621470, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.destination; void 0 === val && (val = void 0); buffer[offset] = destination_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += destination_len; val = fields.source; void 0 === val && (val = void 0); buffer[offset] = source_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += source_len; val = fields.routingKey; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = routingKey_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += routingKey_len; val = fields.nowait; void 0 === val && (val = !1); @@ -2024,7 +2321,8 @@ function decodeExchangeBindOk(buffer) { } function encodeExchangeBindOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(2621471, 7); @@ -2035,30 +2333,33 @@ function encodeExchangeBindOk(channel, fields) { } function decodeExchangeUnbind(buffer) { - var val, len, offset = 0, fields = { - ticket: void 0, - destination: void 0, - source: void 0, - routingKey: void 0, - nowait: void 0, - arguments: void 0 - }; + var val, + len, + offset = 0, + fields = { + ticket: void 0, + destination: void 0, + source: void 0, + routingKey: void 0, + nowait: void 0, + arguments: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.destination = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.source = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.routingKey = val; val = !!(1 & buffer[offset]); @@ -2073,23 +2374,33 @@ function decodeExchangeUnbind(buffer) { } function encodeExchangeUnbind(channel, fields) { - var len, offset = 0, val = null, bits = 0, varyingSize = 0, scratchOffset = 0; + var len, + offset = 0, + val = null, + bits = 0, + varyingSize = 0, + scratchOffset = 0; val = fields.destination; if (void 0 === val) throw new Error("Missing value for mandatory field 'destination'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'destination' is the wrong type; must be a string (up to 255 chars)"); - var destination_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'destination' is the wrong type; must be a string (up to 255 chars)"); + var destination_len = Buffer.byteLength(val, 'utf8'); varyingSize += destination_len; val = fields.source; if (void 0 === val) throw new Error("Missing value for mandatory field 'source'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'source' is the wrong type; must be a string (up to 255 chars)"); - var source_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'source' is the wrong type; must be a string (up to 255 chars)"); + var source_len = Buffer.byteLength(val, 'utf8'); varyingSize += source_len; val = fields.routingKey; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); - var routingKey_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, 'utf8'); varyingSize += routingKey_len; val = fields.arguments; - if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + if (void 0 === val) val = {}; + else if ('object' != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); len = encodeTable(SCRATCH, val, scratchOffset); var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); scratchOffset += len; @@ -2100,26 +2411,27 @@ function encodeExchangeUnbind(channel, fields) { buffer.writeUInt32BE(2621480, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.destination; void 0 === val && (val = void 0); buffer[offset] = destination_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += destination_len; val = fields.source; void 0 === val && (val = void 0); buffer[offset] = source_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += source_len; val = fields.routingKey; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = routingKey_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += routingKey_len; val = fields.nowait; void 0 === val && (val = !1); @@ -2138,7 +2450,8 @@ function decodeExchangeUnbindOk(buffer) { } function encodeExchangeUnbindOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(2621491, 7); @@ -2149,22 +2462,25 @@ function encodeExchangeUnbindOk(channel, fields) { } function decodeQueueDeclare(buffer) { - var val, len, offset = 0, fields = { - ticket: void 0, - queue: void 0, - passive: void 0, - durable: void 0, - exclusive: void 0, - autoDelete: void 0, - nowait: void 0, - arguments: void 0 - }; + var val, + len, + offset = 0, + fields = { + ticket: void 0, + queue: void 0, + passive: void 0, + durable: void 0, + exclusive: void 0, + autoDelete: void 0, + nowait: void 0, + arguments: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.queue = val; val = !!(1 & buffer[offset]); @@ -2187,13 +2503,21 @@ function decodeQueueDeclare(buffer) { } function encodeQueueDeclare(channel, fields) { - var len, offset = 0, val = null, bits = 0, varyingSize = 0, scratchOffset = 0; + var len, + offset = 0, + val = null, + bits = 0, + varyingSize = 0, + scratchOffset = 0; val = fields.queue; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); - var queue_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, 'utf8'); varyingSize += queue_len; val = fields.arguments; - if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + if (void 0 === val) val = {}; + else if ('object' != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); len = encodeTable(SCRATCH, val, scratchOffset); var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); scratchOffset += len; @@ -2204,14 +2528,15 @@ function encodeQueueDeclare(channel, fields) { buffer.writeUInt32BE(3276810, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.queue; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = queue_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += queue_len; val = fields.passive; void 0 === val && (val = !1); @@ -2238,14 +2563,17 @@ function encodeQueueDeclare(channel, fields) { } function decodeQueueDeclareOk(buffer) { - var val, len, offset = 0, fields = { - queue: void 0, - messageCount: void 0, - consumerCount: void 0 - }; + var val, + len, + offset = 0, + fields = { + queue: void 0, + messageCount: void 0, + consumerCount: void 0, + }; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.queue = val; val = buffer.readUInt32BE(offset); @@ -2258,11 +2586,14 @@ function decodeQueueDeclareOk(buffer) { } function encodeQueueDeclareOk(channel, fields) { - var offset = 0, val = null, varyingSize = 0; + var offset = 0, + val = null, + varyingSize = 0; val = fields.queue; if (void 0 === val) throw new Error("Missing value for mandatory field 'queue'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); - var queue_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, 'utf8'); varyingSize += queue_len; var buffer = Buffer.alloc(21 + varyingSize); buffer[0] = 1; @@ -2273,16 +2604,16 @@ function encodeQueueDeclareOk(channel, fields) { void 0 === val && (val = void 0); buffer[offset] = queue_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += queue_len; val = fields.messageCount; if (void 0 === val) throw new Error("Missing value for mandatory field 'messageCount'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt32BE(val, offset); offset += 4; val = fields.consumerCount; if (void 0 === val) throw new Error("Missing value for mandatory field 'consumerCount'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'consumerCount' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'consumerCount' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt32BE(val, offset); offset += 4; buffer[offset] = 206; @@ -2291,30 +2622,33 @@ function encodeQueueDeclareOk(channel, fields) { } function decodeQueueBind(buffer) { - var val, len, offset = 0, fields = { - ticket: void 0, - queue: void 0, - exchange: void 0, - routingKey: void 0, - nowait: void 0, - arguments: void 0 - }; + var val, + len, + offset = 0, + fields = { + ticket: void 0, + queue: void 0, + exchange: void 0, + routingKey: void 0, + nowait: void 0, + arguments: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.queue = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.exchange = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.routingKey = val; val = !!(1 & buffer[offset]); @@ -2329,22 +2663,33 @@ function decodeQueueBind(buffer) { } function encodeQueueBind(channel, fields) { - var len, offset = 0, val = null, bits = 0, varyingSize = 0, scratchOffset = 0; + var len, + offset = 0, + val = null, + bits = 0, + varyingSize = 0, + scratchOffset = 0; val = fields.queue; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); - var queue_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, 'utf8'); varyingSize += queue_len; val = fields.exchange; if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); - var exchange_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, 'utf8'); varyingSize += exchange_len; val = fields.routingKey; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); - var routingKey_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, 'utf8'); varyingSize += routingKey_len; val = fields.arguments; - if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + if (void 0 === val) val = {}; + else if ('object' != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); len = encodeTable(SCRATCH, val, scratchOffset); var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); scratchOffset += len; @@ -2355,26 +2700,27 @@ function encodeQueueBind(channel, fields) { buffer.writeUInt32BE(3276820, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.queue; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = queue_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += queue_len; val = fields.exchange; void 0 === val && (val = void 0); buffer[offset] = exchange_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += exchange_len; val = fields.routingKey; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = routingKey_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += routingKey_len; val = fields.nowait; void 0 === val && (val = !1); @@ -2393,7 +2739,8 @@ function decodeQueueBindOk(buffer) { } function encodeQueueBindOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(3276821, 7); @@ -2404,17 +2751,20 @@ function encodeQueueBindOk(channel, fields) { } function decodeQueuePurge(buffer) { - var val, len, offset = 0, fields = { - ticket: void 0, - queue: void 0, - nowait: void 0 - }; + var val, + len, + offset = 0, + fields = { + ticket: void 0, + queue: void 0, + nowait: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.queue = val; val = !!(1 & buffer[offset]); @@ -2423,10 +2773,15 @@ function decodeQueuePurge(buffer) { } function encodeQueuePurge(channel, fields) { - var offset = 0, val = null, bits = 0, varyingSize = 0; + var offset = 0, + val = null, + bits = 0, + varyingSize = 0; val = fields.queue; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); - var queue_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, 'utf8'); varyingSize += queue_len; var buffer = Buffer.alloc(16 + varyingSize); buffer[0] = 1; @@ -2434,14 +2789,15 @@ function encodeQueuePurge(channel, fields) { buffer.writeUInt32BE(3276830, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.queue; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = queue_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += queue_len; val = fields.nowait; void 0 === val && (val = !1); @@ -2454,9 +2810,11 @@ function encodeQueuePurge(channel, fields) { } function decodeQueuePurgeOk(buffer) { - var val, offset = 0, fields = { - messageCount: void 0 - }; + var val, + offset = 0, + fields = { + messageCount: void 0, + }; val = buffer.readUInt32BE(offset); offset += 4; fields.messageCount = val; @@ -2464,14 +2822,16 @@ function decodeQueuePurgeOk(buffer) { } function encodeQueuePurgeOk(channel, fields) { - var offset = 0, val = null, buffer = Buffer.alloc(16); + var offset = 0, + val = null, + buffer = Buffer.alloc(16); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(3276831, 7); offset = 11; val = fields.messageCount; if (void 0 === val) throw new Error("Missing value for mandatory field 'messageCount'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt32BE(val, offset); offset += 4; buffer[offset] = 206; @@ -2480,19 +2840,22 @@ function encodeQueuePurgeOk(channel, fields) { } function decodeQueueDelete(buffer) { - var val, len, offset = 0, fields = { - ticket: void 0, - queue: void 0, - ifUnused: void 0, - ifEmpty: void 0, - nowait: void 0 - }; + var val, + len, + offset = 0, + fields = { + ticket: void 0, + queue: void 0, + ifUnused: void 0, + ifEmpty: void 0, + nowait: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.queue = val; val = !!(1 & buffer[offset]); @@ -2505,10 +2868,15 @@ function decodeQueueDelete(buffer) { } function encodeQueueDelete(channel, fields) { - var offset = 0, val = null, bits = 0, varyingSize = 0; + var offset = 0, + val = null, + bits = 0, + varyingSize = 0; val = fields.queue; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); - var queue_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, 'utf8'); varyingSize += queue_len; var buffer = Buffer.alloc(16 + varyingSize); buffer[0] = 1; @@ -2516,14 +2884,15 @@ function encodeQueueDelete(channel, fields) { buffer.writeUInt32BE(3276840, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.queue; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = queue_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += queue_len; val = fields.ifUnused; void 0 === val && (val = !1); @@ -2542,9 +2911,11 @@ function encodeQueueDelete(channel, fields) { } function decodeQueueDeleteOk(buffer) { - var val, offset = 0, fields = { - messageCount: void 0 - }; + var val, + offset = 0, + fields = { + messageCount: void 0, + }; val = buffer.readUInt32BE(offset); offset += 4; fields.messageCount = val; @@ -2552,14 +2923,16 @@ function decodeQueueDeleteOk(buffer) { } function encodeQueueDeleteOk(channel, fields) { - var offset = 0, val = null, buffer = Buffer.alloc(16); + var offset = 0, + val = null, + buffer = Buffer.alloc(16); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(3276841, 7); offset = 11; val = fields.messageCount; if (void 0 === val) throw new Error("Missing value for mandatory field 'messageCount'"); - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt32BE(val, offset); offset += 4; buffer[offset] = 206; @@ -2568,29 +2941,32 @@ function encodeQueueDeleteOk(channel, fields) { } function decodeQueueUnbind(buffer) { - var val, len, offset = 0, fields = { - ticket: void 0, - queue: void 0, - exchange: void 0, - routingKey: void 0, - arguments: void 0 - }; + var val, + len, + offset = 0, + fields = { + ticket: void 0, + queue: void 0, + exchange: void 0, + routingKey: void 0, + arguments: void 0, + }; val = buffer.readUInt16BE(offset); offset += 2; fields.ticket = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.queue = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.exchange = val; len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.routingKey = val; len = buffer.readUInt32BE(offset); @@ -2602,22 +2978,32 @@ function decodeQueueUnbind(buffer) { } function encodeQueueUnbind(channel, fields) { - var len, offset = 0, val = null, varyingSize = 0, scratchOffset = 0; + var len, + offset = 0, + val = null, + varyingSize = 0, + scratchOffset = 0; val = fields.queue; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); - var queue_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, 'utf8'); varyingSize += queue_len; val = fields.exchange; if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); - var exchange_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, 'utf8'); varyingSize += exchange_len; val = fields.routingKey; - if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); - var routingKey_len = Buffer.byteLength(val, "utf8"); + if (void 0 === val) val = ''; + else if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, 'utf8'); varyingSize += routingKey_len; val = fields.arguments; - if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + if (void 0 === val) val = {}; + else if ('object' != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); len = encodeTable(SCRATCH, val, scratchOffset); var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); scratchOffset += len; @@ -2628,26 +3014,27 @@ function encodeQueueUnbind(channel, fields) { buffer.writeUInt32BE(3276850, 7); offset = 11; val = fields.ticket; - if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + if (void 0 === val) val = 0; + else if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); buffer.writeUInt16BE(val, offset); offset += 2; val = fields.queue; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = queue_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += queue_len; val = fields.exchange; void 0 === val && (val = void 0); buffer[offset] = exchange_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += exchange_len; val = fields.routingKey; - void 0 === val && (val = ""); + void 0 === val && (val = ''); buffer[offset] = routingKey_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += routingKey_len; offset += arguments_encoded.copy(buffer, offset); buffer[offset] = 206; @@ -2660,7 +3047,8 @@ function decodeQueueUnbindOk(buffer) { } function encodeQueueUnbindOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(3276851, 7); @@ -2675,7 +3063,8 @@ function decodeTxSelect(buffer) { } function encodeTxSelect(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(5898250, 7); @@ -2690,7 +3079,8 @@ function decodeTxSelectOk(buffer) { } function encodeTxSelectOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(5898251, 7); @@ -2705,7 +3095,8 @@ function decodeTxCommit(buffer) { } function encodeTxCommit(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(5898260, 7); @@ -2720,7 +3111,8 @@ function decodeTxCommitOk(buffer) { } function encodeTxCommitOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(5898261, 7); @@ -2735,7 +3127,8 @@ function decodeTxRollback(buffer) { } function encodeTxRollback(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(5898270, 7); @@ -2750,7 +3143,8 @@ function decodeTxRollbackOk(buffer) { } function encodeTxRollbackOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(5898271, 7); @@ -2761,16 +3155,20 @@ function encodeTxRollbackOk(channel, fields) { } function decodeConfirmSelect(buffer) { - var val, fields = { - nowait: void 0 - }; + var val, + fields = { + nowait: void 0, + }; val = !!(1 & buffer[0]); fields.nowait = val; return fields; } function encodeConfirmSelect(channel, fields) { - var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(13); + var offset = 0, + val = null, + bits = 0, + buffer = Buffer.alloc(13); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(5570570, 7); @@ -2790,7 +3188,8 @@ function decodeConfirmSelectOk(buffer) { } function encodeConfirmSelectOk(channel, fields) { - var offset = 0, buffer = Buffer.alloc(12); + var offset = 0, + buffer = Buffer.alloc(12); buffer[0] = 1; buffer.writeUInt16BE(channel, 1); buffer.writeUInt32BE(5570571, 7); @@ -2801,24 +3200,31 @@ function encodeConfirmSelectOk(channel, fields) { } function encodeBasicProperties(channel, size, fields) { - var val, len, offset = 0, flags = 0, scratchOffset = 0, varyingSize = 0; + var val, + len, + offset = 0, + flags = 0, + scratchOffset = 0, + varyingSize = 0; val = fields.contentType; if (void 0 != val) { - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'contentType' is the wrong type; must be a string (up to 255 chars)"); - var contentType_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'contentType' is the wrong type; must be a string (up to 255 chars)"); + var contentType_len = Buffer.byteLength(val, 'utf8'); varyingSize += 1; varyingSize += contentType_len; } val = fields.contentEncoding; if (void 0 != val) { - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'contentEncoding' is the wrong type; must be a string (up to 255 chars)"); - var contentEncoding_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'contentEncoding' is the wrong type; must be a string (up to 255 chars)"); + var contentEncoding_len = Buffer.byteLength(val, 'utf8'); varyingSize += 1; varyingSize += contentEncoding_len; } val = fields.headers; if (void 0 != val) { - if ("object" != typeof val) throw new TypeError("Field 'headers' is the wrong type; must be an object"); + if ('object' != typeof val) throw new TypeError("Field 'headers' is the wrong type; must be an object"); len = encodeTable(SCRATCH, val, scratchOffset); var headers_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); scratchOffset += len; @@ -2826,72 +3232,80 @@ function encodeBasicProperties(channel, size, fields) { } val = fields.deliveryMode; if (void 0 != val) { - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryMode' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryMode' is the wrong type; must be a number (but not NaN)"); varyingSize += 1; } val = fields.priority; if (void 0 != val) { - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'priority' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'priority' is the wrong type; must be a number (but not NaN)"); varyingSize += 1; } val = fields.correlationId; if (void 0 != val) { - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'correlationId' is the wrong type; must be a string (up to 255 chars)"); - var correlationId_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'correlationId' is the wrong type; must be a string (up to 255 chars)"); + var correlationId_len = Buffer.byteLength(val, 'utf8'); varyingSize += 1; varyingSize += correlationId_len; } val = fields.replyTo; if (void 0 != val) { - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'replyTo' is the wrong type; must be a string (up to 255 chars)"); - var replyTo_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'replyTo' is the wrong type; must be a string (up to 255 chars)"); + var replyTo_len = Buffer.byteLength(val, 'utf8'); varyingSize += 1; varyingSize += replyTo_len; } val = fields.expiration; if (void 0 != val) { - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'expiration' is the wrong type; must be a string (up to 255 chars)"); - var expiration_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'expiration' is the wrong type; must be a string (up to 255 chars)"); + var expiration_len = Buffer.byteLength(val, 'utf8'); varyingSize += 1; varyingSize += expiration_len; } val = fields.messageId; if (void 0 != val) { - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'messageId' is the wrong type; must be a string (up to 255 chars)"); - var messageId_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'messageId' is the wrong type; must be a string (up to 255 chars)"); + var messageId_len = Buffer.byteLength(val, 'utf8'); varyingSize += 1; varyingSize += messageId_len; } val = fields.timestamp; if (void 0 != val) { - if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'timestamp' is the wrong type; must be a number (but not NaN)"); + if ('number' != typeof val || isNaN(val)) throw new TypeError("Field 'timestamp' is the wrong type; must be a number (but not NaN)"); varyingSize += 8; } val = fields.type; if (void 0 != val) { - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'type' is the wrong type; must be a string (up to 255 chars)"); - var type_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'type' is the wrong type; must be a string (up to 255 chars)"); + var type_len = Buffer.byteLength(val, 'utf8'); varyingSize += 1; varyingSize += type_len; } val = fields.userId; if (void 0 != val) { - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'userId' is the wrong type; must be a string (up to 255 chars)"); - var userId_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'userId' is the wrong type; must be a string (up to 255 chars)"); + var userId_len = Buffer.byteLength(val, 'utf8'); varyingSize += 1; varyingSize += userId_len; } val = fields.appId; if (void 0 != val) { - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'appId' is the wrong type; must be a string (up to 255 chars)"); - var appId_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'appId' is the wrong type; must be a string (up to 255 chars)"); + var appId_len = Buffer.byteLength(val, 'utf8'); varyingSize += 1; varyingSize += appId_len; } val = fields.clusterId; if (void 0 != val) { - if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'clusterId' is the wrong type; must be a string (up to 255 chars)"); - var clusterId_len = Buffer.byteLength(val, "utf8"); + if (!('string' == typeof val && Buffer.byteLength(val) < 256)) + throw new TypeError("Field 'clusterId' is the wrong type; must be a string (up to 255 chars)"); + var clusterId_len = Buffer.byteLength(val, 'utf8'); varyingSize += 1; varyingSize += clusterId_len; } @@ -2907,7 +3321,7 @@ function encodeBasicProperties(channel, size, fields) { flags += 32768; buffer[offset] = contentType_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += contentType_len; } val = fields.contentEncoding; @@ -2915,7 +3329,7 @@ function encodeBasicProperties(channel, size, fields) { flags += 16384; buffer[offset] = contentEncoding_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += contentEncoding_len; } val = fields.headers; @@ -2940,7 +3354,7 @@ function encodeBasicProperties(channel, size, fields) { flags += 1024; buffer[offset] = correlationId_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += correlationId_len; } val = fields.replyTo; @@ -2948,7 +3362,7 @@ function encodeBasicProperties(channel, size, fields) { flags += 512; buffer[offset] = replyTo_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += replyTo_len; } val = fields.expiration; @@ -2956,7 +3370,7 @@ function encodeBasicProperties(channel, size, fields) { flags += 256; buffer[offset] = expiration_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += expiration_len; } val = fields.messageId; @@ -2964,7 +3378,7 @@ function encodeBasicProperties(channel, size, fields) { flags += 128; buffer[offset] = messageId_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += messageId_len; } val = fields.timestamp; @@ -2978,7 +3392,7 @@ function encodeBasicProperties(channel, size, fields) { flags += 32; buffer[offset] = type_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += type_len; } val = fields.userId; @@ -2986,7 +3400,7 @@ function encodeBasicProperties(channel, size, fields) { flags += 16; buffer[offset] = userId_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += userId_len; } val = fields.appId; @@ -2994,7 +3408,7 @@ function encodeBasicProperties(channel, size, fields) { flags += 8; buffer[offset] = appId_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += appId_len; } val = fields.clusterId; @@ -3002,7 +3416,7 @@ function encodeBasicProperties(channel, size, fields) { flags += 4; buffer[offset] = clusterId_len; offset++; - buffer.write(val, offset, "utf8"); + buffer.write(val, offset, 'utf8'); offset += clusterId_len; } buffer[offset] = 206; @@ -3012,7 +3426,10 @@ function encodeBasicProperties(channel, size, fields) { } function decodeBasicProperties(buffer) { - var flags, val, len, offset = 2; + var flags, + val, + len, + offset = 2; flags = buffer.readUInt16BE(0); if (0 === flags) return {}; var fields = { @@ -3029,19 +3446,19 @@ function decodeBasicProperties(buffer) { type: void 0, userId: void 0, appId: void 0, - clusterId: void 0 + clusterId: void 0, }; if (32768 & flags) { len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.contentType = val; } if (16384 & flags) { len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.contentEncoding = val; } @@ -3065,28 +3482,28 @@ function decodeBasicProperties(buffer) { if (1024 & flags) { len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.correlationId = val; } if (512 & flags) { len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.replyTo = val; } if (256 & flags) { len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.expiration = val; } if (128 & flags) { len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.messageId = val; } @@ -3098,35 +3515,40 @@ function decodeBasicProperties(buffer) { if (32 & flags) { len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.type = val; } if (16 & flags) { len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.userId = val; } if (8 & flags) { len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.appId = val; } if (4 & flags) { len = buffer.readUInt8(offset); offset++; - val = buffer.toString("utf8", offset, offset + len); + val = buffer.toString('utf8', offset, offset + len); offset += len; fields.clusterId = val; } return fields; } -var codec = require("./codec"), ints = require("buffer-more-ints"), encodeTable = codec.encodeTable, decodeFields = codec.decodeFields, SCRATCH = Buffer.alloc(65536), EMPTY_OBJECT = Object.freeze({}); +var codec = require('./codec'), + ints = require('buffer-more-ints'), + encodeTable = codec.encodeTable, + decodeFields = codec.decodeFields, + SCRATCH = Buffer.alloc(65536), + EMPTY_OBJECT = Object.freeze({}); module.exports.constants = { FRAME_METHOD: 1, @@ -3153,1925 +3575,2135 @@ module.exports.constants = { RESOURCE_ERROR: 506, NOT_ALLOWED: 530, NOT_IMPLEMENTED: 540, - INTERNAL_ERROR: 541 + INTERNAL_ERROR: 541, }; module.exports.constant_strs = { - "1": "FRAME-METHOD", - "2": "FRAME-HEADER", - "3": "FRAME-BODY", - "8": "FRAME-HEARTBEAT", - "200": "REPLY-SUCCESS", - "206": "FRAME-END", - "311": "CONTENT-TOO-LARGE", - "312": "NO-ROUTE", - "313": "NO-CONSUMERS", - "320": "CONNECTION-FORCED", - "402": "INVALID-PATH", - "403": "ACCESS-REFUSED", - "404": "NOT-FOUND", - "405": "RESOURCE-LOCKED", - "406": "PRECONDITION-FAILED", - "501": "FRAME-ERROR", - "502": "SYNTAX-ERROR", - "503": "COMMAND-INVALID", - "504": "CHANNEL-ERROR", - "505": "UNEXPECTED-FRAME", - "506": "RESOURCE-ERROR", - "530": "NOT-ALLOWED", - "540": "NOT-IMPLEMENTED", - "541": "INTERNAL-ERROR", - "4096": "FRAME-MIN-SIZE" + 1: 'FRAME-METHOD', + 2: 'FRAME-HEADER', + 3: 'FRAME-BODY', + 8: 'FRAME-HEARTBEAT', + 200: 'REPLY-SUCCESS', + 206: 'FRAME-END', + 311: 'CONTENT-TOO-LARGE', + 312: 'NO-ROUTE', + 313: 'NO-CONSUMERS', + 320: 'CONNECTION-FORCED', + 402: 'INVALID-PATH', + 403: 'ACCESS-REFUSED', + 404: 'NOT-FOUND', + 405: 'RESOURCE-LOCKED', + 406: 'PRECONDITION-FAILED', + 501: 'FRAME-ERROR', + 502: 'SYNTAX-ERROR', + 503: 'COMMAND-INVALID', + 504: 'CHANNEL-ERROR', + 505: 'UNEXPECTED-FRAME', + 506: 'RESOURCE-ERROR', + 530: 'NOT-ALLOWED', + 540: 'NOT-IMPLEMENTED', + 541: 'INTERNAL-ERROR', + 4096: 'FRAME-MIN-SIZE', }; module.exports.FRAME_OVERHEAD = 8; -module.exports.decode = function(id, buf) { +module.exports.decode = function (id, buf) { switch (id) { - case 3932170: - return decodeBasicQos(buf); + case 3932170: + return decodeBasicQos(buf); - case 3932171: - return decodeBasicQosOk(buf); + case 3932171: + return decodeBasicQosOk(buf); - case 3932180: - return decodeBasicConsume(buf); + case 3932180: + return decodeBasicConsume(buf); - case 3932181: - return decodeBasicConsumeOk(buf); + case 3932181: + return decodeBasicConsumeOk(buf); - case 3932190: - return decodeBasicCancel(buf); + case 3932190: + return decodeBasicCancel(buf); - case 3932191: - return decodeBasicCancelOk(buf); + case 3932191: + return decodeBasicCancelOk(buf); - case 3932200: - return decodeBasicPublish(buf); + case 3932200: + return decodeBasicPublish(buf); - case 3932210: - return decodeBasicReturn(buf); + case 3932210: + return decodeBasicReturn(buf); - case 3932220: - return decodeBasicDeliver(buf); + case 3932220: + return decodeBasicDeliver(buf); - case 3932230: - return decodeBasicGet(buf); + case 3932230: + return decodeBasicGet(buf); - case 3932231: - return decodeBasicGetOk(buf); + case 3932231: + return decodeBasicGetOk(buf); - case 3932232: - return decodeBasicGetEmpty(buf); + case 3932232: + return decodeBasicGetEmpty(buf); - case 3932240: - return decodeBasicAck(buf); + case 3932240: + return decodeBasicAck(buf); - case 3932250: - return decodeBasicReject(buf); + case 3932250: + return decodeBasicReject(buf); - case 3932260: - return decodeBasicRecoverAsync(buf); + case 3932260: + return decodeBasicRecoverAsync(buf); - case 3932270: - return decodeBasicRecover(buf); + case 3932270: + return decodeBasicRecover(buf); - case 3932271: - return decodeBasicRecoverOk(buf); + case 3932271: + return decodeBasicRecoverOk(buf); - case 3932280: - return decodeBasicNack(buf); + case 3932280: + return decodeBasicNack(buf); - case 655370: - return decodeConnectionStart(buf); + case 655370: + return decodeConnectionStart(buf); - case 655371: - return decodeConnectionStartOk(buf); + case 655371: + return decodeConnectionStartOk(buf); - case 655380: - return decodeConnectionSecure(buf); + case 655380: + return decodeConnectionSecure(buf); - case 655381: - return decodeConnectionSecureOk(buf); + case 655381: + return decodeConnectionSecureOk(buf); - case 655390: - return decodeConnectionTune(buf); + case 655390: + return decodeConnectionTune(buf); - case 655391: - return decodeConnectionTuneOk(buf); + case 655391: + return decodeConnectionTuneOk(buf); - case 655400: - return decodeConnectionOpen(buf); + case 655400: + return decodeConnectionOpen(buf); - case 655401: - return decodeConnectionOpenOk(buf); + case 655401: + return decodeConnectionOpenOk(buf); - case 655410: - return decodeConnectionClose(buf); + case 655410: + return decodeConnectionClose(buf); - case 655411: - return decodeConnectionCloseOk(buf); + case 655411: + return decodeConnectionCloseOk(buf); - case 655420: - return decodeConnectionBlocked(buf); + case 655420: + return decodeConnectionBlocked(buf); - case 655421: - return decodeConnectionUnblocked(buf); + case 655421: + return decodeConnectionUnblocked(buf); - case 655430: - return decodeConnectionUpdateSecret(buf); + case 655430: + return decodeConnectionUpdateSecret(buf); - case 655431: - return decodeConnectionUpdateSecretOk(buf); + case 655431: + return decodeConnectionUpdateSecretOk(buf); - case 1310730: - return decodeChannelOpen(buf); + case 1310730: + return decodeChannelOpen(buf); - case 1310731: - return decodeChannelOpenOk(buf); + case 1310731: + return decodeChannelOpenOk(buf); - case 1310740: - return decodeChannelFlow(buf); + case 1310740: + return decodeChannelFlow(buf); - case 1310741: - return decodeChannelFlowOk(buf); + case 1310741: + return decodeChannelFlowOk(buf); - case 1310760: - return decodeChannelClose(buf); + case 1310760: + return decodeChannelClose(buf); - case 1310761: - return decodeChannelCloseOk(buf); + case 1310761: + return decodeChannelCloseOk(buf); - case 1966090: - return decodeAccessRequest(buf); + case 1966090: + return decodeAccessRequest(buf); - case 1966091: - return decodeAccessRequestOk(buf); + case 1966091: + return decodeAccessRequestOk(buf); - case 2621450: - return decodeExchangeDeclare(buf); + case 2621450: + return decodeExchangeDeclare(buf); - case 2621451: - return decodeExchangeDeclareOk(buf); + case 2621451: + return decodeExchangeDeclareOk(buf); - case 2621460: - return decodeExchangeDelete(buf); + case 2621460: + return decodeExchangeDelete(buf); - case 2621461: - return decodeExchangeDeleteOk(buf); + case 2621461: + return decodeExchangeDeleteOk(buf); - case 2621470: - return decodeExchangeBind(buf); + case 2621470: + return decodeExchangeBind(buf); - case 2621471: - return decodeExchangeBindOk(buf); + case 2621471: + return decodeExchangeBindOk(buf); - case 2621480: - return decodeExchangeUnbind(buf); + case 2621480: + return decodeExchangeUnbind(buf); - case 2621491: - return decodeExchangeUnbindOk(buf); + case 2621491: + return decodeExchangeUnbindOk(buf); - case 3276810: - return decodeQueueDeclare(buf); + case 3276810: + return decodeQueueDeclare(buf); - case 3276811: - return decodeQueueDeclareOk(buf); + case 3276811: + return decodeQueueDeclareOk(buf); - case 3276820: - return decodeQueueBind(buf); + case 3276820: + return decodeQueueBind(buf); - case 3276821: - return decodeQueueBindOk(buf); + case 3276821: + return decodeQueueBindOk(buf); - case 3276830: - return decodeQueuePurge(buf); + case 3276830: + return decodeQueuePurge(buf); - case 3276831: - return decodeQueuePurgeOk(buf); + case 3276831: + return decodeQueuePurgeOk(buf); - case 3276840: - return decodeQueueDelete(buf); + case 3276840: + return decodeQueueDelete(buf); - case 3276841: - return decodeQueueDeleteOk(buf); + case 3276841: + return decodeQueueDeleteOk(buf); - case 3276850: - return decodeQueueUnbind(buf); + case 3276850: + return decodeQueueUnbind(buf); - case 3276851: - return decodeQueueUnbindOk(buf); + case 3276851: + return decodeQueueUnbindOk(buf); - case 5898250: - return decodeTxSelect(buf); + case 5898250: + return decodeTxSelect(buf); - case 5898251: - return decodeTxSelectOk(buf); + case 5898251: + return decodeTxSelectOk(buf); - case 5898260: - return decodeTxCommit(buf); + case 5898260: + return decodeTxCommit(buf); - case 5898261: - return decodeTxCommitOk(buf); + case 5898261: + return decodeTxCommitOk(buf); - case 5898270: - return decodeTxRollback(buf); + case 5898270: + return decodeTxRollback(buf); - case 5898271: - return decodeTxRollbackOk(buf); + case 5898271: + return decodeTxRollbackOk(buf); - case 5570570: - return decodeConfirmSelect(buf); + case 5570570: + return decodeConfirmSelect(buf); - case 5570571: - return decodeConfirmSelectOk(buf); + case 5570571: + return decodeConfirmSelectOk(buf); - case 60: - return decodeBasicProperties(buf); + case 60: + return decodeBasicProperties(buf); - default: - throw new Error("Unknown class/method ID"); + default: + throw new Error('Unknown class/method ID'); } }; -module.exports.encodeMethod = function(id, channel, fields) { +module.exports.encodeMethod = function (id, channel, fields) { switch (id) { - case 3932170: - return encodeBasicQos(channel, fields); + case 3932170: + return encodeBasicQos(channel, fields); - case 3932171: - return encodeBasicQosOk(channel, fields); + case 3932171: + return encodeBasicQosOk(channel, fields); - case 3932180: - return encodeBasicConsume(channel, fields); + case 3932180: + return encodeBasicConsume(channel, fields); - case 3932181: - return encodeBasicConsumeOk(channel, fields); + case 3932181: + return encodeBasicConsumeOk(channel, fields); - case 3932190: - return encodeBasicCancel(channel, fields); + case 3932190: + return encodeBasicCancel(channel, fields); - case 3932191: - return encodeBasicCancelOk(channel, fields); + case 3932191: + return encodeBasicCancelOk(channel, fields); - case 3932200: - return encodeBasicPublish(channel, fields); + case 3932200: + return encodeBasicPublish(channel, fields); - case 3932210: - return encodeBasicReturn(channel, fields); + case 3932210: + return encodeBasicReturn(channel, fields); - case 3932220: - return encodeBasicDeliver(channel, fields); + case 3932220: + return encodeBasicDeliver(channel, fields); - case 3932230: - return encodeBasicGet(channel, fields); + case 3932230: + return encodeBasicGet(channel, fields); - case 3932231: - return encodeBasicGetOk(channel, fields); + case 3932231: + return encodeBasicGetOk(channel, fields); - case 3932232: - return encodeBasicGetEmpty(channel, fields); + case 3932232: + return encodeBasicGetEmpty(channel, fields); - case 3932240: - return encodeBasicAck(channel, fields); + case 3932240: + return encodeBasicAck(channel, fields); - case 3932250: - return encodeBasicReject(channel, fields); + case 3932250: + return encodeBasicReject(channel, fields); - case 3932260: - return encodeBasicRecoverAsync(channel, fields); + case 3932260: + return encodeBasicRecoverAsync(channel, fields); - case 3932270: - return encodeBasicRecover(channel, fields); + case 3932270: + return encodeBasicRecover(channel, fields); - case 3932271: - return encodeBasicRecoverOk(channel, fields); + case 3932271: + return encodeBasicRecoverOk(channel, fields); - case 3932280: - return encodeBasicNack(channel, fields); + case 3932280: + return encodeBasicNack(channel, fields); - case 655370: - return encodeConnectionStart(channel, fields); + case 655370: + return encodeConnectionStart(channel, fields); - case 655371: - return encodeConnectionStartOk(channel, fields); + case 655371: + return encodeConnectionStartOk(channel, fields); - case 655380: - return encodeConnectionSecure(channel, fields); + case 655380: + return encodeConnectionSecure(channel, fields); - case 655381: - return encodeConnectionSecureOk(channel, fields); + case 655381: + return encodeConnectionSecureOk(channel, fields); - case 655390: - return encodeConnectionTune(channel, fields); + case 655390: + return encodeConnectionTune(channel, fields); - case 655391: - return encodeConnectionTuneOk(channel, fields); + case 655391: + return encodeConnectionTuneOk(channel, fields); - case 655400: - return encodeConnectionOpen(channel, fields); + case 655400: + return encodeConnectionOpen(channel, fields); - case 655401: - return encodeConnectionOpenOk(channel, fields); + case 655401: + return encodeConnectionOpenOk(channel, fields); - case 655410: - return encodeConnectionClose(channel, fields); + case 655410: + return encodeConnectionClose(channel, fields); - case 655411: - return encodeConnectionCloseOk(channel, fields); + case 655411: + return encodeConnectionCloseOk(channel, fields); - case 655420: - return encodeConnectionBlocked(channel, fields); + case 655420: + return encodeConnectionBlocked(channel, fields); - case 655421: - return encodeConnectionUnblocked(channel, fields); + case 655421: + return encodeConnectionUnblocked(channel, fields); - case 655430: - return encodeConnectionUpdateSecret(channel, fields); + case 655430: + return encodeConnectionUpdateSecret(channel, fields); - case 655431: - return encodeConnectionUpdateSecretOk(channel, fields); + case 655431: + return encodeConnectionUpdateSecretOk(channel, fields); - case 1310730: - return encodeChannelOpen(channel, fields); + case 1310730: + return encodeChannelOpen(channel, fields); - case 1310731: - return encodeChannelOpenOk(channel, fields); + case 1310731: + return encodeChannelOpenOk(channel, fields); - case 1310740: - return encodeChannelFlow(channel, fields); + case 1310740: + return encodeChannelFlow(channel, fields); - case 1310741: - return encodeChannelFlowOk(channel, fields); + case 1310741: + return encodeChannelFlowOk(channel, fields); - case 1310760: - return encodeChannelClose(channel, fields); + case 1310760: + return encodeChannelClose(channel, fields); - case 1310761: - return encodeChannelCloseOk(channel, fields); + case 1310761: + return encodeChannelCloseOk(channel, fields); - case 1966090: - return encodeAccessRequest(channel, fields); + case 1966090: + return encodeAccessRequest(channel, fields); - case 1966091: - return encodeAccessRequestOk(channel, fields); + case 1966091: + return encodeAccessRequestOk(channel, fields); - case 2621450: - return encodeExchangeDeclare(channel, fields); + case 2621450: + return encodeExchangeDeclare(channel, fields); - case 2621451: - return encodeExchangeDeclareOk(channel, fields); + case 2621451: + return encodeExchangeDeclareOk(channel, fields); - case 2621460: - return encodeExchangeDelete(channel, fields); + case 2621460: + return encodeExchangeDelete(channel, fields); - case 2621461: - return encodeExchangeDeleteOk(channel, fields); + case 2621461: + return encodeExchangeDeleteOk(channel, fields); - case 2621470: - return encodeExchangeBind(channel, fields); + case 2621470: + return encodeExchangeBind(channel, fields); - case 2621471: - return encodeExchangeBindOk(channel, fields); + case 2621471: + return encodeExchangeBindOk(channel, fields); - case 2621480: - return encodeExchangeUnbind(channel, fields); + case 2621480: + return encodeExchangeUnbind(channel, fields); - case 2621491: - return encodeExchangeUnbindOk(channel, fields); + case 2621491: + return encodeExchangeUnbindOk(channel, fields); - case 3276810: - return encodeQueueDeclare(channel, fields); + case 3276810: + return encodeQueueDeclare(channel, fields); - case 3276811: - return encodeQueueDeclareOk(channel, fields); + case 3276811: + return encodeQueueDeclareOk(channel, fields); - case 3276820: - return encodeQueueBind(channel, fields); + case 3276820: + return encodeQueueBind(channel, fields); - case 3276821: - return encodeQueueBindOk(channel, fields); + case 3276821: + return encodeQueueBindOk(channel, fields); - case 3276830: - return encodeQueuePurge(channel, fields); + case 3276830: + return encodeQueuePurge(channel, fields); - case 3276831: - return encodeQueuePurgeOk(channel, fields); + case 3276831: + return encodeQueuePurgeOk(channel, fields); - case 3276840: - return encodeQueueDelete(channel, fields); + case 3276840: + return encodeQueueDelete(channel, fields); - case 3276841: - return encodeQueueDeleteOk(channel, fields); + case 3276841: + return encodeQueueDeleteOk(channel, fields); - case 3276850: - return encodeQueueUnbind(channel, fields); + case 3276850: + return encodeQueueUnbind(channel, fields); - case 3276851: - return encodeQueueUnbindOk(channel, fields); + case 3276851: + return encodeQueueUnbindOk(channel, fields); - case 5898250: - return encodeTxSelect(channel, fields); + case 5898250: + return encodeTxSelect(channel, fields); - case 5898251: - return encodeTxSelectOk(channel, fields); + case 5898251: + return encodeTxSelectOk(channel, fields); - case 5898260: - return encodeTxCommit(channel, fields); + case 5898260: + return encodeTxCommit(channel, fields); - case 5898261: - return encodeTxCommitOk(channel, fields); + case 5898261: + return encodeTxCommitOk(channel, fields); - case 5898270: - return encodeTxRollback(channel, fields); + case 5898270: + return encodeTxRollback(channel, fields); - case 5898271: - return encodeTxRollbackOk(channel, fields); + case 5898271: + return encodeTxRollbackOk(channel, fields); - case 5570570: - return encodeConfirmSelect(channel, fields); + case 5570570: + return encodeConfirmSelect(channel, fields); - case 5570571: - return encodeConfirmSelectOk(channel, fields); + case 5570571: + return encodeConfirmSelectOk(channel, fields); - default: - throw new Error("Unknown class/method ID"); + default: + throw new Error('Unknown class/method ID'); } }; -module.exports.encodeProperties = function(id, channel, size, fields) { +module.exports.encodeProperties = function (id, channel, size, fields) { switch (id) { - case 60: - return encodeBasicProperties(channel, size, fields); + case 60: + return encodeBasicProperties(channel, size, fields); - default: - throw new Error("Unknown class/properties ID"); + default: + throw new Error('Unknown class/properties ID'); } }; -module.exports.info = function(id) { +module.exports.info = function (id) { switch (id) { - case 3932170: - return methodInfoBasicQos; + case 3932170: + return methodInfoBasicQos; - case 3932171: - return methodInfoBasicQosOk; + case 3932171: + return methodInfoBasicQosOk; - case 3932180: - return methodInfoBasicConsume; + case 3932180: + return methodInfoBasicConsume; - case 3932181: - return methodInfoBasicConsumeOk; + case 3932181: + return methodInfoBasicConsumeOk; - case 3932190: - return methodInfoBasicCancel; + case 3932190: + return methodInfoBasicCancel; - case 3932191: - return methodInfoBasicCancelOk; + case 3932191: + return methodInfoBasicCancelOk; - case 3932200: - return methodInfoBasicPublish; + case 3932200: + return methodInfoBasicPublish; - case 3932210: - return methodInfoBasicReturn; + case 3932210: + return methodInfoBasicReturn; - case 3932220: - return methodInfoBasicDeliver; + case 3932220: + return methodInfoBasicDeliver; - case 3932230: - return methodInfoBasicGet; + case 3932230: + return methodInfoBasicGet; - case 3932231: - return methodInfoBasicGetOk; + case 3932231: + return methodInfoBasicGetOk; - case 3932232: - return methodInfoBasicGetEmpty; + case 3932232: + return methodInfoBasicGetEmpty; - case 3932240: - return methodInfoBasicAck; + case 3932240: + return methodInfoBasicAck; - case 3932250: - return methodInfoBasicReject; + case 3932250: + return methodInfoBasicReject; - case 3932260: - return methodInfoBasicRecoverAsync; + case 3932260: + return methodInfoBasicRecoverAsync; - case 3932270: - return methodInfoBasicRecover; + case 3932270: + return methodInfoBasicRecover; - case 3932271: - return methodInfoBasicRecoverOk; + case 3932271: + return methodInfoBasicRecoverOk; - case 3932280: - return methodInfoBasicNack; + case 3932280: + return methodInfoBasicNack; - case 655370: - return methodInfoConnectionStart; + case 655370: + return methodInfoConnectionStart; - case 655371: - return methodInfoConnectionStartOk; + case 655371: + return methodInfoConnectionStartOk; - case 655380: - return methodInfoConnectionSecure; + case 655380: + return methodInfoConnectionSecure; - case 655381: - return methodInfoConnectionSecureOk; + case 655381: + return methodInfoConnectionSecureOk; - case 655390: - return methodInfoConnectionTune; + case 655390: + return methodInfoConnectionTune; - case 655391: - return methodInfoConnectionTuneOk; + case 655391: + return methodInfoConnectionTuneOk; - case 655400: - return methodInfoConnectionOpen; + case 655400: + return methodInfoConnectionOpen; - case 655401: - return methodInfoConnectionOpenOk; + case 655401: + return methodInfoConnectionOpenOk; - case 655410: - return methodInfoConnectionClose; + case 655410: + return methodInfoConnectionClose; - case 655411: - return methodInfoConnectionCloseOk; + case 655411: + return methodInfoConnectionCloseOk; - case 655420: - return methodInfoConnectionBlocked; + case 655420: + return methodInfoConnectionBlocked; - case 655421: - return methodInfoConnectionUnblocked; + case 655421: + return methodInfoConnectionUnblocked; - case 655430: - return methodInfoConnectionUpdateSecret; + case 655430: + return methodInfoConnectionUpdateSecret; - case 655431: - return methodInfoConnectionUpdateSecretOk; + case 655431: + return methodInfoConnectionUpdateSecretOk; - case 1310730: - return methodInfoChannelOpen; + case 1310730: + return methodInfoChannelOpen; - case 1310731: - return methodInfoChannelOpenOk; + case 1310731: + return methodInfoChannelOpenOk; - case 1310740: - return methodInfoChannelFlow; + case 1310740: + return methodInfoChannelFlow; - case 1310741: - return methodInfoChannelFlowOk; + case 1310741: + return methodInfoChannelFlowOk; - case 1310760: - return methodInfoChannelClose; + case 1310760: + return methodInfoChannelClose; - case 1310761: - return methodInfoChannelCloseOk; + case 1310761: + return methodInfoChannelCloseOk; - case 1966090: - return methodInfoAccessRequest; + case 1966090: + return methodInfoAccessRequest; - case 1966091: - return methodInfoAccessRequestOk; + case 1966091: + return methodInfoAccessRequestOk; - case 2621450: - return methodInfoExchangeDeclare; + case 2621450: + return methodInfoExchangeDeclare; - case 2621451: - return methodInfoExchangeDeclareOk; + case 2621451: + return methodInfoExchangeDeclareOk; - case 2621460: - return methodInfoExchangeDelete; + case 2621460: + return methodInfoExchangeDelete; - case 2621461: - return methodInfoExchangeDeleteOk; + case 2621461: + return methodInfoExchangeDeleteOk; - case 2621470: - return methodInfoExchangeBind; + case 2621470: + return methodInfoExchangeBind; - case 2621471: - return methodInfoExchangeBindOk; + case 2621471: + return methodInfoExchangeBindOk; - case 2621480: - return methodInfoExchangeUnbind; + case 2621480: + return methodInfoExchangeUnbind; - case 2621491: - return methodInfoExchangeUnbindOk; + case 2621491: + return methodInfoExchangeUnbindOk; - case 3276810: - return methodInfoQueueDeclare; + case 3276810: + return methodInfoQueueDeclare; - case 3276811: - return methodInfoQueueDeclareOk; + case 3276811: + return methodInfoQueueDeclareOk; - case 3276820: - return methodInfoQueueBind; + case 3276820: + return methodInfoQueueBind; - case 3276821: - return methodInfoQueueBindOk; + case 3276821: + return methodInfoQueueBindOk; - case 3276830: - return methodInfoQueuePurge; + case 3276830: + return methodInfoQueuePurge; - case 3276831: - return methodInfoQueuePurgeOk; + case 3276831: + return methodInfoQueuePurgeOk; - case 3276840: - return methodInfoQueueDelete; + case 3276840: + return methodInfoQueueDelete; - case 3276841: - return methodInfoQueueDeleteOk; + case 3276841: + return methodInfoQueueDeleteOk; - case 3276850: - return methodInfoQueueUnbind; + case 3276850: + return methodInfoQueueUnbind; - case 3276851: - return methodInfoQueueUnbindOk; + case 3276851: + return methodInfoQueueUnbindOk; - case 5898250: - return methodInfoTxSelect; + case 5898250: + return methodInfoTxSelect; - case 5898251: - return methodInfoTxSelectOk; + case 5898251: + return methodInfoTxSelectOk; - case 5898260: - return methodInfoTxCommit; + case 5898260: + return methodInfoTxCommit; - case 5898261: - return methodInfoTxCommitOk; + case 5898261: + return methodInfoTxCommitOk; - case 5898270: - return methodInfoTxRollback; + case 5898270: + return methodInfoTxRollback; - case 5898271: - return methodInfoTxRollbackOk; + case 5898271: + return methodInfoTxRollbackOk; - case 5570570: - return methodInfoConfirmSelect; + case 5570570: + return methodInfoConfirmSelect; - case 5570571: - return methodInfoConfirmSelectOk; + case 5570571: + return methodInfoConfirmSelectOk; - case 60: - return propertiesInfoBasicProperties; + case 60: + return propertiesInfoBasicProperties; - default: - throw new Error("Unknown class/method ID"); + default: + throw new Error('Unknown class/method ID'); } }; module.exports.BasicQos = 3932170; -var methodInfoBasicQos = module.exports.methodInfoBasicQos = { +var methodInfoBasicQos = (module.exports.methodInfoBasicQos = { id: 3932170, classId: 60, methodId: 10, - name: "BasicQos", - args: [ { - type: "long", - name: "prefetchSize", - default: 0 - }, { - type: "short", - name: "prefetchCount", - default: 0 - }, { - type: "bit", - name: "global", - default: !1 - } ] -}; + name: 'BasicQos', + args: [ + { + type: 'long', + name: 'prefetchSize', + default: 0, + }, + { + type: 'short', + name: 'prefetchCount', + default: 0, + }, + { + type: 'bit', + name: 'global', + default: !1, + }, + ], +}); module.exports.BasicQosOk = 3932171; -var methodInfoBasicQosOk = module.exports.methodInfoBasicQosOk = { +var methodInfoBasicQosOk = (module.exports.methodInfoBasicQosOk = { id: 3932171, classId: 60, methodId: 11, - name: "BasicQosOk", - args: [] -}; + name: 'BasicQosOk', + args: [], +}); module.exports.BasicConsume = 3932180; -var methodInfoBasicConsume = module.exports.methodInfoBasicConsume = { +var methodInfoBasicConsume = (module.exports.methodInfoBasicConsume = { id: 3932180, classId: 60, methodId: 20, - name: "BasicConsume", - args: [ { - type: "short", - name: "ticket", - default: 0 - }, { - type: "shortstr", - name: "queue", - default: "" - }, { - type: "shortstr", - name: "consumerTag", - default: "" - }, { - type: "bit", - name: "noLocal", - default: !1 - }, { - type: "bit", - name: "noAck", - default: !1 - }, { - type: "bit", - name: "exclusive", - default: !1 - }, { - type: "bit", - name: "nowait", - default: !1 - }, { - type: "table", - name: "arguments", - default: {} - } ] -}; + name: 'BasicConsume', + args: [ + { + type: 'short', + name: 'ticket', + default: 0, + }, + { + type: 'shortstr', + name: 'queue', + default: '', + }, + { + type: 'shortstr', + name: 'consumerTag', + default: '', + }, + { + type: 'bit', + name: 'noLocal', + default: !1, + }, + { + type: 'bit', + name: 'noAck', + default: !1, + }, + { + type: 'bit', + name: 'exclusive', + default: !1, + }, + { + type: 'bit', + name: 'nowait', + default: !1, + }, + { + type: 'table', + name: 'arguments', + default: {}, + }, + ], +}); module.exports.BasicConsumeOk = 3932181; -var methodInfoBasicConsumeOk = module.exports.methodInfoBasicConsumeOk = { +var methodInfoBasicConsumeOk = (module.exports.methodInfoBasicConsumeOk = { id: 3932181, classId: 60, methodId: 21, - name: "BasicConsumeOk", - args: [ { - type: "shortstr", - name: "consumerTag" - } ] -}; + name: 'BasicConsumeOk', + args: [ + { + type: 'shortstr', + name: 'consumerTag', + }, + ], +}); module.exports.BasicCancel = 3932190; -var methodInfoBasicCancel = module.exports.methodInfoBasicCancel = { +var methodInfoBasicCancel = (module.exports.methodInfoBasicCancel = { id: 3932190, classId: 60, methodId: 30, - name: "BasicCancel", - args: [ { - type: "shortstr", - name: "consumerTag" - }, { - type: "bit", - name: "nowait", - default: !1 - } ] -}; + name: 'BasicCancel', + args: [ + { + type: 'shortstr', + name: 'consumerTag', + }, + { + type: 'bit', + name: 'nowait', + default: !1, + }, + ], +}); module.exports.BasicCancelOk = 3932191; -var methodInfoBasicCancelOk = module.exports.methodInfoBasicCancelOk = { +var methodInfoBasicCancelOk = (module.exports.methodInfoBasicCancelOk = { id: 3932191, classId: 60, methodId: 31, - name: "BasicCancelOk", - args: [ { - type: "shortstr", - name: "consumerTag" - } ] -}; + name: 'BasicCancelOk', + args: [ + { + type: 'shortstr', + name: 'consumerTag', + }, + ], +}); module.exports.BasicPublish = 3932200; -var methodInfoBasicPublish = module.exports.methodInfoBasicPublish = { +var methodInfoBasicPublish = (module.exports.methodInfoBasicPublish = { id: 3932200, classId: 60, methodId: 40, - name: "BasicPublish", - args: [ { - type: "short", - name: "ticket", - default: 0 - }, { - type: "shortstr", - name: "exchange", - default: "" - }, { - type: "shortstr", - name: "routingKey", - default: "" - }, { - type: "bit", - name: "mandatory", - default: !1 - }, { - type: "bit", - name: "immediate", - default: !1 - } ] -}; + name: 'BasicPublish', + args: [ + { + type: 'short', + name: 'ticket', + default: 0, + }, + { + type: 'shortstr', + name: 'exchange', + default: '', + }, + { + type: 'shortstr', + name: 'routingKey', + default: '', + }, + { + type: 'bit', + name: 'mandatory', + default: !1, + }, + { + type: 'bit', + name: 'immediate', + default: !1, + }, + ], +}); module.exports.BasicReturn = 3932210; -var methodInfoBasicReturn = module.exports.methodInfoBasicReturn = { +var methodInfoBasicReturn = (module.exports.methodInfoBasicReturn = { id: 3932210, classId: 60, methodId: 50, - name: "BasicReturn", - args: [ { - type: "short", - name: "replyCode" - }, { - type: "shortstr", - name: "replyText", - default: "" - }, { - type: "shortstr", - name: "exchange" - }, { - type: "shortstr", - name: "routingKey" - } ] -}; + name: 'BasicReturn', + args: [ + { + type: 'short', + name: 'replyCode', + }, + { + type: 'shortstr', + name: 'replyText', + default: '', + }, + { + type: 'shortstr', + name: 'exchange', + }, + { + type: 'shortstr', + name: 'routingKey', + }, + ], +}); module.exports.BasicDeliver = 3932220; -var methodInfoBasicDeliver = module.exports.methodInfoBasicDeliver = { +var methodInfoBasicDeliver = (module.exports.methodInfoBasicDeliver = { id: 3932220, classId: 60, methodId: 60, - name: "BasicDeliver", - args: [ { - type: "shortstr", - name: "consumerTag" - }, { - type: "longlong", - name: "deliveryTag" - }, { - type: "bit", - name: "redelivered", - default: !1 - }, { - type: "shortstr", - name: "exchange" - }, { - type: "shortstr", - name: "routingKey" - } ] -}; + name: 'BasicDeliver', + args: [ + { + type: 'shortstr', + name: 'consumerTag', + }, + { + type: 'longlong', + name: 'deliveryTag', + }, + { + type: 'bit', + name: 'redelivered', + default: !1, + }, + { + type: 'shortstr', + name: 'exchange', + }, + { + type: 'shortstr', + name: 'routingKey', + }, + ], +}); module.exports.BasicGet = 3932230; -var methodInfoBasicGet = module.exports.methodInfoBasicGet = { +var methodInfoBasicGet = (module.exports.methodInfoBasicGet = { id: 3932230, classId: 60, methodId: 70, - name: "BasicGet", - args: [ { - type: "short", - name: "ticket", - default: 0 - }, { - type: "shortstr", - name: "queue", - default: "" - }, { - type: "bit", - name: "noAck", - default: !1 - } ] -}; + name: 'BasicGet', + args: [ + { + type: 'short', + name: 'ticket', + default: 0, + }, + { + type: 'shortstr', + name: 'queue', + default: '', + }, + { + type: 'bit', + name: 'noAck', + default: !1, + }, + ], +}); module.exports.BasicGetOk = 3932231; -var methodInfoBasicGetOk = module.exports.methodInfoBasicGetOk = { +var methodInfoBasicGetOk = (module.exports.methodInfoBasicGetOk = { id: 3932231, classId: 60, methodId: 71, - name: "BasicGetOk", - args: [ { - type: "longlong", - name: "deliveryTag" - }, { - type: "bit", - name: "redelivered", - default: !1 - }, { - type: "shortstr", - name: "exchange" - }, { - type: "shortstr", - name: "routingKey" - }, { - type: "long", - name: "messageCount" - } ] -}; + name: 'BasicGetOk', + args: [ + { + type: 'longlong', + name: 'deliveryTag', + }, + { + type: 'bit', + name: 'redelivered', + default: !1, + }, + { + type: 'shortstr', + name: 'exchange', + }, + { + type: 'shortstr', + name: 'routingKey', + }, + { + type: 'long', + name: 'messageCount', + }, + ], +}); module.exports.BasicGetEmpty = 3932232; -var methodInfoBasicGetEmpty = module.exports.methodInfoBasicGetEmpty = { +var methodInfoBasicGetEmpty = (module.exports.methodInfoBasicGetEmpty = { id: 3932232, classId: 60, methodId: 72, - name: "BasicGetEmpty", - args: [ { - type: "shortstr", - name: "clusterId", - default: "" - } ] -}; + name: 'BasicGetEmpty', + args: [ + { + type: 'shortstr', + name: 'clusterId', + default: '', + }, + ], +}); module.exports.BasicAck = 3932240; -var methodInfoBasicAck = module.exports.methodInfoBasicAck = { +var methodInfoBasicAck = (module.exports.methodInfoBasicAck = { id: 3932240, classId: 60, methodId: 80, - name: "BasicAck", - args: [ { - type: "longlong", - name: "deliveryTag", - default: 0 - }, { - type: "bit", - name: "multiple", - default: !1 - } ] -}; + name: 'BasicAck', + args: [ + { + type: 'longlong', + name: 'deliveryTag', + default: 0, + }, + { + type: 'bit', + name: 'multiple', + default: !1, + }, + ], +}); module.exports.BasicReject = 3932250; -var methodInfoBasicReject = module.exports.methodInfoBasicReject = { +var methodInfoBasicReject = (module.exports.methodInfoBasicReject = { id: 3932250, classId: 60, methodId: 90, - name: "BasicReject", - args: [ { - type: "longlong", - name: "deliveryTag" - }, { - type: "bit", - name: "requeue", - default: !0 - } ] -}; + name: 'BasicReject', + args: [ + { + type: 'longlong', + name: 'deliveryTag', + }, + { + type: 'bit', + name: 'requeue', + default: !0, + }, + ], +}); module.exports.BasicRecoverAsync = 3932260; -var methodInfoBasicRecoverAsync = module.exports.methodInfoBasicRecoverAsync = { +var methodInfoBasicRecoverAsync = (module.exports.methodInfoBasicRecoverAsync = { id: 3932260, classId: 60, methodId: 100, - name: "BasicRecoverAsync", - args: [ { - type: "bit", - name: "requeue", - default: !1 - } ] -}; + name: 'BasicRecoverAsync', + args: [ + { + type: 'bit', + name: 'requeue', + default: !1, + }, + ], +}); module.exports.BasicRecover = 3932270; -var methodInfoBasicRecover = module.exports.methodInfoBasicRecover = { +var methodInfoBasicRecover = (module.exports.methodInfoBasicRecover = { id: 3932270, classId: 60, methodId: 110, - name: "BasicRecover", - args: [ { - type: "bit", - name: "requeue", - default: !1 - } ] -}; + name: 'BasicRecover', + args: [ + { + type: 'bit', + name: 'requeue', + default: !1, + }, + ], +}); module.exports.BasicRecoverOk = 3932271; -var methodInfoBasicRecoverOk = module.exports.methodInfoBasicRecoverOk = { +var methodInfoBasicRecoverOk = (module.exports.methodInfoBasicRecoverOk = { id: 3932271, classId: 60, methodId: 111, - name: "BasicRecoverOk", - args: [] -}; + name: 'BasicRecoverOk', + args: [], +}); module.exports.BasicNack = 3932280; -var methodInfoBasicNack = module.exports.methodInfoBasicNack = { +var methodInfoBasicNack = (module.exports.methodInfoBasicNack = { id: 3932280, classId: 60, methodId: 120, - name: "BasicNack", - args: [ { - type: "longlong", - name: "deliveryTag", - default: 0 - }, { - type: "bit", - name: "multiple", - default: !1 - }, { - type: "bit", - name: "requeue", - default: !0 - } ] -}; + name: 'BasicNack', + args: [ + { + type: 'longlong', + name: 'deliveryTag', + default: 0, + }, + { + type: 'bit', + name: 'multiple', + default: !1, + }, + { + type: 'bit', + name: 'requeue', + default: !0, + }, + ], +}); module.exports.ConnectionStart = 655370; -var methodInfoConnectionStart = module.exports.methodInfoConnectionStart = { +var methodInfoConnectionStart = (module.exports.methodInfoConnectionStart = { id: 655370, classId: 10, methodId: 10, - name: "ConnectionStart", - args: [ { - type: "octet", - name: "versionMajor", - default: 0 - }, { - type: "octet", - name: "versionMinor", - default: 9 - }, { - type: "table", - name: "serverProperties" - }, { - type: "longstr", - name: "mechanisms", - default: "PLAIN" - }, { - type: "longstr", - name: "locales", - default: "en_US" - } ] -}; + name: 'ConnectionStart', + args: [ + { + type: 'octet', + name: 'versionMajor', + default: 0, + }, + { + type: 'octet', + name: 'versionMinor', + default: 9, + }, + { + type: 'table', + name: 'serverProperties', + }, + { + type: 'longstr', + name: 'mechanisms', + default: 'PLAIN', + }, + { + type: 'longstr', + name: 'locales', + default: 'en_US', + }, + ], +}); module.exports.ConnectionStartOk = 655371; -var methodInfoConnectionStartOk = module.exports.methodInfoConnectionStartOk = { +var methodInfoConnectionStartOk = (module.exports.methodInfoConnectionStartOk = { id: 655371, classId: 10, methodId: 11, - name: "ConnectionStartOk", - args: [ { - type: "table", - name: "clientProperties" - }, { - type: "shortstr", - name: "mechanism", - default: "PLAIN" - }, { - type: "longstr", - name: "response" - }, { - type: "shortstr", - name: "locale", - default: "en_US" - } ] -}; + name: 'ConnectionStartOk', + args: [ + { + type: 'table', + name: 'clientProperties', + }, + { + type: 'shortstr', + name: 'mechanism', + default: 'PLAIN', + }, + { + type: 'longstr', + name: 'response', + }, + { + type: 'shortstr', + name: 'locale', + default: 'en_US', + }, + ], +}); module.exports.ConnectionSecure = 655380; -var methodInfoConnectionSecure = module.exports.methodInfoConnectionSecure = { +var methodInfoConnectionSecure = (module.exports.methodInfoConnectionSecure = { id: 655380, classId: 10, methodId: 20, - name: "ConnectionSecure", - args: [ { - type: "longstr", - name: "challenge" - } ] -}; + name: 'ConnectionSecure', + args: [ + { + type: 'longstr', + name: 'challenge', + }, + ], +}); module.exports.ConnectionSecureOk = 655381; -var methodInfoConnectionSecureOk = module.exports.methodInfoConnectionSecureOk = { +var methodInfoConnectionSecureOk = (module.exports.methodInfoConnectionSecureOk = { id: 655381, classId: 10, methodId: 21, - name: "ConnectionSecureOk", - args: [ { - type: "longstr", - name: "response" - } ] -}; + name: 'ConnectionSecureOk', + args: [ + { + type: 'longstr', + name: 'response', + }, + ], +}); module.exports.ConnectionTune = 655390; -var methodInfoConnectionTune = module.exports.methodInfoConnectionTune = { +var methodInfoConnectionTune = (module.exports.methodInfoConnectionTune = { id: 655390, classId: 10, methodId: 30, - name: "ConnectionTune", - args: [ { - type: "short", - name: "channelMax", - default: 0 - }, { - type: "long", - name: "frameMax", - default: 0 - }, { - type: "short", - name: "heartbeat", - default: 0 - } ] -}; + name: 'ConnectionTune', + args: [ + { + type: 'short', + name: 'channelMax', + default: 0, + }, + { + type: 'long', + name: 'frameMax', + default: 0, + }, + { + type: 'short', + name: 'heartbeat', + default: 0, + }, + ], +}); module.exports.ConnectionTuneOk = 655391; -var methodInfoConnectionTuneOk = module.exports.methodInfoConnectionTuneOk = { +var methodInfoConnectionTuneOk = (module.exports.methodInfoConnectionTuneOk = { id: 655391, classId: 10, methodId: 31, - name: "ConnectionTuneOk", - args: [ { - type: "short", - name: "channelMax", - default: 0 - }, { - type: "long", - name: "frameMax", - default: 0 - }, { - type: "short", - name: "heartbeat", - default: 0 - } ] -}; + name: 'ConnectionTuneOk', + args: [ + { + type: 'short', + name: 'channelMax', + default: 0, + }, + { + type: 'long', + name: 'frameMax', + default: 0, + }, + { + type: 'short', + name: 'heartbeat', + default: 0, + }, + ], +}); module.exports.ConnectionOpen = 655400; -var methodInfoConnectionOpen = module.exports.methodInfoConnectionOpen = { +var methodInfoConnectionOpen = (module.exports.methodInfoConnectionOpen = { id: 655400, classId: 10, methodId: 40, - name: "ConnectionOpen", - args: [ { - type: "shortstr", - name: "virtualHost", - default: "/" - }, { - type: "shortstr", - name: "capabilities", - default: "" - }, { - type: "bit", - name: "insist", - default: !1 - } ] -}; + name: 'ConnectionOpen', + args: [ + { + type: 'shortstr', + name: 'virtualHost', + default: '/', + }, + { + type: 'shortstr', + name: 'capabilities', + default: '', + }, + { + type: 'bit', + name: 'insist', + default: !1, + }, + ], +}); module.exports.ConnectionOpenOk = 655401; -var methodInfoConnectionOpenOk = module.exports.methodInfoConnectionOpenOk = { +var methodInfoConnectionOpenOk = (module.exports.methodInfoConnectionOpenOk = { id: 655401, classId: 10, methodId: 41, - name: "ConnectionOpenOk", - args: [ { - type: "shortstr", - name: "knownHosts", - default: "" - } ] -}; + name: 'ConnectionOpenOk', + args: [ + { + type: 'shortstr', + name: 'knownHosts', + default: '', + }, + ], +}); module.exports.ConnectionClose = 655410; -var methodInfoConnectionClose = module.exports.methodInfoConnectionClose = { +var methodInfoConnectionClose = (module.exports.methodInfoConnectionClose = { id: 655410, classId: 10, methodId: 50, - name: "ConnectionClose", - args: [ { - type: "short", - name: "replyCode" - }, { - type: "shortstr", - name: "replyText", - default: "" - }, { - type: "short", - name: "classId" - }, { - type: "short", - name: "methodId" - } ] -}; + name: 'ConnectionClose', + args: [ + { + type: 'short', + name: 'replyCode', + }, + { + type: 'shortstr', + name: 'replyText', + default: '', + }, + { + type: 'short', + name: 'classId', + }, + { + type: 'short', + name: 'methodId', + }, + ], +}); module.exports.ConnectionCloseOk = 655411; -var methodInfoConnectionCloseOk = module.exports.methodInfoConnectionCloseOk = { +var methodInfoConnectionCloseOk = (module.exports.methodInfoConnectionCloseOk = { id: 655411, classId: 10, methodId: 51, - name: "ConnectionCloseOk", - args: [] -}; + name: 'ConnectionCloseOk', + args: [], +}); module.exports.ConnectionBlocked = 655420; -var methodInfoConnectionBlocked = module.exports.methodInfoConnectionBlocked = { +var methodInfoConnectionBlocked = (module.exports.methodInfoConnectionBlocked = { id: 655420, classId: 10, methodId: 60, - name: "ConnectionBlocked", - args: [ { - type: "shortstr", - name: "reason", - default: "" - } ] -}; + name: 'ConnectionBlocked', + args: [ + { + type: 'shortstr', + name: 'reason', + default: '', + }, + ], +}); module.exports.ConnectionUnblocked = 655421; -var methodInfoConnectionUnblocked = module.exports.methodInfoConnectionUnblocked = { +var methodInfoConnectionUnblocked = (module.exports.methodInfoConnectionUnblocked = { id: 655421, classId: 10, methodId: 61, - name: "ConnectionUnblocked", - args: [] -}; + name: 'ConnectionUnblocked', + args: [], +}); module.exports.ConnectionUpdateSecret = 655430; -var methodInfoConnectionUpdateSecret = module.exports.methodInfoConnectionUpdateSecret = { +var methodInfoConnectionUpdateSecret = (module.exports.methodInfoConnectionUpdateSecret = { id: 655430, classId: 10, methodId: 70, - name: "ConnectionUpdateSecret", - args: [ { - type: "longstr", - name: "newSecret" - }, { - type: "shortstr", - name: "reason" - } ] -}; + name: 'ConnectionUpdateSecret', + args: [ + { + type: 'longstr', + name: 'newSecret', + }, + { + type: 'shortstr', + name: 'reason', + }, + ], +}); module.exports.ConnectionUpdateSecretOk = 655431; -var methodInfoConnectionUpdateSecretOk = module.exports.methodInfoConnectionUpdateSecretOk = { +var methodInfoConnectionUpdateSecretOk = (module.exports.methodInfoConnectionUpdateSecretOk = { id: 655431, classId: 10, methodId: 71, - name: "ConnectionUpdateSecretOk", - args: [] -}; + name: 'ConnectionUpdateSecretOk', + args: [], +}); module.exports.ChannelOpen = 1310730; -var methodInfoChannelOpen = module.exports.methodInfoChannelOpen = { +var methodInfoChannelOpen = (module.exports.methodInfoChannelOpen = { id: 1310730, classId: 20, methodId: 10, - name: "ChannelOpen", - args: [ { - type: "shortstr", - name: "outOfBand", - default: "" - } ] -}; + name: 'ChannelOpen', + args: [ + { + type: 'shortstr', + name: 'outOfBand', + default: '', + }, + ], +}); module.exports.ChannelOpenOk = 1310731; -var methodInfoChannelOpenOk = module.exports.methodInfoChannelOpenOk = { +var methodInfoChannelOpenOk = (module.exports.methodInfoChannelOpenOk = { id: 1310731, classId: 20, methodId: 11, - name: "ChannelOpenOk", - args: [ { - type: "longstr", - name: "channelId", - default: "" - } ] -}; + name: 'ChannelOpenOk', + args: [ + { + type: 'longstr', + name: 'channelId', + default: '', + }, + ], +}); module.exports.ChannelFlow = 1310740; -var methodInfoChannelFlow = module.exports.methodInfoChannelFlow = { +var methodInfoChannelFlow = (module.exports.methodInfoChannelFlow = { id: 1310740, classId: 20, methodId: 20, - name: "ChannelFlow", - args: [ { - type: "bit", - name: "active" - } ] -}; + name: 'ChannelFlow', + args: [ + { + type: 'bit', + name: 'active', + }, + ], +}); module.exports.ChannelFlowOk = 1310741; -var methodInfoChannelFlowOk = module.exports.methodInfoChannelFlowOk = { +var methodInfoChannelFlowOk = (module.exports.methodInfoChannelFlowOk = { id: 1310741, classId: 20, methodId: 21, - name: "ChannelFlowOk", - args: [ { - type: "bit", - name: "active" - } ] -}; + name: 'ChannelFlowOk', + args: [ + { + type: 'bit', + name: 'active', + }, + ], +}); module.exports.ChannelClose = 1310760; -var methodInfoChannelClose = module.exports.methodInfoChannelClose = { +var methodInfoChannelClose = (module.exports.methodInfoChannelClose = { id: 1310760, classId: 20, methodId: 40, - name: "ChannelClose", - args: [ { - type: "short", - name: "replyCode" - }, { - type: "shortstr", - name: "replyText", - default: "" - }, { - type: "short", - name: "classId" - }, { - type: "short", - name: "methodId" - } ] -}; + name: 'ChannelClose', + args: [ + { + type: 'short', + name: 'replyCode', + }, + { + type: 'shortstr', + name: 'replyText', + default: '', + }, + { + type: 'short', + name: 'classId', + }, + { + type: 'short', + name: 'methodId', + }, + ], +}); module.exports.ChannelCloseOk = 1310761; -var methodInfoChannelCloseOk = module.exports.methodInfoChannelCloseOk = { +var methodInfoChannelCloseOk = (module.exports.methodInfoChannelCloseOk = { id: 1310761, classId: 20, methodId: 41, - name: "ChannelCloseOk", - args: [] -}; + name: 'ChannelCloseOk', + args: [], +}); module.exports.AccessRequest = 1966090; -var methodInfoAccessRequest = module.exports.methodInfoAccessRequest = { +var methodInfoAccessRequest = (module.exports.methodInfoAccessRequest = { id: 1966090, classId: 30, methodId: 10, - name: "AccessRequest", - args: [ { - type: "shortstr", - name: "realm", - default: "/data" - }, { - type: "bit", - name: "exclusive", - default: !1 - }, { - type: "bit", - name: "passive", - default: !0 - }, { - type: "bit", - name: "active", - default: !0 - }, { - type: "bit", - name: "write", - default: !0 - }, { - type: "bit", - name: "read", - default: !0 - } ] -}; + name: 'AccessRequest', + args: [ + { + type: 'shortstr', + name: 'realm', + default: '/data', + }, + { + type: 'bit', + name: 'exclusive', + default: !1, + }, + { + type: 'bit', + name: 'passive', + default: !0, + }, + { + type: 'bit', + name: 'active', + default: !0, + }, + { + type: 'bit', + name: 'write', + default: !0, + }, + { + type: 'bit', + name: 'read', + default: !0, + }, + ], +}); module.exports.AccessRequestOk = 1966091; -var methodInfoAccessRequestOk = module.exports.methodInfoAccessRequestOk = { +var methodInfoAccessRequestOk = (module.exports.methodInfoAccessRequestOk = { id: 1966091, classId: 30, methodId: 11, - name: "AccessRequestOk", - args: [ { - type: "short", - name: "ticket", - default: 1 - } ] -}; + name: 'AccessRequestOk', + args: [ + { + type: 'short', + name: 'ticket', + default: 1, + }, + ], +}); module.exports.ExchangeDeclare = 2621450; -var methodInfoExchangeDeclare = module.exports.methodInfoExchangeDeclare = { +var methodInfoExchangeDeclare = (module.exports.methodInfoExchangeDeclare = { id: 2621450, classId: 40, methodId: 10, - name: "ExchangeDeclare", - args: [ { - type: "short", - name: "ticket", - default: 0 - }, { - type: "shortstr", - name: "exchange" - }, { - type: "shortstr", - name: "type", - default: "direct" - }, { - type: "bit", - name: "passive", - default: !1 - }, { - type: "bit", - name: "durable", - default: !1 - }, { - type: "bit", - name: "autoDelete", - default: !1 - }, { - type: "bit", - name: "internal", - default: !1 - }, { - type: "bit", - name: "nowait", - default: !1 - }, { - type: "table", - name: "arguments", - default: {} - } ] -}; + name: 'ExchangeDeclare', + args: [ + { + type: 'short', + name: 'ticket', + default: 0, + }, + { + type: 'shortstr', + name: 'exchange', + }, + { + type: 'shortstr', + name: 'type', + default: 'direct', + }, + { + type: 'bit', + name: 'passive', + default: !1, + }, + { + type: 'bit', + name: 'durable', + default: !1, + }, + { + type: 'bit', + name: 'autoDelete', + default: !1, + }, + { + type: 'bit', + name: 'internal', + default: !1, + }, + { + type: 'bit', + name: 'nowait', + default: !1, + }, + { + type: 'table', + name: 'arguments', + default: {}, + }, + ], +}); module.exports.ExchangeDeclareOk = 2621451; -var methodInfoExchangeDeclareOk = module.exports.methodInfoExchangeDeclareOk = { +var methodInfoExchangeDeclareOk = (module.exports.methodInfoExchangeDeclareOk = { id: 2621451, classId: 40, methodId: 11, - name: "ExchangeDeclareOk", - args: [] -}; + name: 'ExchangeDeclareOk', + args: [], +}); module.exports.ExchangeDelete = 2621460; -var methodInfoExchangeDelete = module.exports.methodInfoExchangeDelete = { +var methodInfoExchangeDelete = (module.exports.methodInfoExchangeDelete = { id: 2621460, classId: 40, methodId: 20, - name: "ExchangeDelete", - args: [ { - type: "short", - name: "ticket", - default: 0 - }, { - type: "shortstr", - name: "exchange" - }, { - type: "bit", - name: "ifUnused", - default: !1 - }, { - type: "bit", - name: "nowait", - default: !1 - } ] -}; + name: 'ExchangeDelete', + args: [ + { + type: 'short', + name: 'ticket', + default: 0, + }, + { + type: 'shortstr', + name: 'exchange', + }, + { + type: 'bit', + name: 'ifUnused', + default: !1, + }, + { + type: 'bit', + name: 'nowait', + default: !1, + }, + ], +}); module.exports.ExchangeDeleteOk = 2621461; -var methodInfoExchangeDeleteOk = module.exports.methodInfoExchangeDeleteOk = { +var methodInfoExchangeDeleteOk = (module.exports.methodInfoExchangeDeleteOk = { id: 2621461, classId: 40, methodId: 21, - name: "ExchangeDeleteOk", - args: [] -}; + name: 'ExchangeDeleteOk', + args: [], +}); module.exports.ExchangeBind = 2621470; -var methodInfoExchangeBind = module.exports.methodInfoExchangeBind = { +var methodInfoExchangeBind = (module.exports.methodInfoExchangeBind = { id: 2621470, classId: 40, methodId: 30, - name: "ExchangeBind", - args: [ { - type: "short", - name: "ticket", - default: 0 - }, { - type: "shortstr", - name: "destination" - }, { - type: "shortstr", - name: "source" - }, { - type: "shortstr", - name: "routingKey", - default: "" - }, { - type: "bit", - name: "nowait", - default: !1 - }, { - type: "table", - name: "arguments", - default: {} - } ] -}; + name: 'ExchangeBind', + args: [ + { + type: 'short', + name: 'ticket', + default: 0, + }, + { + type: 'shortstr', + name: 'destination', + }, + { + type: 'shortstr', + name: 'source', + }, + { + type: 'shortstr', + name: 'routingKey', + default: '', + }, + { + type: 'bit', + name: 'nowait', + default: !1, + }, + { + type: 'table', + name: 'arguments', + default: {}, + }, + ], +}); module.exports.ExchangeBindOk = 2621471; -var methodInfoExchangeBindOk = module.exports.methodInfoExchangeBindOk = { +var methodInfoExchangeBindOk = (module.exports.methodInfoExchangeBindOk = { id: 2621471, classId: 40, methodId: 31, - name: "ExchangeBindOk", - args: [] -}; + name: 'ExchangeBindOk', + args: [], +}); module.exports.ExchangeUnbind = 2621480; -var methodInfoExchangeUnbind = module.exports.methodInfoExchangeUnbind = { +var methodInfoExchangeUnbind = (module.exports.methodInfoExchangeUnbind = { id: 2621480, classId: 40, methodId: 40, - name: "ExchangeUnbind", - args: [ { - type: "short", - name: "ticket", - default: 0 - }, { - type: "shortstr", - name: "destination" - }, { - type: "shortstr", - name: "source" - }, { - type: "shortstr", - name: "routingKey", - default: "" - }, { - type: "bit", - name: "nowait", - default: !1 - }, { - type: "table", - name: "arguments", - default: {} - } ] -}; + name: 'ExchangeUnbind', + args: [ + { + type: 'short', + name: 'ticket', + default: 0, + }, + { + type: 'shortstr', + name: 'destination', + }, + { + type: 'shortstr', + name: 'source', + }, + { + type: 'shortstr', + name: 'routingKey', + default: '', + }, + { + type: 'bit', + name: 'nowait', + default: !1, + }, + { + type: 'table', + name: 'arguments', + default: {}, + }, + ], +}); module.exports.ExchangeUnbindOk = 2621491; -var methodInfoExchangeUnbindOk = module.exports.methodInfoExchangeUnbindOk = { +var methodInfoExchangeUnbindOk = (module.exports.methodInfoExchangeUnbindOk = { id: 2621491, classId: 40, methodId: 51, - name: "ExchangeUnbindOk", - args: [] -}; + name: 'ExchangeUnbindOk', + args: [], +}); module.exports.QueueDeclare = 3276810; -var methodInfoQueueDeclare = module.exports.methodInfoQueueDeclare = { +var methodInfoQueueDeclare = (module.exports.methodInfoQueueDeclare = { id: 3276810, classId: 50, methodId: 10, - name: "QueueDeclare", - args: [ { - type: "short", - name: "ticket", - default: 0 - }, { - type: "shortstr", - name: "queue", - default: "" - }, { - type: "bit", - name: "passive", - default: !1 - }, { - type: "bit", - name: "durable", - default: !1 - }, { - type: "bit", - name: "exclusive", - default: !1 - }, { - type: "bit", - name: "autoDelete", - default: !1 - }, { - type: "bit", - name: "nowait", - default: !1 - }, { - type: "table", - name: "arguments", - default: {} - } ] -}; + name: 'QueueDeclare', + args: [ + { + type: 'short', + name: 'ticket', + default: 0, + }, + { + type: 'shortstr', + name: 'queue', + default: '', + }, + { + type: 'bit', + name: 'passive', + default: !1, + }, + { + type: 'bit', + name: 'durable', + default: !1, + }, + { + type: 'bit', + name: 'exclusive', + default: !1, + }, + { + type: 'bit', + name: 'autoDelete', + default: !1, + }, + { + type: 'bit', + name: 'nowait', + default: !1, + }, + { + type: 'table', + name: 'arguments', + default: {}, + }, + ], +}); module.exports.QueueDeclareOk = 3276811; -var methodInfoQueueDeclareOk = module.exports.methodInfoQueueDeclareOk = { +var methodInfoQueueDeclareOk = (module.exports.methodInfoQueueDeclareOk = { id: 3276811, classId: 50, methodId: 11, - name: "QueueDeclareOk", - args: [ { - type: "shortstr", - name: "queue" - }, { - type: "long", - name: "messageCount" - }, { - type: "long", - name: "consumerCount" - } ] -}; + name: 'QueueDeclareOk', + args: [ + { + type: 'shortstr', + name: 'queue', + }, + { + type: 'long', + name: 'messageCount', + }, + { + type: 'long', + name: 'consumerCount', + }, + ], +}); module.exports.QueueBind = 3276820; -var methodInfoQueueBind = module.exports.methodInfoQueueBind = { +var methodInfoQueueBind = (module.exports.methodInfoQueueBind = { id: 3276820, classId: 50, methodId: 20, - name: "QueueBind", - args: [ { - type: "short", - name: "ticket", - default: 0 - }, { - type: "shortstr", - name: "queue", - default: "" - }, { - type: "shortstr", - name: "exchange" - }, { - type: "shortstr", - name: "routingKey", - default: "" - }, { - type: "bit", - name: "nowait", - default: !1 - }, { - type: "table", - name: "arguments", - default: {} - } ] -}; + name: 'QueueBind', + args: [ + { + type: 'short', + name: 'ticket', + default: 0, + }, + { + type: 'shortstr', + name: 'queue', + default: '', + }, + { + type: 'shortstr', + name: 'exchange', + }, + { + type: 'shortstr', + name: 'routingKey', + default: '', + }, + { + type: 'bit', + name: 'nowait', + default: !1, + }, + { + type: 'table', + name: 'arguments', + default: {}, + }, + ], +}); module.exports.QueueBindOk = 3276821; -var methodInfoQueueBindOk = module.exports.methodInfoQueueBindOk = { +var methodInfoQueueBindOk = (module.exports.methodInfoQueueBindOk = { id: 3276821, classId: 50, methodId: 21, - name: "QueueBindOk", - args: [] -}; + name: 'QueueBindOk', + args: [], +}); module.exports.QueuePurge = 3276830; -var methodInfoQueuePurge = module.exports.methodInfoQueuePurge = { +var methodInfoQueuePurge = (module.exports.methodInfoQueuePurge = { id: 3276830, classId: 50, methodId: 30, - name: "QueuePurge", - args: [ { - type: "short", - name: "ticket", - default: 0 - }, { - type: "shortstr", - name: "queue", - default: "" - }, { - type: "bit", - name: "nowait", - default: !1 - } ] -}; + name: 'QueuePurge', + args: [ + { + type: 'short', + name: 'ticket', + default: 0, + }, + { + type: 'shortstr', + name: 'queue', + default: '', + }, + { + type: 'bit', + name: 'nowait', + default: !1, + }, + ], +}); module.exports.QueuePurgeOk = 3276831; -var methodInfoQueuePurgeOk = module.exports.methodInfoQueuePurgeOk = { +var methodInfoQueuePurgeOk = (module.exports.methodInfoQueuePurgeOk = { id: 3276831, classId: 50, methodId: 31, - name: "QueuePurgeOk", - args: [ { - type: "long", - name: "messageCount" - } ] -}; + name: 'QueuePurgeOk', + args: [ + { + type: 'long', + name: 'messageCount', + }, + ], +}); module.exports.QueueDelete = 3276840; -var methodInfoQueueDelete = module.exports.methodInfoQueueDelete = { +var methodInfoQueueDelete = (module.exports.methodInfoQueueDelete = { id: 3276840, classId: 50, methodId: 40, - name: "QueueDelete", - args: [ { - type: "short", - name: "ticket", - default: 0 - }, { - type: "shortstr", - name: "queue", - default: "" - }, { - type: "bit", - name: "ifUnused", - default: !1 - }, { - type: "bit", - name: "ifEmpty", - default: !1 - }, { - type: "bit", - name: "nowait", - default: !1 - } ] -}; + name: 'QueueDelete', + args: [ + { + type: 'short', + name: 'ticket', + default: 0, + }, + { + type: 'shortstr', + name: 'queue', + default: '', + }, + { + type: 'bit', + name: 'ifUnused', + default: !1, + }, + { + type: 'bit', + name: 'ifEmpty', + default: !1, + }, + { + type: 'bit', + name: 'nowait', + default: !1, + }, + ], +}); module.exports.QueueDeleteOk = 3276841; -var methodInfoQueueDeleteOk = module.exports.methodInfoQueueDeleteOk = { +var methodInfoQueueDeleteOk = (module.exports.methodInfoQueueDeleteOk = { id: 3276841, classId: 50, methodId: 41, - name: "QueueDeleteOk", - args: [ { - type: "long", - name: "messageCount" - } ] -}; + name: 'QueueDeleteOk', + args: [ + { + type: 'long', + name: 'messageCount', + }, + ], +}); module.exports.QueueUnbind = 3276850; -var methodInfoQueueUnbind = module.exports.methodInfoQueueUnbind = { +var methodInfoQueueUnbind = (module.exports.methodInfoQueueUnbind = { id: 3276850, classId: 50, methodId: 50, - name: "QueueUnbind", - args: [ { - type: "short", - name: "ticket", - default: 0 - }, { - type: "shortstr", - name: "queue", - default: "" - }, { - type: "shortstr", - name: "exchange" - }, { - type: "shortstr", - name: "routingKey", - default: "" - }, { - type: "table", - name: "arguments", - default: {} - } ] -}; + name: 'QueueUnbind', + args: [ + { + type: 'short', + name: 'ticket', + default: 0, + }, + { + type: 'shortstr', + name: 'queue', + default: '', + }, + { + type: 'shortstr', + name: 'exchange', + }, + { + type: 'shortstr', + name: 'routingKey', + default: '', + }, + { + type: 'table', + name: 'arguments', + default: {}, + }, + ], +}); module.exports.QueueUnbindOk = 3276851; -var methodInfoQueueUnbindOk = module.exports.methodInfoQueueUnbindOk = { +var methodInfoQueueUnbindOk = (module.exports.methodInfoQueueUnbindOk = { id: 3276851, classId: 50, methodId: 51, - name: "QueueUnbindOk", - args: [] -}; + name: 'QueueUnbindOk', + args: [], +}); module.exports.TxSelect = 5898250; -var methodInfoTxSelect = module.exports.methodInfoTxSelect = { +var methodInfoTxSelect = (module.exports.methodInfoTxSelect = { id: 5898250, classId: 90, methodId: 10, - name: "TxSelect", - args: [] -}; + name: 'TxSelect', + args: [], +}); module.exports.TxSelectOk = 5898251; -var methodInfoTxSelectOk = module.exports.methodInfoTxSelectOk = { +var methodInfoTxSelectOk = (module.exports.methodInfoTxSelectOk = { id: 5898251, classId: 90, methodId: 11, - name: "TxSelectOk", - args: [] -}; + name: 'TxSelectOk', + args: [], +}); module.exports.TxCommit = 5898260; -var methodInfoTxCommit = module.exports.methodInfoTxCommit = { +var methodInfoTxCommit = (module.exports.methodInfoTxCommit = { id: 5898260, classId: 90, methodId: 20, - name: "TxCommit", - args: [] -}; + name: 'TxCommit', + args: [], +}); module.exports.TxCommitOk = 5898261; -var methodInfoTxCommitOk = module.exports.methodInfoTxCommitOk = { +var methodInfoTxCommitOk = (module.exports.methodInfoTxCommitOk = { id: 5898261, classId: 90, methodId: 21, - name: "TxCommitOk", - args: [] -}; + name: 'TxCommitOk', + args: [], +}); module.exports.TxRollback = 5898270; -var methodInfoTxRollback = module.exports.methodInfoTxRollback = { +var methodInfoTxRollback = (module.exports.methodInfoTxRollback = { id: 5898270, classId: 90, methodId: 30, - name: "TxRollback", - args: [] -}; + name: 'TxRollback', + args: [], +}); module.exports.TxRollbackOk = 5898271; -var methodInfoTxRollbackOk = module.exports.methodInfoTxRollbackOk = { +var methodInfoTxRollbackOk = (module.exports.methodInfoTxRollbackOk = { id: 5898271, classId: 90, methodId: 31, - name: "TxRollbackOk", - args: [] -}; + name: 'TxRollbackOk', + args: [], +}); module.exports.ConfirmSelect = 5570570; -var methodInfoConfirmSelect = module.exports.methodInfoConfirmSelect = { +var methodInfoConfirmSelect = (module.exports.methodInfoConfirmSelect = { id: 5570570, classId: 85, methodId: 10, - name: "ConfirmSelect", - args: [ { - type: "bit", - name: "nowait", - default: !1 - } ] -}; + name: 'ConfirmSelect', + args: [ + { + type: 'bit', + name: 'nowait', + default: !1, + }, + ], +}); module.exports.ConfirmSelectOk = 5570571; -var methodInfoConfirmSelectOk = module.exports.methodInfoConfirmSelectOk = { +var methodInfoConfirmSelectOk = (module.exports.methodInfoConfirmSelectOk = { id: 5570571, classId: 85, methodId: 11, - name: "ConfirmSelectOk", - args: [] -}; + name: 'ConfirmSelectOk', + args: [], +}); module.exports.BasicProperties = 60; -var propertiesInfoBasicProperties = module.exports.propertiesInfoBasicProperties = { +var propertiesInfoBasicProperties = (module.exports.propertiesInfoBasicProperties = { id: 60, - name: "BasicProperties", - args: [ { - type: "shortstr", - name: "contentType" - }, { - type: "shortstr", - name: "contentEncoding" - }, { - type: "table", - name: "headers" - }, { - type: "octet", - name: "deliveryMode" - }, { - type: "octet", - name: "priority" - }, { - type: "shortstr", - name: "correlationId" - }, { - type: "shortstr", - name: "replyTo" - }, { - type: "shortstr", - name: "expiration" - }, { - type: "shortstr", - name: "messageId" - }, { - type: "timestamp", - name: "timestamp" - }, { - type: "shortstr", - name: "type" - }, { - type: "shortstr", - name: "userId" - }, { - type: "shortstr", - name: "appId" - }, { - type: "shortstr", - name: "clusterId" - } ] -}; \ No newline at end of file + name: 'BasicProperties', + args: [ + { + type: 'shortstr', + name: 'contentType', + }, + { + type: 'shortstr', + name: 'contentEncoding', + }, + { + type: 'table', + name: 'headers', + }, + { + type: 'octet', + name: 'deliveryMode', + }, + { + type: 'octet', + name: 'priority', + }, + { + type: 'shortstr', + name: 'correlationId', + }, + { + type: 'shortstr', + name: 'replyTo', + }, + { + type: 'shortstr', + name: 'expiration', + }, + { + type: 'shortstr', + name: 'messageId', + }, + { + type: 'timestamp', + name: 'timestamp', + }, + { + type: 'shortstr', + name: 'type', + }, + { + type: 'shortstr', + name: 'userId', + }, + { + type: 'shortstr', + name: 'appId', + }, + { + type: 'shortstr', + name: 'clusterId', + }, + ], +}); diff --git a/lib/error.js b/lib/error.js index 02c49030..438d483d 100644 --- a/lib/error.js +++ b/lib/error.js @@ -16,8 +16,7 @@ IllegalOperationError.prototype.name = 'IllegalOperationError'; function stackCapture(reason) { var e = new Error(); - return 'Stack capture: ' + reason + '\n' + - trimStack(e.stack, 2); + return 'Stack capture: ' + reason + '\n' + trimStack(e.stack, 2); } module.exports.IllegalOperationError = IllegalOperationError; diff --git a/lib/format.js b/lib/format.js index f9fcc3d0..7abc3436 100644 --- a/lib/format.js +++ b/lib/format.js @@ -10,30 +10,22 @@ var defs = require('./defs'); var format = require('util').format; var HEARTBEAT = require('./frame').HEARTBEAT; -module.exports.closeMessage = function(close) { +module.exports.closeMessage = function (close) { var code = close.fields.replyCode; - return format('%d (%s) with message "%s"', - code, defs.constant_strs[code], - close.fields.replyText); -} + return format('%d (%s) with message "%s"', code, defs.constant_strs[code], close.fields.replyText); +}; -module.exports.methodName = function(id) { +module.exports.methodName = function (id) { return defs.info(id).name; }; -module.exports.inspect = function(frame, showFields) { +module.exports.inspect = function (frame, showFields) { if (frame === HEARTBEAT) { return ''; - } - else if (!frame.id) { - return format('', - frame.channel, frame.size); - } - else { + } else if (!frame.id) { + return format('', frame.channel, frame.size); + } else { var info = defs.info(frame.id); - return format('<%s channel:%d%s>', info.name, frame.channel, - (showFields) - ? ' ' + JSON.stringify(frame.fields, undefined, 2) - : ''); + return format('<%s channel:%d%s>', info.name, frame.channel, showFields ? ' ' + JSON.stringify(frame.fields, undefined, 2) : ''); } -} +}; diff --git a/lib/frame.js b/lib/frame.js index 9989a037..4fafeb32 100644 --- a/lib/frame.js +++ b/lib/frame.js @@ -4,12 +4,12 @@ 'use strict'; -const ints = require('buffer-more-ints') +const ints = require('buffer-more-ints'); var defs = require('./defs'); var constants = defs.constants; var decode = defs.decode; -module.exports.PROTOCOL_HEADER = "AMQP" + String.fromCharCode(0, 0, 9, 1); +module.exports.PROTOCOL_HEADER = 'AMQP' + String.fromCharCode(0, 0, 9, 1); /* Frame format: @@ -27,17 +27,17 @@ module.exports.PROTOCOL_HEADER = "AMQP" + String.fromCharCode(0, 0, 9, 1); // framing constants var FRAME_METHOD = constants.FRAME_METHOD, -FRAME_HEARTBEAT = constants.FRAME_HEARTBEAT, -FRAME_HEADER = constants.FRAME_HEADER, -FRAME_BODY = constants.FRAME_BODY, -FRAME_END = constants.FRAME_END; + FRAME_HEARTBEAT = constants.FRAME_HEARTBEAT, + FRAME_HEADER = constants.FRAME_HEADER, + FRAME_BODY = constants.FRAME_BODY, + FRAME_END = constants.FRAME_END; // expected byte sizes for frame parts -const TYPE_BYTES = 1 -const CHANNEL_BYTES = 2 -const SIZE_BYTES = 4 -const FRAME_HEADER_BYTES = TYPE_BYTES + CHANNEL_BYTES + SIZE_BYTES -const FRAME_END_BYTES = 1 +const TYPE_BYTES = 1; +const CHANNEL_BYTES = 2; +const SIZE_BYTES = 4; +const FRAME_HEADER_BYTES = TYPE_BYTES + CHANNEL_BYTES + SIZE_BYTES; +const FRAME_END_BYTES = 1; /** * @typedef {{ @@ -61,10 +61,10 @@ function readInt64BE(buffer, offset) { * buffer-more-ints does not */ if (typeof Buffer.prototype.readBigInt64BE === 'function') { - return Number(buffer.readBigInt64BE(offset)) + return Number(buffer.readBigInt64BE(offset)); } - return ints.readInt64BE(buffer, offset) + return ints.readInt64BE(buffer, offset); } // %%% TESTME possibly better to cons the first bit and write the @@ -75,22 +75,22 @@ function readInt64BE(buffer, offset) { * @arg { Buffer } payload */ module.exports.makeBodyFrame = function (channel, payload) { - const frameSize = FRAME_HEADER_BYTES + payload.length + FRAME_END_BYTES + const frameSize = FRAME_HEADER_BYTES + payload.length + FRAME_END_BYTES; - const frame = Buffer.alloc(frameSize) + const frame = Buffer.alloc(frameSize); - let offset = 0 + let offset = 0; - offset = frame.writeUInt8(FRAME_BODY, offset) - offset = frame.writeUInt16BE(channel, offset) - offset = frame.writeInt32BE(payload.length, offset) + offset = frame.writeUInt8(FRAME_BODY, offset); + offset = frame.writeUInt16BE(channel, offset); + offset = frame.writeInt32BE(payload.length, offset); - payload.copy(frame, offset) - offset += payload.length + payload.copy(frame, offset); + offset += payload.length; - frame.writeUInt8(FRAME_END, offset) + frame.writeUInt8(FRAME_END, offset); - return frame + return frame; }; /** @@ -101,23 +101,23 @@ module.exports.makeBodyFrame = function (channel, payload) { */ function parseFrame(bin) { if (bin.length < FRAME_HEADER_BYTES) { - return false + return false; } - const type = bin.readUInt8(0) - const channel = bin.readUInt16BE(1) - const size = bin.readUInt32BE(3) + const type = bin.readUInt8(0); + const channel = bin.readUInt16BE(1); + const size = bin.readUInt32BE(3); - const totalSize = FRAME_HEADER_BYTES + size + FRAME_END_BYTES + const totalSize = FRAME_HEADER_BYTES + size + FRAME_END_BYTES; if (bin.length < totalSize) { - return false + return false; } - const frameEnd = bin.readUInt8(FRAME_HEADER_BYTES + size) + const frameEnd = bin.readUInt8(FRAME_HEADER_BYTES + size); if (frameEnd !== FRAME_END) { - throw new Error('Invalid frame') + throw new Error('Invalid frame'); } return { @@ -125,8 +125,8 @@ function parseFrame(bin) { channel, size, payload: bin.subarray(FRAME_HEADER_BYTES, FRAME_HEADER_BYTES + size), - rest: bin.subarray(totalSize) - } + rest: bin.subarray(totalSize), + }; } module.exports.parseFrame = parseFrame; @@ -139,37 +139,43 @@ var HEARTBEAT = {channel: 0}; * @returns */ module.exports.decodeFrame = (frame) => { - const payload = frame.payload - const channel = frame.channel + const payload = frame.payload; + const channel = frame.channel; switch (frame.type) { case FRAME_METHOD: { - const id = payload.readUInt32BE(0) - const args = payload.subarray(4) - const fields = decode(id, args) - return { id, channel, fields } + const id = payload.readUInt32BE(0); + const args = payload.subarray(4); + const fields = decode(id, args); + return {id, channel, fields}; } case FRAME_HEADER: { - const id = payload.readUInt16BE(0) + const id = payload.readUInt16BE(0); // const weight = payload.readUInt16BE(2) - const size = readInt64BE(payload, 4) - const flagsAndfields = payload.subarray(12) - const fields = decode(id, flagsAndfields) - return { id, channel, size, fields } + const size = readInt64BE(payload, 4); + const flagsAndfields = payload.subarray(12); + const fields = decode(id, flagsAndfields); + return {id, channel, size, fields}; } case FRAME_BODY: - return { channel, content: payload } + return {channel, content: payload}; case FRAME_HEARTBEAT: - return HEARTBEAT + return HEARTBEAT; default: - throw new Error('Unknown frame type ' + frame.type) + throw new Error('Unknown frame type ' + frame.type); } -} +}; // encoded heartbeat -module.exports.HEARTBEAT_BUF = Buffer.from([constants.FRAME_HEARTBEAT, - 0, 0, 0, 0, // size = 0 - 0, 0, // channel = 0 - constants.FRAME_END]); - -module.exports.HEARTBEAT = HEARTBEAT; \ No newline at end of file +module.exports.HEARTBEAT_BUF = Buffer.from([ + constants.FRAME_HEARTBEAT, + 0, + 0, + 0, + 0, // size = 0 + 0, + 0, // channel = 0 + constants.FRAME_END, +]); + +module.exports.HEARTBEAT = HEARTBEAT; diff --git a/lib/heartbeat.js b/lib/heartbeat.js index e5f373ab..98a98717 100644 --- a/lib/heartbeat.js +++ b/lib/heartbeat.js @@ -53,7 +53,7 @@ var EventEmitter = require('events'); module.exports.UNITS_TO_MS = 1000; class Heart extends EventEmitter { - constructor (interval, checkSend, checkRecv) { + constructor(interval, checkSend, checkRecv) { super(); this.interval = interval; @@ -63,29 +63,28 @@ class Heart extends EventEmitter { var beat = this.emit.bind(this, 'beat'); var timeout = this.emit.bind(this, 'timeout'); - this.sendTimer = setInterval( - this.runHeartbeat.bind(this, checkSend, beat), intervalMs / 2); + this.sendTimer = setInterval(this.runHeartbeat.bind(this, checkSend, beat), intervalMs / 2); // A timeout occurs if I see nothing for *two consecutive* intervals var recvMissed = 0; - function missedTwo () { - if (!checkRecv()) - return (++recvMissed < 2); - else { recvMissed = 0; return true; } + function missedTwo() { + if (!checkRecv()) return ++recvMissed < 2; + else { + recvMissed = 0; + return true; + } } - this.recvTimer = setInterval( - this.runHeartbeat.bind(this, missedTwo, timeout), intervalMs); + this.recvTimer = setInterval(this.runHeartbeat.bind(this, missedTwo, timeout), intervalMs); } - clear () { + clear() { clearInterval(this.sendTimer); clearInterval(this.recvTimer); } - runHeartbeat (check, fail) { + runHeartbeat(check, fail) { // Have we seen activity? - if (!check()) - fail(); + if (!check()) fail(); } } diff --git a/lib/mux.js b/lib/mux.js index c712cd77..6b07139e 100644 --- a/lib/mux.js +++ b/lib/mux.js @@ -10,11 +10,10 @@ var assert = require('assert'); -var schedule = (typeof setImmediate === 'function') ? - setImmediate : process.nextTick; +var schedule = typeof setImmediate === 'function' ? setImmediate : process.nextTick; class Mux { - constructor (downstream) { + constructor(downstream) { this.newStreams = []; this.oldStreams = []; this.blocked = false; @@ -37,8 +36,7 @@ class Mux { // capacity, we will either run out of outbound capacity (`#write` // returns false), or run out of packets (all calls to an // `inbound.read()` have returned null). - _readIncoming () { - + _readIncoming() { // We may be sent here speculatively, if an incoming stream has // become readable if (this.blocked) return; @@ -48,7 +46,7 @@ class Mux { // Try to read a chunk from each stream in turn, until all streams // are empty, or we exhaust our ability to accept chunks. - function roundrobin (streams) { + function roundrobin(streams) { var s; while (accepting && (s = streams.shift())) { var chunk = s.read(); @@ -66,13 +64,14 @@ class Mux { // those with packets left) become old streams. This effectively // prioritises streams that keep their buffers close to empty over // those that are constantly near full. - if (accepting) { // all new queues are exhausted, write as many as + if (accepting) { + // all new queues are exhausted, write as many as // we can from the old streams assert.equal(0, this.newStreams.length); roundrobin(this.oldStreams); - } - else { // ran out of room - assert(this.newStreams.length > 0, "Expect some new streams to remain"); + } else { + // ran out of room + assert(this.newStreams.length > 0, 'Expect some new streams to remain'); Array.prototype.push.apply(this.oldStreams, this.newStreams); this.newStreams = []; } @@ -82,7 +81,7 @@ class Mux { this.blocked = !accepting; } - _scheduleRead () { + _scheduleRead() { var self = this; if (!self.scheduledRead) { @@ -94,21 +93,21 @@ class Mux { } } - pipeFrom (readable) { + pipeFrom(readable) { var self = this; - function enqueue () { + function enqueue() { self.newStreams.push(readable); self._scheduleRead(); } - function cleanup () { + function cleanup() { readable.removeListener('readable', enqueue); readable.removeListener('error', cleanup); readable.removeListener('end', cleanup); readable.removeListener('unpipeFrom', cleanupIfMe); } - function cleanupIfMe (dest) { + function cleanupIfMe(dest) { if (dest === self) cleanup(); } @@ -118,7 +117,7 @@ class Mux { readable.on('readable', enqueue); } - unpipeFrom (readable) { + unpipeFrom(readable) { readable.emit('unpipeFrom', this); } } diff --git a/package-lock.json b/package-lock.json index 7db0b61d..65f16561 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,13 +13,15 @@ "url-parse": "~1.5.10" }, "devDependencies": { + "@biomejs/biome": "^2.2.2", "claire": "0.4.1", + "lefthook": "^1.12.3", "mocha": "^9.2.2", "nyc": "^15.1.0", "uglify-js": "2.8.x" }, "engines": { - "node": ">=10" + "node": ">=16" } }, "node_modules/@ampproject/remapping": { @@ -316,6 +318,169 @@ "node": ">=6.9.0" } }, + "node_modules/@biomejs/biome": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.2.2.tgz", + "integrity": "sha512-j1omAiQWCkhuLgwpMKisNKnsM6W8Xtt1l0WZmqY/dFj8QPNkIoTvk4tSsi40FaAAkBE1PU0AFG2RWFBWenAn+w==", + "dev": true, + "license": "MIT OR Apache-2.0", + "bin": { + "biome": "bin/biome" + }, + "engines": { + "node": ">=14.21.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/biome" + }, + "optionalDependencies": { + "@biomejs/cli-darwin-arm64": "2.2.2", + "@biomejs/cli-darwin-x64": "2.2.2", + "@biomejs/cli-linux-arm64": "2.2.2", + "@biomejs/cli-linux-arm64-musl": "2.2.2", + "@biomejs/cli-linux-x64": "2.2.2", + "@biomejs/cli-linux-x64-musl": "2.2.2", + "@biomejs/cli-win32-arm64": "2.2.2", + "@biomejs/cli-win32-x64": "2.2.2" + } + }, + "node_modules/@biomejs/cli-darwin-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.2.2.tgz", + "integrity": "sha512-6ePfbCeCPryWu0CXlzsWNZgVz/kBEvHiPyNpmViSt6A2eoDf4kXs3YnwQPzGjy8oBgQulrHcLnJL0nkCh80mlQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.2.2.tgz", + "integrity": "sha512-Tn4JmVO+rXsbRslml7FvKaNrlgUeJot++FkvYIhl1OkslVCofAtS35MPlBMhXgKWF9RNr9cwHanrPTUUXcYGag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.2.2.tgz", + "integrity": "sha512-JfrK3gdmWWTh2J5tq/rcWCOsImVyzUnOS2fkjhiYKCQ+v8PqM+du5cfB7G1kXas+7KQeKSWALv18iQqdtIMvzw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64-musl": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.2.2.tgz", + "integrity": "sha512-/MhYg+Bd6renn6i1ylGFL5snYUn/Ct7zoGVKhxnro3bwekiZYE8Kl39BSb0MeuqM+72sThkQv4TnNubU9njQRw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.2.2.tgz", + "integrity": "sha512-Ogb+77edO5LEP/xbNicACOWVLt8mgC+E1wmpUakr+O4nKwLt9vXe74YNuT3T1dUBxC/SnrVmlzZFC7kQJEfquQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64-musl": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.2.2.tgz", + "integrity": "sha512-ZCLXcZvjZKSiRY/cFANKg+z6Fhsf9MHOzj+NrDQcM+LbqYRT97LyCLWy2AS+W2vP+i89RyRM+kbGpUzbRTYWig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.2.2.tgz", + "integrity": "sha512-wBe2wItayw1zvtXysmHJQoQqXlTzHSpQRyPpJKiNIR21HzH/CrZRDFic1C1jDdp+zAPtqhNExa0owKMbNwW9cQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.2.2.tgz", + "integrity": "sha512-DAuHhHekGfiGb6lCcsT4UyxQmVwQiBCBUMwVra/dcOSs9q8OhfaZgey51MlekT3p8UwRqtXQfFuEJBhJNdLZwg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, "node_modules/@istanbuljs/load-nyc-config": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", @@ -1478,6 +1643,169 @@ "node": ">=0.10.0" } }, + "node_modules/lefthook": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook/-/lefthook-1.12.3.tgz", + "integrity": "sha512-huMg+mGp6wHPjkaLdchuOvxVRMzvz6OVdhivatiH2Qn47O5Zm46jwzbVPYIanX6N/8ZTjGLBxv8tZ0KYmKt/Jg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "lefthook": "bin/index.js" + }, + "optionalDependencies": { + "lefthook-darwin-arm64": "1.12.3", + "lefthook-darwin-x64": "1.12.3", + "lefthook-freebsd-arm64": "1.12.3", + "lefthook-freebsd-x64": "1.12.3", + "lefthook-linux-arm64": "1.12.3", + "lefthook-linux-x64": "1.12.3", + "lefthook-openbsd-arm64": "1.12.3", + "lefthook-openbsd-x64": "1.12.3", + "lefthook-windows-arm64": "1.12.3", + "lefthook-windows-x64": "1.12.3" + } + }, + "node_modules/lefthook-darwin-arm64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-darwin-arm64/-/lefthook-darwin-arm64-1.12.3.tgz", + "integrity": "sha512-j1lwaosWRy3vhz8oQgCS1M6EUFN95aIYeNuqkczsBoAA6BDNAmVP1ctYEIYUK4bYaIgENbqbA9prYMAhyzh6Og==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/lefthook-darwin-x64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-darwin-x64/-/lefthook-darwin-x64-1.12.3.tgz", + "integrity": "sha512-x6aWFfLQX4m5zQ4X9zh5+hHOE5XTvNjz2zB9DI+xbIBLs2RRg0xJNT3OfgSrBU1QtEBneJ5dRQP5nl47td9GDQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/lefthook-freebsd-arm64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-freebsd-arm64/-/lefthook-freebsd-arm64-1.12.3.tgz", + "integrity": "sha512-41OmulLqVZ0EOHmmHouJrpL59SwDD7FLoso4RsQVIBPaf8fHacdLo07Ye28VWQ5XolZQvnWcr1YXKo4JhqQMyw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/lefthook-freebsd-x64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-freebsd-x64/-/lefthook-freebsd-x64-1.12.3.tgz", + "integrity": "sha512-741/JRCJIS++hgYEH2uefN4FsH872V7gy2zDhcfQofiZnWP7+qhl4Wmwi8IpjIu4X7hLOC4cT18LOVU5L8KV9Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/lefthook-linux-arm64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-linux-arm64/-/lefthook-linux-arm64-1.12.3.tgz", + "integrity": "sha512-BXIy1aDFZmFgmebJliNrEqZfX1lSOD4b/USvANv1UirFrNgTq5SRssd1CKfflT2PwKX6LsJTD4WabLLWZOxp9A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/lefthook-linux-x64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-linux-x64/-/lefthook-linux-x64-1.12.3.tgz", + "integrity": "sha512-FRdwdj5jsQAP2eVrtkVUqMqYNCbQ2Ix84izy29/BvLlu/hVypAGbDfUkgFnsmAd6ZsCBeYCEtPuqyg3E3SO0Rg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/lefthook-openbsd-arm64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-openbsd-arm64/-/lefthook-openbsd-arm64-1.12.3.tgz", + "integrity": "sha512-tch5wXY4GOjKAYohH7OFoxNdVHuUSYt2Pulo2VTkMYEG8IrvJnRO5MkvgHtKDHzU5mfABQYv5+ccJykDx5hQWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/lefthook-openbsd-x64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-openbsd-x64/-/lefthook-openbsd-x64-1.12.3.tgz", + "integrity": "sha512-IHbHg/rUFXrAN7LnjcQEtutCHBaD49CZge96Hpk0GZ2eEG5GTCNRnUyEf+Kf3+RTqHFgwtADdpeDa/ZaGZTM4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/lefthook-windows-arm64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-windows-arm64/-/lefthook-windows-arm64-1.12.3.tgz", + "integrity": "sha512-wghcE5TSpb+mbtemUV6uAo9hEK09kxRzhf2nPdeDX+fw42cL2TGZsbaCnDyzaY144C+L2/wEWrLIHJMnZYkuqA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/lefthook-windows-x64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-windows-x64/-/lefthook-windows-x64-1.12.3.tgz", + "integrity": "sha512-7Co/L8e2x2hGC1L33jDJ4ZlTkO3PJm25GOGpLfN1kqwhGB/uzMLeTI/PBczjlIN8isUv26ouNd9rVR7Bibrwyg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/locate-path": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", @@ -3016,6 +3344,78 @@ "to-fast-properties": "^2.0.0" } }, + "@biomejs/biome": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.2.2.tgz", + "integrity": "sha512-j1omAiQWCkhuLgwpMKisNKnsM6W8Xtt1l0WZmqY/dFj8QPNkIoTvk4tSsi40FaAAkBE1PU0AFG2RWFBWenAn+w==", + "dev": true, + "requires": { + "@biomejs/cli-darwin-arm64": "2.2.2", + "@biomejs/cli-darwin-x64": "2.2.2", + "@biomejs/cli-linux-arm64": "2.2.2", + "@biomejs/cli-linux-arm64-musl": "2.2.2", + "@biomejs/cli-linux-x64": "2.2.2", + "@biomejs/cli-linux-x64-musl": "2.2.2", + "@biomejs/cli-win32-arm64": "2.2.2", + "@biomejs/cli-win32-x64": "2.2.2" + } + }, + "@biomejs/cli-darwin-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.2.2.tgz", + "integrity": "sha512-6ePfbCeCPryWu0CXlzsWNZgVz/kBEvHiPyNpmViSt6A2eoDf4kXs3YnwQPzGjy8oBgQulrHcLnJL0nkCh80mlQ==", + "dev": true, + "optional": true + }, + "@biomejs/cli-darwin-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.2.2.tgz", + "integrity": "sha512-Tn4JmVO+rXsbRslml7FvKaNrlgUeJot++FkvYIhl1OkslVCofAtS35MPlBMhXgKWF9RNr9cwHanrPTUUXcYGag==", + "dev": true, + "optional": true + }, + "@biomejs/cli-linux-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.2.2.tgz", + "integrity": "sha512-JfrK3gdmWWTh2J5tq/rcWCOsImVyzUnOS2fkjhiYKCQ+v8PqM+du5cfB7G1kXas+7KQeKSWALv18iQqdtIMvzw==", + "dev": true, + "optional": true + }, + "@biomejs/cli-linux-arm64-musl": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.2.2.tgz", + "integrity": "sha512-/MhYg+Bd6renn6i1ylGFL5snYUn/Ct7zoGVKhxnro3bwekiZYE8Kl39BSb0MeuqM+72sThkQv4TnNubU9njQRw==", + "dev": true, + "optional": true + }, + "@biomejs/cli-linux-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.2.2.tgz", + "integrity": "sha512-Ogb+77edO5LEP/xbNicACOWVLt8mgC+E1wmpUakr+O4nKwLt9vXe74YNuT3T1dUBxC/SnrVmlzZFC7kQJEfquQ==", + "dev": true, + "optional": true + }, + "@biomejs/cli-linux-x64-musl": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.2.2.tgz", + "integrity": "sha512-ZCLXcZvjZKSiRY/cFANKg+z6Fhsf9MHOzj+NrDQcM+LbqYRT97LyCLWy2AS+W2vP+i89RyRM+kbGpUzbRTYWig==", + "dev": true, + "optional": true + }, + "@biomejs/cli-win32-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.2.2.tgz", + "integrity": "sha512-wBe2wItayw1zvtXysmHJQoQqXlTzHSpQRyPpJKiNIR21HzH/CrZRDFic1C1jDdp+zAPtqhNExa0owKMbNwW9cQ==", + "dev": true, + "optional": true + }, + "@biomejs/cli-win32-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.2.2.tgz", + "integrity": "sha512-DAuHhHekGfiGb6lCcsT4UyxQmVwQiBCBUMwVra/dcOSs9q8OhfaZgey51MlekT3p8UwRqtXQfFuEJBhJNdLZwg==", + "dev": true, + "optional": true + }, "@istanbuljs/load-nyc-config": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", @@ -3881,6 +4281,94 @@ "integrity": "sha1-odePw6UEdMuAhF07O24dpJpEbo4=", "dev": true }, + "lefthook": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook/-/lefthook-1.12.3.tgz", + "integrity": "sha512-huMg+mGp6wHPjkaLdchuOvxVRMzvz6OVdhivatiH2Qn47O5Zm46jwzbVPYIanX6N/8ZTjGLBxv8tZ0KYmKt/Jg==", + "dev": true, + "requires": { + "lefthook-darwin-arm64": "1.12.3", + "lefthook-darwin-x64": "1.12.3", + "lefthook-freebsd-arm64": "1.12.3", + "lefthook-freebsd-x64": "1.12.3", + "lefthook-linux-arm64": "1.12.3", + "lefthook-linux-x64": "1.12.3", + "lefthook-openbsd-arm64": "1.12.3", + "lefthook-openbsd-x64": "1.12.3", + "lefthook-windows-arm64": "1.12.3", + "lefthook-windows-x64": "1.12.3" + } + }, + "lefthook-darwin-arm64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-darwin-arm64/-/lefthook-darwin-arm64-1.12.3.tgz", + "integrity": "sha512-j1lwaosWRy3vhz8oQgCS1M6EUFN95aIYeNuqkczsBoAA6BDNAmVP1ctYEIYUK4bYaIgENbqbA9prYMAhyzh6Og==", + "dev": true, + "optional": true + }, + "lefthook-darwin-x64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-darwin-x64/-/lefthook-darwin-x64-1.12.3.tgz", + "integrity": "sha512-x6aWFfLQX4m5zQ4X9zh5+hHOE5XTvNjz2zB9DI+xbIBLs2RRg0xJNT3OfgSrBU1QtEBneJ5dRQP5nl47td9GDQ==", + "dev": true, + "optional": true + }, + "lefthook-freebsd-arm64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-freebsd-arm64/-/lefthook-freebsd-arm64-1.12.3.tgz", + "integrity": "sha512-41OmulLqVZ0EOHmmHouJrpL59SwDD7FLoso4RsQVIBPaf8fHacdLo07Ye28VWQ5XolZQvnWcr1YXKo4JhqQMyw==", + "dev": true, + "optional": true + }, + "lefthook-freebsd-x64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-freebsd-x64/-/lefthook-freebsd-x64-1.12.3.tgz", + "integrity": "sha512-741/JRCJIS++hgYEH2uefN4FsH872V7gy2zDhcfQofiZnWP7+qhl4Wmwi8IpjIu4X7hLOC4cT18LOVU5L8KV9Q==", + "dev": true, + "optional": true + }, + "lefthook-linux-arm64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-linux-arm64/-/lefthook-linux-arm64-1.12.3.tgz", + "integrity": "sha512-BXIy1aDFZmFgmebJliNrEqZfX1lSOD4b/USvANv1UirFrNgTq5SRssd1CKfflT2PwKX6LsJTD4WabLLWZOxp9A==", + "dev": true, + "optional": true + }, + "lefthook-linux-x64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-linux-x64/-/lefthook-linux-x64-1.12.3.tgz", + "integrity": "sha512-FRdwdj5jsQAP2eVrtkVUqMqYNCbQ2Ix84izy29/BvLlu/hVypAGbDfUkgFnsmAd6ZsCBeYCEtPuqyg3E3SO0Rg==", + "dev": true, + "optional": true + }, + "lefthook-openbsd-arm64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-openbsd-arm64/-/lefthook-openbsd-arm64-1.12.3.tgz", + "integrity": "sha512-tch5wXY4GOjKAYohH7OFoxNdVHuUSYt2Pulo2VTkMYEG8IrvJnRO5MkvgHtKDHzU5mfABQYv5+ccJykDx5hQWA==", + "dev": true, + "optional": true + }, + "lefthook-openbsd-x64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-openbsd-x64/-/lefthook-openbsd-x64-1.12.3.tgz", + "integrity": "sha512-IHbHg/rUFXrAN7LnjcQEtutCHBaD49CZge96Hpk0GZ2eEG5GTCNRnUyEf+Kf3+RTqHFgwtADdpeDa/ZaGZTM4g==", + "dev": true, + "optional": true + }, + "lefthook-windows-arm64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-windows-arm64/-/lefthook-windows-arm64-1.12.3.tgz", + "integrity": "sha512-wghcE5TSpb+mbtemUV6uAo9hEK09kxRzhf2nPdeDX+fw42cL2TGZsbaCnDyzaY144C+L2/wEWrLIHJMnZYkuqA==", + "dev": true, + "optional": true + }, + "lefthook-windows-x64": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/lefthook-windows-x64/-/lefthook-windows-x64-1.12.3.tgz", + "integrity": "sha512-7Co/L8e2x2hGC1L33jDJ4ZlTkO3PJm25GOGpLfN1kqwhGB/uzMLeTI/PBczjlIN8isUv26ouNd9rVR7Bibrwyg==", + "dev": true, + "optional": true + }, "locate-path": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", diff --git a/package.json b/package.json index b4f6f36a..1384dbc4 100644 --- a/package.json +++ b/package.json @@ -9,20 +9,23 @@ "url": "git+https://github.com/amqp-node/amqplib.git" }, "engines": { - "node": ">=10" + "node": ">=16" }, "dependencies": { "buffer-more-ints": "~1.0.0", "url-parse": "~1.5.10" }, "devDependencies": { + "@biomejs/biome": "^2.2.2", "claire": "0.4.1", + "lefthook": "^1.12.3", "mocha": "^9.2.2", "nyc": "^15.1.0", "uglify-js": "2.8.x" }, "scripts": { - "test": "make test" + "test": "make test", + "format": "biome format . --write" }, "keywords": [ "AMQP", diff --git a/test/bitset.js b/test/bitset.js index 3108aafe..8083a218 100644 --- a/test/bitset.js +++ b/test/bitset.js @@ -3,67 +3,97 @@ const claire = require('claire'); const {BitSet} = require('../lib/bitset'); -const { - forAll, - data: arb, - label, - choice, - transform -} = claire; +const {forAll, data: arb, label, choice, transform} = claire; const PosInt = transform(Math.floor, arb.Positive); -const EmptyBitSet = label('bitset', transform( - size => { - return new BitSet(size); - }, - choice(arb.Nothing, PosInt))); +const EmptyBitSet = label( + 'bitset', + transform( + (size) => { + return new BitSet(size); + }, + choice(arb.Nothing, PosInt), + ), +); suite('BitSet', () => { + test( + 'get bit', + forAll(EmptyBitSet, PosInt) + .satisfy((b, bit) => { + b.set(bit); + return b.get(bit); + }) + .asTest(), + ); -test('get bit', forAll(EmptyBitSet, PosInt) - .satisfy((b, bit) => { - b.set(bit); - return b.get(bit); - }).asTest()); + test( + 'clear bit', + forAll(EmptyBitSet, PosInt) + .satisfy((b, bit) => { + b.set(bit); + b.clear(bit); + return !b.get(bit); + }) + .asTest(), + ); -test('clear bit', forAll(EmptyBitSet, PosInt) - .satisfy((b, bit) => { - b.set(bit); - b.clear(bit); - return !b.get(bit); - }).asTest()); + test( + 'next set of empty', + forAll(EmptyBitSet) + .satisfy((b) => { + return b.nextSetBit(0) === -1; + }) + .asTest(), + ); -test('next set of empty', forAll(EmptyBitSet) - .satisfy(b => { - return b.nextSetBit(0) === -1; - }).asTest()); + test( + 'next set of one bit', + forAll(EmptyBitSet, PosInt) + .satisfy((b, bit) => { + b.set(bit); + return b.nextSetBit(0) === bit; + }) + .asTest(), + ); -test('next set of one bit', forAll(EmptyBitSet, PosInt) - .satisfy((b, bit) => { - b.set(bit); - return b.nextSetBit(0) === bit; - }).asTest()); + test( + 'next set same bit', + forAll(EmptyBitSet, PosInt) + .satisfy((b, bit) => { + b.set(bit); + return b.nextSetBit(bit) === bit; + }) + .asTest(), + ); -test('next set same bit', forAll(EmptyBitSet, PosInt) - .satisfy((b, bit) => { - b.set(bit); - return b.nextSetBit(bit) === bit; - }).asTest()); + test( + 'next set following bit', + forAll(EmptyBitSet, PosInt) + .satisfy((b, bit) => { + b.set(bit); + return b.nextSetBit(bit + 1) === -1; + }) + .asTest(), + ); -test('next set following bit', forAll(EmptyBitSet, PosInt) - .satisfy((b, bit) => { - b.set(bit); - return b.nextSetBit(bit+1) === -1; - }).asTest()); + test( + 'next clear of empty', + forAll(EmptyBitSet, PosInt) + .satisfy((b, bit) => { + return b.nextClearBit(bit) === bit; + }) + .asTest(), + ); -test('next clear of empty', forAll(EmptyBitSet, PosInt) - .satisfy((b, bit) => { return b.nextClearBit(bit) === bit; }) - .asTest()); - -test('next clear of one set', forAll(EmptyBitSet, PosInt) - .satisfy((b, bit) => { - b.set(bit); - return b.nextClearBit(bit) === bit + 1; - }).asTest()); + test( + 'next clear of one set', + forAll(EmptyBitSet, PosInt) + .satisfy((b, bit) => { + b.set(bit); + return b.nextClearBit(bit) === bit + 1; + }) + .asTest(), + ); }); diff --git a/test/callback_api.js b/test/callback_api.js index 51dd662d..77295a48 100644 --- a/test/callback_api.js +++ b/test/callback_api.js @@ -17,7 +17,7 @@ function connect(cb) { // Construct a node-style callback from a `done` function function doneCallback(done) { - return function(err, _) { + return function (err, _) { if (err == null) done(); else done(err); }; @@ -26,189 +26,218 @@ function doneCallback(done) { function ignore() {} function twice(done) { - var first = function(err) { + var first = function (err) { if (err == undefined) second = done; - else second = ignore, done(err); + else (second = ignore), done(err); }; - var second = function(err) { + var second = function (err) { if (err == undefined) first = done; - else first = ignore, done(err); + else (first = ignore), done(err); + }; + return { + first: function (err) { + first(err); + }, + second: function (err) { + second(err); + }, }; - return {first: function(err) { first(err); }, - second: function(err) { second(err); }}; } // Adapt 'done' to a callback that's expected to fail function failCallback(done) { - return function(err, _) { + return function (err, _) { if (err == null) done(new Error('Expected failure, got ' + val)); else done(); }; } function waitForMessages(ch, q, k) { - ch.checkQueue(q, function(e, ok) { + ch.checkQueue(q, function (e, ok) { if (e != null) return k(e); else if (ok.messageCount > 0) return k(null, ok); else schedule(waitForMessages.bind(null, ch, q, k)); }); } - -suite('connect', function() { - - test('at all', function(done) { +suite('connect', function () { + test('at all', function (done) { connect(doneCallback(done)); }); - }); -suite('updateSecret', function() { - test('updateSecret', function(done) { - connect(kCallback(function(c) { - c.updateSecret(Buffer.from('new secret'), 'no reason', doneCallback(done)); - })); +suite('updateSecret', function () { + test('updateSecret', function (done) { + connect( + kCallback(function (c) { + c.updateSecret(Buffer.from('new secret'), 'no reason', doneCallback(done)); + }), + ); }); }); function channel_test_fn(method) { - return function(name, options, chfun) { + return function (name, options, chfun) { if (arguments.length === 2) { chfun = options; options = {}; } - test(name, function(done) { - connect(kCallback(function(c) { - c[method](options, kCallback(function(ch) { - chfun(ch, done); - }, done)); - }, done)); + test(name, function (done) { + connect( + kCallback(function (c) { + c[method]( + options, + kCallback(function (ch) { + chfun(ch, done); + }, done), + ); + }, done), + ); }); }; } var channel_test = channel_test_fn('createChannel'); var confirm_channel_test = channel_test_fn('createConfirmChannel'); -suite('channel open', function() { - - channel_test('at all', function(ch, done) { +suite('channel open', function () { + channel_test('at all', function (ch, done) { done(); }); - channel_test('open and close', function(ch, done) { + channel_test('open and close', function (ch, done) { ch.close(doneCallback(done)); }); - }); -suite('assert, check, delete', function() { - - channel_test('assert, check, delete queue', function(ch, done) { - ch.assertQueue('test.cb.queue', {}, kCallback(function(q) { - ch.checkQueue('test.cb.queue', kCallback(function(ok) { - ch.deleteQueue('test.cb.queue', {}, doneCallback(done)); - }, done)); - }, done)); +suite('assert, check, delete', function () { + channel_test('assert, check, delete queue', function (ch, done) { + ch.assertQueue( + 'test.cb.queue', + {}, + kCallback(function (q) { + ch.checkQueue( + 'test.cb.queue', + kCallback(function (ok) { + ch.deleteQueue('test.cb.queue', {}, doneCallback(done)); + }, done), + ); + }, done), + ); }); - channel_test('assert, check, delete exchange', function(ch, done) { + channel_test('assert, check, delete exchange', function (ch, done) { ch.assertExchange( - 'test.cb.exchange', 'topic', {}, kCallback(function(ex) { - ch.checkExchange('test.cb.exchange', kCallback(function(ok) { - ch.deleteExchange('test.cb.exchange', {}, doneCallback(done)); - }, done)); - }, done)); + 'test.cb.exchange', + 'topic', + {}, + kCallback(function (ex) { + ch.checkExchange( + 'test.cb.exchange', + kCallback(function (ok) { + ch.deleteExchange('test.cb.exchange', {}, doneCallback(done)); + }, done), + ); + }, done), + ); }); - channel_test('fail on check non-queue', function(ch, done) { + channel_test('fail on check non-queue', function (ch, done) { var both = twice(done); ch.on('error', failCallback(both.first)); ch.checkQueue('test.cb.nothere', failCallback(both.second)); }); - channel_test('fail on check non-exchange', function(ch, done) { + channel_test('fail on check non-exchange', function (ch, done) { var both = twice(done); ch.on('error', failCallback(both.first)); ch.checkExchange('test.cb.nothere', failCallback(both.second)); }); - }); -suite('bindings', function() { - - channel_test('bind queue', function(ch, done) { - ch.assertQueue('test.cb.bindq', {}, kCallback(function(q) { - ch.assertExchange( - 'test.cb.bindex', 'fanout', {}, kCallback(function(ex) { - ch.bindQueue(q.queue, ex.exchange, '', {}, - doneCallback(done)); - }, done)); - }, done)); +suite('bindings', function () { + channel_test('bind queue', function (ch, done) { + ch.assertQueue( + 'test.cb.bindq', + {}, + kCallback(function (q) { + ch.assertExchange( + 'test.cb.bindex', + 'fanout', + {}, + kCallback(function (ex) { + ch.bindQueue(q.queue, ex.exchange, '', {}, doneCallback(done)); + }, done), + ); + }, done), + ); }); - channel_test('bind exchange', function(ch, done) { + channel_test('bind exchange', function (ch, done) { ch.assertExchange( - 'test.cb.bindex1', 'fanout', {}, kCallback(function(ex1) { + 'test.cb.bindex1', + 'fanout', + {}, + kCallback(function (ex1) { ch.assertExchange( - 'test.cb.bindex2', 'fanout', {}, kCallback(function(ex2) { - ch.bindExchange(ex1.exchange, - ex2.exchange, '', {}, - doneCallback(done)); - }, done)); - }, done)); + 'test.cb.bindex2', + 'fanout', + {}, + kCallback(function (ex2) { + ch.bindExchange(ex1.exchange, ex2.exchange, '', {}, doneCallback(done)); + }, done), + ); + }, done), + ); }); - }); -suite('sending messages', function() { - - channel_test('send to queue and consume noAck', function(ch, done) { +suite('sending messages', function () { + channel_test('send to queue and consume noAck', function (ch, done) { var msg = randomString(); - ch.assertQueue('', {exclusive: true}, function(e, q) { + ch.assertQueue('', {exclusive: true}, function (e, q) { if (e !== null) return done(e); - ch.consume(q.queue, function(m) { - if (m.content.toString() == msg) done(); - else done(new Error("message content doesn't match:" + - msg + " =/= " + m.content.toString())); - }, {noAck: true, exclusive: true}); + ch.consume( + q.queue, + function (m) { + if (m.content.toString() == msg) done(); + else done(new Error("message content doesn't match:" + msg + ' =/= ' + m.content.toString())); + }, + {noAck: true, exclusive: true}, + ); ch.sendToQueue(q.queue, Buffer.from(msg)); }); }); - channel_test('send to queue and consume ack', function(ch, done) { + channel_test('send to queue and consume ack', function (ch, done) { var msg = randomString(); - ch.assertQueue('', {exclusive: true}, function(e, q) { + ch.assertQueue('', {exclusive: true}, function (e, q) { if (e !== null) return done(e); - ch.consume(q.queue, function(m) { - if (m.content.toString() == msg) { - ch.ack(m); - done(); - } - else done(new Error("message content doesn't match:" + - msg + " =/= " + m.content.toString())); - }, {noAck: false, exclusive: true}); + ch.consume( + q.queue, + function (m) { + if (m.content.toString() == msg) { + ch.ack(m); + done(); + } else done(new Error("message content doesn't match:" + msg + ' =/= ' + m.content.toString())); + }, + {noAck: false, exclusive: true}, + ); ch.sendToQueue(q.queue, Buffer.from(msg)); }); }); - channel_test('send to and get from queue', function(ch, done) { - ch.assertQueue('', {exclusive: true}, function(e, q) { + channel_test('send to and get from queue', function (ch, done) { + ch.assertQueue('', {exclusive: true}, function (e, q) { if (e != null) return done(e); var msg = randomString(); ch.sendToQueue(q.queue, Buffer.from(msg)); - waitForMessages(ch, q.queue, function(e, _) { + waitForMessages(ch, q.queue, function (e, _) { if (e != null) return done(e); - ch.get(q.queue, {noAck: true}, function(e, m) { - if (e != null) - return done(e); - else if (!m) - return done(new Error('Empty (false) not expected')); - else if (m.content.toString() == msg) - return done(); - else - return done( - new Error('Messages do not match: ' + - msg + ' =/= ' + m.content.toString())); + ch.get(q.queue, {noAck: true}, function (e, m) { + if (e != null) return done(e); + else if (!m) return done(new Error('Empty (false) not expected')); + else if (m.content.toString() == msg) return done(); + else return done(new Error('Messages do not match: ' + msg + ' =/= ' + m.content.toString())); }); }); }); @@ -216,22 +245,22 @@ suite('sending messages', function() { var channelOptions = {}; - channel_test('find high watermark', function(ch, done) { + channel_test('find high watermark', function (ch, done) { var msg = randomString(); var baseline = 0; - ch.assertQueue('', {exclusive: true}, function(e, q) { + ch.assertQueue('', {exclusive: true}, function (e, q) { if (e !== null) return done(e); while (ch.sendToQueue(q.queue, Buffer.from(msg))) { baseline++; - }; + } channelOptions.highWaterMark = baseline * 2; done(); - }) + }); }); - channel_test('set high watermark', channelOptions, function(ch, done) { + channel_test('set high watermark', channelOptions, function (ch, done) { var msg = randomString(); - ch.assertQueue('', {exclusive: true}, function(e, q) { + ch.assertQueue('', {exclusive: true}, function (e, q) { if (e !== null) return done(e); var ok; for (var i = 0; i < channelOptions.highWaterMark; i++) { @@ -243,17 +272,16 @@ suite('sending messages', function() { }); }); -suite('ConfirmChannel', function() { - - confirm_channel_test('Receive confirmation', function(ch, done) { +suite('ConfirmChannel', function () { + confirm_channel_test('Receive confirmation', function (ch, done) { // An unroutable message, on the basis that you're not allowed a // queue with an empty name, and you can't make bindings to the // default exchange. Tricky eh? ch.publish('', '', Buffer.from('foo'), {}, done); }); - confirm_channel_test('Wait for confirms', function(ch, done) { - for (var i=0; i < 1000; i++) { + confirm_channel_test('Wait for confirms', function (ch, done) { + for (var i = 0; i < 1000; i++) { ch.publish('', '', Buffer.from('foo'), {}); } ch.waitForConfirms(done); @@ -261,22 +289,22 @@ suite('ConfirmChannel', function() { var channelOptions = {}; - confirm_channel_test('find high watermark', function(ch, done) { + confirm_channel_test('find high watermark', function (ch, done) { var msg = randomString(); var baseline = 0; - ch.assertQueue('', {exclusive: true}, function(e, q) { + ch.assertQueue('', {exclusive: true}, function (e, q) { if (e !== null) return done(e); while (ch.sendToQueue(q.queue, Buffer.from(msg))) { baseline++; - }; + } channelOptions.highWaterMark = baseline * 2; done(); - }) + }); }); - confirm_channel_test('set high watermark', channelOptions, function(ch, done) { + confirm_channel_test('set high watermark', channelOptions, function (ch, done) { var msg = randomString(); - ch.assertQueue('', {exclusive: true}, function(e, q) { + ch.assertQueue('', {exclusive: true}, function (e, q) { if (e !== null) return done(e); var ok; for (var i = 0; i < channelOptions.highWaterMark; i++) { @@ -286,11 +314,9 @@ suite('ConfirmChannel', function() { done(); }); }); - }); -suite("Error handling", function() { - +suite('Error handling', function () { /* I don't like having to do this, but there appears to be something broken about domains in Node.JS v0.8 and mocha. Apparently it has to @@ -305,75 +331,80 @@ suite("Error handling", function() { program. */ if (util.versionGreaterThan(process.versions.node, '0.8')) { - test('Throw error in connection open callback', function(done) { + test('Throw error in connection open callback', function (done) { var dom = domain.createDomain(); dom.on('error', failCallback(done)); - connect(dom.bind(function(err, conn) { - throw new Error('Spurious connection open callback error'); - })); + connect( + dom.bind(function (err, conn) { + throw new Error('Spurious connection open callback error'); + }), + ); }); } // TODO: refactor {error_test, channel_test} function error_test(name, fun) { - test(name, function(done) { + test(name, function (done) { var dom = domain.createDomain(); - dom.run(function() { - connect(kCallback(function(c) { - // Seems like there were some unironed wrinkles in 0.8's - // implementation of domains; explicitly adding the connection - // to the domain makes sure any exception thrown in the course - // of processing frames is handled by the domain. For other - // versions of Node.JS, this ends up being belt-and-braces. - dom.add(c); - c.createChannel(kCallback(function(ch) { - fun(ch, done, dom); - }, done)); - }, done)); + dom.run(function () { + connect( + kCallback(function (c) { + // Seems like there were some unironed wrinkles in 0.8's + // implementation of domains; explicitly adding the connection + // to the domain makes sure any exception thrown in the course + // of processing frames is handled by the domain. For other + // versions of Node.JS, this ends up being belt-and-braces. + dom.add(c); + c.createChannel( + kCallback(function (ch) { + fun(ch, done, dom); + }, done), + ); + }, done), + ); }); }); } - error_test('Channel open callback throws an error', function(ch, done, dom) { + error_test('Channel open callback throws an error', function (ch, done, dom) { dom.on('error', failCallback(done)); throw new Error('Error in open callback'); }); - error_test('RPC callback throws error', function(ch, done, dom) { + error_test('RPC callback throws error', function (ch, done, dom) { dom.on('error', failCallback(done)); - ch.prefetch(0, false, function(err, ok) { + ch.prefetch(0, false, function (err, ok) { throw new Error('Spurious callback error'); }); }); - error_test('Get callback throws error', function(ch, done, dom) { + error_test('Get callback throws error', function (ch, done, dom) { dom.on('error', failCallback(done)); - ch.assertQueue('test.cb.get-with-error', {}, function(err, ok) { - ch.get('test.cb.get-with-error', {noAck: true}, function() { + ch.assertQueue('test.cb.get-with-error', {}, function (err, ok) { + ch.get('test.cb.get-with-error', {noAck: true}, function () { throw new Error('Spurious callback error'); }); }); }); - error_test('Consume callback throws error', function(ch, done, dom) { + error_test('Consume callback throws error', function (ch, done, dom) { dom.on('error', failCallback(done)); - ch.assertQueue('test.cb.consume-with-error', {}, function(err, ok) { - ch.consume('test.cb.consume-with-error', ignore, {noAck: true}, function() { + ch.assertQueue('test.cb.consume-with-error', {}, function (err, ok) { + ch.consume('test.cb.consume-with-error', ignore, {noAck: true}, function () { throw new Error('Spurious callback error'); }); }); }); - error_test('Get from non-queue invokes error k', function(ch, done, dom) { + error_test('Get from non-queue invokes error k', function (ch, done, dom) { var both = twice(failCallback(done)); dom.on('error', both.first); ch.get('', {}, both.second); }); - error_test('Consume from non-queue invokes error k', function(ch, done, dom) { + error_test('Consume from non-queue invokes error k', function (ch, done, dom) { var both = twice(failCallback(done)); dom.on('error', both.first); ch.consume('', both.second); }); - }); diff --git a/test/channel.js b/test/channel.js index 03657ce7..c18befe0 100644 --- a/test/channel.js +++ b/test/channel.js @@ -7,7 +7,9 @@ var promisify = require('util').promisify; var Channel = require('../lib/channel').Channel; var Connection = require('../lib/connection').Connection; var util = require('./util'); -var succeed = util.succeed, fail = util.fail, latch = util.latch; +var succeed = util.succeed, + fail = util.fail, + latch = util.latch; var completes = util.completes; var defs = require('../lib/defs'); var conn_handshake = require('./connection').connection_handshake; @@ -16,52 +18,51 @@ var OPEN_OPTS = require('./connection').OPEN_OPTS; var LOG_ERRORS = process.env.LOG_ERRORS; function baseChannelTest(client, server) { - return function(done) { + return function (done) { var bothDone = latch(2, done); var pair = util.socketPair(); var c = new Connection(pair.client); if (LOG_ERRORS) c.on('error', console.warn); - c.open(OPEN_OPTS, function(err, ok) { + c.open(OPEN_OPTS, function (err, ok) { if (err === null) client(c, bothDone); else fail(bothDone); }); pair.server.read(8); // discard the protocol header - var s = util.runServer(pair.server, function(send, wait) { - conn_handshake(send, wait) - .then(function() { - server(send, wait, bothDone); - }, fail(bothDone)); + var s = util.runServer(pair.server, function (send, wait) { + conn_handshake(send, wait).then(function () { + server(send, wait, bothDone); + }, fail(bothDone)); }); }; } function channelTest(client, server) { return baseChannelTest( - function(conn, done) { + function (conn, done) { var ch = new Channel(conn); if (LOG_ERRORS) ch.on('error', console.warn); client(ch, done, conn); }, - function(send, wait, done) { + function (send, wait, done) { channel_handshake(send, wait) - .then(function(ch) { - return server(send, wait, done, ch); - }).then(null, fail(done)); // so you can return a promise to let - // errors bubble out - } + .then(function (ch) { + return server(send, wait, done, ch); + }) + .then(null, fail(done)); // so you can return a promise to let + // errors bubble out + }, ); -}; +} function channel_handshake(send, wait) { - return wait(defs.ChannelOpen)() - .then(function(open) { - assert.notEqual(0, open.channel); - send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, open.channel); - return open.channel; - }); + return wait(defs.ChannelOpen)().then(function (open) { + assert.notEqual(0, open.channel); + send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, open.channel); + return open.channel; + }); } // fields for deliver and publish and get-ok @@ -77,545 +78,695 @@ var DELIVER_FIELDS = { function open(ch) { ch.allocate(); - return promisify(function(cb) { + return promisify(function (cb) { ch._rpc(defs.ChannelOpen, {outOfBand: ''}, defs.ChannelOpenOk, cb); })(); } -suite("channel open and close", function() { - -test("open", channelTest( - function(ch, done) { - open(ch).then(succeed(done), fail(done)); - }, - function(send, wait, done) { - done(); - })); - -test("bad server", baseChannelTest( - function(c, done) { - var ch = new Channel(c); - open(ch).then(fail(done), succeed(done)); - }, - function(send, wait, done) { - return wait(defs.ChannelOpen)() - .then(function(open) { - send(defs.ChannelCloseOk, {}, open.channel); - }).then(succeed(done), fail(done)); - })); - -test("open, close", channelTest( - function(ch, done) { - open(ch) - .then(function() { - return new Promise(function(resolve) { - ch.closeBecause("Bye", defs.constants.REPLY_SUCCESS, resolve); - }); - }) - .then(succeed(done), fail(done)); - }, - function(send, wait, done, ch) { - return wait(defs.ChannelClose)() - .then(function(close) { - send(defs.ChannelCloseOk, {}, ch); - }).then(succeed(done), fail(done)); - })); - -test("server close", channelTest( - function(ch, done) { - ch.on('error', function(error) { - assert.strictEqual(504, error.code); - assert.strictEqual(0, error.classId); - assert.strictEqual(0, error.methodId); - succeed(done)(); - }); - open(ch); - }, - function(send, wait, done, ch) { - send(defs.ChannelClose, { - replyText: 'Forced close', - replyCode: defs.constants.CHANNEL_ERROR, - classId: 0, methodId: 0 - }, ch); - wait(defs.ChannelCloseOk)() - .then(succeed(done), fail(done)); - })); - -test("overlapping channel/server close", channelTest( - function(ch, done, conn) { - var both = latch(2, done); - conn.on('error', succeed(both)); - ch.on('close', succeed(both)); - open(ch).then(function() { - ch.closeBecause("Bye", defs.constants.REPLY_SUCCESS); - }, fail(both)); - }, - function(send, wait, done, ch) { - wait(defs.ChannelClose)() - .then(function() { - send(defs.ConnectionClose, { - replyText: 'Got there first', - replyCode: defs.constants.INTERNAL_ERROR, - classId: 0, methodId: 0 - }, 0); - }) - .then(wait(defs.ConnectionCloseOk)) - .then(succeed(done), fail(done)); - })); - -test("double close", channelTest( - function(ch, done) { - open(ch).then(function() { - ch.closeBecause("First close", defs.constants.REPLY_SUCCESS); - // NB no synchronisation, we do this straight away - assert.throws(function() { - ch.closeBecause("Second close", defs.constants.REPLY_SUCCESS); - }); - }).then(succeed(done), fail(done)); - }, - function(send, wait, done, ch) { - wait(defs.ChannelClose)() - .then(function() { - send(defs.ChannelCloseOk, { - }, ch); - }) - .then(succeed(done), fail(done)); - })); +suite('channel open and close', function () { + test( + 'open', + channelTest( + function (ch, done) { + open(ch).then(succeed(done), fail(done)); + }, + function (send, wait, done) { + done(); + }, + ), + ); -}); //suite + test( + 'bad server', + baseChannelTest( + function (c, done) { + var ch = new Channel(c); + open(ch).then(fail(done), succeed(done)); + }, + function (send, wait, done) { + return wait(defs.ChannelOpen)() + .then(function (open) { + send(defs.ChannelCloseOk, {}, open.channel); + }) + .then(succeed(done), fail(done)); + }, + ), + ); -suite("channel machinery", function() { - -test("RPC", channelTest( - function(ch, done) { - var rpcLatch = latch(3, done); - open(ch).then(function() { - - function wheeboom(err, f) { - if (err !== null) rpcLatch(err); - else rpcLatch(); - } - - var fields = { - prefetchCount: 10, - prefetchSize: 0, - global: false - }; - - ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); - ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); - ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); - }).then(null, fail(rpcLatch)); - }, - function(send, wait, done, ch) { - function sendOk(f) { - send(defs.BasicQosOk, {}, ch); - } - - return wait(defs.BasicQos)() - .then(sendOk) - .then(wait(defs.BasicQos)) - .then(sendOk) - .then(wait(defs.BasicQos)) - .then(sendOk) - .then(succeed(done), fail(done)); - })); - -test("Bad RPC", channelTest( - function(ch, done) { - // We want to see the RPC rejected and the channel closed (with an - // error) - var errLatch = latch(2, done); - ch.on('error', function(error) { - assert.strictEqual(505, error.code); - assert.strictEqual(60, error.classId); - assert.strictEqual(72, error.methodId); - succeed(errLatch)(); - }); + test( + 'open, close', + channelTest( + function (ch, done) { + open(ch) + .then(function () { + return new Promise(function (resolve) { + ch.closeBecause('Bye', defs.constants.REPLY_SUCCESS, resolve); + }); + }) + .then(succeed(done), fail(done)); + }, + function (send, wait, done, ch) { + return wait(defs.ChannelClose)() + .then(function (close) { + send(defs.ChannelCloseOk, {}, ch); + }) + .then(succeed(done), fail(done)); + }, + ), + ); - open(ch) - .then(function() { - ch._rpc(defs.BasicRecover, {requeue: true}, defs.BasicRecoverOk, - function(err) { - if (err !== null) errLatch(); - else errLatch(new Error('Expected RPC failure')); - }); - }, fail(errLatch)); - }, - function(send, wait, done, ch) { - return wait()() - .then(function() { - send(defs.BasicGetEmpty, {clusterId: ''}, ch); - }) // oh wait! that was wrong! expect a channel close - .then(wait(defs.ChannelClose)) - .then(function() { - send(defs.ChannelCloseOk, {}, ch); - }).then(succeed(done), fail(done)); - })); - -test("RPC on closed channel", channelTest( - function(ch, done) { - open(ch); - - var close = new Promise(function(resolve) { - ch.on('error', function(error) { + test( + 'server close', + channelTest( + function (ch, done) { + ch.on('error', function (error) { assert.strictEqual(504, error.code); assert.strictEqual(0, error.classId); assert.strictEqual(0, error.methodId); - resolve(); - }); - }); + succeed(done)(); + }); + open(ch); + }, + function (send, wait, done, ch) { + send( + defs.ChannelClose, + { + replyText: 'Forced close', + replyCode: defs.constants.CHANNEL_ERROR, + classId: 0, + methodId: 0, + }, + ch, + ); + wait(defs.ChannelCloseOk)().then(succeed(done), fail(done)); + }, + ), + ); - function failureCb(resolve, reject) { - return function(err) { - if (err !== null) resolve(); - else reject(); - } - } + test( + 'overlapping channel/server close', + channelTest( + function (ch, done, conn) { + var both = latch(2, done); + conn.on('error', succeed(both)); + ch.on('close', succeed(both)); + open(ch).then(function () { + ch.closeBecause('Bye', defs.constants.REPLY_SUCCESS); + }, fail(both)); + }, + function (send, wait, done, ch) { + wait(defs.ChannelClose)() + .then(function () { + send( + defs.ConnectionClose, + { + replyText: 'Got there first', + replyCode: defs.constants.INTERNAL_ERROR, + classId: 0, + methodId: 0, + }, + 0, + ); + }) + .then(wait(defs.ConnectionCloseOk)) + .then(succeed(done), fail(done)); + }, + ), + ); - var fail1 = new Promise(function(resolve, reject) { - return ch._rpc(defs.BasicRecover, {requeue:true}, defs.BasicRecoverOk, - failureCb(resolve, reject)); - }); + test( + 'double close', + channelTest( + function (ch, done) { + open(ch) + .then(function () { + ch.closeBecause('First close', defs.constants.REPLY_SUCCESS); + // NB no synchronisation, we do this straight away + assert.throws(function () { + ch.closeBecause('Second close', defs.constants.REPLY_SUCCESS); + }); + }) + .then(succeed(done), fail(done)); + }, + function (send, wait, done, ch) { + wait(defs.ChannelClose)() + .then(function () { + send(defs.ChannelCloseOk, {}, ch); + }) + .then(succeed(done), fail(done)); + }, + ), + ); +}); //suite - var fail2 = new Promise(function(resolve, reject) { - return ch._rpc(defs.BasicRecover, {requeue:true}, defs.BasicRecoverOk, - failureCb(resolve, reject)); - }); +suite('channel machinery', function () { + test( + 'RPC', + channelTest( + function (ch, done) { + var rpcLatch = latch(3, done); + open(ch) + .then(function () { + function wheeboom(err, f) { + if (err !== null) rpcLatch(err); + else rpcLatch(); + } + + var fields = { + prefetchCount: 10, + prefetchSize: 0, + global: false, + }; + + ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); + ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); + ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); + }) + .then(null, fail(rpcLatch)); + }, + function (send, wait, done, ch) { + function sendOk(f) { + send(defs.BasicQosOk, {}, ch); + } + + return wait(defs.BasicQos)() + .then(sendOk) + .then(wait(defs.BasicQos)) + .then(sendOk) + .then(wait(defs.BasicQos)) + .then(sendOk) + .then(succeed(done), fail(done)); + }, + ), + ); - Promise.all([close, fail1, fail2]) - .then(succeed(done)) - .catch(fail(done)); - }, - function(send, wait, done, ch) { - wait(defs.BasicRecover)() - .then(function() { - send(defs.ChannelClose, { - replyText: 'Nuh-uh!', - replyCode: defs.constants.CHANNEL_ERROR, - methodId: 0, classId: 0 - }, ch); - return wait(defs.ChannelCloseOk); - }) - .then(succeed(done)) - .catch(fail(done)); - })); - -test("publish all < single chunk threshold", channelTest( - function(ch, done) { - open(ch) - .then(function() { - ch.sendMessage({ - exchange: 'foo', routingKey: 'bar', - mandatory: false, immediate: false, ticket: 0 - }, {}, Buffer.from('foobar')); - }) - .then(succeed(done), fail(done)); - }, - function(send, wait, done, ch) { - wait(defs.BasicPublish)() - .then(wait(defs.BasicProperties)) - .then(wait(undefined)) // content frame - .then(function(f) { - assert.equal('foobar', f.content.toString()); - }).then(succeed(done), fail(done)); - })); - -test("publish content > single chunk threshold", channelTest( - function(ch, done) { - open(ch); - completes(function() { - ch.sendMessage({ - exchange: 'foo', routingKey: 'bar', - mandatory: false, immediate: false, ticket: 0 - }, {}, Buffer.alloc(3000)); - }, done); - }, - function(send, wait, done, ch) { - wait(defs.BasicPublish)() - .then(wait(defs.BasicProperties)) - .then(wait(undefined)) // content frame - .then(function(f) { - assert.equal(3000, f.content.length); - }).then(succeed(done), fail(done)); - })); - -test("publish method & headers > threshold", channelTest( - function(ch, done) { - open(ch); - completes(function() { - ch.sendMessage({ - exchange: 'foo', routingKey: 'bar', - mandatory: false, immediate: false, ticket: 0 - }, { - headers: {foo: Buffer.alloc(3000)} - }, Buffer.from('foobar')); - }, done); - }, - function(send, wait, done, ch) { - wait(defs.BasicPublish)() - .then(wait(defs.BasicProperties)) - .then(wait(undefined)) // content frame - .then(function(f) { - assert.equal('foobar', f.content.toString()); - }).then(succeed(done), fail(done)); - })); - -test("publish zero-length message", channelTest( - function(ch, done) { - open(ch); - completes(function() { - ch.sendMessage({ - exchange: 'foo', routingKey: 'bar', - mandatory: false, immediate: false, ticket: 0 - }, {}, Buffer.alloc(0)); - ch.sendMessage({ - exchange: 'foo', routingKey: 'bar', - mandatory: false, immediate: false, ticket: 0 - }, {}, Buffer.alloc(0)); - }, done); - }, - function(send, wait, done, ch) { - wait(defs.BasicPublish)() - .then(wait(defs.BasicProperties)) - // no content frame for a zero-length message - .then(wait(defs.BasicPublish)) - .then(succeed(done), fail(done)); - })); - -test("delivery", channelTest( - function(ch, done) { - open(ch); - ch.on('delivery', function(m) { - completes(function() { - assert.equal('barfoo', m.content.toString()); - }, done); - }); - }, - function(send, wait, done, ch) { - completes(function() { - send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('barfoo')); - }, done); - })); - -test("zero byte msg", channelTest( - function(ch, done) { - open(ch); - ch.on('delivery', function(m) { - completes(function() { - assert.deepEqual(Buffer.alloc(0), m.content); - }, done); - }); - }, - function(send, wait, done, ch) { - completes(function() { - send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('')); - }, done); - })); - -test("bad delivery", channelTest( - function(ch, done) { - var errorAndClose = latch(2, done); - ch.on('error', function(error) { - assert.strictEqual(505, error.code); - assert.strictEqual(60, error.classId); - assert.strictEqual(60, error.methodId); - succeed(errorAndClose)(); - }); - ch.on('close', succeed(errorAndClose)); - open(ch); - }, - function(send, wait, done, ch) { - send(defs.BasicDeliver, DELIVER_FIELDS, ch); - // now send another deliver without having sent the content - send(defs.BasicDeliver, DELIVER_FIELDS, ch); - return wait(defs.ChannelClose)() - .then(function() { - send(defs.ChannelCloseOk, {}, ch); - }).then(succeed(done), fail(done)); - })); - -test("bad content send", channelTest( - function(ch, done) { - completes(function() { - open(ch); - assert.throws(function() { - ch.sendMessage({routingKey: 'foo', - exchange: 'amq.direct'}, - {}, null); - }); - }, done); - }, - function(send, wait, done, ch) { - done(); - })); - -test("bad properties send", channelTest( - function(ch, done) { - completes(function() { - open(ch); - assert.throws(function() { - ch.sendMessage({routingKey: 'foo', - exchange: 'amq.direct'}, - {contentEncoding: 7}, - Buffer.from('foobar')); - }); - }, done); - }, - function(send, wait, done, ch) { - done(); - })); - -test("bad consumer", channelTest( - function(ch, done) { - var errorAndClose = latch(2, done); - ch.on('delivery', function() { - throw new Error("I am a bad consumer"); - }); - ch.on('error', function(error) { - assert.strictEqual(541, error.code); - assert.strictEqual(undefined, error.classId); - assert.strictEqual(undefined, error.methodId); - succeed(errorAndClose)(); - }); - ch.on('close', succeed(errorAndClose)); - open(ch); - }, - function(send, wait, done, ch) { - send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('barfoo')); - return wait(defs.ChannelClose)() - .then(function() { - send(defs.ChannelCloseOk, {}, ch); - }).then(succeed(done), fail(done)); - })); - -test("bad send in consumer", channelTest( - function(ch, done) { - var errorAndClose = latch(2, done); - ch.on('close', succeed(errorAndClose)); - ch.on('error', function(error) { - assert.strictEqual(541, error.code); - assert.strictEqual(undefined, error.classId); - assert.strictEqual(undefined, error.methodId); - succeed(errorAndClose)(); - }); + test( + 'Bad RPC', + channelTest( + function (ch, done) { + // We want to see the RPC rejected and the channel closed (with an + // error) + var errLatch = latch(2, done); + ch.on('error', function (error) { + assert.strictEqual(505, error.code); + assert.strictEqual(60, error.classId); + assert.strictEqual(72, error.methodId); + succeed(errLatch)(); + }); - ch.on('delivery', function() { - ch.sendMessage({routingKey: 'foo', - exchange: 'amq.direct'}, - {}, null); // can't send null - }); + open(ch).then(function () { + ch._rpc(defs.BasicRecover, {requeue: true}, defs.BasicRecoverOk, function (err) { + if (err !== null) errLatch(); + else errLatch(new Error('Expected RPC failure')); + }); + }, fail(errLatch)); + }, + function (send, wait, done, ch) { + return wait()() + .then(function () { + send(defs.BasicGetEmpty, {clusterId: ''}, ch); + }) // oh wait! that was wrong! expect a channel close + .then(wait(defs.ChannelClose)) + .then(function () { + send(defs.ChannelCloseOk, {}, ch); + }) + .then(succeed(done), fail(done)); + }, + ), + ); - open(ch); - }, - function(send, wait, done, ch) { - completes(function() { - send(defs.BasicDeliver, DELIVER_FIELDS, ch, - Buffer.from('barfoo')); - }, done); - return wait(defs.ChannelClose)() - .then(function() { - send(defs.ChannelCloseOk, {}, ch); - }).then(succeed(done), fail(done)); - })); - -test("return", channelTest( - function(ch, done) { - ch.on('return', function(m) { - completes(function() { - assert.equal('barfoo', m.content.toString()); - }, done); - }); - open(ch); - }, - function(send, wait, done, ch) { - completes(function() { - send(defs.BasicReturn, DELIVER_FIELDS, ch, Buffer.from('barfoo')); - }, done); - })); - -test("cancel", channelTest( - function(ch, done) { - ch.on('cancel', function(f) { - completes(function() { - assert.equal('product of society', f.consumerTag); - }, done); - }); - open(ch); - }, - function(send, wait, done, ch) { - completes(function() { - send(defs.BasicCancel, { - consumerTag: 'product of society', - nowait: false - }, ch); - }, done); - })); - -function confirmTest(variety, Method) { - return test('confirm ' + variety, channelTest( - function(ch, done) { - ch.on(variety, function(f) { - completes(function() { - assert.equal(1, f.deliveryTag); + test( + 'RPC on closed channel', + channelTest( + function (ch, done) { + open(ch); + + var close = new Promise(function (resolve) { + ch.on('error', function (error) { + assert.strictEqual(504, error.code); + assert.strictEqual(0, error.classId); + assert.strictEqual(0, error.methodId); + resolve(); + }); + }); + + function failureCb(resolve, reject) { + return function (err) { + if (err !== null) resolve(); + else reject(); + }; + } + + var fail1 = new Promise(function (resolve, reject) { + return ch._rpc(defs.BasicRecover, {requeue: true}, defs.BasicRecoverOk, failureCb(resolve, reject)); + }); + + var fail2 = new Promise(function (resolve, reject) { + return ch._rpc(defs.BasicRecover, {requeue: true}, defs.BasicRecoverOk, failureCb(resolve, reject)); + }); + + Promise.all([close, fail1, fail2]).then(succeed(done)).catch(fail(done)); + }, + function (send, wait, done, ch) { + wait(defs.BasicRecover)() + .then(function () { + send( + defs.ChannelClose, + { + replyText: 'Nuh-uh!', + replyCode: defs.constants.CHANNEL_ERROR, + methodId: 0, + classId: 0, + }, + ch, + ); + return wait(defs.ChannelCloseOk); + }) + .then(succeed(done)) + .catch(fail(done)); + }, + ), + ); + + test( + 'publish all < single chunk threshold', + channelTest( + function (ch, done) { + open(ch) + .then(function () { + ch.sendMessage( + { + exchange: 'foo', + routingKey: 'bar', + mandatory: false, + immediate: false, + ticket: 0, + }, + {}, + Buffer.from('foobar'), + ); + }) + .then(succeed(done), fail(done)); + }, + function (send, wait, done, ch) { + wait(defs.BasicPublish)() + .then(wait(defs.BasicProperties)) + .then(wait(undefined)) // content frame + .then(function (f) { + assert.equal('foobar', f.content.toString()); + }) + .then(succeed(done), fail(done)); + }, + ), + ); + + test( + 'publish content > single chunk threshold', + channelTest( + function (ch, done) { + open(ch); + completes(function () { + ch.sendMessage( + { + exchange: 'foo', + routingKey: 'bar', + mandatory: false, + immediate: false, + ticket: 0, + }, + {}, + Buffer.alloc(3000), + ); }, done); - }); - open(ch); - }, - function(send, wait, done, ch) { - completes(function() { - send(Method, { - deliveryTag: 1, - multiple: false - }, ch); - }, done); - })); -} + }, + function (send, wait, done, ch) { + wait(defs.BasicPublish)() + .then(wait(defs.BasicProperties)) + .then(wait(undefined)) // content frame + .then(function (f) { + assert.equal(3000, f.content.length); + }) + .then(succeed(done), fail(done)); + }, + ), + ); -confirmTest("ack", defs.BasicAck); -confirmTest("nack", defs.BasicNack); + test( + 'publish method & headers > threshold', + channelTest( + function (ch, done) { + open(ch); + completes(function () { + ch.sendMessage( + { + exchange: 'foo', + routingKey: 'bar', + mandatory: false, + immediate: false, + ticket: 0, + }, + { + headers: {foo: Buffer.alloc(3000)}, + }, + Buffer.from('foobar'), + ); + }, done); + }, + function (send, wait, done, ch) { + wait(defs.BasicPublish)() + .then(wait(defs.BasicProperties)) + .then(wait(undefined)) // content frame + .then(function (f) { + assert.equal('foobar', f.content.toString()); + }) + .then(succeed(done), fail(done)); + }, + ), + ); -test("out-of-order acks", channelTest( - function(ch, done) { - var allConfirms = latch(3, function() { - completes(function() { - assert.equal(0, ch.unconfirmed.length); - assert.equal(4, ch.lwm); - }, done); - }); - ch.pushConfirmCallback(allConfirms); - ch.pushConfirmCallback(allConfirms); - ch.pushConfirmCallback(allConfirms); - open(ch); - }, - function(send, wait, done, ch) { - completes(function() { - send(defs.BasicAck, {deliveryTag: 2, multiple: false}, ch); - send(defs.BasicAck, {deliveryTag: 3, multiple: false}, ch); - send(defs.BasicAck, {deliveryTag: 1, multiple: false}, ch); - }, done); - })); - -test("not all out-of-order acks", channelTest( - function(ch, done) { - var allConfirms = latch(2, function() { - completes(function() { - assert.equal(1, ch.unconfirmed.length); - assert.equal(3, ch.lwm); - }, done); - }); - ch.pushConfirmCallback(allConfirms); // tag = 1 - ch.pushConfirmCallback(allConfirms); // tag = 2 - ch.pushConfirmCallback(function() { - done(new Error('Confirm callback should not be called')); - }); - open(ch); - }, - function(send, wait, done, ch) { - completes(function() { - send(defs.BasicAck, {deliveryTag: 2, multiple: false}, ch); - send(defs.BasicAck, {deliveryTag: 1, multiple: false}, ch); - }, done); - })); + test( + 'publish zero-length message', + channelTest( + function (ch, done) { + open(ch); + completes(function () { + ch.sendMessage( + { + exchange: 'foo', + routingKey: 'bar', + mandatory: false, + immediate: false, + ticket: 0, + }, + {}, + Buffer.alloc(0), + ); + ch.sendMessage( + { + exchange: 'foo', + routingKey: 'bar', + mandatory: false, + immediate: false, + ticket: 0, + }, + {}, + Buffer.alloc(0), + ); + }, done); + }, + function (send, wait, done, ch) { + wait(defs.BasicPublish)() + .then(wait(defs.BasicProperties)) + // no content frame for a zero-length message + .then(wait(defs.BasicPublish)) + .then(succeed(done), fail(done)); + }, + ), + ); + + test( + 'delivery', + channelTest( + function (ch, done) { + open(ch); + ch.on('delivery', function (m) { + completes(function () { + assert.equal('barfoo', m.content.toString()); + }, done); + }); + }, + function (send, wait, done, ch) { + completes(function () { + send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('barfoo')); + }, done); + }, + ), + ); + + test( + 'zero byte msg', + channelTest( + function (ch, done) { + open(ch); + ch.on('delivery', function (m) { + completes(function () { + assert.deepEqual(Buffer.alloc(0), m.content); + }, done); + }); + }, + function (send, wait, done, ch) { + completes(function () { + send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('')); + }, done); + }, + ), + ); + + test( + 'bad delivery', + channelTest( + function (ch, done) { + var errorAndClose = latch(2, done); + ch.on('error', function (error) { + assert.strictEqual(505, error.code); + assert.strictEqual(60, error.classId); + assert.strictEqual(60, error.methodId); + succeed(errorAndClose)(); + }); + ch.on('close', succeed(errorAndClose)); + open(ch); + }, + function (send, wait, done, ch) { + send(defs.BasicDeliver, DELIVER_FIELDS, ch); + // now send another deliver without having sent the content + send(defs.BasicDeliver, DELIVER_FIELDS, ch); + return wait(defs.ChannelClose)() + .then(function () { + send(defs.ChannelCloseOk, {}, ch); + }) + .then(succeed(done), fail(done)); + }, + ), + ); + + test( + 'bad content send', + channelTest( + function (ch, done) { + completes(function () { + open(ch); + assert.throws(function () { + ch.sendMessage({routingKey: 'foo', exchange: 'amq.direct'}, {}, null); + }); + }, done); + }, + function (send, wait, done, ch) { + done(); + }, + ), + ); + + test( + 'bad properties send', + channelTest( + function (ch, done) { + completes(function () { + open(ch); + assert.throws(function () { + ch.sendMessage({routingKey: 'foo', exchange: 'amq.direct'}, {contentEncoding: 7}, Buffer.from('foobar')); + }); + }, done); + }, + function (send, wait, done, ch) { + done(); + }, + ), + ); + + test( + 'bad consumer', + channelTest( + function (ch, done) { + var errorAndClose = latch(2, done); + ch.on('delivery', function () { + throw new Error('I am a bad consumer'); + }); + ch.on('error', function (error) { + assert.strictEqual(541, error.code); + assert.strictEqual(undefined, error.classId); + assert.strictEqual(undefined, error.methodId); + succeed(errorAndClose)(); + }); + ch.on('close', succeed(errorAndClose)); + open(ch); + }, + function (send, wait, done, ch) { + send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('barfoo')); + return wait(defs.ChannelClose)() + .then(function () { + send(defs.ChannelCloseOk, {}, ch); + }) + .then(succeed(done), fail(done)); + }, + ), + ); + + test( + 'bad send in consumer', + channelTest( + function (ch, done) { + var errorAndClose = latch(2, done); + ch.on('close', succeed(errorAndClose)); + ch.on('error', function (error) { + assert.strictEqual(541, error.code); + assert.strictEqual(undefined, error.classId); + assert.strictEqual(undefined, error.methodId); + succeed(errorAndClose)(); + }); + + ch.on('delivery', function () { + ch.sendMessage({routingKey: 'foo', exchange: 'amq.direct'}, {}, null); // can't send null + }); + + open(ch); + }, + function (send, wait, done, ch) { + completes(function () { + send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('barfoo')); + }, done); + return wait(defs.ChannelClose)() + .then(function () { + send(defs.ChannelCloseOk, {}, ch); + }) + .then(succeed(done), fail(done)); + }, + ), + ); + + test( + 'return', + channelTest( + function (ch, done) { + ch.on('return', function (m) { + completes(function () { + assert.equal('barfoo', m.content.toString()); + }, done); + }); + open(ch); + }, + function (send, wait, done, ch) { + completes(function () { + send(defs.BasicReturn, DELIVER_FIELDS, ch, Buffer.from('barfoo')); + }, done); + }, + ), + ); + test( + 'cancel', + channelTest( + function (ch, done) { + ch.on('cancel', function (f) { + completes(function () { + assert.equal('product of society', f.consumerTag); + }, done); + }); + open(ch); + }, + function (send, wait, done, ch) { + completes(function () { + send( + defs.BasicCancel, + { + consumerTag: 'product of society', + nowait: false, + }, + ch, + ); + }, done); + }, + ), + ); + + function confirmTest(variety, Method) { + return test( + 'confirm ' + variety, + channelTest( + function (ch, done) { + ch.on(variety, function (f) { + completes(function () { + assert.equal(1, f.deliveryTag); + }, done); + }); + open(ch); + }, + function (send, wait, done, ch) { + completes(function () { + send( + Method, + { + deliveryTag: 1, + multiple: false, + }, + ch, + ); + }, done); + }, + ), + ); + } + + confirmTest('ack', defs.BasicAck); + confirmTest('nack', defs.BasicNack); + + test( + 'out-of-order acks', + channelTest( + function (ch, done) { + var allConfirms = latch(3, function () { + completes(function () { + assert.equal(0, ch.unconfirmed.length); + assert.equal(4, ch.lwm); + }, done); + }); + ch.pushConfirmCallback(allConfirms); + ch.pushConfirmCallback(allConfirms); + ch.pushConfirmCallback(allConfirms); + open(ch); + }, + function (send, wait, done, ch) { + completes(function () { + send(defs.BasicAck, {deliveryTag: 2, multiple: false}, ch); + send(defs.BasicAck, {deliveryTag: 3, multiple: false}, ch); + send(defs.BasicAck, {deliveryTag: 1, multiple: false}, ch); + }, done); + }, + ), + ); + + test( + 'not all out-of-order acks', + channelTest( + function (ch, done) { + var allConfirms = latch(2, function () { + completes(function () { + assert.equal(1, ch.unconfirmed.length); + assert.equal(3, ch.lwm); + }, done); + }); + ch.pushConfirmCallback(allConfirms); // tag = 1 + ch.pushConfirmCallback(allConfirms); // tag = 2 + ch.pushConfirmCallback(function () { + done(new Error('Confirm callback should not be called')); + }); + open(ch); + }, + function (send, wait, done, ch) { + completes(function () { + send(defs.BasicAck, {deliveryTag: 2, multiple: false}, ch); + send(defs.BasicAck, {deliveryTag: 1, multiple: false}, ch); + }, done); + }, + ), + ); }); diff --git a/test/channel_api.js b/test/channel_api.js index f3a1691d..cfc855a6 100644 --- a/test/channel_api.js +++ b/test/channel_api.js @@ -3,7 +3,8 @@ var assert = require('assert'); var api = require('../channel_api'); var util = require('./util'); -var succeed = util.succeed, fail = util.fail; +var succeed = util.succeed, + fail = util.fail; var schedule = util.schedule; var randomString = util.randomString; var promisify = require('util').promisify; @@ -16,55 +17,65 @@ function connect() { // Expect this promise to fail, and flip the results accordingly. function expectFail(promise) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { return promise.then(reject).catch(resolve); }); } // I'll rely on operations being rejected, rather than the channel // close error, to detect failure. -function ignore () {} +function ignore() {} function ignoreErrors(c) { - c.on('error', ignore); return c; + c.on('error', ignore); + return c; } function logErrors(c) { - c.on('error', console.warn); return c; + c.on('error', console.warn); + return c; } // Run a test with `name`, given a function that takes an open // channel, and returns a promise that is resolved on test success or // rejected on test failure. function channel_test(chmethod, name, chfun) { - test(name, function(done) { - connect(URL).then(logErrors).then(function(c) { - c[chmethod]().then(ignoreErrors).then(chfun) - .then(succeed(done), fail(done)) - // close the connection regardless of what happens with the test - .finally(function() {c.close();}); - }); + test(name, function (done) { + connect(URL) + .then(logErrors) + .then(function (c) { + c[chmethod]() + .then(ignoreErrors) + .then(chfun) + .then(succeed(done), fail(done)) + // close the connection regardless of what happens with the test + .finally(function () { + c.close(); + }); + }); }); } var chtest = channel_test.bind(null, 'createChannel'); -suite("connect", function() { - - test("at all", function(done) { - connect(URL).then(function(c) { - return c.close() - ;}).then(succeed(done), fail(done)); +suite('connect', function () { + test('at all', function (done) { + connect(URL) + .then(function (c) { + return c.close(); + }) + .then(succeed(done), fail(done)); }); - chtest("create channel", ignore); // i.e., just don't bork - + chtest('create channel', ignore); // i.e., just don't bork }); -suite("updateSecret", function() { - test("updateSecret", function(done) { - connect().then(function(c) { - c.updateSecret(Buffer.from("new secret"), "no reason") +suite('updateSecret', function () { + test('updateSecret', function (done) { + connect().then(function (c) { + c.updateSecret(Buffer.from('new secret'), 'no reason') .then(succeed(done), fail(done)) - .finally(function() { c.close(); }); + .finally(function () { + c.close(); + }); }); }); }); @@ -72,158 +83,141 @@ suite("updateSecret", function() { var QUEUE_OPTS = {durable: false}; var EX_OPTS = {durable: false}; -suite("assert, check, delete", function() { - - chtest("assert and check queue", function(ch) { - return ch.assertQueue('test.check-queue', QUEUE_OPTS) - .then(function(qok) { - return ch.checkQueue('test.check-queue'); - }); +suite('assert, check, delete', function () { + chtest('assert and check queue', function (ch) { + return ch.assertQueue('test.check-queue', QUEUE_OPTS).then(function (qok) { + return ch.checkQueue('test.check-queue'); + }); }); - chtest("assert and check exchange", function(ch) { - return ch.assertExchange('test.check-exchange', 'direct', EX_OPTS) - .then(function(eok) { - assert.equal('test.check-exchange', eok.exchange); - return ch.checkExchange('test.check-exchange'); - }); + chtest('assert and check exchange', function (ch) { + return ch.assertExchange('test.check-exchange', 'direct', EX_OPTS).then(function (eok) { + assert.equal('test.check-exchange', eok.exchange); + return ch.checkExchange('test.check-exchange'); + }); }); - chtest("fail on reasserting queue with different options", - function(ch) { - var q = 'test.reassert-queue'; - return ch.assertQueue( - q, {durable: false, autoDelete: true}) - .then(function() { - return expectFail( - ch.assertQueue(q, {durable: false, - autoDelete: false})); - }); - }); + chtest('fail on reasserting queue with different options', function (ch) { + var q = 'test.reassert-queue'; + return ch.assertQueue(q, {durable: false, autoDelete: true}).then(function () { + return expectFail(ch.assertQueue(q, {durable: false, autoDelete: false})); + }); + }); - chtest("fail on checking a queue that's not there", function(ch) { + chtest("fail on checking a queue that's not there", function (ch) { return expectFail(ch.checkQueue('test.random-' + randomString())); }); - chtest("fail on checking an exchange that's not there", function(ch) { + chtest("fail on checking an exchange that's not there", function (ch) { return expectFail(ch.checkExchange('test.random-' + randomString())); }); - chtest("fail on reasserting exchange with different type", - function(ch) { - var ex = 'test.reassert-ex'; - return ch.assertExchange(ex, 'fanout', EX_OPTS) - .then(function() { - return expectFail( - ch.assertExchange(ex, 'direct', EX_OPTS)); - }); - }); + chtest('fail on reasserting exchange with different type', function (ch) { + var ex = 'test.reassert-ex'; + return ch.assertExchange(ex, 'fanout', EX_OPTS).then(function () { + return expectFail(ch.assertExchange(ex, 'direct', EX_OPTS)); + }); + }); - chtest("channel break on publishing to non-exchange", function(ch) { - return new Promise(function(resolve) { + chtest('channel break on publishing to non-exchange', function (ch) { + return new Promise(function (resolve) { ch.on('error', resolve); ch.publish(randomString(), '', Buffer.from('foobar')); }); }); - chtest("delete queue", function(ch) { + chtest('delete queue', function (ch) { var q = 'test.delete-queue'; - return Promise.all([ - ch.assertQueue(q, QUEUE_OPTS), - ch.checkQueue(q)]) - .then(function() { - return ch.deleteQueue(q);}) - .then(function() { - return expectFail(ch.checkQueue(q));}); + return Promise.all([ch.assertQueue(q, QUEUE_OPTS), ch.checkQueue(q)]) + .then(function () { + return ch.deleteQueue(q); + }) + .then(function () { + return expectFail(ch.checkQueue(q)); + }); }); - chtest("delete exchange", function(ch) { + chtest('delete exchange', function (ch) { var ex = 'test.delete-exchange'; - return Promise.all([ - ch.assertExchange(ex, 'fanout', EX_OPTS), - ch.checkExchange(ex)]) - .then(function() { - return ch.deleteExchange(ex);}) - .then(function() { - return expectFail(ch.checkExchange(ex));}); + return Promise.all([ch.assertExchange(ex, 'fanout', EX_OPTS), ch.checkExchange(ex)]) + .then(function () { + return ch.deleteExchange(ex); + }) + .then(function () { + return expectFail(ch.checkExchange(ex)); + }); }); - }); // Wait for the queue to meet the condition; useful for waiting for // messages to arrive, for example. function waitForQueue(q, condition) { - return connect(URL).then(function(c) { - return c.createChannel() - .then(function(ch) { - return ch.checkQueue(q).then(function(qok) { - function check() { - return ch.checkQueue(q).then(function(qok) { - if (condition(qok)) { - c.close(); - return qok; - } - else schedule(check); - }); - } - return check(); - }); + return connect(URL).then(function (c) { + return c.createChannel().then(function (ch) { + return ch.checkQueue(q).then(function (qok) { + function check() { + return ch.checkQueue(q).then(function (qok) { + if (condition(qok)) { + c.close(); + return qok; + } else schedule(check); + }); + } + return check(); }); + }); }); } // Return a promise that resolves when the queue has at least `num` // messages. If num is not supplied its assumed to be 1. function waitForMessages(q, num) { - var min = (num === undefined) ? 1 : num; - return waitForQueue(q, function(qok) { + var min = num === undefined ? 1 : num; + return waitForQueue(q, function (qok) { return qok.messageCount >= min; }); } -suite("sendMessage", function() { - +suite('sendMessage', function () { // publish different size messages - chtest("send to queue and get from queue", function(ch) { + chtest('send to queue and get from queue', function (ch) { var q = 'test.send-to-q'; var msg = randomString(); return Promise.all([ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)]) - .then(function() { + .then(function () { ch.sendToQueue(q, Buffer.from(msg)); return waitForMessages(q); }) - .then(function() { + .then(function () { return ch.get(q, {noAck: true}); }) - .then(function(m) { + .then(function (m) { assert(m); assert.equal(msg, m.content.toString()); }); }); - chtest("send (and get) zero content to queue", function(ch) { + chtest('send (and get) zero content to queue', function (ch) { var q = 'test.send-to-q'; var msg = Buffer.alloc(0); - return Promise.all([ - ch.assertQueue(q, QUEUE_OPTS), - ch.purgeQueue(q)]) - .then(function() { + return Promise.all([ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)]) + .then(function () { ch.sendToQueue(q, msg); - return waitForMessages(q);}) - .then(function() { - return ch.get(q, {noAck: true});}) - .then(function(m) { + return waitForMessages(q); + }) + .then(function () { + return ch.get(q, {noAck: true}); + }) + .then(function (m) { assert(m); assert.deepEqual(msg, m.content); }); }); - }); -suite("binding, consuming", function() { - +suite('binding, consuming', function () { // bind, publish, get - chtest("route message", function(ch) { + chtest('route message', function (ch) { var ex = 'test.route-message'; var q = 'test.route-message-q'; var msg = randomString(); @@ -232,35 +226,41 @@ suite("binding, consuming", function() { ch.assertExchange(ex, 'fanout', EX_OPTS), ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q), - ch.bindQueue(q, ex, '', {})]) - .then(function() { + ch.bindQueue(q, ex, '', {}), + ]) + .then(function () { ch.publish(ex, '', Buffer.from(msg)); - return waitForMessages(q);}) - .then(function() { - return ch.get(q, {noAck: true});}) - .then(function(m) { + return waitForMessages(q); + }) + .then(function () { + return ch.get(q, {noAck: true}); + }) + .then(function (m) { assert(m); assert.equal(msg, m.content.toString()); }); }); // send to queue, purge, get-empty - chtest("purge queue", function(ch) { + chtest('purge queue', function (ch) { var q = 'test.purge-queue'; - return ch.assertQueue(q, {durable: false}) - .then(function() { + return ch + .assertQueue(q, {durable: false}) + .then(function () { ch.sendToQueue(q, Buffer.from('foobar')); - return waitForMessages(q);}) - .then(function() { + return waitForMessages(q); + }) + .then(function () { ch.purgeQueue(q); - return ch.get(q, {noAck: true});}) - .then(function(m) { + return ch.get(q, {noAck: true}); + }) + .then(function (m) { assert(!m); // get-empty }); }); // bind again, unbind, publish, get-empty - chtest("unbind queue", function(ch) { + chtest('unbind queue', function (ch) { var ex = 'test.unbind-queue-ex'; var q = 'test.unbind-queue'; var viabinding = randomString(); @@ -270,23 +270,32 @@ suite("binding, consuming", function() { ch.assertExchange(ex, 'fanout', EX_OPTS), ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q), - ch.bindQueue(q, ex, '', {})]) - .then(function() { + ch.bindQueue(q, ex, '', {}), + ]) + .then(function () { ch.publish(ex, '', Buffer.from('foobar')); - return waitForMessages(q);}) - .then(function() { // message got through! - return ch.get(q, {noAck:true}) - .then(function(m) {assert(m);});}) - .then(function() { - return ch.unbindQueue(q, ex, '', {});}) - .then(function() { + return waitForMessages(q); + }) + .then(function () { + // message got through! + return ch.get(q, {noAck: true}).then(function (m) { + assert(m); + }); + }) + .then(function () { + return ch.unbindQueue(q, ex, '', {}); + }) + .then(function () { // via the no-longer-existing binding ch.publish(ex, '', Buffer.from(viabinding)); // direct to the queue ch.sendToQueue(q, Buffer.from(direct)); - return waitForMessages(q);}) - .then(function() {return ch.get(q)}) - .then(function(m) { + return waitForMessages(q); + }) + .then(function () { + return ch.get(q); + }) + .then(function (m) { // the direct to queue message got through, the via-binding // message (sent first) did not assert.equal(direct, m.content.toString()); @@ -295,34 +304,34 @@ suite("binding, consuming", function() { // To some extent this is now just testing semantics of the server, // but we can at least try out a few settings, and consume. - chtest("consume via exchange-exchange binding", function(ch) { - var ex1 = 'test.ex-ex-binding1', ex2 = 'test.ex-ex-binding2'; + chtest('consume via exchange-exchange binding', function (ch) { + var ex1 = 'test.ex-ex-binding1', + ex2 = 'test.ex-ex-binding2'; var q = 'test.ex-ex-binding-q'; - var rk = 'test.routing.key', msg = randomString(); + var rk = 'test.routing.key', + msg = randomString(); return Promise.all([ ch.assertExchange(ex1, 'direct', EX_OPTS), - ch.assertExchange(ex2, 'fanout', - {durable: false, internal: true}), + ch.assertExchange(ex2, 'fanout', {durable: false, internal: true}), ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q), ch.bindExchange(ex2, ex1, rk, {}), - ch.bindQueue(q, ex2, '', {})]) - .then(function() { - return new Promise(function(resolve, reject) { - function delivery(m) { - if (m.content.toString() === msg) resolve(); - else reject(new Error("Wrong message")); - } - ch.consume(q, delivery, {noAck: true}) - .then(function() { - ch.publish(ex1, rk, Buffer.from(msg)); - }); + ch.bindQueue(q, ex2, '', {}), + ]).then(function () { + return new Promise(function (resolve, reject) { + function delivery(m) { + if (m.content.toString() === msg) resolve(); + else reject(new Error('Wrong message')); + } + ch.consume(q, delivery, {noAck: true}).then(function () { + ch.publish(ex1, rk, Buffer.from(msg)); }); }); + }); }); // bind again, unbind, publish, get-empty - chtest("unbind exchange", function(ch) { + chtest('unbind exchange', function (ch) { var source = 'test.unbind-ex-source'; var dest = 'test.unbind-ex-dest'; var q = 'test.unbind-ex-queue'; @@ -335,23 +344,32 @@ suite("binding, consuming", function() { ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q), ch.bindExchange(dest, source, '', {}), - ch.bindQueue(q, dest, '', {})]) - .then(function() { + ch.bindQueue(q, dest, '', {}), + ]) + .then(function () { ch.publish(source, '', Buffer.from('foobar')); - return waitForMessages(q);}) - .then(function() { // message got through! - return ch.get(q, {noAck:true}) - .then(function(m) {assert(m);});}) - .then(function() { - return ch.unbindExchange(dest, source, '', {});}) - .then(function() { + return waitForMessages(q); + }) + .then(function () { + // message got through! + return ch.get(q, {noAck: true}).then(function (m) { + assert(m); + }); + }) + .then(function () { + return ch.unbindExchange(dest, source, '', {}); + }) + .then(function () { // via the no-longer-existing binding ch.publish(source, '', Buffer.from(viabinding)); // direct to the queue ch.sendToQueue(q, Buffer.from(direct)); - return waitForMessages(q);}) - .then(function() {return ch.get(q)}) - .then(function(m) { + return waitForMessages(q); + }) + .then(function () { + return ch.get(q); + }) + .then(function (m) { // the direct to queue message got through, the via-binding // message (sent first) did not assert.equal(direct, m.content.toString()); @@ -359,33 +377,36 @@ suite("binding, consuming", function() { }); // This is a bit convoluted. Sorry. - chtest("cancel consumer", function(ch) { + chtest('cancel consumer', function (ch) { var q = 'test.consumer-cancel'; var ctag; var recv1 = new Promise(function (resolve, reject) { - Promise.all([ - ch.assertQueue(q, QUEUE_OPTS), - ch.purgeQueue(q), - // My callback is 'resolve the promise in `arrived`' - ch.consume(q, resolve, {noAck:true}) - .then(function(ok) { - ctag = ok.consumerTag; - ch.sendToQueue(q, Buffer.from('foo')); - })]); + Promise.all([ + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q), + // My callback is 'resolve the promise in `arrived`' + ch + .consume(q, resolve, {noAck: true}) + .then(function (ok) { + ctag = ok.consumerTag; + ch.sendToQueue(q, Buffer.from('foo')); + }), + ]); }); // A message should arrive because of the consume - return recv1.then(function() { + return recv1.then(function () { var recv2 = Promise.all([ - ch.cancel(ctag).then(function() { + ch.cancel(ctag).then(function () { return ch.sendToQueue(q, Buffer.from('bar')); }), // but check a message did arrive in the queue - waitForMessages(q)]) - .then(function() { - return ch.get(q, {noAck:true}); + waitForMessages(q), + ]) + .then(function () { + return ch.get(q, {noAck: true}); }) - .then(function(m) { + .then(function (m) { // I'm going to reject it, because I flip succeed/fail // just below if (m.content.toString() === 'bar') { @@ -393,50 +414,49 @@ suite("binding, consuming", function() { } }); - return expectFail(recv2); + return expectFail(recv2); }); }); - chtest("cancelled consumer", function(ch) { + chtest('cancelled consumer', function (ch) { var q = 'test.cancelled-consumer'; - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { return Promise.all([ ch.assertQueue(q), ch.purgeQueue(q), - ch.consume(q, function(msg) { + ch.consume(q, function (msg) { if (msg === null) resolve(); else reject(new Error('Message not expected')); - })]) - .then(function() { - return ch.deleteQueue(q); - }); + }), + ]).then(function () { + return ch.deleteQueue(q); + }); }); }); // ack, by default, removes a single message from the queue - chtest("ack", function(ch) { + chtest('ack', function (ch) { var q = 'test.ack'; - var msg1 = randomString(), msg2 = randomString(); + var msg1 = randomString(), + msg2 = randomString(); - return Promise.all([ - ch.assertQueue(q, QUEUE_OPTS), - ch.purgeQueue(q)]) - .then(function() { + return Promise.all([ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)]) + .then(function () { ch.sendToQueue(q, Buffer.from(msg1)); ch.sendToQueue(q, Buffer.from(msg2)); return waitForMessages(q, 2); }) - .then(function() { - return ch.get(q, {noAck: false}) + .then(function () { + return ch.get(q, {noAck: false}); }) - .then(function(m) { + .then(function (m) { assert.equal(msg1, m.content.toString()); ch.ack(m); // %%% is there a race here? may depend on // rabbitmq-sepcific semantics return ch.get(q); }) - .then(function(m) { + .then(function (m) { assert(m); assert.equal(msg2, m.content.toString()); }); @@ -444,24 +464,27 @@ suite("binding, consuming", function() { // Nack, by default, puts a message back on the queue (where in the // queue is up to the server) - chtest("nack", function(ch) { + chtest('nack', function (ch) { var q = 'test.nack'; var msg1 = randomString(); - return Promise.all([ - ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)]) - .then(function() { + return Promise.all([ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)]) + .then(function () { ch.sendToQueue(q, Buffer.from(msg1)); - return waitForMessages(q);}) - .then(function() { - return ch.get(q, {noAck: false})}) - .then(function(m) { + return waitForMessages(q); + }) + .then(function () { + return ch.get(q, {noAck: false}); + }) + .then(function (m) { assert.equal(msg1, m.content.toString()); ch.nack(m); - return waitForMessages(q);}) - .then(function() { - return ch.get(q);}) - .then(function(m) { + return waitForMessages(q); + }) + .then(function () { + return ch.get(q); + }) + .then(function (m) { assert(m); assert.equal(msg1, m.content.toString()); }); @@ -469,41 +492,42 @@ suite("binding, consuming", function() { // reject is a near-synonym for nack, the latter of which is not // available in earlier RabbitMQ (or in AMQP proper). - chtest("reject", function(ch) { + chtest('reject', function (ch) { var q = 'test.reject'; var msg1 = randomString(); - return Promise.all([ - ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)]) - .then(function() { + return Promise.all([ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)]) + .then(function () { ch.sendToQueue(q, Buffer.from(msg1)); - return waitForMessages(q);}) - .then(function() { - return ch.get(q, {noAck: false})}) - .then(function(m) { + return waitForMessages(q); + }) + .then(function () { + return ch.get(q, {noAck: false}); + }) + .then(function (m) { assert.equal(msg1, m.content.toString()); ch.reject(m); - return waitForMessages(q);}) - .then(function() { - return ch.get(q);}) - .then(function(m) { + return waitForMessages(q); + }) + .then(function () { + return ch.get(q); + }) + .then(function (m) { assert(m); assert.equal(msg1, m.content.toString()); }); }); - chtest("prefetch", function(ch) { + chtest('prefetch', function (ch) { var q = 'test.prefetch'; - return Promise.all([ - ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q), - ch.prefetch(1)]) - .then(function() { + return Promise.all([ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q), ch.prefetch(1)]) + .then(function () { ch.sendToQueue(q, Buffer.from('foobar')); ch.sendToQueue(q, Buffer.from('foobar')); return waitForMessages(q, 2); }) - .then(function() { - return new Promise(function(resolve) { + .then(function () { + return new Promise(function (resolve) { var messageCount = 0; function receive(msg) { ch.ack(msg); @@ -511,33 +535,29 @@ suite("binding, consuming", function() { resolve(messageCount); } } - return ch.consume(q, receive, {noAck: false}) + return ch.consume(q, receive, {noAck: false}); }); }) - .then(function(c) { + .then(function (c) { return assert.equal(2, c); }); }); - chtest('close', function(ch) { + chtest('close', function (ch) { // Resolving promise guarantees // channel is closed return ch.close(); }); - }); var confirmtest = channel_test.bind(null, 'createConfirmChannel'); -suite("confirms", function() { - - confirmtest('message is confirmed', function(ch) { +suite('confirms', function () { + confirmtest('message is confirmed', function (ch) { var q = 'test.confirm-message'; - return Promise.all([ - ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)]) - .then(function() { - return ch.sendToQueue(q, Buffer.from('bleep')); - }); + return Promise.all([ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)]).then(function () { + return ch.sendToQueue(q, Buffer.from('bleep')); + }); }); // Usually one can provoke the server into confirming more than one @@ -545,62 +565,62 @@ suite("confirms", function() { // succession; a bit unscientific I know. Luckily we can eavesdrop on // the acknowledgements coming through to see if we really did get a // multi-ack. - confirmtest('multiple confirms', function(ch) { + confirmtest('multiple confirms', function (ch) { var q = 'test.multiple-confirms'; - return Promise.all([ - ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)]) - .then(function() { - var multipleRainbows = false; - ch.on('ack', function(a) { - if (a.multiple) multipleRainbows = true; - }); - - function prod(num) { - var cs = []; + return Promise.all([ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)]).then(function () { + var multipleRainbows = false; + ch.on('ack', function (a) { + if (a.multiple) multipleRainbows = true; + }); - function sendAndPushPromise() { - var conf = promisify(function(cb) { - return ch.sendToQueue(q, Buffer.from('bleep'), {}, cb); - })(); - cs.push(conf); - } + function prod(num) { + var cs = []; - for (var i=0; i < num; i++) sendAndPushPromise(); - - return Promise.all(cs).then(function() { - if (multipleRainbows) return true; - else if (num > 500) throw new Error( - "Couldn't provoke the server" + - " into multi-acking with " + num + - " messages; giving up"); - else { - //console.warn("Failed with " + num + "; trying " + num * 2); - return prod(num * 2); - } - }); + function sendAndPushPromise() { + var conf = promisify(function (cb) { + return ch.sendToQueue(q, Buffer.from('bleep'), {}, cb); + })(); + cs.push(conf); } - return prod(5); - }); + + for (var i = 0; i < num; i++) sendAndPushPromise(); + + return Promise.all(cs).then(function () { + if (multipleRainbows) return true; + else if (num > 500) throw new Error("Couldn't provoke the server" + ' into multi-acking with ' + num + ' messages; giving up'); + else { + //console.warn("Failed with " + num + "; trying " + num * 2); + return prod(num * 2); + } + }); + } + return prod(5); + }); }); - confirmtest('wait for confirms', function(ch) { - for (var i=0; i < 1000; i++) { + confirmtest('wait for confirms', function (ch) { + for (var i = 0; i < 1000; i++) { ch.publish('', '', Buffer.from('foobar'), {}); } return ch.waitForConfirms(); - }) + }); - confirmtest('works when channel is closed', function(ch) { - for (var i=0; i < 1000; i++) { + confirmtest('works when channel is closed', function (ch) { + for (var i = 0; i < 1000; i++) { ch.publish('', '', Buffer.from('foobar'), {}); } - return ch.close().then(function () { - return ch.waitForConfirms() - }).then(function () { - assert.strictEqual(true, false, 'Wait should have failed.') - }, function (e) { - assert.strictEqual(e.message, 'channel closed') - }); + return ch + .close() + .then(function () { + return ch.waitForConfirms(); + }) + .then( + function () { + assert.strictEqual(true, false, 'Wait should have failed.'); + }, + function (e) { + assert.strictEqual(e.message, 'channel closed'); + }, + ); }); - }); diff --git a/test/codec.js b/test/codec.js index 6048e9c9..09e54162 100644 --- a/test/codec.js +++ b/test/codec.js @@ -11,60 +11,80 @@ var forAll = C.forAll; // RabbitMQ's binary generator module. var testCases = [ - // integers - ['byte', {byte: 112}, [4,98,121,116,101,98,112]], - ['byte max value', {byte: 127}, [4,98,121,116,101,98,127]], - ['byte min value', {byte: -128}, [4,98,121,116,101,98,128]], - ['< -128 promoted to signed short', {short: -129}, [5,115,104,111,114,116,115,255,127]], - ['> 127 promoted to short', {short: 128}, [5,115,104,111,114,116,115,0,128]], - ['< 2^15 still a short', {short: 0x7fff}, [5,115,104,111,114,116,115,127,255]], - ['-2^15 still a short', {short: -0x8000}, [5,115,104,111,114,116,115,128,0]], - ['>= 2^15 promoted to int', {int: 0x8000}, [3,105,110,116,73,0,0,128,0]], - ['< -2^15 promoted to int', {int: -0x8001}, [3,105,110,116,73,255,255,127,255]], - ['< 2^31 still an int', {int: 0x7fffffff}, [3,105,110,116,73,127,255,255,255]], - ['>= -2^31 still an int', {int: -0x80000000}, [3,105,110,116,73,128,0,0,0]], - ['>= 2^31 promoted to long', {long: 0x80000000}, [4,108,111,110,103,108,0,0,0,0,128,0,0,0]], - ['< -2^31 promoted to long', {long: -0x80000001}, [4,108,111,110,103,108,255,255,255,255,127,255,255,255]], - - // floating point - ['float value', {double: 0.5}, [6,100,111,117,98,108,101,100,63,224,0,0,0,0,0,0]], - ['negative float value', {double: -0.5}, [6,100,111,117,98,108,101,100,191,224,0,0,0,0,0,0]], - // %% test some boundaries of precision? - - // string - ['string', {string: "boop"}, [6,115,116,114,105,110,103,83,0,0,0,4,98,111,111,112]], - - // buffer -> byte array - ['byte array from buffer', {bytes: Buffer.from([1,2,3,4])}, - [5,98,121,116,101,115,120,0,0,0,4,1,2,3,4]], - - // boolean, void - ['true', {bool: true}, [4,98,111,111,108,116,1]], - ['false', {bool: false}, [4,98,111,111,108,116,0]], - ['null', {'void': null}, [4,118,111,105,100,86]], - - // array, object - ['array', {array: [6, true, "foo"]},[5,97,114,114,97,121,65,0,0,0,12,98,6,116,1,83,0,0,0,3,102,111,111]], - ['object', {object: {foo: "bar", baz: 12}},[6,111,98,106,101,99,116,70,0,0,0,18,3,102,111,111,83,0,0,0,3,98,97,114,3,98,97,122,98,12]], - - // exotic types - ['timestamp', {timestamp: {'!': 'timestamp', value: 1357212277527}},[9,116,105,109,101,115,116,97,109,112,84,0,0,1,60,0,39,219,23]], - ['decimal', {decimal: {'!': 'decimal', value: {digits: 2345, places: 2}}},[7,100,101,99,105,109,97,108,68,2,0,0,9,41]], - ['float', {float: {'!': 'float', value: 0.1}},[5,102,108,111,97,116,102,61,204,204,205]], - ['unsignedbyte', {unsignedbyte:{'!': 'unsignedbyte', value: 255}}, [12,117,110,115,105,103,110,101,100,98,121,116,101,66,255]], - ['unsignedshort', {unsignedshort:{'!': 'unsignedshort', value: 65535}}, [13,117,110,115,105,103,110,101,100,115,104,111,114,116,117,255,255]], - ['unsignedint', {unsignedint:{'!': 'unsignedint', value: 4294967295}}, [11,117,110,115,105,103,110,101,100,105,110,116,105,255,255,255,255]], + // integers + ['byte', {byte: 112}, [4, 98, 121, 116, 101, 98, 112]], + ['byte max value', {byte: 127}, [4, 98, 121, 116, 101, 98, 127]], + ['byte min value', {byte: -128}, [4, 98, 121, 116, 101, 98, 128]], + ['< -128 promoted to signed short', {short: -129}, [5, 115, 104, 111, 114, 116, 115, 255, 127]], + ['> 127 promoted to short', {short: 128}, [5, 115, 104, 111, 114, 116, 115, 0, 128]], + ['< 2^15 still a short', {short: 0x7fff}, [5, 115, 104, 111, 114, 116, 115, 127, 255]], + ['-2^15 still a short', {short: -0x8000}, [5, 115, 104, 111, 114, 116, 115, 128, 0]], + ['>= 2^15 promoted to int', {int: 0x8000}, [3, 105, 110, 116, 73, 0, 0, 128, 0]], + ['< -2^15 promoted to int', {int: -0x8001}, [3, 105, 110, 116, 73, 255, 255, 127, 255]], + ['< 2^31 still an int', {int: 0x7fffffff}, [3, 105, 110, 116, 73, 127, 255, 255, 255]], + ['>= -2^31 still an int', {int: -0x80000000}, [3, 105, 110, 116, 73, 128, 0, 0, 0]], + ['>= 2^31 promoted to long', {long: 0x80000000}, [4, 108, 111, 110, 103, 108, 0, 0, 0, 0, 128, 0, 0, 0]], + ['< -2^31 promoted to long', {long: -0x80000001}, [4, 108, 111, 110, 103, 108, 255, 255, 255, 255, 127, 255, 255, 255]], + + // floating point + ['float value', {double: 0.5}, [6, 100, 111, 117, 98, 108, 101, 100, 63, 224, 0, 0, 0, 0, 0, 0]], + ['negative float value', {double: -0.5}, [6, 100, 111, 117, 98, 108, 101, 100, 191, 224, 0, 0, 0, 0, 0, 0]], + // %% test some boundaries of precision? + + // string + ['string', {string: 'boop'}, [6, 115, 116, 114, 105, 110, 103, 83, 0, 0, 0, 4, 98, 111, 111, 112]], + + // buffer -> byte array + ['byte array from buffer', {bytes: Buffer.from([1, 2, 3, 4])}, [5, 98, 121, 116, 101, 115, 120, 0, 0, 0, 4, 1, 2, 3, 4]], + + // boolean, void + ['true', {bool: true}, [4, 98, 111, 111, 108, 116, 1]], + ['false', {bool: false}, [4, 98, 111, 111, 108, 116, 0]], + ['null', {void: null}, [4, 118, 111, 105, 100, 86]], + + // array, object + ['array', {array: [6, true, 'foo']}, [5, 97, 114, 114, 97, 121, 65, 0, 0, 0, 12, 98, 6, 116, 1, 83, 0, 0, 0, 3, 102, 111, 111]], + [ + 'object', + {object: {foo: 'bar', baz: 12}}, + [6, 111, 98, 106, 101, 99, 116, 70, 0, 0, 0, 18, 3, 102, 111, 111, 83, 0, 0, 0, 3, 98, 97, 114, 3, 98, 97, 122, 98, 12], + ], + + // exotic types + [ + 'timestamp', + {timestamp: {'!': 'timestamp', value: 1357212277527}}, + [9, 116, 105, 109, 101, 115, 116, 97, 109, 112, 84, 0, 0, 1, 60, 0, 39, 219, 23], + ], + ['decimal', {decimal: {'!': 'decimal', value: {digits: 2345, places: 2}}}, [7, 100, 101, 99, 105, 109, 97, 108, 68, 2, 0, 0, 9, 41]], + ['float', {float: {'!': 'float', value: 0.1}}, [5, 102, 108, 111, 97, 116, 102, 61, 204, 204, 205]], + [ + 'unsignedbyte', + {unsignedbyte: {'!': 'unsignedbyte', value: 255}}, + [12, 117, 110, 115, 105, 103, 110, 101, 100, 98, 121, 116, 101, 66, 255], + ], + [ + 'unsignedshort', + {unsignedshort: {'!': 'unsignedshort', value: 65535}}, + [13, 117, 110, 115, 105, 103, 110, 101, 100, 115, 104, 111, 114, 116, 117, 255, 255], + ], + [ + 'unsignedint', + {unsignedint: {'!': 'unsignedint', value: 4294967295}}, + [11, 117, 110, 115, 105, 103, 110, 101, 100, 105, 110, 116, 105, 255, 255, 255, 255], + ], ]; function bufferToArray(b) { - return Array.prototype.slice.call(b); + return Array.prototype.slice.call(b); } -suite("Implicit encodings", function() { - - testCases.forEach(function(tc) { - var name = tc[0], val = tc[1], expect = tc[2]; - test(name, function() { +suite('Implicit encodings', function () { + testCases.forEach(function (tc) { + var name = tc[0], + val = tc[1], + expect = tc[2]; + test(name, function () { var buffer = Buffer.alloc(1000); var size = codec.encodeTable(buffer, val, 0); var result = buffer.subarray(4, size); @@ -83,16 +103,19 @@ function roundtrip_table(t) { var decoded = codec.decodeFields(buf.subarray(4, size)); // ignore the length-prefix try { assert.deepEqual(removeExplicitTypes(t), decoded); + } catch (e) { + return false; } - catch (e) { return false; } return true; } function roundtrips(T) { - return forAll(T).satisfy(function(v) { return roundtrip_table({value: v}); }); + return forAll(T).satisfy(function (v) { + return roundtrip_table({value: v}); + }); } -suite("Roundtrip values", function() { +suite('Roundtrip values', function () { [ amqp.Octet, amqp.ShortStr, @@ -112,8 +135,8 @@ suite("Roundtrip values", function() { amqp.Double, amqp.Float, amqp.FieldArray, - amqp.FieldTable - ].forEach(function(T) { + amqp.FieldTable, + ].forEach(function (T) { test(T.toString() + ' roundtrip', roundtrips(T).asTest()); }); }); @@ -122,39 +145,39 @@ suite("Roundtrip values", function() { // int32, 50}`. Most of these do not appear in the decoded values, so // to compare like-to-like we have to remove them from the input. function removeExplicitTypes(input) { - switch (typeof input) { + switch (typeof input) { case 'object': - if (input == null) { - return null; - } - if (Array.isArray(input)) { - var newArr = []; - for (var i = 0; i < input.length; i++) { - newArr[i] = removeExplicitTypes(input[i]); - } - return newArr; - } - if (Buffer.isBuffer(input)) { - return input; + if (input == null) { + return null; + } + if (Array.isArray(input)) { + var newArr = []; + for (var i = 0; i < input.length; i++) { + newArr[i] = removeExplicitTypes(input[i]); } - switch (input['!']) { + return newArr; + } + if (Buffer.isBuffer(input)) { + return input; + } + switch (input['!']) { case 'timestamp': case 'decimal': case 'float': - return input; + return input; case undefined: - var newObj = {} - for (var k in input) { - newObj[k] = removeExplicitTypes(input[k]); - } - return newObj; + var newObj = {}; + for (var k in input) { + newObj[k] = removeExplicitTypes(input[k]); + } + return newObj; default: - return input.value; - } + return input.value; + } default: - return input; - } + return input; + } } // Asserts that the decoded fields are equal to the original fields, @@ -169,7 +192,7 @@ function removeExplicitTypes(input) { // same so far as these tests are concerned. function assertEqualModuloDefaults(original, decodedFields) { var args = defs.info(original.id).args; - for (var i=0; i < args.length; i++) { + for (var i = 0; i < args.length; i++) { var arg = args[i]; var originalValue = original.fields[arg.name]; var decodedValue = decodedFields[arg.name]; @@ -178,18 +201,13 @@ function assertEqualModuloDefaults(original, decodedFields) { // longstr gets special treatment here, since the defaults are // given as strings rather than buffers, but the decoded values // will be buffers. - assert.deepEqual((arg.type === 'longstr') ? - Buffer.from(arg.default) : arg.default, - decodedValue); - } - else { + assert.deepEqual(arg.type === 'longstr' ? Buffer.from(arg.default) : arg.default, decodedValue); + } else { assert.deepEqual(removeExplicitTypes(originalValue), decodedValue); } - } - catch (assertionErr) { + } catch (assertionErr) { var methodOrProps = defs.info(original.id).name; - assertionErr.message += ' (frame ' + methodOrProps + - ' field ' + arg.name + ')'; + assertionErr.message += ' (frame ' + methodOrProps + ' field ' + arg.name + ')'; throw assertionErr; } } @@ -201,7 +219,7 @@ function assertEqualModuloDefaults(original, decodedFields) { module.exports.assertEqualModuloDefaults = assertEqualModuloDefaults; function roundtripMethod(Method) { - return forAll(Method).satisfy(function(method) { + return forAll(Method).satisfy(function (method) { var buf = defs.encodeMethod(method.id, 0, method.fields); // FIXME depends on framing, ugh var fs1 = defs.decode(method.id, buf.subarray(11, buf.length)); @@ -211,9 +229,8 @@ function roundtripMethod(Method) { } function roundtripProperties(Properties) { - return forAll(Properties).satisfy(function(properties) { - var buf = defs.encodeProperties(properties.id, 0, properties.size, - properties.fields); + return forAll(Properties).satisfy(function (properties) { + var buf = defs.encodeProperties(properties.id, 0, properties.size, properties.fields); // FIXME depends on framing, ugh var fs1 = defs.decode(properties.id, buf.subarray(19, buf.length)); assert.equal(properties.size, ints.readUInt64BE(buf, 11)); @@ -222,16 +239,14 @@ function roundtripProperties(Properties) { }); } -suite("Roundtrip methods", function() { - amqp.methods.forEach(function(Method) { - test(Method.toString() + ' roundtrip', - roundtripMethod(Method).asTest()); +suite('Roundtrip methods', function () { + amqp.methods.forEach(function (Method) { + test(Method.toString() + ' roundtrip', roundtripMethod(Method).asTest()); }); }); -suite("Roundtrip properties", function() { - amqp.properties.forEach(function(Properties) { - test(Properties.toString() + ' roundtrip', - roundtripProperties(Properties).asTest()); +suite('Roundtrip properties', function () { + amqp.properties.forEach(function (Properties) { + test(Properties.toString() + ' roundtrip', roundtripProperties(Properties).asTest()); }); }); diff --git a/test/connect.js b/test/connect.js index 281e7f2f..ec0b1fc2 100644 --- a/test/connect.js +++ b/test/connect.js @@ -6,70 +6,68 @@ var defs = require('../lib/defs'); var assert = require('assert'); var util = require('./util'); var net = require('net'); -var fail = util.fail, succeed = util.succeed, latch = util.latch, - kCallback = util.kCallback, - succeedIfAttributeEquals = util.succeedIfAttributeEquals; +var fail = util.fail, + succeed = util.succeed, + latch = util.latch, + kCallback = util.kCallback, + succeedIfAttributeEquals = util.succeedIfAttributeEquals; var format = require('util').format; var URL = process.env.URL || 'amqp://localhost'; var urlparse = require('url-parse'); -suite("Credentials", function() { - +suite('Credentials', function () { function checkCreds(creds, user, pass, done) { if (creds.mechanism != 'PLAIN') { return done('expected mechanism PLAIN'); } if (creds.username != user || creds.password != pass) { - return done(format("expected '%s', '%s'; got '%s', '%s'", - user, pass, creds.username, creds.password)); + return done(format("expected '%s', '%s'; got '%s', '%s'", user, pass, creds.username, creds.password)); } done(); } - test("no creds", function(done) { + test('no creds', function (done) { var parts = urlparse('amqp://localhost'); var creds = credentialsFromUrl(parts); checkCreds(creds, 'guest', 'guest', done); }); - test("usual user:pass", function(done) { - var parts = urlparse('amqp://user:pass@localhost') + test('usual user:pass', function (done) { + var parts = urlparse('amqp://user:pass@localhost'); var creds = credentialsFromUrl(parts); checkCreds(creds, 'user', 'pass', done); }); - test("missing user", function(done) { + test('missing user', function (done) { var parts = urlparse('amqps://:password@localhost'); var creds = credentialsFromUrl(parts); checkCreds(creds, '', 'password', done); }); - test("missing password", function(done) { + test('missing password', function (done) { var parts = urlparse('amqps://username:@localhost'); var creds = credentialsFromUrl(parts); checkCreds(creds, 'username', '', done); }); - test("escaped colons", function(done) { - var parts = urlparse('amqp://user%3Aname:pass%3Aword@localhost') + test('escaped colons', function (done) { + var parts = urlparse('amqp://user%3Aname:pass%3Aword@localhost'); var creds = credentialsFromUrl(parts); checkCreds(creds, 'user:name', 'pass:word', done); }); }); -suite("Connect API", function() { - - test("Connection refused", function(done) { - connect('amqp://localhost:23450', {}, - kCallback(fail(done), succeed(done))); +suite('Connect API', function () { + test('Connection refused', function (done) { + connect('amqp://localhost:23450', {}, kCallback(fail(done), succeed(done))); }); // %% this ought to fail the promise, rather than throwing an error - test("bad URL", function() { - assert.throws(function() { + test('bad URL', function () { + assert.throws(function () { connect('blurble'); }); }); - test("wrongly typed open option", function(done) { + test('wrongly typed open option', function (done) { var url = require('url'); var parts = url.parse(URL, true); var q = parts.query || {}; @@ -79,18 +77,20 @@ suite("Connect API", function() { connect(u, {}, kCallback(fail(done), succeed(done))); }); - test("serverProperties", function(done) { + test('serverProperties', function (done) { var url = require('url'); var parts = url.parse(URL, true); var config = parts.query || {}; - connect(config, {}, function(err, connection) { - if (err) { return done(err); } + connect(config, {}, function (err, connection) { + if (err) { + return done(err); + } assert.equal(connection.serverProperties.product, 'RabbitMQ'); done(); }); }); - test("using custom heartbeat option", function(done) { + test('using custom heartbeat option', function (done) { var url = require('url'); var parts = url.parse(URL, true); var config = parts.query || {}; @@ -98,7 +98,7 @@ suite("Connect API", function() { connect(config, {}, kCallback(succeedIfAttributeEquals('heartbeat', 20, done), fail(done))); }); - test("wrongly typed heartbeat option", function(done) { + test('wrongly typed heartbeat option', function (done) { var url = require('url'); var parts = url.parse(URL, true); var config = parts.query || {}; @@ -106,97 +106,101 @@ suite("Connect API", function() { connect(config, {}, kCallback(fail(done), succeed(done))); }); - test("using plain credentials", function(done) { + test('using plain credentials', function (done) { var url = require('url'); var parts = url.parse(URL, true); - var u = 'guest', p = 'guest'; + var u = 'guest', + p = 'guest'; if (parts.auth) { - var auth = parts.auth.split(":"); - u = auth[0], p = auth[1]; + var auth = parts.auth.split(':'); + (u = auth[0]), (p = auth[1]); } - connect(URL, {credentials: require('../lib/credentials').plain(u, p)}, - kCallback(succeed(done), fail(done))); + connect(URL, {credentials: require('../lib/credentials').plain(u, p)}, kCallback(succeed(done), fail(done))); }); - test("using amqplain credentials", function(done) { + test('using amqplain credentials', function (done) { var url = require('url'); var parts = url.parse(URL, true); - var u = 'guest', p = 'guest'; + var u = 'guest', + p = 'guest'; if (parts.auth) { - var auth = parts.auth.split(":"); - u = auth[0], p = auth[1]; + var auth = parts.auth.split(':'); + (u = auth[0]), (p = auth[1]); } - connect(URL, {credentials: require('../lib/credentials').amqplain(u, p)}, - kCallback(succeed(done), fail(done))); + connect(URL, {credentials: require('../lib/credentials').amqplain(u, p)}, kCallback(succeed(done), fail(done))); }); - test("ipv6", function(done) { - connect('amqp://[::1]', {}, function(err, connection) { - if (err) { return done(err); } + test('ipv6', function (done) { + connect('amqp://[::1]', {}, function (err, connection) { + if (err) { + return done(err); + } done(); }); }); - test("using unsupported mechanism", function(done) { + test('using unsupported mechanism', function (done) { var creds = { mechanism: 'UNSUPPORTED', - response: function() { return Buffer.from(''); } + response: function () { + return Buffer.from(''); + }, }; - connect(URL, {credentials: creds}, - kCallback(fail(done), succeed(done))); + connect(URL, {credentials: creds}, kCallback(fail(done), succeed(done))); }); - test("with a given connection timeout", function(done) { - var timeoutServer = net.createServer(function() {}).listen(31991); + test('with a given connection timeout', function (done) { + var timeoutServer = net.createServer(function () {}).listen(31991); - connect('amqp://localhost:31991', {timeout: 50}, function(err, val) { - timeoutServer.close(); - if (val) done(new Error('Expected connection timeout, did not')); - else done(); + connect('amqp://localhost:31991', {timeout: 50}, function (err, val) { + timeoutServer.close(); + if (val) done(new Error('Expected connection timeout, did not')); + else done(); }); }); }); -suite('Errors on connect', function() { - var server - teardown(function() { +suite('Errors on connect', function () { + var server; + teardown(function () { if (server) { server.close(); } - }) + }); - test("closes underlying connection on authentication error", function(done) { + test('closes underlying connection on authentication error', function (done) { var bothDone = latch(2, done); - server = net.createServer(function(socket) { - socket.once('data', function(protocolHeader) { - assert.deepStrictEqual( - protocolHeader, - Buffer.from("AMQP" + String.fromCharCode(0,0,9,1)) - ); - util.runServer(socket, function(send, wait) { - send(defs.ConnectionStart, - {versionMajor: 0, + server = net + .createServer(function (socket) { + socket.once('data', function (protocolHeader) { + assert.deepStrictEqual(protocolHeader, Buffer.from('AMQP' + String.fromCharCode(0, 0, 9, 1))); + util.runServer(socket, function (send, wait) { + send(defs.ConnectionStart, { + versionMajor: 0, versionMinor: 9, serverProperties: {}, mechanisms: Buffer.from('PLAIN'), - locales: Buffer.from('en_US')}); - wait(defs.ConnectionStartOk)().then(function() { - send(defs.ConnectionClose, - {replyCode: 403, - replyText: 'ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN', - classId: 0, - methodId: 0}); + locales: Buffer.from('en_US'), + }); + wait(defs.ConnectionStartOk)().then(function () { + send(defs.ConnectionClose, { + replyCode: 403, + replyText: 'ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN', + classId: 0, + methodId: 0, + }); + }); }); }); - }); - // Wait for the connection to be closed after the authentication error - socket.once('end', function() { - bothDone(); - }); - }).listen(0); + // Wait for the connection to be closed after the authentication error + socket.once('end', function () { + bothDone(); + }); + }) + .listen(0); - connect('amqp://localhost:' + server.address().port, {}, function(err) { + connect('amqp://localhost:' + server.address().port, {}, function (err) { if (!err) bothDone(new Error('Expected authentication error')); bothDone(); }); diff --git a/test/connection.js b/test/connection.js index e6d23fb6..07900623 100644 --- a/test/connection.js +++ b/test/connection.js @@ -6,7 +6,9 @@ var Connection = require('../lib/connection').Connection; var HEARTBEAT = require('../lib/frame').HEARTBEAT; var HB_BUF = require('../lib/frame').HEARTBEAT_BUF; var util = require('./util'); -var succeed = util.succeed, fail = util.fail, latch = util.latch; +var succeed = util.succeed, + fail = util.fail, + latch = util.latch; var completes = util.completes; var kCallback = util.kCallback; @@ -14,49 +16,46 @@ var LOG_ERRORS = process.env.LOG_ERRORS; var OPEN_OPTS = { // start-ok - 'clientProperties': {}, - 'mechanism': 'PLAIN', - 'response': Buffer.from(['', 'guest', 'guest'].join(String.fromCharCode(0))), - 'locale': 'en_US', + clientProperties: {}, + mechanism: 'PLAIN', + response: Buffer.from(['', 'guest', 'guest'].join(String.fromCharCode(0))), + locale: 'en_US', // tune-ok - 'channelMax': 0, - 'frameMax': 0, - 'heartbeat': 0, + channelMax: 0, + frameMax: 0, + heartbeat: 0, // open - 'virtualHost': '/', - 'capabilities': '', - 'insist': 0 + virtualHost: '/', + capabilities: '', + insist: 0, }; module.exports.OPEN_OPTS = OPEN_OPTS; function happy_open(send, wait) { // kick it off - send(defs.ConnectionStart, - {versionMajor: 0, - versionMinor: 9, - serverProperties: {}, - mechanisms: Buffer.from('PLAIN'), - locales: Buffer.from('en_US')}); + send(defs.ConnectionStart, { + versionMajor: 0, + versionMinor: 9, + serverProperties: {}, + mechanisms: Buffer.from('PLAIN'), + locales: Buffer.from('en_US'), + }); return wait(defs.ConnectionStartOk)() - .then(function(f) { - send(defs.ConnectionTune, - {channelMax: 0, - heartbeat: 0, - frameMax: 0}); + .then(function (f) { + send(defs.ConnectionTune, {channelMax: 0, heartbeat: 0, frameMax: 0}); }) .then(wait(defs.ConnectionTuneOk)) .then(wait(defs.ConnectionOpen)) - .then(function(f) { - send(defs.ConnectionOpenOk, - {knownHosts: ''}); + .then(function (f) { + send(defs.ConnectionOpenOk, {knownHosts: ''}); }); } module.exports.connection_handshake = happy_open; function connectionTest(client, server) { - return function(done) { + return function (done) { var bothDone = latch(2, done); var pair = util.socketPair(); var c = new Connection(pair.client); @@ -65,326 +64,391 @@ function connectionTest(client, server) { // NB only not a race here because the writes are synchronous var protocolHeader = pair.server.read(8); - assert.deepEqual(Buffer.from("AMQP" + String.fromCharCode(0,0,9,1)), - protocolHeader); + assert.deepEqual(Buffer.from('AMQP' + String.fromCharCode(0, 0, 9, 1)), protocolHeader); - var s = util.runServer(pair.server, function(send, wait) { + var s = util.runServer(pair.server, function (send, wait) { server(send, wait, bothDone, pair.server); }); }; } -suite("Connection errors", function() { - - test("socket close during open", function(done) { +suite('Connection errors', function () { + test('socket close during open', function (done) { // RabbitMQ itself will take at least 3 seconds to close the socket // in the event of a handshake problem. Instead of using a live // connection, I'm just going to pretend. var pair = util.socketPair(); var conn = new Connection(pair.client); - pair.server.on('readable', function() { + pair.server.on('readable', function () { pair.server.end(); }); conn.open({}, kCallback(fail(done), succeed(done))); }); - test("bad frame during open", function(done) { + test('bad frame during open', function (done) { var ss = util.socketPair(); var conn = new (require('../lib/connection').Connection)(ss.client); - ss.server.on('readable', function() { + ss.server.on('readable', function () { ss.server.write(Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])); }); conn.open({}, kCallback(fail(done), succeed(done))); }); - }); -suite("Connection open", function() { - -test("happy", connectionTest( - function(c, done) { - c.open(OPEN_OPTS, kCallback(succeed(done), fail(done))); - }, - function(send, wait, done) { - happy_open(send, wait).then(succeed(done), fail(done)); - })); - -test("wrong first frame", connectionTest( - function(c, done) { - c.open(OPEN_OPTS, kCallback(fail(done), succeed(done))); - }, - function(send, wait, done) { - // bad server! bad! whatever were you thinking? - completes(function() { - send(defs.ConnectionTune, - {channelMax: 0, - heartbeat: 0, - frameMax: 0}); - }, done); - })); - -test("unexpected socket close", connectionTest( - function(c, done) { - c.open(OPEN_OPTS, kCallback(fail(done), succeed(done))); - }, - function(send, wait, done, socket) { - send(defs.ConnectionStart, - {versionMajor: 0, +suite('Connection open', function () { + test( + 'happy', + connectionTest( + function (c, done) { + c.open(OPEN_OPTS, kCallback(succeed(done), fail(done))); + }, + function (send, wait, done) { + happy_open(send, wait).then(succeed(done), fail(done)); + }, + ), + ); + + test( + 'wrong first frame', + connectionTest( + function (c, done) { + c.open(OPEN_OPTS, kCallback(fail(done), succeed(done))); + }, + function (send, wait, done) { + // bad server! bad! whatever were you thinking? + completes(function () { + send(defs.ConnectionTune, {channelMax: 0, heartbeat: 0, frameMax: 0}); + }, done); + }, + ), + ); + + test( + 'unexpected socket close', + connectionTest( + function (c, done) { + c.open(OPEN_OPTS, kCallback(fail(done), succeed(done))); + }, + function (send, wait, done, socket) { + send(defs.ConnectionStart, { + versionMajor: 0, versionMinor: 9, serverProperties: {}, mechanisms: Buffer.from('PLAIN'), - locales: Buffer.from('en_US')}); - return wait(defs.ConnectionStartOk)() - .then(function() { - socket.end(); - }) - .then(succeed(done), fail(done)); - })); - -}); - -suite("Connection running", function() { - -test("wrong frame on channel 0", connectionTest( - function(c, done) { - c.on('error', succeed(done)); - c.open(OPEN_OPTS); - }, - function(send, wait, done) { - happy_open(send, wait) - .then(function() { - // there's actually nothing that would plausibly be sent to a - // just opened connection, so this is violating more than one - // rule. Nonetheless. - send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, 0); - }) - .then(wait(defs.ConnectionClose)) - .then(function(close) { - send(defs.ConnectionCloseOk, {}, 0); - }).then(succeed(done), fail(done)); - })); - -test("unopened channel", connectionTest( - function(c, done) { - c.on('error', succeed(done)); - c.open(OPEN_OPTS); - }, - function(send, wait, done) { - happy_open(send, wait) - .then(function() { - // there's actually nothing that would plausibly be sent to a - // just opened connection, so this is violating more than one - // rule. Nonetheless. - send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, 3); - }) - .then(wait(defs.ConnectionClose)) - .then(function(close) { - send(defs.ConnectionCloseOk, {}, 0); - }).then(succeed(done), fail(done)); - })); - -test("unexpected socket close", connectionTest( - function(c, done) { - var errorAndClosed = latch(2, done); - c.on('error', succeed(errorAndClosed)); - c.on('close', succeed(errorAndClosed)); - c.open(OPEN_OPTS, kCallback(function() { - c.sendHeartbeat(); - }, fail(errorAndClosed))); - }, - function(send, wait, done, socket) { - happy_open(send, wait) - .then(wait()) - .then(function() { - socket.end(); - }).then(succeed(done)); - })); - -test("connection.blocked", connectionTest( - function(c, done) { - c.on('blocked', succeed(done)); - c.open(OPEN_OPTS); - }, - function(send, wait, done, socket) { - happy_open(send, wait) - .then(function() { - send(defs.ConnectionBlocked, {reason: 'felt like it'}, 0); - }) - .then(succeed(done)); - })); - -test("connection.unblocked", connectionTest( - function(c, done) { - c.on('unblocked', succeed(done)); - c.open(OPEN_OPTS); - }, - function(send, wait, done, socket) { - happy_open(send, wait) - .then(function() { - send(defs.ConnectionUnblocked, {}, 0); - }) - .then(succeed(done)); - })); - - -}); - -suite("Connection close", function() { - -test("happy", connectionTest( - function(c, done0) { - var done = latch(2, done0); - c.on('close', done); - c.open(OPEN_OPTS, kCallback(function(_ok) { - c.close(kCallback(succeed(done), fail(done))); - }, function() {})); - }, - function(send, wait, done) { - happy_open(send, wait) - .then(wait(defs.ConnectionClose)) - .then(function(close) { - send(defs.ConnectionCloseOk, {}); - }) - .then(succeed(done), fail(done)); - })); - -test("interleaved close frames", connectionTest( - function(c, done0) { - var done = latch(2, done0); - c.on('close', done); - c.open(OPEN_OPTS, kCallback(function(_ok) { - c.close(kCallback(succeed(done), fail(done))); - }, done)); - }, - function(send, wait, done) { - happy_open(send, wait) - .then(wait(defs.ConnectionClose)) - .then(function(f) { - send(defs.ConnectionClose, { - replyText: "Ha!", - replyCode: defs.constants.REPLY_SUCCESS, - methodId: 0, classId: 0 - }); - }) - .then(wait(defs.ConnectionCloseOk)) - .then(function(f) { - send(defs.ConnectionCloseOk, {}); - }) - .then(succeed(done), fail(done)); - })); - -test("server error close", connectionTest( - function(c, done0) { - var done = latch(2, done0); - c.on('close', succeed(done)); - c.on('error', succeed(done)); - c.open(OPEN_OPTS); - }, - function(send, wait, done) { - happy_open(send, wait) - .then(function(f) { - send(defs.ConnectionClose, { - replyText: "Begone", - replyCode: defs.constants.INTERNAL_ERROR, - methodId: 0, classId: 0 - }); - }) - .then(wait(defs.ConnectionCloseOk)) - .then(succeed(done), fail(done)); - })); - -test("operator-intiated close", connectionTest( - function(c, done) { - c.on('close', succeed(done)); - c.on('error', fail(done)); - c.open(OPEN_OPTS); - }, - function(send, wait, done) { - happy_open(send, wait) - .then(function(f) { - send(defs.ConnectionClose, { - replyText: "Begone", - replyCode: defs.constants.CONNECTION_FORCED, - methodId: 0, classId: 0 + locales: Buffer.from('en_US'), }); - }) - .then(wait(defs.ConnectionCloseOk)) - .then(succeed(done), fail(done)); - })); - - -test("double close", connectionTest( - function(c, done) { - c.open(OPEN_OPTS, kCallback(function() { - c.close(); - // NB no synchronisation, we do this straight away - assert.throws(function() { - c.close(); - }); - done(); - }, done)); - }, - function(send, wait, done) { - happy_open(send, wait) - .then(wait(defs.ConnectionClose)) - .then(function() { - send(defs.ConnectionCloseOk, {}); - }) - .then(succeed(done), fail(done)); - })); - + return wait(defs.ConnectionStartOk)() + .then(function () { + socket.end(); + }) + .then(succeed(done), fail(done)); + }, + ), + ); }); -suite("heartbeats", function() { - -var heartbeat = require('../lib/heartbeat'); - -setup(function() { - heartbeat.UNITS_TO_MS = 20; +suite('Connection running', function () { + test( + 'wrong frame on channel 0', + connectionTest( + function (c, done) { + c.on('error', succeed(done)); + c.open(OPEN_OPTS); + }, + function (send, wait, done) { + happy_open(send, wait) + .then(function () { + // there's actually nothing that would plausibly be sent to a + // just opened connection, so this is violating more than one + // rule. Nonetheless. + send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, 0); + }) + .then(wait(defs.ConnectionClose)) + .then(function (close) { + send(defs.ConnectionCloseOk, {}, 0); + }) + .then(succeed(done), fail(done)); + }, + ), + ); + + test( + 'unopened channel', + connectionTest( + function (c, done) { + c.on('error', succeed(done)); + c.open(OPEN_OPTS); + }, + function (send, wait, done) { + happy_open(send, wait) + .then(function () { + // there's actually nothing that would plausibly be sent to a + // just opened connection, so this is violating more than one + // rule. Nonetheless. + send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, 3); + }) + .then(wait(defs.ConnectionClose)) + .then(function (close) { + send(defs.ConnectionCloseOk, {}, 0); + }) + .then(succeed(done), fail(done)); + }, + ), + ); + + test( + 'unexpected socket close', + connectionTest( + function (c, done) { + var errorAndClosed = latch(2, done); + c.on('error', succeed(errorAndClosed)); + c.on('close', succeed(errorAndClosed)); + c.open( + OPEN_OPTS, + kCallback(function () { + c.sendHeartbeat(); + }, fail(errorAndClosed)), + ); + }, + function (send, wait, done, socket) { + happy_open(send, wait) + .then(wait()) + .then(function () { + socket.end(); + }) + .then(succeed(done)); + }, + ), + ); + + test( + 'connection.blocked', + connectionTest( + function (c, done) { + c.on('blocked', succeed(done)); + c.open(OPEN_OPTS); + }, + function (send, wait, done, socket) { + happy_open(send, wait) + .then(function () { + send(defs.ConnectionBlocked, {reason: 'felt like it'}, 0); + }) + .then(succeed(done)); + }, + ), + ); + + test( + 'connection.unblocked', + connectionTest( + function (c, done) { + c.on('unblocked', succeed(done)); + c.open(OPEN_OPTS); + }, + function (send, wait, done, socket) { + happy_open(send, wait) + .then(function () { + send(defs.ConnectionUnblocked, {}, 0); + }) + .then(succeed(done)); + }, + ), + ); }); -teardown(function() { - heartbeat.UNITS_TO_MS = 1000; +suite('Connection close', function () { + test( + 'happy', + connectionTest( + function (c, done0) { + var done = latch(2, done0); + c.on('close', done); + c.open( + OPEN_OPTS, + kCallback( + function (_ok) { + c.close(kCallback(succeed(done), fail(done))); + }, + function () {}, + ), + ); + }, + function (send, wait, done) { + happy_open(send, wait) + .then(wait(defs.ConnectionClose)) + .then(function (close) { + send(defs.ConnectionCloseOk, {}); + }) + .then(succeed(done), fail(done)); + }, + ), + ); + + test( + 'interleaved close frames', + connectionTest( + function (c, done0) { + var done = latch(2, done0); + c.on('close', done); + c.open( + OPEN_OPTS, + kCallback(function (_ok) { + c.close(kCallback(succeed(done), fail(done))); + }, done), + ); + }, + function (send, wait, done) { + happy_open(send, wait) + .then(wait(defs.ConnectionClose)) + .then(function (f) { + send(defs.ConnectionClose, { + replyText: 'Ha!', + replyCode: defs.constants.REPLY_SUCCESS, + methodId: 0, + classId: 0, + }); + }) + .then(wait(defs.ConnectionCloseOk)) + .then(function (f) { + send(defs.ConnectionCloseOk, {}); + }) + .then(succeed(done), fail(done)); + }, + ), + ); + + test( + 'server error close', + connectionTest( + function (c, done0) { + var done = latch(2, done0); + c.on('close', succeed(done)); + c.on('error', succeed(done)); + c.open(OPEN_OPTS); + }, + function (send, wait, done) { + happy_open(send, wait) + .then(function (f) { + send(defs.ConnectionClose, { + replyText: 'Begone', + replyCode: defs.constants.INTERNAL_ERROR, + methodId: 0, + classId: 0, + }); + }) + .then(wait(defs.ConnectionCloseOk)) + .then(succeed(done), fail(done)); + }, + ), + ); + + test( + 'operator-intiated close', + connectionTest( + function (c, done) { + c.on('close', succeed(done)); + c.on('error', fail(done)); + c.open(OPEN_OPTS); + }, + function (send, wait, done) { + happy_open(send, wait) + .then(function (f) { + send(defs.ConnectionClose, { + replyText: 'Begone', + replyCode: defs.constants.CONNECTION_FORCED, + methodId: 0, + classId: 0, + }); + }) + .then(wait(defs.ConnectionCloseOk)) + .then(succeed(done), fail(done)); + }, + ), + ); + + test( + 'double close', + connectionTest( + function (c, done) { + c.open( + OPEN_OPTS, + kCallback(function () { + c.close(); + // NB no synchronisation, we do this straight away + assert.throws(function () { + c.close(); + }); + done(); + }, done), + ); + }, + function (send, wait, done) { + happy_open(send, wait) + .then(wait(defs.ConnectionClose)) + .then(function () { + send(defs.ConnectionCloseOk, {}); + }) + .then(succeed(done), fail(done)); + }, + ), + ); }); -test("send heartbeat after open", connectionTest( - function(c, done) { - completes(function() { - var opts = Object.create(OPEN_OPTS); - opts.heartbeat = 1; - // Don't leave the error waiting to happen for the next test, this - // confuses mocha awfully - c.on('error', function() {}); - c.open(opts); - }, done); - }, - function(send, wait, done, socket) { - var timer; - happy_open(send, wait) - .then(function() { - timer = setInterval(function() { - socket.write(HB_BUF); - }, heartbeat.UNITS_TO_MS); - }) - .then(wait()) - .then(function(hb) { - if (hb === HEARTBEAT) done(); - else done("Next frame after silence not a heartbeat"); - clearInterval(timer); - }); - })); +suite('heartbeats', function () { + var heartbeat = require('../lib/heartbeat'); + + setup(function () { + heartbeat.UNITS_TO_MS = 20; + }); -test("detect lack of heartbeats", connectionTest( - function(c, done) { - var opts = Object.create(OPEN_OPTS); - opts.heartbeat = 1; - c.on('error', succeed(done)); - c.open(opts); - }, - function(send, wait, done, socket) { - happy_open(send, wait) - .then(succeed(done), fail(done)); - // conspicuously not sending anything ... - })); + teardown(function () { + heartbeat.UNITS_TO_MS = 1000; + }); + test( + 'send heartbeat after open', + connectionTest( + function (c, done) { + completes(function () { + var opts = Object.create(OPEN_OPTS); + opts.heartbeat = 1; + // Don't leave the error waiting to happen for the next test, this + // confuses mocha awfully + c.on('error', function () {}); + c.open(opts); + }, done); + }, + function (send, wait, done, socket) { + var timer; + happy_open(send, wait) + .then(function () { + timer = setInterval(function () { + socket.write(HB_BUF); + }, heartbeat.UNITS_TO_MS); + }) + .then(wait()) + .then(function (hb) { + if (hb === HEARTBEAT) done(); + else done('Next frame after silence not a heartbeat'); + clearInterval(timer); + }); + }, + ), + ); + + test( + 'detect lack of heartbeats', + connectionTest( + function (c, done) { + var opts = Object.create(OPEN_OPTS); + opts.heartbeat = 1; + c.on('error', succeed(done)); + c.open(opts); + }, + function (send, wait, done, socket) { + happy_open(send, wait).then(succeed(done), fail(done)); + // conspicuously not sending anything ... + }, + ), + ); }); diff --git a/test/data.js b/test/data.js index d2dbe2e5..39b6e06b 100644 --- a/test/data.js +++ b/test/data.js @@ -30,8 +30,12 @@ function chooseInt(a, b) { } function rangeInt(name, a, b) { - return label(name, - asGenerator(function(_) { return chooseInt(a, b); })); + return label( + name, + asGenerator(function (_) { + return chooseInt(a, b); + }), + ); } function toFloat32(i) { @@ -41,66 +45,85 @@ function toFloat32(i) { } function floatChooser(maxExp) { - return function() { + return function () { var n = Number.NaN; while (isNaN(n)) { var mantissa = Math.random() * 2 - 1; var exponent = chooseInt(0, maxExp); n = Math.pow(mantissa, exponent); - } + } return n; - } + }; } function explicitType(t, underlying) { - return label(t, transform(function(n) { - return {'!': t, value: n}; - }, underlying)); + return label( + t, + transform(function (n) { + return {'!': t, value: n}; + }, underlying), + ); } // FIXME null, byte array, others? var Octet = rangeInt('octet', 0, 255); -var ShortStr = label('shortstr', - transform(function(s) { - return s.substr(0, 255); - }, arb.Str)); - -var LongStr = label('longstr', - transform( - function(bytes) { return Buffer.from(bytes); }, - repeat(Octet))); +var ShortStr = label( + 'shortstr', + transform(function (s) { + return s.substr(0, 255); + }, arb.Str), +); + +var LongStr = label( + 'longstr', + transform(function (bytes) { + return Buffer.from(bytes); + }, repeat(Octet)), +); var UShort = rangeInt('short-uint', 0, 0xffff); var ULong = rangeInt('long-uint', 0, 0xffffffff); var ULongLong = rangeInt('longlong-uint', 0, 0xffffffffffffffff); var Short = rangeInt('short-int', -0x8000, 0x7fff); var Long = rangeInt('long-int', -0x80000000, 0x7fffffff); -var LongLong = rangeInt('longlong-int', -0x8000000000000000, - 0x7fffffffffffffff); +var LongLong = rangeInt('longlong-int', -0x8000000000000000, 0x7fffffffffffffff); var Bit = label('bit', arb.Bool); var Double = label('double', asGenerator(floatChooser(308))); var Float = label('float', transform(toFloat32, floatChooser(38))); -var Timestamp = label('timestamp', transform( - function(n) { +var Timestamp = label( + 'timestamp', + transform(function (n) { return {'!': 'timestamp', value: n}; - }, ULongLong)); -var Decimal = label('decimal', transform( - function(args) { - return {'!': 'decimal', value: {places: args[1], digits: args[0]}}; - }, sequence(arb.UInt, Octet))); -var UnsignedByte = label('unsignedbyte', transform( - function(n) { + }, ULongLong), +); +var Decimal = label( + 'decimal', + transform( + function (args) { + return {'!': 'decimal', value: {places: args[1], digits: args[0]}}; + }, + sequence(arb.UInt, Octet), + ), +); +var UnsignedByte = label( + 'unsignedbyte', + transform(function (n) { return {'!': 'unsignedbyte', value: n}; - }, Octet)); -var UnsignedShort = label('unsignedshort', transform( - function(n) { + }, Octet), +); +var UnsignedShort = label( + 'unsignedshort', + transform(function (n) { return {'!': 'unsignedshort', value: n}; - }, UShort)); -var UnsignedInt = label('unsignedint', transform( - function(n) { + }, UShort), +); +var UnsignedInt = label( + 'unsignedint', + transform(function (n) { return {'!': 'unsignedint', value: n}; - }, ULong)); + }, ULong), +); // Signed 8 bit int var Byte = rangeInt('byte', -128, 127); @@ -115,58 +138,178 @@ var ExInt32 = explicitType('int32', Long); var ExLong = explicitType('long', LongLong); var ExInt64 = explicitType('int64', LongLong); -var FieldArray = label('field-array', recursive(function() { - return arb.Array( - arb.Null, - LongStr, ShortStr, - Octet, UShort, ULong, ULongLong, - Byte, Short, Long, LongLong, - ExByte, ExInt8, ExShort, ExInt16, - ExInt, ExInt32, ExLong, ExInt64, - Bit, Float, Double, FieldTable, FieldArray) -})); - -var FieldTable = label('table', recursive(function() { - return sized(function() { return 5; }, - arb.Object( - arb.Null, - LongStr, ShortStr, Octet, - UShort, ULong, ULongLong, - Byte, Short, Long, LongLong, - ExByte, ExInt8, ExShort, ExInt16, - ExInt, ExInt32, ExLong, ExInt64, - Bit, Float, Double, FieldArray, FieldTable)) -})); +var FieldArray = label( + 'field-array', + recursive(function () { + return arb.Array( + arb.Null, + LongStr, + ShortStr, + Octet, + UShort, + ULong, + ULongLong, + Byte, + Short, + Long, + LongLong, + ExByte, + ExInt8, + ExShort, + ExInt16, + ExInt, + ExInt32, + ExLong, + ExInt64, + Bit, + Float, + Double, + FieldTable, + FieldArray, + ); + }), +); + +var FieldTable = label( + 'table', + recursive(function () { + return sized( + function () { + return 5; + }, + arb.Object( + arb.Null, + LongStr, + ShortStr, + Octet, + UShort, + ULong, + ULongLong, + Byte, + Short, + Long, + LongLong, + ExByte, + ExInt8, + ExShort, + ExInt16, + ExInt, + ExInt32, + ExLong, + ExInt64, + Bit, + Float, + Double, + FieldArray, + FieldTable, + ), + ); + }), +); // Internal tests of our properties var domainProps = [ - [Octet, function(n) { return n >= 0 && n < 256; }], - [ShortStr, function(s) { return typeof s === 'string' && s.length < 256; }], - [LongStr, function(s) { return Buffer.isBuffer(s); }], - [UShort, function(n) { return n >= 0 && n <= 0xffff; }], - [ULong, function(n) { return n >= 0 && n <= 0xffffffff; }], - [ULongLong, function(n) { - return n >= 0 && n <= 0xffffffffffffffff; }], - [Short, function(n) { return n >= -0x8000 && n <= 0x8000; }], - [Long, function(n) { return n >= -0x80000000 && n < 0x80000000; }], - [LongLong, function(n) { return n >= -0x8000000000000000 && n < 0x8000000000000000; }], - [Bit, function(b) { return typeof b === 'boolean'; }], - [Double, function(f) { return !isNaN(f) && isFinite(f); }], - [Float, function(f) { return !isNaN(f) && isFinite(f) && (Math.log(Math.abs(f)) * Math.LOG10E) < 309; }], - [Decimal, function(d) { - return d['!'] === 'decimal' && - d.value['places'] <= 255 && - d.value['digits'] <= 0xffffffff; - }], - [Timestamp, function(t) { return t['!'] === 'timestamp'; }], - [FieldTable, function(t) { return typeof t === 'object'; }], - [FieldArray, function(a) { return Array.isArray(a); }] + [ + Octet, + function (n) { + return n >= 0 && n < 256; + }, + ], + [ + ShortStr, + function (s) { + return typeof s === 'string' && s.length < 256; + }, + ], + [ + LongStr, + function (s) { + return Buffer.isBuffer(s); + }, + ], + [ + UShort, + function (n) { + return n >= 0 && n <= 0xffff; + }, + ], + [ + ULong, + function (n) { + return n >= 0 && n <= 0xffffffff; + }, + ], + [ + ULongLong, + function (n) { + return n >= 0 && n <= 0xffffffffffffffff; + }, + ], + [ + Short, + function (n) { + return n >= -0x8000 && n <= 0x8000; + }, + ], + [ + Long, + function (n) { + return n >= -0x80000000 && n < 0x80000000; + }, + ], + [ + LongLong, + function (n) { + return n >= -0x8000000000000000 && n < 0x8000000000000000; + }, + ], + [ + Bit, + function (b) { + return typeof b === 'boolean'; + }, + ], + [ + Double, + function (f) { + return !isNaN(f) && isFinite(f); + }, + ], + [ + Float, + function (f) { + return !isNaN(f) && isFinite(f) && Math.log(Math.abs(f)) * Math.LOG10E < 309; + }, + ], + [ + Decimal, + function (d) { + return d['!'] === 'decimal' && d.value['places'] <= 255 && d.value['digits'] <= 0xffffffff; + }, + ], + [ + Timestamp, + function (t) { + return t['!'] === 'timestamp'; + }, + ], + [ + FieldTable, + function (t) { + return typeof t === 'object'; + }, + ], + [ + FieldArray, + function (a) { + return Array.isArray(a); + }, + ], ]; -suite("Domains", function() { - domainProps.forEach(function(p) { - test(p[0] + ' domain', - forAll(p[0]).satisfy(p[1]).asTest({times: 500})); +suite('Domains', function () { + domainProps.forEach(function (p) { + test(p[0] + ' domain', forAll(p[0]).satisfy(p[1]).asTest({times: 500})); }); }); @@ -176,43 +319,48 @@ var ArgTimestamp = label('timestamp', ULongLong); // These are the domains used in method arguments var ARG_TYPES = { - 'octet': Octet, - 'shortstr': ShortStr, - 'longstr': LongStr, - 'short': UShort, - 'long': ULong, - 'longlong': ULongLong, - 'bit': Bit, - 'table': FieldTable, - 'timestamp': ArgTimestamp + octet: Octet, + shortstr: ShortStr, + longstr: LongStr, + short: UShort, + long: ULong, + longlong: ULongLong, + bit: Bit, + table: FieldTable, + timestamp: ArgTimestamp, }; function argtype(thing) { if (thing.default === undefined) { return ARG_TYPES[thing.type]; - } - else { + } else { return choice(ARG_TYPES[thing.type], Undefined); } } function zipObject(vals, names) { var obj = {}; - vals.forEach(function(v, i) { obj[names[i]] = v; }); + vals.forEach(function (v, i) { + obj[names[i]] = v; + }); return obj; } -function name(arg) { return arg.name; } +function name(arg) { + return arg.name; +} var defs = require('../lib/defs'); function method(info) { var domain = sequence.apply(null, info.args.map(argtype)); var names = info.args.map(name); - return label(info.name, transform(function(fieldVals) { - return {id: info.id, - fields: zipObject(fieldVals, names)}; - }, domain)); + return label( + info.name, + transform(function (fieldVals) { + return {id: info.id, fields: zipObject(fieldVals, names)}; + }, domain), + ); } function properties(info) { @@ -220,11 +368,12 @@ function properties(info) { types.unshift(ULongLong); // size var domain = sequence.apply(null, types); var names = info.args.map(name); - return label(info.name, transform(function(fieldVals) { - return {id: info.id, - size: fieldVals[0], - fields: zipObject(fieldVals.slice(1), names)}; - }, domain)); + return label( + info.name, + transform(function (fieldVals) { + return {id: info.id, size: fieldVals[0], fields: zipObject(fieldVals.slice(1), names)}; + }, domain), + ); } var methods = []; @@ -234,12 +383,11 @@ for (var k in defs) { if (k.substr(0, 10) === 'methodInfo') { methods.push(method(defs[k])); methods[defs[k].name] = method(defs[k]); - } - else if (k.substr(0, 14) === 'propertiesInfo') { + } else if (k.substr(0, 14) === 'propertiesInfo') { propertieses.push(properties(defs[k])); propertieses[defs[k].name] = properties(defs[k]); } -}; +} module.exports = { Octet: Octet, @@ -263,7 +411,7 @@ module.exports = { FieldTable: FieldTable, methods: methods, - properties: propertieses + properties: propertieses, }; module.exports.rangeInt = rangeInt; diff --git a/test/frame.js b/test/frame.js index bfdff0bf..cd439ca2 100644 --- a/test/frame.js +++ b/test/frame.js @@ -19,14 +19,19 @@ function inputs() { return new PassThrough({objectMode: true}); } -var HB = Buffer.from([defs.constants.FRAME_HEARTBEAT, - 0, 0, // channel 0 - 0, 0, 0, 0, // zero size - defs.constants.FRAME_END]); - -suite("Explicit parsing", function() { - - test('Parse heartbeat', function() { +var HB = Buffer.from([ + defs.constants.FRAME_HEARTBEAT, + 0, + 0, // channel 0 + 0, + 0, + 0, + 0, // zero size + defs.constants.FRAME_END, +]); + +suite('Explicit parsing', function () { + test('Parse heartbeat', function () { var input = inputs(); var frames = new Frames(input); input.write(HB); @@ -34,7 +39,7 @@ suite("Explicit parsing", function() { assert(!frames.recvFrame()); }); - test('Parse partitioned', function() { + test('Parse partitioned', function () { var input = inputs(); var frames = new Frames(input); input.write(HB.subarray(0, 3)); @@ -45,30 +50,44 @@ suite("Explicit parsing", function() { }); function testBogusFrame(name, bytes) { - test(name, function(done) { + test(name, function (done) { var input = inputs(); var frames = new Frames(input); frames.frameMax = 5; //for the max frame test input.write(Buffer.from(bytes)); - frames.step(function(err, frame) { + frames.step(function (err, frame) { if (err != null) done(); else done(new Error('Was a bogus frame!')); }); }); } - testBogusFrame('Wrong sized frame', - [defs.constants.FRAME_BODY, - 0,0, 0,0,0,0, // zero length - 65, // but a byte! - defs.constants.FRAME_END]); - - testBogusFrame('Unknown method frame', - [defs.constants.FRAME_METHOD, - 0,0, 0,0,0,4, - 0,0,0,0, // garbage ID - defs.constants.FRAME_END]); - + testBogusFrame('Wrong sized frame', [ + defs.constants.FRAME_BODY, + 0, + 0, + 0, + 0, + 0, + 0, // zero length + 65, // but a byte! + defs.constants.FRAME_END, + ]); + + testBogusFrame('Unknown method frame', [ + defs.constants.FRAME_METHOD, + 0, + 0, + 0, + 0, + 0, + 4, + 0, + 0, + 0, + 0, // garbage ID + defs.constants.FRAME_END, + ]); }); // Now for a bit more fun. @@ -83,109 +102,116 @@ var sequence = claire.sequence; var transform = claire.transform; var sized = claire.sized; -var assertEqualModuloDefaults = - require('./codec').assertEqualModuloDefaults; +var assertEqualModuloDefaults = require('./codec').assertEqualModuloDefaults; -var Trace = label('frame trace', - repeat(choice.apply(choice, amqp.methods))); - -suite("Parsing", function() { +var Trace = label('frame trace', repeat(choice.apply(choice, amqp.methods))); +suite('Parsing', function () { function testPartitioning(partition) { - return forAll(Trace).satisfy(function(t) { - var bufs = []; - var input = inputs(); - var frames = new Frames(input); - var i = 0, ex; - frames.accept = function(f) { - // A minor hack to make sure we get the assertion exception; - // otherwise, it's just a test that we reached the line - // incrementing `i` for each frame. - try { - assertEqualModuloDefaults(t[i], f.fields); - } - catch (e) { - ex = e; - } - i++; - }; - - t.forEach(function(f) { - f.channel = 0; - bufs.push(defs.encodeMethod(f.id, 0, f.fields)); - }); + return forAll(Trace) + .satisfy(function (t) { + var bufs = []; + var input = inputs(); + var frames = new Frames(input); + var i = 0, + ex; + frames.accept = function (f) { + // A minor hack to make sure we get the assertion exception; + // otherwise, it's just a test that we reached the line + // incrementing `i` for each frame. + try { + assertEqualModuloDefaults(t[i], f.fields); + } catch (e) { + ex = e; + } + i++; + }; + + t.forEach(function (f) { + f.channel = 0; + bufs.push(defs.encodeMethod(f.id, 0, f.fields)); + }); + + partition(bufs).forEach(function (chunk) { + input.write(chunk); + }); + frames.acceptLoop(); + if (ex) throw ex; + return i === t.length; + }) + .asTest({times: 20}); + } - partition(bufs).forEach(function (chunk) { input.write(chunk); }); - frames.acceptLoop(); - if (ex) throw ex; - return i === t.length; - }).asTest({times: 20}) - }; - - test("Parse trace of methods", - testPartitioning(function(bufs) { return bufs; })); - - test("Parse concat'd methods", - testPartitioning(function(bufs) { - return [Buffer.concat(bufs)]; - })); - - test("Parse partitioned methods", - testPartitioning(function(bufs) { - var full = Buffer.concat(bufs); - var onethird = Math.floor(full.length / 3); - var twothirds = 2 * onethird; - return [ - full.subarray(0, onethird), - full.subarray(onethird, twothirds), - full.subarray(twothirds) - ]; - })); + test( + 'Parse trace of methods', + testPartitioning(function (bufs) { + return bufs; + }), + ); + + test( + "Parse concat'd methods", + testPartitioning(function (bufs) { + return [Buffer.concat(bufs)]; + }), + ); + + test( + 'Parse partitioned methods', + testPartitioning(function (bufs) { + var full = Buffer.concat(bufs); + var onethird = Math.floor(full.length / 3); + var twothirds = 2 * onethird; + return [full.subarray(0, onethird), full.subarray(onethird, twothirds), full.subarray(twothirds)]; + }), + ); }); var FRAME_MAX_MAX = 4096 * 4; var FRAME_MAX_MIN = 4096; -var FrameMax = amqp.rangeInt('frame max', - FRAME_MAX_MIN, - FRAME_MAX_MAX); +var FrameMax = amqp.rangeInt('frame max', FRAME_MAX_MIN, FRAME_MAX_MAX); -var Body = sized(function(_n) { +var Body = sized(function (_n) { return Math.floor(Math.random() * FRAME_MAX_MAX); }, repeat(amqp.Octet)); -var Content = transform(function(args) { - return { - method: args[0].fields, - header: args[1].fields, - body: Buffer.from(args[2]) - } -}, sequence(amqp.methods['BasicDeliver'], - amqp.properties['BasicProperties'], Body)); - -suite("Content framing", function() { - test("Adhere to frame max", - forAll(Content, FrameMax).satisfy(function(content, max) { - var input = inputs(); - var frames = new Frames(input); - frames.frameMax = max; - frames.sendMessage( - 0, - defs.BasicDeliver, content.method, - defs.BasicProperties, content.header, - content.body); - var f, i = 0, largest = 0; - while (f = input.read()) { - i++; - if (f.length > largest) largest = f.length; - if (f.length > max) { - return false; - } - } - // The ratio of frames to 'contents' should always be >= 2 - // (one properties frame and at least one content frame); > 2 - // indicates fragmentation. The largest is always, of course <= frame max - //console.log('Frames: %d; frames per message: %d; largest frame %d', i, i / t.length, largest); - return true; - }).asTest()); +var Content = transform( + function (args) { + return { + method: args[0].fields, + header: args[1].fields, + body: Buffer.from(args[2]), + }; + }, + sequence(amqp.methods['BasicDeliver'], amqp.properties['BasicProperties'], Body), +); + +suite('Content framing', function () { + test( + 'Adhere to frame max', + forAll(Content, FrameMax) + .satisfy(function (content, max) { + var input = inputs(); + var frames = new Frames(input); + frames.frameMax = max; + frames.sendMessage(0, defs.BasicDeliver, content.method, defs.BasicProperties, content.header, content.body); + var f, + i = 0, + largest = 0; + while ((f = input.read())) { + i++; + if (f.length > largest) largest = f.length; + if (f.length > max) { + return false; + } + } + // The ratio of frames to 'contents' should always be >= 2 + // (one properties frame and at least one content frame); > 2 + // indicates fragmentation. The largest is always, of course <= frame max + //console.log('Frames: %d; frames per message: %d; largest frame %d', i, i / t.length, largest); + return true; + }) + .asTest(), + ); }); diff --git a/test/mux.js b/test/mux.js index 395f6e15..b2f184a0 100644 --- a/test/mux.js +++ b/test/mux.js @@ -22,27 +22,33 @@ function readAllObjects(s, cb) { } } - s.on('end', function() { cb(objs); }); + s.on('end', function () { + cb(objs); + }); s.on('readable', read); read(); } -test("single input", function(done) { +test('single input', function (done) { var input = stream(); var output = stream(); - input.on('end', function() { output.end() }); + input.on('end', function () { + output.end(); + }); var mux = new Mux(output); mux.pipeFrom(input); - var data = [1,2,3,4,5,6,7,8,9]; + var data = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // not 0, it's treated specially by PassThrough for some reason. By // 'specially' I mean it breaks the stream. See e.g., // https://github.com/isaacs/readable-stream/pull/55 - data.forEach(function (chunk) { input.write(chunk); }); + data.forEach(function (chunk) { + input.write(chunk); + }); - readAllObjects(output, function(vals) { + readAllObjects(output, function (vals) { assert.deepEqual(data, vals); done(); }); @@ -50,41 +56,45 @@ test("single input", function(done) { input.end(); }); -test("single input, resuming stream", function(done) { +test('single input, resuming stream', function (done) { var input = stream(); var output = stream(); - input.on('end', function() { output.end() }); + input.on('end', function () { + output.end(); + }); var mux = new Mux(output); mux.pipeFrom(input); // Streams might be blocked and become readable again, simulate this // using a special read function and a marker - var data = [1,2,3,4,'skip',6,7,8,9]; + var data = [1, 2, 3, 4, 'skip', 6, 7, 8, 9]; - var oldRead = input.read; - input.read = function(size) { - var val = oldRead.call(input, size) + var oldRead = input.read; + input.read = function (size) { + var val = oldRead.call(input, size); if (val === 'skip') { input.emit('readable'); - return null + return null; } return val; - } + }; - data.forEach(function (chunk) { input.write(chunk); }); + data.forEach(function (chunk) { + input.write(chunk); + }); - readAllObjects(output, function(vals) { - assert.deepEqual([1,2,3,4,6,7,8,9], vals); + readAllObjects(output, function (vals) { + assert.deepEqual([1, 2, 3, 4, 6, 7, 8, 9], vals); done(); }); input.end(); }); -test("two sequential inputs", function(done) { +test('two sequential inputs', function (done) { var input1 = stream(); var input2 = stream(); var output = stream(); @@ -92,23 +102,29 @@ test("two sequential inputs", function(done) { mux.pipeFrom(input1); mux.pipeFrom(input2); - var data = [1,2,3,4,5,6,7,8,9]; - data.forEach(function(v) { input1.write(v); }); + var data = [1, 2, 3, 4, 5, 6, 7, 8, 9]; + data.forEach(function (v) { + input1.write(v); + }); - input1.on('end', function() { - data.forEach(function (v) { input2.write(v); }); + input1.on('end', function () { + data.forEach(function (v) { + input2.write(v); + }); input2.end(); }); - input2.on('end', function() { output.end(); }); + input2.on('end', function () { + output.end(); + }); input1.end(); - readAllObjects(output, function(vs) { + readAllObjects(output, function (vs) { assert.equal(2 * data.length, vs.length); done(); }); }); -test("two interleaved inputs", function(done) { +test('two interleaved inputs', function (done) { var input1 = stream(); var input2 = stream(); var output = stream(); @@ -116,65 +132,76 @@ test("two interleaved inputs", function(done) { mux.pipeFrom(input1); mux.pipeFrom(input2); - var endLatch = latch(2, function() { output.end(); }); + var endLatch = latch(2, function () { + output.end(); + }); input1.on('end', endLatch); input2.on('end', endLatch); - var data = [1,2,3,4,5,6,7,8,9]; - data.forEach(function(v) { input1.write(v); }); + var data = [1, 2, 3, 4, 5, 6, 7, 8, 9]; + data.forEach(function (v) { + input1.write(v); + }); input1.end(); - data.forEach(function(v) { input2.write(v); }); + data.forEach(function (v) { + input2.write(v); + }); input2.end(); - readAllObjects(output, function(vs) { + readAllObjects(output, function (vs) { assert.equal(2 * data.length, vs.length); done(); }); }); -test("unpipe", function(done) { +test('unpipe', function (done) { var input = stream(); var output = stream(); var mux = new Mux(output); - var pipedData = [1,2,3,4,5]; - var unpipedData = [6,7,8,9]; + var pipedData = [1, 2, 3, 4, 5]; + var unpipedData = [6, 7, 8, 9]; mux.pipeFrom(input); - schedule(function() { - pipedData.forEach(function (chunk) { input.write(chunk); }); + schedule(function () { + pipedData.forEach(function (chunk) { + input.write(chunk); + }); - schedule(function() { + schedule(function () { mux.unpipeFrom(input); - schedule(function() { - unpipedData.forEach(function(chunk) { input.write(chunk); }); + schedule(function () { + unpipedData.forEach(function (chunk) { + input.write(chunk); + }); input.end(); - schedule(function() { + schedule(function () { // exhaust so that 'end' fires - var v; while (v = input.read()); + var v; + while ((v = input.read())); }); }); }); - }); - input.on('end', function() { + input.on('end', function () { output.end(); }); - readAllObjects(output, function(vals) { + readAllObjects(output, function (vals) { try { assert.deepEqual(pipedData, vals); done(); + } catch (e) { + done(e); } - catch (e) { done(e); } }); }); -test("roundrobin", function(done) { +test('roundrobin', function (done) { var input1 = stream(); var input2 = stream(); var output = stream(); @@ -183,21 +210,26 @@ test("roundrobin", function(done) { mux.pipeFrom(input1); mux.pipeFrom(input2); - var endLatch = latch(2, function() { output.end(); }); + var endLatch = latch(2, function () { + output.end(); + }); input1.on('end', endLatch); input2.on('end', endLatch); - var ones = [1,1,1,1,1]; - ones.forEach(function(v) { input1.write(v); }); + var ones = [1, 1, 1, 1, 1]; + ones.forEach(function (v) { + input1.write(v); + }); input1.end(); - var twos = [2,2,2,2,2]; - twos.forEach(function(v) { input2.write(v); }); + var twos = [2, 2, 2, 2, 2]; + twos.forEach(function (v) { + input2.write(v); + }); input2.end(); - readAllObjects(output, function(vs) { - assert.deepEqual([1,2,1,2,1,2,1,2,1,2], vs); + readAllObjects(output, function (vs) { + assert.deepEqual([1, 2, 1, 2, 1, 2, 1, 2, 1, 2], vs); done(); }); - }); diff --git a/test/util.js b/test/util.js index 919ea7b9..d0da127c 100644 --- a/test/util.js +++ b/test/util.js @@ -6,8 +6,7 @@ var PassThrough = require('stream').PassThrough; var defs = require('../lib/defs'); var assert = require('assert'); -var schedule = (typeof setImmediate === 'function') ? - setImmediate : process.nextTick; +var schedule = typeof setImmediate === 'function' ? setImmediate : process.nextTick; function randomString() { var hash = crypto.createHash('sha1'); @@ -15,7 +14,6 @@ function randomString() { return hash.digest('base64'); } - // Set up a socket pair {client, server}, such that writes to the // client are readable from the server, and writes to the server are // readable at the client. @@ -60,34 +58,27 @@ function runServer(socket, run) { function send(id, fields, channel, content) { channel = channel || 0; if (content) { - schedule(function() { - frames.sendMessage(channel, id, fields, - defs.BasicProperties, fields, - content); + schedule(function () { + frames.sendMessage(channel, id, fields, defs.BasicProperties, fields, content); }); - } - else { - schedule(function() { + } else { + schedule(function () { frames.sendMethod(channel, id, fields); }); } } function wait(method) { - return function() { - return new Promise(function(resolve, reject) { + return function () { + return new Promise(function (resolve, reject) { if (method) { - frames.step(function(e, f) { + frames.step(function (e, f) { if (e !== null) return reject(e); - if (f.id === method) - resolve(f); - else - reject(new Error("Expected method: " + method + - ", got " + f.id)); + if (f.id === method) resolve(f); + else reject(new Error('Expected method: ' + method + ', got ' + f.id)); }); - } - else { - frames.step(function(e, f) { + } else { + frames.step(function (e, f) { if (e !== null) return reject(e); else resolve(f); }); @@ -101,19 +92,21 @@ function runServer(socket, run) { // Produce a callback that will complete the test successfully function succeed(done) { - return function() { done(); } + return function () { + done(); + }; } // Produce a callback that will complete the test successfully // only if the value is an object, it has the specified // attribute, and its value is equals to the expected value function succeedIfAttributeEquals(attribute, value, done) { - return function(object) { + return function (object) { if (object && !(object instanceof Error) && value === object[attribute]) { return done(); } - done(new Error(attribute + " is not equal to " + value)); + done(new Error(attribute + ' is not equal to ' + value)); }; } @@ -121,10 +114,10 @@ function succeedIfAttributeEquals(attribute, value, done) { // (to be used as a failure continuation) or any other value (to be // used as a success continuation when failure is expected) function fail(done) { - return function(err) { + return function (err) { if (err instanceof Error) done(err); - else done(new Error("Expected to fail, instead got " + err.toString())); - } + else done(new Error('Expected to fail, instead got ' + err.toString())); + }; } // Create a function that will call done once it's been called itself @@ -133,12 +126,11 @@ function fail(done) { function latch(count, done) { var awaiting = count; var alive = true; - return function(err) { + return function (err) { if (err instanceof Error && alive) { alive = false; done(err); - } - else { + } else { awaiting--; if (awaiting === 0 && alive) { alive = false; @@ -154,14 +146,15 @@ function completes(thunk, done) { try { thunk(); done(); + } catch (e) { + done(e); } - catch (e) { done(e); } } // Construct a Node.JS-style callback from a success continuation and // an error continuation function kCallback(k, ek) { - return function(err, val) { + return function (err, val) { if (err === null) k && k(val); else ek && ek(err); }; @@ -169,37 +162,37 @@ function kCallback(k, ek) { // A noddy way to make tests depend on the node version. function versionGreaterThan(actual, spec) { - - function int(e) { return parseInt(e); } + function int(e) { + return parseInt(e); + } var version = actual.split('.').map(int); var desired = spec.split('.').map(int); - for (var i=0; i < desired.length; i++) { - var a = version[i], b = desired[i]; + for (var i = 0; i < desired.length; i++) { + var a = version[i], + b = desired[i]; if (a != b) return a > b; } return false; } -suite('versionGreaterThan', function() { - -test('full spec', function() { - assert(versionGreaterThan('0.8.26', '0.6.12')); - assert(versionGreaterThan('0.8.26', '0.8.21')); -}); +suite('versionGreaterThan', function () { + test('full spec', function () { + assert(versionGreaterThan('0.8.26', '0.6.12')); + assert(versionGreaterThan('0.8.26', '0.8.21')); + }); -test('partial spec', function() { - assert(versionGreaterThan('0.9.12', '0.8')); -}); - -test('not greater', function() { - assert(!versionGreaterThan('0.8.12', '0.8.26')); - assert(!versionGreaterThan('0.6.2', '0.6.12')); - assert(!versionGreaterThan('0.8.29', '0.8')); -}); + test('partial spec', function () { + assert(versionGreaterThan('0.9.12', '0.8')); + }); -test + test('not greater', function () { + assert(!versionGreaterThan('0.8.12', '0.8.26')); + assert(!versionGreaterThan('0.6.2', '0.6.12')); + assert(!versionGreaterThan('0.8.29', '0.8')); + }); + test; }); module.exports = { @@ -213,5 +206,5 @@ module.exports = { kCallback: kCallback, schedule: schedule, randomString: randomString, - versionGreaterThan: versionGreaterThan + versionGreaterThan: versionGreaterThan, }; diff --git a/todo.md b/todo.md index dcf29159..67d5c95d 100644 --- a/todo.md +++ b/todo.md @@ -1,16 +1,37 @@ # Code Formatting Implementation Plan +This document outlines the implementation of Biome formatter for the amqplib project, introducing consistent code formatting with automated pre-commit hooks. + ## Implementation Steps -1. Update Node.js engine requirement to v16 (preparation for future test harness updates) -2. Install Biome as development dependency -3. Generate lib/defs.js using existing make target to ensure it is properly formatted -4. Apply Biome formatting to all source code in lib/ directory -5. Execute complete test suite to verify code changes maintain functionality -6. Add npm format script to package.json for formatting lib/ directory -7. Install and configure Lefthook with pre-commit hook to auto-format staged files -8. Widen formatting scope to include all files and folders (not restricted to lib/) -9. Apply Biome formatting to all files -10. Execute complete test suite to verify all changes maintain functionality + +### Phase 1: Foundation Setup +1. **Update Node.js engine requirement** - Bump to v16 minimum (preparation for future test harness modernisation) +2. **Install Biome formatter** - Add @biomejs/biome as development dependency +3. **Configure Biome settings** - Create biome.json with project formatting standards: + - Indent: 2 spaces + - Line width: 140 characters + - Brackets: no spacing + - Quotes: single + - Trailing commas: all + - Semicolons: always + - Parentheses: always around arrow function parameters + +### Phase 2: Initial Formatting (lib/ directory) +4. **Generate lib/defs.js** - Run make target to ensure generated code is properly formatted +5. **Format lib/ directory** - Apply Biome formatting to all source code in lib/ only +6. **Validate changes** - Execute complete test suite to verify formatting maintains functionality +7. **Add format script** - Create npm script for formatting lib/ directory + +### Phase 3: Automation Setup +8. **Install Lefthook** - Add Lefthook as development dependency for git hooks +9. **Configure pre-commit hook** - Set up automatic formatting of staged files before commit + +### Phase 4: Project-wide Formatting +10. **Expand formatting scope** - Update configuration to format all project files +11. **Format entire codebase** - Apply Biome formatting to all JavaScript files +12. **Final validation** - Execute complete test suite to verify all changes maintain functionality +13. **Update changelog** - Add entry for v1.0.0 summarising the formatting implementation +14. **Commit changes** - Create commit for project-wide formatting implementation ## Pull Request Structure