@meyer/hyperdeck-emulator
Advanced tools
Comparing version 0.0.4-canary.28.6476ee1 to 0.0.4-canary.29.c1a834c
@@ -8,2 +8,3 @@ 'use strict'; | ||
var events = require('events'); | ||
var util = _interopDefault(require('util')); | ||
var net = require('net'); | ||
@@ -277,2 +278,12 @@ var pino = _interopDefault(require('pino')); | ||
function invariant(condition, message) { | ||
if (!condition) { | ||
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { | ||
args[_key - 2] = arguments[_key]; | ||
} | ||
throw new Error(util.format.apply(util, [message].concat(args))); | ||
} | ||
} | ||
var MultilineParser = /*#__PURE__*/function () { | ||
@@ -291,3 +302,3 @@ function MultilineParser(logger) { | ||
var newLines = data.split('\r\n'); // remove the blank line at the end from the intentionally trailing \r\n | ||
var newLines = data.split(CRLF); // remove the blank line at the end from the intentionally trailing \r\n | ||
@@ -305,7 +316,7 @@ if (newLines.length > 0 && newLines[newLines.length - 1] === '') newLines.pop(); | ||
if (this.linesQueue[0].indexOf(':') === -1 || this.linesQueue.length === 1 && this.linesQueue[0].indexOf(':') > 0) { | ||
var _r = this.parseResponse(this.linesQueue.splice(0, 1)); | ||
if (!this.linesQueue[0].includes(':') || this.linesQueue.length === 1 && this.linesQueue[0].includes(':')) { | ||
var parsedResponse = this.parseResponse(this.linesQueue.splice(0, 1)); | ||
if (_r) { | ||
res.push(_r); | ||
if (parsedResponse) { | ||
res.push(parsedResponse); | ||
} | ||
@@ -325,3 +336,6 @@ | ||
var r = this.parseResponse(lines); | ||
if (r) res.push(r); | ||
if (r) { | ||
res.push(r); | ||
} | ||
} | ||
@@ -332,18 +346,19 @@ | ||
_proto.parseResponse = function parseResponse(lines) { | ||
lines = lines.map(function (l) { | ||
_proto.parseResponse = function parseResponse(responseLines) { | ||
var lines = responseLines.map(function (l) { | ||
return l.trim(); | ||
}); | ||
if (lines.length === 1 && lines[0].indexOf(':') > -1) { | ||
if (lines.length === 1 && lines[0].includes(':')) { | ||
var bits = lines[0].split(': '); | ||
var msg = bits.shift(); | ||
if (!msg) throw new Error('Unrecognised command'); | ||
!msg ? invariant(false, 'Unrecognised command') : void 0; | ||
var params = {}; | ||
var paramNames = new Set(parametersByCommandName[msg]); | ||
var param = bits.shift(); | ||
if (!param) throw new Error('No named parameters found'); | ||
!param ? invariant(false, 'No named parameters found') : void 0; | ||
for (var i = 0; i < bits.length - 1; i++) { | ||
var bobs = bits[i].split(' '); | ||
var bit = bits[i]; | ||
var bobs = bit.split(' '); | ||
var nextParam = ''; | ||
@@ -359,6 +374,3 @@ | ||
if (!bobs.length) { | ||
throw new Error('Command malformed / paramName not recognised'); | ||
} | ||
!(bobs.length > 0) ? invariant(false, 'Command malformed / paramName not recognised: `%s`', bit) : void 0; | ||
params[param] = bobs.join(' '); | ||
@@ -370,3 +382,3 @@ param = nextParam; | ||
return { | ||
raw: lines.join('\r\n'), | ||
raw: lines.join(CRLF), | ||
name: msg, | ||
@@ -402,3 +414,3 @@ parameters: params | ||
var res = { | ||
raw: lines.join('\r\n'), | ||
raw: lines.join(CRLF), | ||
name: _msg, | ||
@@ -454,3 +466,3 @@ parameters: _params | ||
} else { | ||
throw new Error('Unhandled value type: ' + typeof value); | ||
invariant(false, 'Unhandled value type: `%s`', typeof value) ; | ||
} // convert camelCase keys to space-separated words | ||
@@ -481,4 +493,3 @@ | ||
configuration: false, | ||
'dropped frames': false // @todo: implement | ||
'dropped frames': false | ||
}; | ||
@@ -820,3 +831,3 @@ _this.parser = new MultilineParser(logger); | ||
throw new Error('Unhandled command name: ' + cmd.name); | ||
!false ? "development" !== "production" ? invariant(false, 'Unhandled command name: `%s`', cmd.name) : invariant(false) : void 0; | ||
} | ||
@@ -1221,8 +1232,4 @@ | ||
var codeInt = Math.floor(code); | ||
!(codeInt === code && code >= 0 && code <= 99) ? invariant(false, 'Timecode params must be an integer between 0 and 99') : void 0; // turn the integer into a potentially zero-prefixed string | ||
if (codeInt !== code || code < 0 || code > 99) { | ||
throw new Error('Timecode params must be an integer between 0 and 99'); | ||
} // turn the integer into a potentially zero-prefixed string | ||
return (codeInt + 100).toString().slice(-2); | ||
@@ -1229,0 +1236,0 @@ }).join(':'); |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,n,t,r,o,i=require("events"),s=require("net"),a=(e=require("pino"))&&"object"==typeof e&&"default"in e?e.default:e;function u(e,n){e.prototype=Object.create(n.prototype),e.prototype.constructor=e,e.__proto__=n}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function c(e,n){return(c=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function l(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function p(e,n,t){return(p=l()?Reflect.construct:function(e,n,t){var r=[null];r.push.apply(r,n);var o=new(Function.bind.apply(e,r));return t&&c(o,t.prototype),o}).apply(null,arguments)}function m(e){var n="function"==typeof Map?new Map:void 0;return(m=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(e))return n.get(e);n.set(e,t)}function t(){return p(e,arguments,f(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),c(t,e)})(e)}function d(e,n){(null==n||n>e.length)&&(n=e.length);for(var t=0,r=new Array(n);t<n;t++)r[t]=e[t];return r}"undefined"!=typeof Symbol&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator"))),"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator"))),function(e){e[e.SyntaxError=100]="SyntaxError",e[e.UnsupportedParameter=101]="UnsupportedParameter",e[e.InvalidValue=102]="InvalidValue",e[e.Unsupported=103]="Unsupported",e[e.DiskFull=104]="DiskFull",e[e.NoDisk=105]="NoDisk",e[e.DiskError=106]="DiskError",e[e.TimelineEmpty=107]="TimelineEmpty",e[e.InternalError=108]="InternalError",e[e.OutOfRange=109]="OutOfRange",e[e.NoInput=110]="NoInput",e[e.RemoteControlDisabled=111]="RemoteControlDisabled",e[e.ConnectionRejected=120]="ConnectionRejected",e[e.InvalidState=150]="InvalidState",e[e.InvalidCodec=151]="InvalidCodec",e[e.InvalidFormat=160]="InvalidFormat",e[e.InvalidToken=161]="InvalidToken",e[e.FormatNotPrepared=162]="FormatNotPrepared"}(t||(t={})),function(e){e[e.OK=200]="OK",e[e.SlotInfo=202]="SlotInfo",e[e.DeviceInfo=204]="DeviceInfo",e[e.ClipsInfo=205]="ClipsInfo",e[e.DiskList=206]="DiskList",e[e.TransportInfo=208]="TransportInfo",e[e.Notify=209]="Notify",e[e.Remote=210]="Remote",e[e.Configuration=211]="Configuration",e[e.ClipsCount=214]="ClipsCount",e[e.Uptime=215]="Uptime",e[e.FormatReady=216]="FormatReady"}(r||(r={})),function(e){e[e.ConnectionInfo=500]="ConnectionInfo",e[e.SlotInfo=502]="SlotInfo",e[e.TransportInfo=508]="TransportInfo",e[e.RemoteInfo=510]="RemoteInfo",e[e.ConfigurationInfo=511]="ConfigurationInfo"}(o||(o={}));var h,v,g,y=((n={})[o.ConfigurationInfo]="configuration info",n[o.ConnectionInfo]="connection info",n[o.RemoteInfo]="remote info",n[o.SlotInfo]="slot info",n[o.TransportInfo]="transport info",n[t.ConnectionRejected]="connection rejected",n[t.DiskError]="disk error",n[t.DiskFull]="disk full",n[t.FormatNotPrepared]="format not prepared",n[t.InternalError]="internal error",n[t.InvalidCodec]="invalid codec",n[t.InvalidFormat]="invalid format",n[t.InvalidState]="invalid state",n[t.InvalidToken]="invalid token",n[t.InvalidValue]="invalid value",n[t.NoDisk]="no disk",n[t.NoInput]="no input",n[t.OutOfRange]="out of range",n[t.RemoteControlDisabled]="remote control disabled",n[t.SyntaxError]="syntax error",n[t.TimelineEmpty]="timeline empty",n[t.Unsupported]="unsupported",n[t.UnsupportedParameter]="unsupported parameter",n[r.ClipsCount]="clips count",n[r.ClipsInfo]="clips info",n[r.Configuration]="configuration",n[r.DeviceInfo]="device info",n[r.DiskList]="disk list",n[r.FormatReady]="format ready",n[r.Notify]="notify",n[r.OK]="ok",n[r.Remote]="remote",n[r.SlotInfo]="slot info",n[r.TransportInfo]="transport info",n[r.Uptime]="uptime",n);!function(e){e.QuickTimeUncompressed="QuickTimeUncompressed",e.QuickTimeProResHQ="QuickTimeProResHQ",e.QuickTimeProRes="QuickTimeProRes",e.QuickTimeProResLT="QuickTimeProResLT",e.QuickTimeProResProxy="QuickTimeProResProxy",e.QuickTimeDNxHR220="QuickTimeDNxHR220",e.DNxHR220="DNxHR220"}(h||(h={})),function(e){e.embedded="embedded",e.XLR="XLR",e.RCA="RCA"}(v||(v={})),function(e){e.SDI="SDI",e.HDMI="HDMI",e.component="component"}(g||(g={}));var I={help:[],commands:[],"device info":[],"disk list":["slot id"],quit:[],ping:[],preview:["enable"],play:["speed","loop","single clip"],"playrange set":["clip id","in","out"],"playrange clear":[],record:["name"],stop:[],"clips count":[],"clips get":["clip id","count"],"clips add":["name"],"clips clear":[],"transport info":[],"slot info":["slot id"],"slot select":["slot id","video format"],notify:["remote","transport","slot","configuration","dropped frames"],goto:["clip id","clip","timeline","timecode","slot id"],jog:["timecode"],shuttle:["speed"],remote:["enable","override"],configuration:["video input","audio input","file format"],uptime:[],format:["prepare","confirm"],identify:["enable"],watchdog:["period"]},S=function(){function e(e){this.linesQueue=[],this.logger=e.child({name:"MultilineParser"})}var n=e.prototype;return n.receivedString=function(e){var n=[],t=e.split("\r\n");for(t.length>0&&""===t[t.length-1]&&t.pop(),this.linesQueue=this.linesQueue.concat(t);this.linesQueue.length>0;)if(""!==this.linesQueue[0])if(-1===this.linesQueue[0].indexOf(":")||1===this.linesQueue.length&&this.linesQueue[0].indexOf(":")>0){var r=this.parseResponse(this.linesQueue.splice(0,1));r&&n.push(r)}else{var o=this.linesQueue.indexOf("");if(-1===o)break;var i=this.linesQueue.splice(0,o+1),s=this.parseResponse(i);s&&n.push(s)}else this.linesQueue.shift();return n},n.parseResponse=function(e){if(1===(e=e.map((function(e){return e.trim()}))).length&&e[0].indexOf(":")>-1){var n=e[0].split(": "),t=n.shift();if(!t)throw new Error("Unrecognised command");var r={},o=new Set(I[t]),i=n.shift();if(!i)throw new Error("No named parameters found");for(var s=0;s<n.length-1;s++){for(var a=n[s].split(" "),u="",f=a.length-1;f>=0&&(u=(a.pop()+" "+u).trim(),!o.has(u));f--);if(!a.length)throw new Error("Command malformed / paramName not recognised");r[i]=a.join(" "),i=u}return r[i]=n[n.length-1],{raw:e.join("\r\n"),name:t,parameters:r}}var c=e[0].match(/(.+?)(:|)$/im);if(!c)return this.logger.error({header:e[0]},"failed to parse header"),null;for(var l=c[1],p={},m=1;m<e.length;m++){var d=e[m].match(/^(.*?): (.*)$/im);d?p[d[1]]=d[2]:this.logger.error({line:e[m]},"failed to parse line")}return{raw:e.join("\r\n"),name:l,parameters:p}},e}(),b=function(e){function n(n,t,r){var i;return(i=e.call(this)||this).socket=n,i.logger=t,i.receivedCommand=r,i.lastReceivedMS=-1,i.watchdogTimer=null,i.notifySettings={slot:!1,transport:!1,remote:!1,configuration:!1,"dropped frames":!1},i.parser=new S(t),i.socket.setEncoding("utf-8"),i.socket.on("data",(function(e){i.onMessage(e)})),i.socket.on("error",(function(e){t.info({err:e},"error"),i.socket.destroy(),i.emit("disconnected"),t.info("manually disconnected")})),i.sendResponse(o.ConnectionInfo,{"protocol version":"1.11",model:"NodeJS HyperDeck Server Library"}),i}u(n,e);var i=n.prototype;return i.onMessage=function(e){var n=this;this.logger.info({data:e},"<-- received message from client"),this.lastReceivedMS=Date.now();var i=this.parser.receivedString(e);this.logger.info({cmds:i},"parsed commands");for(var s,a=function(){var e=s.value;if("watchdog"===e.name){n.watchdogTimer&&clearInterval(n.watchdogTimer);var i=e;i.parameters.period&&(n.watchdogTimer=setInterval((function(){Date.now()-n.lastReceivedMS>Number(i.parameters.period)&&(n.socket.destroy(),n.emit("disconnected"),n.watchdogTimer&&clearInterval(n.watchdogTimer))}),1e3*Number(i.parameters.period)))}else if("notify"===e.name){var a=e;if(!(Object.keys(a.parameters).length>0)){for(var u={},f=0,c=Object.keys(n.notifySettings);f<c.length;f++){var l=c[f];u[l]=n.notifySettings[l]?"true":"false"}return n.sendResponse(r.Notify,u,e),"continue"}for(var p=0,m=Object.keys(a.parameters);p<m.length;p++){var d=m[p];void 0!==n.notifySettings[d]&&(n.notifySettings[d]="true"===a.parameters[d])}}n.receivedCommand(e).then((function(i){return"object"==typeof i?n.sendResponse(i.code,"params"in i&&i.params||"message"in i&&i.message||void 0,e):"number"==typeof i&&(t[i]||r[i]||o[i])?n.sendResponse(i,void 0,e):(n.logger.error({cmd:e,codeOrObj:i},"codeOrObj was neither a ResponseCode nor a response object"),void n.sendResponse(t.InternalError,void 0,e))}),(function(){return n.sendResponse(t.Unsupported,void 0,e)}))},u=function(e,n){var t;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(t=function(e,n){if(e){if("string"==typeof e)return d(e,void 0);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?d(e,void 0):void 0}}(e))){t&&(e=t);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(t=e[Symbol.iterator]()).next.bind(t)}(i);!(s=u()).done;)a()},i.sendResponse=function(e,n,r){var o=function(e,n){if("string"==typeof n)return e+" "+n.replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/:/g,"")+"\r\n";var t=e+" "+y[e];if(!n)return t+"\r\n";var r=Object.entries(n).filter((function(e){return null!=e[1]}));return 0===r.length?t+"\r\n":r.reduce((function(e,n){var t,r=n[0],o=n[1];if("string"==typeof o)t=o;else if("boolean"==typeof o)t=o?"true":"false";else{if("number"!=typeof o)throw new Error("Unhandled value type: "+typeof o);t=o.toString()}return e+r.replace(/([a-z])([A-Z]+)/,"$1 $2").toLowerCase()+": "+t+"\r\n"}),t+":\r\n")+"\r\n"}(e,n);this.logger[t[e]?"error":"info"]({responseText:o,cmd:r},"--\x3e send response to client"),this.socket.write(o)},i.notify=function(e,n){this.logger.info({type:e,params:n},"notify"),"configuration"===e&&this.notifySettings.configuration?this.sendResponse(o.ConfigurationInfo,n):"remote"===e&&this.notifySettings.remote?this.sendResponse(o.RemoteInfo,n):"slot"===e&&this.notifySettings.slot?this.sendResponse(o.SlotInfo,n):"transport"===e&&this.notifySettings.transport?this.sendResponse(o.TransportInfo,n):this.logger.error({type:e,params:n},"unhandled notify type")},n}(i.EventEmitter),R=function(e){for(var n=e.clips.length,t={clipsCount:n},r=0;r<n;r++){var o=e.clips[r];t[(r+1).toString()]=o.name+" "+o.startT+" "+o.duration}return t},k=function(e){function n(){return e.apply(this,arguments)||this}return u(n,e),n}(m(Error)),C=function(){try{throw new k}catch(e){return Promise.reject(e)}};exports.HyperDeckServer=function(){function e(e,n){var o=this,i=this;void 0===n&&(n=a()),this.sockets={},this.onDeviceInfo=C,this.onDiskList=C,this.onPreview=C,this.onPlay=C,this.onPlayrangeSet=C,this.onPlayrangeClear=C,this.onRecord=C,this.onStop=C,this.onClipsCount=C,this.onClipsGet=C,this.onClipsAdd=C,this.onClipsClear=C,this.onTransportInfo=C,this.onSlotInfo=C,this.onSlotSelect=C,this.onGoTo=C,this.onJog=C,this.onShuttle=C,this.onConfiguration=C,this.onUptime=C,this.onFormat=C,this.onIdentify=C,this.onWatchdog=C,this.receivedCommand=function(e){try{return Promise.resolve(new Promise((function(e){return setTimeout((function(){return e()}),200)}))).then((function(){var n=!1;return i.logger.info({cmd:e},"<-- "+e.name),function(t,o){try{var s=function(){function t(t){var o=!1;if(n)return t;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){if(o)return n;if("watchdog"===e.name)return r.OK;if("ping"===e.name)return r.OK;throw new Error("Unhandled command name: "+e.name)}var a=function(){if("identify"===e.name)return Promise.resolve(i.onIdentify(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("format"===e.name)return Promise.resolve(i.onFormat(e)).then((function(e){return e?(t=!0,{code:r.FormatReady,params:e}):(t=!0,r.OK)}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("uptime"===e.name)return Promise.resolve(i.onUptime(e)).then((function(e){return o=!0,{code:r.Uptime,params:e}}))}();return a&&a.then?a.then(s):s(a)}if("remote"===e.name)return{code:r.Remote,params:{enabled:!0,override:!1}};var a=function(){if("configuration"===e.name)return Promise.resolve(i.onConfiguration(e)).then((function(e){return e?(t=!0,{code:r.Configuration,params:e}):(t=!0,r.OK)}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("shuttle"===e.name)return Promise.resolve(i.onShuttle(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("jog"===e.name)return Promise.resolve(i.onJog(e)).then((function(){return t=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}if("notify"===e.name)return r.OK;var a=function(){if("go to"===e.name)return Promise.resolve(i.onGoTo(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("slot select"===e.name)return Promise.resolve(i.onSlotSelect(e)).then((function(){return t=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("slot info"===e.name)return Promise.resolve(i.onSlotInfo(e)).then((function(e){return o=!0,{code:r.SlotInfo,params:e}}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("transport info"===e.name)return Promise.resolve(i.onTransportInfo(e)).then((function(e){return t=!0,{code:r.TransportInfo,params:e}}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("clips clear"===e.name)return Promise.resolve(i.onClipsClear(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("clips add"===e.name)return Promise.resolve(i.onClipsAdd(e)).then((function(){return t=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("clips get"===e.name)return Promise.resolve(i.onClipsGet(e).then(R)).then((function(e){return o=!0,{code:r.ClipsInfo,params:e}}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("clips count"===e.name)return Promise.resolve(i.onClipsCount(e)).then((function(e){return t=!0,{code:r.ClipsCount,params:e}}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("stop"===e.name)return Promise.resolve(i.onStop(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("record"===e.name)return Promise.resolve(i.onRecord(e)).then((function(){return t=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("playrange clear"===e.name)return Promise.resolve(i.onPlayrangeClear(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("playrange set"===e.name)return Promise.resolve(i.onPlayrangeSet(e)).then((function(){return t=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("play"===e.name)return Promise.resolve(i.onPlay(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("preview"===e.name)return Promise.resolve(i.onPreview(e)).then((function(){return t=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("disk list"===e.name)return Promise.resolve(i.onDiskList(e)).then((function(e){return o=!0,{code:r.DiskList,params:e}}))}();return a&&a.then?a.then(s):s(a)}var o=function(){if("device info"===e.name)return Promise.resolve(i.onDeviceInfo(e)).then((function(e){return n=!0,{code:r.DeviceInfo,params:e}}))}();return o&&o.then?o.then(t):t(o)}()}catch(e){return o(e)}return s&&s.then?s.then(void 0,o):s}(0,(function(n){return n instanceof k?(i.logger.error({cmd:e},"unimplemented"),t.Unsupported):(i.logger.error({cmd:e,err:n.message},"unhandled command name"),t.InternalError)}))}))}catch(e){return Promise.reject(e)}},this.logger=n.child({name:"HyperDeck Emulator"}),this.server=s.createServer((function(e){o.logger.info("connection");var n=Math.random().toString(35).substr(-6),t=o.logger.child({name:"HyperDeck socket "+n});o.sockets[n]=new b(e,t,(function(e){return o.receivedCommand(e)})),o.sockets[n].on("disconnected",(function(){t.info("disconnected"),delete o.sockets[n]}))})),this.server.on("listening",(function(){return o.logger.info("listening")})),this.server.on("close",(function(){return o.logger.info("connection closed")})),this.server.on("error",(function(e){return o.logger.error("server error:",e)})),this.server.maxConnections=1,this.server.listen(9993,e)}var n=e.prototype;return n.close=function(){this.server.unref()},n.notifySlot=function(e){this.notify("slot",e)},n.notifyTransport=function(e){this.notify("transport",e)},n.notify=function(e,n){for(var t=0,r=Object.keys(this.sockets);t<r.length;t++)this.sockets[r[t]].notify(e,n)},e}(),exports.ResponseInterface={__proto__:null},exports.Timecode=function(e,n,t,r){var o=[e,n,t,r].map((function(e){var n=Math.floor(e);if(n!==e||e<0||e>99)throw new Error("Timecode params must be an integer between 0 and 99");return(n+100).toString().slice(-2)})).join(":");this.toString=function(){return o}}; | ||
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var n,t,r,o,i=require("events"),s=e(require("util")),a=require("net"),u=e(require("pino"));function c(e,n){e.prototype=Object.create(n.prototype),e.prototype.constructor=e,e.__proto__=n}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function l(e,n){return(l=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function p(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function m(e,n,t){return(m=p()?Reflect.construct:function(e,n,t){var r=[null];r.push.apply(r,n);var o=new(Function.bind.apply(e,r));return t&&l(o,t.prototype),o}).apply(null,arguments)}function d(e){var n="function"==typeof Map?new Map:void 0;return(d=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(e))return n.get(e);n.set(e,t)}function t(){return m(e,arguments,f(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),l(t,e)})(e)}function h(e,n){(null==n||n>e.length)&&(n=e.length);for(var t=0,r=new Array(n);t<n;t++)r[t]=e[t];return r}"undefined"!=typeof Symbol&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator"))),"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator"))),function(e){e[e.SyntaxError=100]="SyntaxError",e[e.UnsupportedParameter=101]="UnsupportedParameter",e[e.InvalidValue=102]="InvalidValue",e[e.Unsupported=103]="Unsupported",e[e.DiskFull=104]="DiskFull",e[e.NoDisk=105]="NoDisk",e[e.DiskError=106]="DiskError",e[e.TimelineEmpty=107]="TimelineEmpty",e[e.InternalError=108]="InternalError",e[e.OutOfRange=109]="OutOfRange",e[e.NoInput=110]="NoInput",e[e.RemoteControlDisabled=111]="RemoteControlDisabled",e[e.ConnectionRejected=120]="ConnectionRejected",e[e.InvalidState=150]="InvalidState",e[e.InvalidCodec=151]="InvalidCodec",e[e.InvalidFormat=160]="InvalidFormat",e[e.InvalidToken=161]="InvalidToken",e[e.FormatNotPrepared=162]="FormatNotPrepared"}(t||(t={})),function(e){e[e.OK=200]="OK",e[e.SlotInfo=202]="SlotInfo",e[e.DeviceInfo=204]="DeviceInfo",e[e.ClipsInfo=205]="ClipsInfo",e[e.DiskList=206]="DiskList",e[e.TransportInfo=208]="TransportInfo",e[e.Notify=209]="Notify",e[e.Remote=210]="Remote",e[e.Configuration=211]="Configuration",e[e.ClipsCount=214]="ClipsCount",e[e.Uptime=215]="Uptime",e[e.FormatReady=216]="FormatReady"}(r||(r={})),function(e){e[e.ConnectionInfo=500]="ConnectionInfo",e[e.SlotInfo=502]="SlotInfo",e[e.TransportInfo=508]="TransportInfo",e[e.RemoteInfo=510]="RemoteInfo",e[e.ConfigurationInfo=511]="ConfigurationInfo"}(o||(o={}));var v,g,y,I=((n={})[o.ConfigurationInfo]="configuration info",n[o.ConnectionInfo]="connection info",n[o.RemoteInfo]="remote info",n[o.SlotInfo]="slot info",n[o.TransportInfo]="transport info",n[t.ConnectionRejected]="connection rejected",n[t.DiskError]="disk error",n[t.DiskFull]="disk full",n[t.FormatNotPrepared]="format not prepared",n[t.InternalError]="internal error",n[t.InvalidCodec]="invalid codec",n[t.InvalidFormat]="invalid format",n[t.InvalidState]="invalid state",n[t.InvalidToken]="invalid token",n[t.InvalidValue]="invalid value",n[t.NoDisk]="no disk",n[t.NoInput]="no input",n[t.OutOfRange]="out of range",n[t.RemoteControlDisabled]="remote control disabled",n[t.SyntaxError]="syntax error",n[t.TimelineEmpty]="timeline empty",n[t.Unsupported]="unsupported",n[t.UnsupportedParameter]="unsupported parameter",n[r.ClipsCount]="clips count",n[r.ClipsInfo]="clips info",n[r.Configuration]="configuration",n[r.DeviceInfo]="device info",n[r.DiskList]="disk list",n[r.FormatReady]="format ready",n[r.Notify]="notify",n[r.OK]="ok",n[r.Remote]="remote",n[r.SlotInfo]="slot info",n[r.TransportInfo]="transport info",n[r.Uptime]="uptime",n);!function(e){e.QuickTimeUncompressed="QuickTimeUncompressed",e.QuickTimeProResHQ="QuickTimeProResHQ",e.QuickTimeProRes="QuickTimeProRes",e.QuickTimeProResLT="QuickTimeProResLT",e.QuickTimeProResProxy="QuickTimeProResProxy",e.QuickTimeDNxHR220="QuickTimeDNxHR220",e.DNxHR220="DNxHR220"}(v||(v={})),function(e){e.embedded="embedded",e.XLR="XLR",e.RCA="RCA"}(g||(g={})),function(e){e.SDI="SDI",e.HDMI="HDMI",e.component="component"}(y||(y={}));var S={help:[],commands:[],"device info":[],"disk list":["slot id"],quit:[],ping:[],preview:["enable"],play:["speed","loop","single clip"],"playrange set":["clip id","in","out"],"playrange clear":[],record:["name"],stop:[],"clips count":[],"clips get":["clip id","count"],"clips add":["name"],"clips clear":[],"transport info":[],"slot info":["slot id"],"slot select":["slot id","video format"],notify:["remote","transport","slot","configuration","dropped frames"],goto:["clip id","clip","timeline","timecode","slot id"],jog:["timecode"],shuttle:["speed"],remote:["enable","override"],configuration:["video input","audio input","file format"],uptime:[],format:["prepare","confirm"],identify:["enable"],watchdog:["period"]};function R(e,n){if(!e){for(var t=arguments.length,r=new Array(t>2?t-2:0),o=2;o<t;o++)r[o-2]=arguments[o];throw new Error(s.format.apply(s,[n].concat(r)))}}var b=function(){function e(e){this.linesQueue=[],this.logger=e.child({name:"MultilineParser"})}var n=e.prototype;return n.receivedString=function(e){var n=[],t=e.split("\r\n");for(t.length>0&&""===t[t.length-1]&&t.pop(),this.linesQueue=this.linesQueue.concat(t);this.linesQueue.length>0;)if(""!==this.linesQueue[0])if(!this.linesQueue[0].includes(":")||1===this.linesQueue.length&&this.linesQueue[0].includes(":")){var r=this.parseResponse(this.linesQueue.splice(0,1));r&&n.push(r)}else{var o=this.linesQueue.indexOf("");if(-1===o)break;var i=this.linesQueue.splice(0,o+1),s=this.parseResponse(i);s&&n.push(s)}else this.linesQueue.shift();return n},n.parseResponse=function(e){var n=e.map((function(e){return e.trim()}));if(1===n.length&&n[0].includes(":")){var t=n[0].split(": "),r=t.shift();r||R(!1);var o={},i=new Set(S[r]),s=t.shift();s||R(!1);for(var a=0;a<t.length-1;a++){for(var u=t[a].split(" "),c="",f=u.length-1;f>=0&&(c=(u.pop()+" "+c).trim(),!i.has(c));f--);u.length>0||R(!1),o[s]=u.join(" "),s=c}return o[s]=t[t.length-1],{raw:n.join("\r\n"),name:r,parameters:o}}var l=n[0].match(/(.+?)(:|)$/im);if(!l)return this.logger.error({header:n[0]},"failed to parse header"),null;for(var p=l[1],m={},d=1;d<n.length;d++){var h=n[d].match(/^(.*?): (.*)$/im);h?m[h[1]]=h[2]:this.logger.error({line:n[d]},"failed to parse line")}return{raw:n.join("\r\n"),name:p,parameters:m}},e}(),k=function(e){function n(n,t,r){var i;return(i=e.call(this)||this).socket=n,i.logger=t,i.receivedCommand=r,i.lastReceivedMS=-1,i.watchdogTimer=null,i.notifySettings={slot:!1,transport:!1,remote:!1,configuration:!1,"dropped frames":!1},i.parser=new b(t),i.socket.setEncoding("utf-8"),i.socket.on("data",(function(e){i.onMessage(e)})),i.socket.on("error",(function(e){t.info({err:e},"error"),i.socket.destroy(),i.emit("disconnected"),t.info("manually disconnected")})),i.sendResponse(o.ConnectionInfo,{"protocol version":"1.11",model:"NodeJS HyperDeck Server Library"}),i}c(n,e);var i=n.prototype;return i.onMessage=function(e){var n=this;this.logger.info({data:e},"<-- received message from client"),this.lastReceivedMS=Date.now();var i=this.parser.receivedString(e);this.logger.info({cmds:i},"parsed commands");for(var s,a=function(){var e=s.value;if("watchdog"===e.name){n.watchdogTimer&&clearInterval(n.watchdogTimer);var i=e;i.parameters.period&&(n.watchdogTimer=setInterval((function(){Date.now()-n.lastReceivedMS>Number(i.parameters.period)&&(n.socket.destroy(),n.emit("disconnected"),n.watchdogTimer&&clearInterval(n.watchdogTimer))}),1e3*Number(i.parameters.period)))}else if("notify"===e.name){var a=e;if(!(Object.keys(a.parameters).length>0)){for(var u={},c=0,f=Object.keys(n.notifySettings);c<f.length;c++){var l=f[c];u[l]=n.notifySettings[l]?"true":"false"}return n.sendResponse(r.Notify,u,e),"continue"}for(var p=0,m=Object.keys(a.parameters);p<m.length;p++){var d=m[p];void 0!==n.notifySettings[d]&&(n.notifySettings[d]="true"===a.parameters[d])}}n.receivedCommand(e).then((function(i){return"object"==typeof i?n.sendResponse(i.code,"params"in i&&i.params||"message"in i&&i.message||void 0,e):"number"==typeof i&&(t[i]||r[i]||o[i])?n.sendResponse(i,void 0,e):(n.logger.error({cmd:e,codeOrObj:i},"codeOrObj was neither a ResponseCode nor a response object"),void n.sendResponse(t.InternalError,void 0,e))}),(function(){return n.sendResponse(t.Unsupported,void 0,e)}))},u=function(e,n){var t;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(t=function(e,n){if(e){if("string"==typeof e)return h(e,void 0);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?h(e,void 0):void 0}}(e))){t&&(e=t);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(t=e[Symbol.iterator]()).next.bind(t)}(i);!(s=u()).done;)a()},i.sendResponse=function(e,n,r){var o=function(e,n){if("string"==typeof n)return e+" "+n.replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/:/g,"")+"\r\n";var t=e+" "+I[e];if(!n)return t+"\r\n";var r=Object.entries(n).filter((function(e){return null!=e[1]}));return 0===r.length?t+"\r\n":r.reduce((function(e,n){var t,r=n[0],o=n[1];return"string"==typeof o?t=o:"boolean"==typeof o?t=o?"true":"false":"number"==typeof o?t=o.toString():R(!1),e+r.replace(/([a-z])([A-Z]+)/,"$1 $2").toLowerCase()+": "+t+"\r\n"}),t+":\r\n")+"\r\n"}(e,n);this.logger[t[e]?"error":"info"]({responseText:o,cmd:r},"--\x3e send response to client"),this.socket.write(o)},i.notify=function(e,n){this.logger.info({type:e,params:n},"notify"),"configuration"===e&&this.notifySettings.configuration?this.sendResponse(o.ConfigurationInfo,n):"remote"===e&&this.notifySettings.remote?this.sendResponse(o.RemoteInfo,n):"slot"===e&&this.notifySettings.slot?this.sendResponse(o.SlotInfo,n):"transport"===e&&this.notifySettings.transport?this.sendResponse(o.TransportInfo,n):this.logger.error({type:e,params:n},"unhandled notify type")},n}(i.EventEmitter),C=function(e){for(var n=e.clips.length,t={clipsCount:n},r=0;r<n;r++){var o=e.clips[r];t[(r+1).toString()]=o.name+" "+o.startT+" "+o.duration}return t},P=function(e){function n(){return e.apply(this,arguments)||this}return c(n,e),n}(d(Error)),O=function(){try{throw new P}catch(e){return Promise.reject(e)}};exports.HyperDeckServer=function(){function e(e,n){var o=this,i=this;void 0===n&&(n=u()),this.sockets={},this.onDeviceInfo=O,this.onDiskList=O,this.onPreview=O,this.onPlay=O,this.onPlayrangeSet=O,this.onPlayrangeClear=O,this.onRecord=O,this.onStop=O,this.onClipsCount=O,this.onClipsGet=O,this.onClipsAdd=O,this.onClipsClear=O,this.onTransportInfo=O,this.onSlotInfo=O,this.onSlotSelect=O,this.onGoTo=O,this.onJog=O,this.onShuttle=O,this.onConfiguration=O,this.onUptime=O,this.onFormat=O,this.onIdentify=O,this.onWatchdog=O,this.receivedCommand=function(e){try{return Promise.resolve(new Promise((function(e){return setTimeout((function(){return e()}),200)}))).then((function(){var n=!1;return i.logger.info({cmd:e},"<-- "+e.name),function(t,o){try{var s=function(){function t(t){var o=!1;if(n)return t;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){var t=!1;if(o)return n;function s(n){var o=!1;if(t)return n;function s(n){return o?n:"watchdog"===e.name||"ping"===e.name?r.OK:void R(!1)}var a=function(){if("identify"===e.name)return Promise.resolve(i.onIdentify(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("format"===e.name)return Promise.resolve(i.onFormat(e)).then((function(e){return e?(t=!0,{code:r.FormatReady,params:e}):(t=!0,r.OK)}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("uptime"===e.name)return Promise.resolve(i.onUptime(e)).then((function(e){return o=!0,{code:r.Uptime,params:e}}))}();return a&&a.then?a.then(s):s(a)}if("remote"===e.name)return{code:r.Remote,params:{enabled:!0,override:!1}};var a=function(){if("configuration"===e.name)return Promise.resolve(i.onConfiguration(e)).then((function(e){return e?(t=!0,{code:r.Configuration,params:e}):(t=!0,r.OK)}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("shuttle"===e.name)return Promise.resolve(i.onShuttle(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("jog"===e.name)return Promise.resolve(i.onJog(e)).then((function(){return t=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}if("notify"===e.name)return r.OK;var a=function(){if("go to"===e.name)return Promise.resolve(i.onGoTo(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("slot select"===e.name)return Promise.resolve(i.onSlotSelect(e)).then((function(){return t=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("slot info"===e.name)return Promise.resolve(i.onSlotInfo(e)).then((function(e){return o=!0,{code:r.SlotInfo,params:e}}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("transport info"===e.name)return Promise.resolve(i.onTransportInfo(e)).then((function(e){return t=!0,{code:r.TransportInfo,params:e}}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("clips clear"===e.name)return Promise.resolve(i.onClipsClear(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("clips add"===e.name)return Promise.resolve(i.onClipsAdd(e)).then((function(){return t=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("clips get"===e.name)return Promise.resolve(i.onClipsGet(e).then(C)).then((function(e){return o=!0,{code:r.ClipsInfo,params:e}}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("clips count"===e.name)return Promise.resolve(i.onClipsCount(e)).then((function(e){return t=!0,{code:r.ClipsCount,params:e}}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("stop"===e.name)return Promise.resolve(i.onStop(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("record"===e.name)return Promise.resolve(i.onRecord(e)).then((function(){return t=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("playrange clear"===e.name)return Promise.resolve(i.onPlayrangeClear(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("playrange set"===e.name)return Promise.resolve(i.onPlayrangeSet(e)).then((function(){return t=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("play"===e.name)return Promise.resolve(i.onPlay(e)).then((function(){return o=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("preview"===e.name)return Promise.resolve(i.onPreview(e)).then((function(){return t=!0,r.OK}))}();return a&&a.then?a.then(s):s(a)}var a=function(){if("disk list"===e.name)return Promise.resolve(i.onDiskList(e)).then((function(e){return o=!0,{code:r.DiskList,params:e}}))}();return a&&a.then?a.then(s):s(a)}var o=function(){if("device info"===e.name)return Promise.resolve(i.onDeviceInfo(e)).then((function(e){return n=!0,{code:r.DeviceInfo,params:e}}))}();return o&&o.then?o.then(t):t(o)}()}catch(e){return o(e)}return s&&s.then?s.then(void 0,o):s}(0,(function(n){return n instanceof P?(i.logger.error({cmd:e},"unimplemented"),t.Unsupported):(i.logger.error({cmd:e,err:n.message},"unhandled command name"),t.InternalError)}))}))}catch(e){return Promise.reject(e)}},this.logger=n.child({name:"HyperDeck Emulator"}),this.server=a.createServer((function(e){o.logger.info("connection");var n=Math.random().toString(35).substr(-6),t=o.logger.child({name:"HyperDeck socket "+n});o.sockets[n]=new k(e,t,(function(e){return o.receivedCommand(e)})),o.sockets[n].on("disconnected",(function(){t.info("disconnected"),delete o.sockets[n]}))})),this.server.on("listening",(function(){return o.logger.info("listening")})),this.server.on("close",(function(){return o.logger.info("connection closed")})),this.server.on("error",(function(e){return o.logger.error("server error:",e)})),this.server.maxConnections=1,this.server.listen(9993,e)}var n=e.prototype;return n.close=function(){this.server.unref()},n.notifySlot=function(e){this.notify("slot",e)},n.notifyTransport=function(e){this.notify("transport",e)},n.notify=function(e,n){for(var t=0,r=Object.keys(this.sockets);t<r.length;t++)this.sockets[r[t]].notify(e,n)},e}(),exports.ResponseInterface={__proto__:null},exports.Timecode=function(e,n,t,r){var o=[e,n,t,r].map((function(e){var n=Math.floor(e);return n===e&&e>=0&&e<=99||R(!1),(n+100).toString().slice(-2)})).join(":");this.toString=function(){return o}}; | ||
//# sourceMappingURL=hyperdeck-emulator.cjs.production.min.js.map |
import { EventEmitter } from 'events'; | ||
import util from 'util'; | ||
import { createServer } from 'net'; | ||
@@ -270,2 +271,12 @@ import pino from 'pino'; | ||
function invariant(condition, message) { | ||
if (!condition) { | ||
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { | ||
args[_key - 2] = arguments[_key]; | ||
} | ||
throw new Error(util.format.apply(util, [message].concat(args))); | ||
} | ||
} | ||
var MultilineParser = /*#__PURE__*/function () { | ||
@@ -284,3 +295,3 @@ function MultilineParser(logger) { | ||
var newLines = data.split('\r\n'); // remove the blank line at the end from the intentionally trailing \r\n | ||
var newLines = data.split(CRLF); // remove the blank line at the end from the intentionally trailing \r\n | ||
@@ -298,7 +309,7 @@ if (newLines.length > 0 && newLines[newLines.length - 1] === '') newLines.pop(); | ||
if (this.linesQueue[0].indexOf(':') === -1 || this.linesQueue.length === 1 && this.linesQueue[0].indexOf(':') > 0) { | ||
var _r = this.parseResponse(this.linesQueue.splice(0, 1)); | ||
if (!this.linesQueue[0].includes(':') || this.linesQueue.length === 1 && this.linesQueue[0].includes(':')) { | ||
var parsedResponse = this.parseResponse(this.linesQueue.splice(0, 1)); | ||
if (_r) { | ||
res.push(_r); | ||
if (parsedResponse) { | ||
res.push(parsedResponse); | ||
} | ||
@@ -318,3 +329,6 @@ | ||
var r = this.parseResponse(lines); | ||
if (r) res.push(r); | ||
if (r) { | ||
res.push(r); | ||
} | ||
} | ||
@@ -325,18 +339,19 @@ | ||
_proto.parseResponse = function parseResponse(lines) { | ||
lines = lines.map(function (l) { | ||
_proto.parseResponse = function parseResponse(responseLines) { | ||
var lines = responseLines.map(function (l) { | ||
return l.trim(); | ||
}); | ||
if (lines.length === 1 && lines[0].indexOf(':') > -1) { | ||
if (lines.length === 1 && lines[0].includes(':')) { | ||
var bits = lines[0].split(': '); | ||
var msg = bits.shift(); | ||
if (!msg) throw new Error('Unrecognised command'); | ||
!msg ? process.env.NODE_ENV !== "production" ? invariant(false, 'Unrecognised command') : invariant(false) : void 0; | ||
var params = {}; | ||
var paramNames = new Set(parametersByCommandName[msg]); | ||
var param = bits.shift(); | ||
if (!param) throw new Error('No named parameters found'); | ||
!param ? process.env.NODE_ENV !== "production" ? invariant(false, 'No named parameters found') : invariant(false) : void 0; | ||
for (var i = 0; i < bits.length - 1; i++) { | ||
var bobs = bits[i].split(' '); | ||
var bit = bits[i]; | ||
var bobs = bit.split(' '); | ||
var nextParam = ''; | ||
@@ -352,6 +367,3 @@ | ||
if (!bobs.length) { | ||
throw new Error('Command malformed / paramName not recognised'); | ||
} | ||
!(bobs.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Command malformed / paramName not recognised: `%s`', bit) : invariant(false) : void 0; | ||
params[param] = bobs.join(' '); | ||
@@ -363,3 +375,3 @@ param = nextParam; | ||
return { | ||
raw: lines.join('\r\n'), | ||
raw: lines.join(CRLF), | ||
name: msg, | ||
@@ -395,3 +407,3 @@ parameters: params | ||
var res = { | ||
raw: lines.join('\r\n'), | ||
raw: lines.join(CRLF), | ||
name: _msg, | ||
@@ -447,3 +459,3 @@ parameters: _params | ||
} else { | ||
throw new Error('Unhandled value type: ' + typeof value); | ||
process.env.NODE_ENV !== "production" ? invariant(false, 'Unhandled value type: `%s`', typeof value) : invariant(false) ; | ||
} // convert camelCase keys to space-separated words | ||
@@ -474,4 +486,3 @@ | ||
configuration: false, | ||
'dropped frames': false // @todo: implement | ||
'dropped frames': false | ||
}; | ||
@@ -813,3 +824,3 @@ _this.parser = new MultilineParser(logger); | ||
throw new Error('Unhandled command name: ' + cmd.name); | ||
!false ? process.env.NODE_ENV !== "production" ? invariant(false, 'Unhandled command name: `%s`', cmd.name) : invariant(false) : void 0; | ||
} | ||
@@ -1214,8 +1225,4 @@ | ||
var codeInt = Math.floor(code); | ||
!(codeInt === code && code >= 0 && code <= 99) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Timecode params must be an integer between 0 and 99') : invariant(false) : void 0; // turn the integer into a potentially zero-prefixed string | ||
if (codeInt !== code || code < 0 || code > 99) { | ||
throw new Error('Timecode params must be an integer between 0 and 99'); | ||
} // turn the integer into a potentially zero-prefixed string | ||
return (codeInt + 100).toString().slice(-2); | ||
@@ -1222,0 +1229,0 @@ }).join(':'); |
@@ -8,4 +8,4 @@ import type { DeserializedCommand } from './types'; | ||
receivedString(data: string): DeserializedCommand[]; | ||
parseResponse(lines: string[]): DeserializedCommand | null; | ||
private parseResponse; | ||
} | ||
//# sourceMappingURL=MultilineParser.d.ts.map |
{ | ||
"name": "@meyer/hyperdeck-emulator", | ||
"version": "0.0.4-canary.28.6476ee1", | ||
"version": "0.0.4-canary.29.c1a834c", | ||
"description": "Typescript Node.js library for emulating a Blackmagic Hyperdeck", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
import type { Socket } from 'net' | ||
import { EventEmitter } from 'events' | ||
import { getTestLogger } from './utils' | ||
import { invariant } from '../invariant' | ||
@@ -18,5 +19,3 @@ const noop = (): any => { | ||
const mockSocket = new MockSocket() | ||
if (!connectionListener) { | ||
throw new Error('Missing connectionListener') | ||
} | ||
invariant(connectionListener, 'Missing connectionListener') | ||
connectionListener(mockSocket) | ||
@@ -117,3 +116,3 @@ return { | ||
}, | ||
"err": "Unhandled command name: banana", | ||
"err": "Unhandled command name: \`banana\`", | ||
"level": 50, | ||
@@ -120,0 +119,0 @@ "msg": "unhandled command name", |
@@ -53,4 +53,4 @@ import { messageForCode } from '../messageForCode' | ||
messageForCode(SynchronousCode.OK, { param1: { hmmm: true } }) | ||
).toThrowErrorMatchingInlineSnapshot(`"Unhandled value type: object"`) | ||
).toThrowErrorMatchingInlineSnapshot(`"Unhandled value type: \`object\`"`) | ||
}) | ||
}) |
@@ -71,3 +71,3 @@ import { MultilineParser } from '../MultilineParser' | ||
expect(parseMe).toThrowErrorMatchingInlineSnapshot( | ||
`"Command malformed / paramName not recognised"` | ||
`"Command malformed / paramName not recognised: \`true slottttttttt\`"` | ||
) | ||
@@ -74,0 +74,0 @@ }) |
@@ -9,2 +9,3 @@ import { HyperDeckSocket } from './HyperDeckSocket' | ||
import pino from 'pino' | ||
import { invariant } from './invariant' | ||
@@ -242,3 +243,3 @@ type Handler<C extends DeserializedCommand, R extends any> = (command: C) => Promise<R> | ||
throw new Error('Unhandled command name: ' + cmd.name) | ||
invariant(false, 'Unhandled command name: `%s`', cmd.name) | ||
} catch (err) { | ||
@@ -245,0 +246,0 @@ if (err instanceof UnimplementedError) { |
@@ -68,3 +68,3 @@ import type { Socket } from 'net' | ||
configuration: false, | ||
'dropped frames': false // @todo: implement | ||
'dropped frames': false | ||
} | ||
@@ -71,0 +71,0 @@ |
import { CRLF } from './constants' | ||
import { ResponseCode, responseNamesByCode } from './types' | ||
import { invariant } from './invariant' | ||
@@ -45,3 +46,3 @@ // escape CR/LF and remove colons | ||
} else { | ||
throw new Error('Unhandled value type: ' + typeof value) | ||
invariant(false, 'Unhandled value type: `%s`', typeof value) | ||
} | ||
@@ -48,0 +49,0 @@ |
import type { DeserializedCommand } from './types' | ||
import { parametersByCommandName } from './constants' | ||
import { parametersByCommandName, CRLF } from './constants' | ||
import type { Logger } from 'pino' | ||
import { invariant } from './invariant' | ||
@@ -13,7 +14,7 @@ export class MultilineParser { | ||
receivedString(data: string): DeserializedCommand[] { | ||
public receivedString(data: string): DeserializedCommand[] { | ||
const res: DeserializedCommand[] = [] | ||
// add new lines to processing queue | ||
const newLines = data.split('\r\n') | ||
const newLines = data.split(CRLF) | ||
@@ -34,8 +35,8 @@ // remove the blank line at the end from the intentionally trailing \r\n | ||
if ( | ||
this.linesQueue[0].indexOf(':') === -1 || | ||
(this.linesQueue.length === 1 && this.linesQueue[0].indexOf(':') > 0) | ||
!this.linesQueue[0].includes(':') || | ||
(this.linesQueue.length === 1 && this.linesQueue[0].includes(':')) | ||
) { | ||
const r = this.parseResponse(this.linesQueue.splice(0, 1)) | ||
if (r) { | ||
res.push(r) | ||
const parsedResponse = this.parseResponse(this.linesQueue.splice(0, 1)) | ||
if (parsedResponse) { | ||
res.push(parsedResponse) | ||
} | ||
@@ -53,3 +54,5 @@ continue | ||
const r = this.parseResponse(lines) | ||
if (r) res.push(r) | ||
if (r) { | ||
res.push(r) | ||
} | ||
} | ||
@@ -60,10 +63,10 @@ | ||
parseResponse(lines: string[]): DeserializedCommand | null { | ||
lines = lines.map((l) => l.trim()) | ||
private parseResponse(responseLines: string[]): DeserializedCommand | null { | ||
const lines = responseLines.map((l) => l.trim()) | ||
if (lines.length === 1 && lines[0].indexOf(':') > -1) { | ||
if (lines.length === 1 && lines[0].includes(':')) { | ||
const bits = lines[0].split(': ') | ||
const msg = bits.shift() as keyof typeof parametersByCommandName | ||
if (!msg) throw new Error('Unrecognised command') | ||
invariant(msg, 'Unrecognised command') | ||
@@ -73,5 +76,7 @@ const params: Record<string, string> = {} | ||
let param = bits.shift() | ||
if (!param) throw new Error('No named parameters found') | ||
invariant(param, 'No named parameters found') | ||
for (let i = 0; i < bits.length - 1; i++) { | ||
const bobs = bits[i].split(' ') | ||
const bit = bits[i] | ||
const bobs = bit.split(' ') | ||
@@ -86,5 +91,7 @@ let nextParam = '' | ||
if (!bobs.length) { | ||
throw new Error('Command malformed / paramName not recognised') | ||
} | ||
invariant( | ||
bobs.length > 0, | ||
'Command malformed / paramName not recognised: `%s`', | ||
bit | ||
) | ||
@@ -94,6 +101,7 @@ params[param] = bobs.join(' ') | ||
} | ||
params[param] = bits[bits.length - 1] | ||
return { | ||
raw: lines.join('\r\n'), | ||
raw: lines.join(CRLF), | ||
name: msg, | ||
@@ -124,3 +132,3 @@ parameters: params | ||
const res: DeserializedCommand = { | ||
raw: lines.join('\r\n'), | ||
raw: lines.join(CRLF), | ||
name: msg, | ||
@@ -127,0 +135,0 @@ parameters: params |
@@ -0,1 +1,3 @@ | ||
import { invariant } from './invariant' | ||
export class Timecode { | ||
@@ -6,5 +8,7 @@ constructor(hh: number, mm: number, ss: number, ff: number) { | ||
const codeInt = Math.floor(code) | ||
if (codeInt !== code || code < 0 || code > 99) { | ||
throw new Error('Timecode params must be an integer between 0 and 99') | ||
} | ||
invariant( | ||
codeInt === code && code >= 0 && code <= 99, | ||
'Timecode params must be an integer between 0 and 99' | ||
) | ||
// turn the integer into a potentially zero-prefixed string | ||
@@ -11,0 +15,0 @@ return (codeInt + 100).toString().slice(-2) |
@@ -70,7 +70,7 @@ import type { Timecode } from '../Timecode' | ||
export interface Uptime { | ||
uptime: string // @todo: is broken in hyperdeck | ||
uptime: string | ||
} | ||
export interface Format { | ||
token: string // @todo: is broken in hyperdeck | ||
token: string | ||
} | ||
@@ -77,0 +77,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
404239
3885
3
8