59 lines
1.6 KiB
JavaScript
59 lines
1.6 KiB
JavaScript
|
|
"use strict";
|
||
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||
|
|
exports.validateProtocolMessage = validateProtocolMessage;
|
||
|
|
exports.createProtocolMessage = createProtocolMessage;
|
||
|
|
function validateProtocolMessage(body, withData = true) {
|
||
|
|
const isHex = (s) => /^[0-9A-Fa-f]+$/g.test(s);
|
||
|
|
const isValidProtocol = (s) => s === 'v1' || s === 'bridge';
|
||
|
|
if (typeof body === 'string') {
|
||
|
|
if ((withData && isHex(body)) || (!withData && !body.length)) {
|
||
|
|
return {
|
||
|
|
data: body,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
}
|
||
|
|
let json;
|
||
|
|
if (typeof body === 'object') {
|
||
|
|
json = body;
|
||
|
|
}
|
||
|
|
else {
|
||
|
|
try {
|
||
|
|
json = JSON.parse(body);
|
||
|
|
}
|
||
|
|
catch {
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if (!json) {
|
||
|
|
throw new Error('Invalid BridgeProtocolMessage body');
|
||
|
|
}
|
||
|
|
if (typeof json.protocol !== 'string' || !isValidProtocol(json.protocol)) {
|
||
|
|
throw new Error('Invalid BridgeProtocolMessage protocol');
|
||
|
|
}
|
||
|
|
if (withData && (typeof json.data !== 'string' || !isHex(json.data))) {
|
||
|
|
throw new Error('Invalid BridgeProtocolMessage data');
|
||
|
|
}
|
||
|
|
return {
|
||
|
|
protocol: json.protocol,
|
||
|
|
data: json.data,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
function createProtocolMessage(body, protocol) {
|
||
|
|
let data;
|
||
|
|
if (Buffer.isBuffer(body)) {
|
||
|
|
data = body.toString('hex');
|
||
|
|
}
|
||
|
|
if (typeof body === 'string') {
|
||
|
|
data = body;
|
||
|
|
}
|
||
|
|
if (typeof data !== 'string') {
|
||
|
|
data = '';
|
||
|
|
}
|
||
|
|
if (!protocol) {
|
||
|
|
return data;
|
||
|
|
}
|
||
|
|
return JSON.stringify({
|
||
|
|
protocol: typeof protocol === 'string' ? protocol : protocol.name,
|
||
|
|
data,
|
||
|
|
});
|
||
|
|
}
|
||
|
|
//# sourceMappingURL=bridgeProtocolMessage.js.map
|