messages: pure builders for every event the bridge sends

src/messages builds Response, StateReport, DeferredResponse, ErrorResponse, ChangeReport and the scene, doorbell
and simple events from plain values; messageId and times are parameters, so a test compares whole objects.
StateBuilder collects properties checked by the descriptors, AlexaError and AlexaErrors carry the payload fields
of an error type. AlexaStatusMessage and AlexaErrorResponse move to src/compat and are written on the builders.
On the wire, against 1.5.2: a DeferredResponse has no context key, a ChangeReport has no correlationToken, the
namespace of an ErrorResponse follows its type, and a ChangeReport without a changed property is not published:
send() resolves "" and the bridge reports an error that names the endpoint.
143 tests pass (108 before).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
David 2026-09-28 19:28:05 +00:00
parent 2558e21787
commit 46fa06728c
68 changed files with 3410 additions and 1208 deletions

70
dist/cjs/messages/StateBuilder.js vendored Normal file
View file

@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StateBuilder = void 0;
const EndpointHealth_js_1 = require("../registry/interfaces/EndpointHealth.js");
const schema_js_1 = require("../registry/schema.js");
const property_js_1 = require("./property.js");
/**
* Collects the properties of one message. For a Response or a StateReport they are its context. For a ChangeReport
* changed() and unchanged() say which of the two lists the properties that follow belong to.
*/
class StateBuilder {
constructor(options = {}) {
this.lists = { context: [], change: [] };
this.target = options.target ?? "context";
this.now = options.now ?? (() => new Date());
}
/**
* A property of an interface the library describes, its value checked: set(PowerController, "powerState", "ON").
* Given a capability of a device in place of the interface, the property carries the instance of the capability.
* Throws SchemaError for a value Alexa would not take.
*/
set(source, name, value, options = {}) {
const descriptor = "descriptor" in source ? source.descriptor : source;
const instance = options.instance ?? ("descriptor" in source ? source.instance : "");
const where = `${descriptor.namespace}${instance ? ` "${instance}"` : ""}: ${name}`;
const described = descriptor.properties[name];
if (!described) {
const names = Object.keys(descriptor.properties);
throw new schema_js_1.SchemaError(where, names.length > 0
? `not a property of the interface, which has ${names.join(", ")}`
: "the library knows no property of the interface, report it with setRaw()");
}
if (descriptor.instanced && !instance) {
throw new schema_js_1.SchemaError(where, "the interface has instances, pass the one that is reported: { instance: \"Blind.Lift\" }");
}
return this.setRaw(descriptor.namespace, described.name, described.value.parse(value, where), { ...options, instance });
}
/** A property as given, nothing checked: for an interface or a value the library does not describe. */
setRaw(namespace, name, value, options = {}) {
return this.add((0, property_js_1.property)(namespace, name, value, { ...options, timeOfSample: options.timeOfSample ?? this.now() }));
}
/** The connectivity of Alexa.EndpointHealth, which belongs in every report of an endpoint that declares it. */
health(value, reason, options = {}) {
return this.set(EndpointHealth_js_1.EndpointHealth, "connectivity", reason ? { value, reason } : { value }, options);
}
/** A property built elsewhere, to the list that is filled now or to the one named. */
add(built, target = this.target) {
this.lists[target].push(built);
return this;
}
/** The properties that follow are the ones that changed. */
changed() {
this.target = "change";
return this;
}
/** The properties that follow did not change: a ChangeReport lists them in its context. */
unchanged() {
this.target = "context";
return this;
}
/** The properties for the context of the message, in the order they were set. */
get context() {
return [...this.lists.context];
}
/** The properties for payload.change of a ChangeReport. */
get change() {
return [...this.lists.change];
}
}
exports.StateBuilder = StateBuilder;

136
dist/cjs/messages/build.js vendored Normal file
View file

@ -0,0 +1,136 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageError = void 0;
exports.response = response;
exports.stateReport = stateReport;
exports.deferredResponse = deferredResponse;
exports.errorResponse = errorResponse;
exports.changeReport = changeReport;
exports.sceneEvent = sceneEvent;
exports.doorbellPress = doorbellPress;
exports.simpleEvent = simpleEvent;
// Every message the bridge publishes, built from plain values. Nothing here reads the clock or makes an id unless
// the caller leaves messageId or a time out, so a test that passes both compares whole objects.
const crypto_1 = require("crypto");
const errors_js_1 = require("./errors.js");
const property_js_1 = require("./property.js");
/** A message that would be dropped on its way to Alexa, refused where it is built. */
class MessageError extends Error {
constructor(endpointId, problem) {
super(`${endpointId}: ${problem}`);
this.endpointId = endpointId;
this.problem = problem;
this.name = "MessageError";
}
}
exports.MessageError = MessageError;
// The fields in the order of the examples
function header(namespace, name, fields) {
return {
namespace,
name,
...(fields.instance ? { instance: fields.instance } : {}),
messageId: fields.messageId ?? (0, crypto_1.randomUUID)(),
...(fields.correlationToken !== undefined ? { correlationToken: fields.correlationToken } : {}),
payloadVersion: fields.payloadVersion ?? "3",
};
}
/**
* The answer to a directive (alexa-response.html, "Synchronous response"). An endpoint with nothing to report
* answers with an empty list of properties, not without a context (state-reporting-for-smart-home-addons.html,
* "Directive response example for a property that isn't retrievable").
*/
function response(fields) {
return {
event: {
header: header(fields.namespace ?? "Alexa", fields.name ?? "Response", fields),
endpoint: { endpointId: fields.endpointId },
payload: fields.payload ?? {},
},
context: { properties: [...(fields.context ?? [])] },
};
}
/** The answer to ReportState: every retrievable property of the endpoint. */
function stateReport(fields) {
return response({ ...fields, name: "StateReport", namespace: "Alexa", payload: {} });
}
/**
* "The directive arrived, the answer follows": no context, the state is in the Response that follows
* (alexa-response.html, "Deferred response example").
*/
function deferredResponse(fields) {
const { estimatedDeferralInSeconds } = fields;
return {
event: {
header: header("Alexa", "DeferredResponse", fields),
endpoint: { endpointId: fields.endpointId },
payload: estimatedDeferralInSeconds === undefined ? {} : { estimatedDeferralInSeconds },
},
};
}
/** The answer to a directive the endpoint could not follow (alexa-errorresponse.html). */
function errorResponse(fields) {
return {
event: {
header: header(fields.namespace ?? (0, errors_js_1.errorNamespace)(fields.type), "ErrorResponse", fields),
endpoint: { endpointId: fields.endpointId },
payload: { type: fields.type, message: fields.message, ...fields.extra },
},
};
}
const sameProperty = (a, b) => a.namespace === b.namespace && a.name === b.name && (a.instance ?? "") === (b.instance ?? "");
/**
* A change of state nobody asked for. The header has no correlationToken (message-guide.html, "Header object").
* A property that changed is left out of the context: it is reported in one of the two (same page, "Context
* object"). Throws MessageError when nothing changed: Alex2MQTT drops such a report without a word.
*/
function changeReport(fields) {
const { endpointId, changed, context = [] } = fields;
if (changed.length === 0) {
throw new MessageError(endpointId, "a ChangeReport needs at least one property that changed, this one has none. "
+ "Add the changed property before unchanged(), or send no report when nothing changed");
}
return {
event: {
header: header("Alexa", "ChangeReport", { messageId: fields.messageId }),
endpoint: { endpointId },
payload: { change: { cause: { type: fields.cause ?? "PHYSICAL_INTERACTION" }, properties: [...changed] } },
},
context: { properties: context.filter((property) => !changed.some((other) => sameProperty(property, other))) },
};
}
/** The answer to Activate and Deactivate of a scene (alexa-scenecontroller.html). */
function sceneEvent(fields) {
return {
event: {
header: header("Alexa.SceneController", fields.activated ? "ActivationStarted" : "DeactivationStarted", fields),
endpoint: { endpointId: fields.endpointId },
payload: { cause: { type: fields.cause ?? "VOICE_INTERACTION" }, timestamp: (0, property_js_1.isoTime)(fields.timestamp) },
},
context: {},
};
}
/** Somebody rang (alexa-doorbelleventsource.html). */
function doorbellPress(fields) {
return {
event: {
header: header("Alexa.DoorbellEventSource", "DoorbellPress", { messageId: fields.messageId }),
endpoint: { endpointId: fields.endpointId },
payload: { cause: { type: fields.cause ?? "PHYSICAL_INTERACTION" }, timestamp: (0, property_js_1.isoTime)(fields.timestamp) },
},
};
}
/** An event of a button or a sensor that routines start on (alexa-simpleeventsource.html). */
function simpleEvent(fields) {
return {
event: {
header: header("Alexa.SimpleEventSource", "Event", {
instance: fields.instance,
messageId: fields.messageId,
payloadVersion: "1.0",
}),
endpoint: { endpointId: fields.endpointId },
payload: { id: fields.id, timestamp: (0, property_js_1.isoTime)(fields.timestamp) },
},
};
}

74
dist/cjs/messages/errors.js vendored Normal file
View file

@ -0,0 +1,74 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AlexaErrors = exports.AlexaError = void 0;
exports.errorNamespace = errorNamespace;
// The errors a device answers a directive with (alexa-errorresponse.html). A helper for each type whose payload
// has fields of its own, so that the fields cannot be misspelt.
const catalog_js_1 = require("../registry/catalog.js");
/**
* The namespace an ErrorResponse of this type goes under: the one the table of error types lists it with
* (THERMOSTAT_IS_OFF: Alexa.ThermostatController, OBSTACLE_DETECTED: Alexa.Safety), Alexa for a type the table
* does not have.
*/
function errorNamespace(type) {
return Object.prototype.hasOwnProperty.call(catalog_js_1.ERROR_TYPES, type) ? catalog_js_1.ERROR_TYPES[type] : "Alexa";
}
/** Thrown by a directive handler, or built to be sent: the directive is answered with this ErrorResponse. */
class AlexaError extends Error {
constructor(type, message, extra = {}, namespace = errorNamespace(type)) {
super(`${type}: ${message}`);
this.name = "AlexaError";
this.type = type;
this.alexaMessage = message;
this.extra = extra;
this.namespace = namespace;
}
}
exports.AlexaError = AlexaError;
// A field that was not given is left out of the payload
function given(fields) {
return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
}
exports.AlexaErrors = {
/** An error of any type. */
of(type, message, extra = {}) {
return new AlexaError(type, message, extra);
},
/** The value is outside what the endpoint takes. For a temperature: temperatureOutOfRange(). */
valueOutOfRange(message, validRange) {
return new AlexaError("VALUE_OUT_OF_RANGE", message, { validRange });
},
temperatureOutOfRange(message, validRange) {
return new AlexaError("TEMPERATURE_VALUE_OUT_OF_RANGE", message, { validRange });
},
/** A light showing a color asked for a color temperature: "COLOR". */
notSupportedInCurrentMode(message, currentDeviceMode) {
return new AlexaError("NOT_SUPPORTED_IN_CURRENT_MODE", message, { currentDeviceMode });
},
/** percentageState: what is left of the battery, 0 to 100. */
endpointLowPower(message, percentageState) {
return new AlexaError("ENDPOINT_LOW_POWER", message, given({ percentageState }));
},
endpointControlUnavailable(message, reason) {
return new AlexaError("ENDPOINT_CONTROL_UNAVAILABLE", message, { reason });
},
notSupportedWithCurrentBatteryChargeState(message, currentChargeState, currentChargeLevelInPercentage) {
return new AlexaError("NOT_SUPPORTED_WITH_CURRENT_BATTERY_CHARGE_STATE", message, given({ currentChargeState, currentChargeLevelInPercentage }));
},
/** What has to be refilled. */
insufficientResource(message, resourceType) {
return new AlexaError("INSUFFICIENT_RESOURCE", message, { resourceType });
},
/** What the user has to do first. */
maintenanceRequired(message, maintenanceAction) {
return new AlexaError("MAINTENANCE_REQUIRED", message, given({ maintenanceAction }));
},
/** Goes under Alexa.ThermostatController. minimumTemperatureDelta: how far apart the setpoints have to be. */
setpointsTooClose(message, minimumTemperatureDelta) {
return new AlexaError("REQUESTED_SETPOINTS_TOO_CLOSE", message, given({ minimumTemperatureDelta }));
},
/** Goes under Alexa.SecurityPanelController. With the endpoints listed, the user can bypass them by voice. */
bypassNeeded(message, endpointsNeedingBypass) {
return new AlexaError("BYPASS_NEEDED", message, given({ endpointsNeedingBypass }));
},
};

22
dist/cjs/messages/index.js vendored Normal file
View file

@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StateBuilder = exports.property = exports.errorNamespace = exports.AlexaErrors = exports.AlexaError = exports.MessageError = exports.stateReport = exports.simpleEvent = exports.sceneEvent = exports.response = exports.errorResponse = exports.doorbellPress = exports.deferredResponse = exports.changeReport = void 0;
// The messages of the bridge without the bridge: builders, the state collector and the errors.
var build_js_1 = require("./build.js");
Object.defineProperty(exports, "changeReport", { enumerable: true, get: function () { return build_js_1.changeReport; } });
Object.defineProperty(exports, "deferredResponse", { enumerable: true, get: function () { return build_js_1.deferredResponse; } });
Object.defineProperty(exports, "doorbellPress", { enumerable: true, get: function () { return build_js_1.doorbellPress; } });
Object.defineProperty(exports, "errorResponse", { enumerable: true, get: function () { return build_js_1.errorResponse; } });
Object.defineProperty(exports, "response", { enumerable: true, get: function () { return build_js_1.response; } });
Object.defineProperty(exports, "sceneEvent", { enumerable: true, get: function () { return build_js_1.sceneEvent; } });
Object.defineProperty(exports, "simpleEvent", { enumerable: true, get: function () { return build_js_1.simpleEvent; } });
Object.defineProperty(exports, "stateReport", { enumerable: true, get: function () { return build_js_1.stateReport; } });
Object.defineProperty(exports, "MessageError", { enumerable: true, get: function () { return build_js_1.MessageError; } });
var errors_js_1 = require("./errors.js");
Object.defineProperty(exports, "AlexaError", { enumerable: true, get: function () { return errors_js_1.AlexaError; } });
Object.defineProperty(exports, "AlexaErrors", { enumerable: true, get: function () { return errors_js_1.AlexaErrors; } });
Object.defineProperty(exports, "errorNamespace", { enumerable: true, get: function () { return errors_js_1.errorNamespace; } });
var property_js_1 = require("./property.js");
Object.defineProperty(exports, "property", { enumerable: true, get: function () { return property_js_1.property; } });
var StateBuilder_js_1 = require("./StateBuilder.js");
Object.defineProperty(exports, "StateBuilder", { enumerable: true, get: function () { return StateBuilder_js_1.StateBuilder; } });

19
dist/cjs/messages/property.js vendored Normal file
View file

@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isoTime = isoTime;
exports.property = property;
/** A time as Alexa wants it: ISO 8601 in UTC. Text is taken as given. */
function isoTime(time = new Date()) {
return typeof time === "string" ? time : time.toISOString();
}
/** One property of a context or of a change, its fields in the order of the examples. */
function property(namespace, name, value, options = {}) {
return {
namespace,
...(options.instance ? { instance: options.instance } : {}),
name,
value,
timeOfSample: isoTime(options.timeOfSample),
uncertaintyInMilliseconds: options.uncertaintyInMilliseconds ?? 0,
};
}

3
dist/cjs/messages/types.js vendored Normal file
View file

@ -0,0 +1,3 @@
"use strict";
// The messages the bridge publishes, as message-guide.html and alexa-response.html draw them.
Object.defineProperty(exports, "__esModule", { value: true });