discovery: generate capability JSON from the registry

A capability is a descriptor plus what the endpoint declares (device/Capability.ts), and its discovery object is
generated from the two. The new API is bridge.addDevice({ endpointId, name, categories, ... }) and
device.add(PowerController, options): both throw a DeclarationError that names the endpoint, the interface and
the instance (device/validate.ts), and leave the bridge and the device as they were. AlexaInterface is the same
Capability with the 1.x methods on it; it, ActionMapping and the enums moved to src/compat/, Device to src/device/.

What a 1.x caller can observe:
- every endpoint ends with { type: "AlexaInterface", interface: "Alexa", version: "3" } (alexa-interface.html);
  new Alex2MQTT(..., { alexaInterface: false }) leaves it out
- the fields of a capability object come in the order of Amazon's examples; their content is unchanged
- addCapability() with a name that is not an interface throws (1.5.2 announced it with the version "UNKNOWN")
- ActionMapping takes the payload as an object; a JSON string is parsed (1.5.2 sent the string), any other throws
- what Alexa would reject in a 1.x declaration is not refused: device.check() lists it and the bridge logs each
  line once, as "warning: ..." through the log hook, when it answers a discovery
- a device whose JSON cannot be built is left out of the answer and reported as an error event
- PowerController and EndpointHealth are the descriptors and keep ON/OFF and OK/UNREACHABLE; PowerState is new

Tests: six zoo devices declared the 1.x way give the JSON that Alexa accepted from 1.5.2 on 2026-09-28, plus the
Alexa capability. npm test: 85 pass (was 57) in 10-12 s, also on Node 18.20.8 and 20.20.2.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
David 2026-09-28 15:35:46 +00:00
parent aa0ffd64ea
commit c492ef74d1
90 changed files with 5539 additions and 1760 deletions

View file

@ -0,0 +1,108 @@
"use strict";
// The 1.x way of declaring capabilities, on the classes 2.0 generates discovery from.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const alex2node = require("alex2node");
const {
ActionMapping, AlexaActions, AlexaInterface, AlexaInterfaceType, Capability, DeclarationError, EndpointHealth, PowerController,
PowerState, registry,
} = alex2node;
const { endpoint } = require("../helpers/endpoint.js");
test("every export of 1.5.2 is there", () => {
const exported = [
"ActionMapping", "Alex2MQTT", "AlexaActions", "AlexaErrorResponse", "AlexaErrorType", "AlexaInterface", "AlexaInterfaceType",
"AlexaStatusMessage", "DEFAULT_HOST", "Device", "DisplayCategory", "EndpointHealth", "PowerController",
"TemperatureSensorScale", "ThermostatMode",
];
assert.deepEqual(exported.filter((name) => alex2node[name] === undefined), []);
});
test("PowerController and EndpointHealth are the enums of 1.x and the descriptors of 2.0", () => {
assert.deepEqual([PowerController.ON, PowerController.OFF], ["ON", "OFF"]);
assert.deepEqual([EndpointHealth.OK, EndpointHealth.UNREACHABLE], ["OK", "UNREACHABLE"]);
assert.equal(PowerController, registry.get("Alexa.PowerController"));
assert.equal(EndpointHealth, registry.get(AlexaInterfaceType.ENDPOINT_HEALTH));
assert.deepEqual(PowerState, { ON: "ON", OFF: "OFF" });
});
test("AlexaInterface: the constructor and the getters of 1.x", () => {
const capability = new AlexaInterface(AlexaInterfaceType.THERMOSTAT_CONTROLLER, false, true);
assert.ok(capability instanceof Capability);
assert.equal(capability.type, "Alexa.ThermostatController");
assert.equal(capability.getType(), AlexaInterfaceType.THERMOSTAT_CONTROLLER);
assert.equal(capability.getTypeString(), "Alexa.ThermostatController");
assert.equal(capability.getVersion(), "3.2");
assert.deepEqual(capability.getProps(), ["targetSetpoint", "lowerSetpoint", "upperSetpoint", "thermostatMode"]);
assert.deepEqual([capability.retrievable, capability.proactivelyReported, capability.instance], [false, true, ""]);
assert.deepEqual(capability.getJSON(), capability.toJSON());
const toggle = new AlexaInterface("Alexa.ToggleController", true, false, "Fan.Oscillate");
toggle.setInstance("Fan.Swing");
toggle.addFriendlyName("Swing", "en-GB");
assert.equal(toggle.getJSON().instance, "Fan.Swing");
assert.deepEqual(toggle.getJSON().capabilityResources, { friendlyNames: [{ "@type": "text", value: { text: "Swing", locale: "en-GB" } }] });
});
test("addCapability takes the enum member or the namespace, and throws for a name that is not an interface", () => {
const lamp = endpoint();
const byMember = lamp.addCapability(AlexaInterfaceType.POWER_CONTROLLER, { proactivelyReported: true });
const byName = lamp.addCapability("Alexa.BrightnessController");
assert.ok(byMember instanceof AlexaInterface);
assert.equal(byMember.descriptor, PowerController);
assert.deepEqual(lamp.getCapabilities(), [byMember, byName]);
for (const name of ["Alexa.PowerControler", AlexaInterfaceType.UNKNOWN, undefined]) {
assert.throws(
() => lamp.addCapability(name),
(err) => err instanceof DeclarationError && err.message === `lamp-1: ${JSON.stringify(name)} is not an interface alex2node knows`
);
}
assert.equal(lamp.getCapabilities().length, 2);
assert.throws(() => new AlexaInterface("Alexa.PowerControler"), DeclarationError);
});
test("getJSON replaced on a capability, as 1.x callers did to correct it, is what discovery lists", () => {
const lock = endpoint("lock-1", "Front Door", ["SMARTLOCK"]);
const capability = lock.addCapability(AlexaInterfaceType.LOCK_CONTROLLER);
const original = capability.getJSON.bind(capability);
capability.getJSON = () => ({ ...original(), properties: { ...original().properties, supported: [{ name: "lockState" }] } });
assert.deepEqual(lock.getJSON().capabilities[0].properties.supported, [{ name: "lockState" }]);
});
test("ActionMapping: the payload is an object and reaches discovery as one", () => {
const open = new ActionMapping([AlexaActions.Open, AlexaActions.Raise], "SetRangeValue", { rangeValue: 100 });
assert.deepEqual(open.toJSON(), {
"@type": "ActionsToDirective",
actions: ["Alexa.Actions.Open", "Alexa.Actions.Raise"],
directive: { name: "SetRangeValue", payload: { rangeValue: 100 } },
});
assert.equal(open.deprecation, undefined);
// An empty payload is kept: the ToggleController examples of Amazon have "payload": {}
assert.deepEqual(new ActionMapping([AlexaActions.Close], "TurnOff", {}).toJSON().directive, { name: "TurnOff", payload: {} });
// None at all, and the "" that 1.x took for none
assert.deepEqual(new ActionMapping([AlexaActions.Close], "TurnOff").toJSON().directive, { name: "TurnOff" });
assert.deepEqual(new ActionMapping([AlexaActions.Close], "TurnOff", "").toJSON().directive, { name: "TurnOff" });
});
test("ActionMapping: a JSON string is parsed and noted as deprecated, any other string throws", () => {
const blinds = endpoint("blinds-1", "Blinds", ["INTERIOR_BLIND"]);
const lift = blinds.addCapability(AlexaInterfaceType.RANGE_CONTROLLER, { instance: "Blind.Lift" });
lift.addActionMapping(new ActionMapping([AlexaActions.Close], "SetRangeValue", JSON.stringify({ rangeValue: 0 })));
lift.addActionMapping(new ActionMapping([AlexaActions.Open], "SetRangeValue", { rangeValue: 100 }));
// 1.5.2 put the string itself into discovery: "payload": "{\"rangeValue\":0}"
assert.deepEqual(lift.getJSON().semantics.actionMappings.map((mapping) => mapping.directive.payload), [{ rangeValue: 0 }, { rangeValue: 100 }]);
assert.deepEqual(
blinds.check().filter((line) => line.includes("JSON string")),
['blinds-1: Alexa.RangeController "Blind.Lift": the payload of the action mapping for SetRangeValue is a JSON string, pass the object']
);
for (const text of ["rangeValue: 0", "0", "[0]", "null", '"closed"']) {
assert.throws(
() => new ActionMapping([AlexaActions.Close], "SetRangeValue", text),
(err) => err instanceof DeclarationError
&& err.message === `the payload of the action mapping for SetRangeValue is an object, got the string ${JSON.stringify(text)}`
);
}
});

View file

@ -0,0 +1,253 @@
"use strict";
// The discovery JSON of an endpoint: generated from the descriptors of its capabilities, in the order they were
// declared, with the capabilities the library adds at the end.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const {
Alex2MQTT, ActionMapping, Alexa, AlexaActions, AlexaInterfaceType, BrightnessController, DisplayCategory, EndpointHealth,
PowerController, TemperatureSensor, registry,
} = require("alex2node");
const interfaces = require("../fixtures/interfaces.js");
const { endpoint } = require("../helpers/endpoint.js");
const { capabilities, zoo } = require("../helpers/fixtures.js");
const { setup, until } = require("../helpers/harness.js");
const ALEXA = { type: "AlexaInterface", interface: "Alexa", version: "3" };
const names = (json) => json.capabilities.map((capability) => capability.interface);
// Ask as Alex2MQTT does and return the endpoints of the one answer.
async function discover(alexa, root) {
const before = alexa.on(`${root}/discover_r`).length;
alexa.publish(`${root}/discover`, { namespace: "Alexa.Discovery", name: "Discover" });
await until(() => alexa.on(`${root}/discover_r`).length === before + 1, 3000, "discovery reply");
return alexa.on(`${root}/discover_r`)[before];
}
for (const { namespace, page, declared } of interfaces) {
test(`${namespace}: device.add() gives the capability object of ${page}.html`, () => {
for (const { options, as: [example, n = 0] } of declared) {
const capability = endpoint().add(registry.get(namespace), options);
assert.deepEqual(capability.toJSON(), capabilities(page, namespace, example)[n], `${example}[${n}]`);
}
});
}
test("the fields of a capability object are in the order of the examples: type, interface, version, properties", () => {
const lamp = endpoint();
lamp.add(PowerController, { proactivelyReported: true });
assert.equal(
JSON.stringify(lamp.getJSON().capabilities[0]),
'{"type":"AlexaInterface","interface":"Alexa.PowerController","version":"3",'
+ '"properties":{"supported":[{"name":"powerState"}],"proactivelyReported":true,"retrievable":true}}'
);
});
test("capabilities are listed as declared, the Alexa interface after them", () => {
const thermostat = endpoint("thermo-1", "Thermostat", ["THERMOSTAT", "TEMPERATURE_SENSOR"]);
thermostat.add(TemperatureSensor);
thermostat.add(PowerController);
thermostat.add(BrightnessController);
assert.deepEqual(names(thermostat.getJSON()), ["Alexa.TemperatureSensor", "Alexa.PowerController", "Alexa.BrightnessController", "Alexa"]);
assert.deepEqual(thermostat.getJSON().capabilities.at(-1), ALEXA);
assert.deepEqual(thermostat.getCapabilities().map((capability) => capability.namespace), ["Alexa.TemperatureSensor", "Alexa.PowerController", "Alexa.BrightnessController"]);
// Declared by the device itself, it stays where it was declared and is listed once
const lamp = endpoint();
lamp.add(Alexa);
lamp.add(PowerController);
assert.deepEqual(names(lamp.getJSON()), ["Alexa", "Alexa.PowerController"]);
});
test("defaults of a declaration: retrievable, not proactively reported, nonControllable left out unless given", () => {
const lamp = endpoint();
assert.deepEqual(lamp.add(PowerController).toJSON().properties, { supported: [{ name: "powerState" }], proactivelyReported: false, retrievable: true });
assert.deepEqual(
lamp.add(BrightnessController, { retrievable: false, proactivelyReported: true, nonControllable: true }).toJSON().properties,
{ supported: [{ name: "brightness" }], proactivelyReported: true, retrievable: false, nonControllable: true }
);
assert.equal(lamp.add(TemperatureSensor, { nonControllable: false }).toJSON().properties.nonControllable, false);
});
test("PowerController verificationsRequired: the directives Alexa asks the user to confirm", () => {
const capability = endpoint().add(PowerController, { verificationsRequired: ["TurnOff"] });
assert.deepEqual(capability.toJSON().verificationsRequired, [{ directive: "TurnOff", methods: [{ "@type": "Confirmation" }] }]);
assert.equal("verificationsRequired" in endpoint().add(PowerController).toJSON(), false);
});
test("1.x declarations are announced as 1.5.2 announced them, with the Alexa interface added", () => {
const T = AlexaInterfaceType;
// zoo.js, the devices whose discovery JSON 1.5.2 produced without corrections
const declarations = {
"zoo-dimmer": (device) => {
device.addCapability(T.POWER_CONTROLLER, { proactivelyReported: true });
device.addCapability(T.BRIGHTNESS_CONTROLLER, { proactivelyReported: true });
},
"zoo-thermostat": (device) => {
device.addCapability(T.THERMOSTAT_CONTROLLER, { proactivelyReported: true });
device.addCapability(T.TEMPERATURE_SENSOR, { proactivelyReported: true });
},
"zoo-curtain": (device) => {
device.addCapability(T.POWER_CONTROLLER, { proactivelyReported: true });
const toggle = device.addCapability(T.TOGGLE_CONTROLLER, { proactivelyReported: true, instance: "Zoo.Shade" });
toggle.addFriendlyName("Shade", "en-US");
toggle.addActionMapping(new ActionMapping([AlexaActions.Close], "TurnOn"));
toggle.addActionMapping(new ActionMapping([AlexaActions.Open], "TurnOff"));
},
"zoo-fan": (device) => {
device.addCapability(T.POWER_CONTROLLER, { proactivelyReported: true });
const mode = device.addCapability(T.MODE_CONTROLLER, { proactivelyReported: true });
mode.setInstance("Fan.Speed");
mode.addFriendlyName("Speed", "en-US");
mode.addSupportedModes(["Low", "Medium", "High"].map((text) => ({
value: `Speed.${text}`,
modeResources: { friendlyNames: [{ "@type": "text", value: { text, locale: "en-US" } }] },
})));
},
"zoo-scene": (device) => device.addCapability(T.SCENE_CONTROLLER),
"zoo-tv": (device) => {
device.addCapability("Alexa.PowerController", { proactivelyReported: true });
device.addCapability("Alexa.ChannelController", { proactivelyReported: true });
},
};
for (const [endpointId, declare] of Object.entries(declarations)) {
const accepted = zoo(endpointId);
const device = endpoint(endpointId, accepted.friendlyName, accepted.displayCategories);
device.setDescription(accepted.description);
device.setManufacturerName(accepted.manufacturerName);
device.setManufacturer(accepted.additionalAttributes.manufacturer);
device.setModel(accepted.additionalAttributes.model);
declare(device);
assert.deepEqual(device.getJSON(), { ...accepted, capabilities: [...accepted.capabilities, ALEXA] }, endpointId);
assert.deepEqual(device.check(), [], endpointId);
}
});
test("registerDevice: every endpoint ends with the Alexa interface; alexaInterface: false leaves it out", async () => {
const { alexa, bridge } = await setup(Alex2MQTT, "root");
const lamp = bridge.registerDevice("Lamp", "lamp-1", DisplayCategory.LIGHT);
lamp.addCapability(AlexaInterfaceType.POWER_CONTROLLER);
lamp.addCapability(AlexaInterfaceType.ENDPOINT_HEALTH);
const scene = bridge.registerDevice("Evening", "scene-1", DisplayCategory.SCENE_TRIGGER);
scene.addCapability(AlexaInterfaceType.SCENE_CONTROLLER);
// A registerDevice() device gets no Alexa.EndpointHealth it did not declare
const bare = bridge.registerDevice("Plug", "plug-1", DisplayCategory.SMARTPLUG);
bare.addCapability(AlexaInterfaceType.POWER_CONTROLLER);
assert.deepEqual((await discover(alexa, "root")).map(names), [
["Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"],
["Alexa.SceneController", "Alexa"],
["Alexa.PowerController", "Alexa"],
]);
const without = await setup(Alex2MQTT, "root-1x", { alexaInterface: false });
without.bridge.registerDevice("Lamp", "lamp-1", DisplayCategory.LIGHT).addCapability(AlexaInterfaceType.POWER_CONTROLLER);
without.bridge.addDevice({ endpointId: "lamp-2", name: "Lamp Two", categories: ["LIGHT"], endpointHealth: false }).add(PowerController);
assert.deepEqual((await discover(without.alexa, "root-1x")).map(names), [["Alexa.PowerController"], ["Alexa.PowerController"]]);
});
test("addDevice: the fields of the definition reach discovery; the defaults are those of registerDevice", async () => {
const { alexa, bridge } = await setup(Alex2MQTT, "root");
bridge.addDevice({
endpointId: "bedroom-blinds",
name: "Bedroom Blinds",
categories: ["INTERIOR_BLIND", DisplayCategory.OTHER],
description: "Roller blind by Acme",
manufacturerName: "Acme",
manufacturer: "Acme Inc",
model: "RB-2",
serialNumber: "0042",
firmwareVersion: "2.1.0",
softwareVersion: "2.1.3",
customIdentifier: "acme-rb2-0042",
cookie: { room: "bedroom" },
endpointHealth: false,
});
bridge.addDevice({ endpointId: "lamp-1", name: "Lamp", categories: ["LIGHT"], endpointHealth: false });
const registered = bridge.registerDevice("Lamp", "lamp-2", DisplayCategory.LIGHT);
const [blinds, lamp] = await discover(alexa, "root");
assert.deepEqual(blinds, {
endpointId: "bedroom-blinds",
friendlyName: "Bedroom Blinds",
description: "Roller blind by Acme",
manufacturerName: "Acme",
displayCategories: ["INTERIOR_BLIND", "OTHER"],
additionalAttributes: {
manufacturer: "Acme Inc",
model: "RB-2",
serialNumber: "0042",
firmwareVersion: "2.1.0",
softwareVersion: "2.1.3",
customIdentifier: "acme-rb2-0042",
},
cookie: { room: "bedroom" },
capabilities: [ALEXA],
});
assert.deepEqual(lamp, { ...registered.getJSON(), endpointId: "lamp-1" });
assert.equal("cookie" in lamp, false);
});
test("addDevice: Alexa.EndpointHealth is listed for the device unless it declares one, opts out or is a scene", async () => {
const { alexa, bridge } = await setup(Alex2MQTT, "root");
bridge.addDevice({ endpointId: "lamp-1", name: "Lamp", categories: ["LIGHT"] }).add(PowerController);
const reporting = bridge.addDevice({ endpointId: "lamp-2", name: "Lamp Two", categories: ["LIGHT"] });
reporting.add(EndpointHealth, { proactivelyReported: true });
reporting.add(PowerController);
bridge.addDevice({ endpointId: "lamp-3", name: "Lamp Three", categories: ["LIGHT"], endpointHealth: false }).add(PowerController);
bridge.addDevice({ endpointId: "scene-1", name: "Evening", categories: ["SCENE_TRIGGER"], description: "Evening scene" })
.addCapability(AlexaInterfaceType.SCENE_CONTROLLER);
const [lamp, declared, optedOut, scene] = await discover(alexa, "root");
assert.deepEqual(names(lamp), ["Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"]);
assert.deepEqual(lamp.capabilities[1], {
type: "AlexaInterface",
interface: "Alexa.EndpointHealth",
version: "3.1",
properties: { supported: [{ name: "connectivity" }], proactivelyReported: false, retrievable: true },
});
assert.deepEqual(names(declared), ["Alexa.EndpointHealth", "Alexa.PowerController", "Alexa"]);
assert.equal(declared.capabilities[0].properties.proactivelyReported, true);
assert.deepEqual(names(optedOut), ["Alexa.PowerController", "Alexa"]);
assert.deepEqual(names(scene), ["Alexa.SceneController", "Alexa"]);
});
test("discovery logs what check() says about the devices, each line once", async () => {
const logged = [];
const { alexa, bridge } = await setup(Alex2MQTT, "root", { log: (message) => logged.push(message) });
const warnings = () => logged.filter((message) => message.startsWith("warning: "));
const lamp = bridge.registerDevice("Dave's Lamp", "lamp-1", DisplayCategory.LIGHT);
lamp.addCapability(AlexaInterfaceType.POWER_CONTROLLER);
lamp.addCapability(AlexaInterfaceType.POWER_CONTROLLER);
lamp.addCapability(AlexaInterfaceType.LOCK_CONTROLLER);
bridge.registerDevice("Lamp", "lamp-2", DisplayCategory.LIGHT).addCapability(AlexaInterfaceType.POWER_CONTROLLER);
// Announced all the same: 1.x announced it, and Alexa may have taken it
const [first] = await discover(alexa, "root");
assert.deepEqual(names(first), ["Alexa.PowerController", "Alexa.PowerController", "Alexa.LockController", "Alexa"]);
assert.deepEqual(warnings(), [
'warning: lamp-1: the name "Dave\'s Lamp" takes up to 256 letters, digits and spaces, no punctuation',
"warning: lamp-1: Alexa.PowerController: the interface is declared twice",
"warning: lamp-1: Alexa.LockController: no property list known, discovery lists it with no supported properties",
]);
lamp.setName("Daves Lamp");
bridge.registerDevice("Timer!", "lamp-3", DisplayCategory.LIGHT);
await discover(alexa, "root");
assert.deepEqual(warnings().slice(3), ['warning: lamp-3: the name "Timer!" takes up to 256 letters, digits and spaces, no punctuation']);
});
test("a device that cannot be described is left out of the answer and reported; the others are announced", async () => {
const { alexa, bridge } = await setup(Alex2MQTT, "root");
const errors = [];
bridge.on("error", (err) => errors.push(err.message));
bridge.registerDevice("Lamp", "lamp-1", DisplayCategory.LIGHT).addCapability(AlexaInterfaceType.POWER_CONTROLLER);
const lock = bridge.registerDevice("Front Door", "lock-1", DisplayCategory.SMARTLOCK);
lock.addCapability(AlexaInterfaceType.LOCK_CONTROLLER).getJSON = () => { throw new TypeError("state is not defined"); };
assert.deepEqual((await discover(alexa, "root")).map((each) => each.endpointId), ["lamp-1"]);
assert.deepEqual(errors, ["lock-1 is not in the discovery answer: state is not defined"]);
// Without an error listener the same discovery is answered and nothing is thrown
bridge.removeAllListeners("error");
assert.deepEqual((await discover(alexa, "root")).map((each) => each.endpointId), ["lamp-1"]);
});

View file

@ -0,0 +1,148 @@
"use strict";
// What Alexa rejects at discovery is refused where it is declared: bridge.addDevice() and device.add() throw a
// DeclarationError that names the endpoint, the interface and the instance, and leave everything as it was.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const {
Alex2MQTT, AlexaInterfaceType, BrightnessController, DeclarationError, EndpointHealth, PowerController, TemperatureSensor, registry,
} = require("alex2node");
const { endpoint } = require("../helpers/endpoint.js");
const { setup, sleep } = require("../helpers/harness.js");
// The DeclarationError that declare() throws.
function refused(declare) {
try {
declare();
} catch (err) {
assert.ok(err instanceof DeclarationError, `threw ${err && err.stack}`);
return err;
}
return assert.fail("the declaration was accepted");
}
test("addDevice refuses an endpoint Alexa would reject, registers nothing and publishes nothing", async () => {
const { alexa, bridge } = await setup(Alex2MQTT, "root");
const lamp = { endpointId: "lamp-1", name: "Lamp", categories: ["LIGHT"] };
const cases = [
[{ endpointId: "garage/lamp" }, "garage/lamp: the endpointId takes up to 256 letters, digits, spaces and _ - = # ; : ? @ &"],
[{ endpointId: "x".repeat(257) }, `${"x".repeat(61)}...: the endpointId takes up to 256 letters, digits, spaces and _ - = # ; : ? @ &`],
[{ endpointId: "" }, "an endpoint needs an endpointId"],
[{ name: "Dave's Lamp" }, 'lamp-1: the name "Dave\'s Lamp" takes up to 256 letters, digits and spaces, no punctuation'],
[{ name: "L".repeat(257) }, `lamp-1: the name "${"L".repeat(257)}" takes up to 256 letters, digits and spaces, no punctuation`],
[{ name: undefined }, "lamp-1: an endpoint needs a name"],
[{ description: "d".repeat(129) }, "lamp-1: the description takes 1 to 128 characters"],
[{ manufacturerName: "" }, "lamp-1: the manufacturerName takes 1 to 128 characters"],
[{ categories: undefined }, "lamp-1: an endpoint needs a display category"],
[{ categories: [] }, "lamp-1: an endpoint needs a display category"],
[{ categories: ["LAMP"] }, 'lamp-1: "LAMP" is not a display category'],
// In the DisplayCategory enum since 1.x, no longer on Amazon's list
[{ categories: ["LIGHT", "VEHICLE"] }, 'lamp-1: "VEHICLE" is not a display category'],
[{ model: "m".repeat(257) }, "lamp-1: model takes up to 256 characters"],
[{ cookie: { note: "c".repeat(5000) } }, "lamp-1: the cookie is 5011 bytes, 5000 is the most"],
[{ category: ["LIGHT"] }, "lamp-1: category is not a field of an endpoint"],
];
for (const [fields, message] of cases) {
const err = refused(() => bridge.addDevice({ ...lamp, ...fields }));
assert.equal(err.message, message);
assert.equal(err.name, "DeclarationError");
}
assert.deepEqual(bridge.getDevices(), []);
// What the rules allow: every character of an endpointId, a name in another script, a cookie of 5000 bytes
bridge.addDevice({ ...lamp, endpointId: "A z0_-=#;:?@&", name: "Lampe für Küche 2", cookie: { note: "c".repeat(4989) } });
bridge.addDevice({ ...lamp, endpointId: "x".repeat(256), name: "寝室のライト" });
assert.equal(bridge.getDevices().length, 2);
const twice = refused(() => bridge.addDevice({ ...lamp, endpointId: "A z0_-=#;:?@&", name: "Another" }));
assert.equal(twice.message, 'A z0_-=#;:?@&: is registered already, as "Lampe für Küche 2"');
assert.equal(twice.endpointId, "A z0_-=#;:?@&");
assert.equal(bridge.getDevices().length, 2);
await sleep(50);
assert.deepEqual(alexa.got, []);
});
test("device.add refuses the interface declared twice, an instance or a friendly name where the interface has none", () => {
const lamp = endpoint();
lamp.add(PowerController);
const cases = [
[() => lamp.add(PowerController), "lamp-1: Alexa.PowerController: the interface is declared twice"],
[() => lamp.add(BrightnessController, { instance: "Lamp.Level" }), 'lamp-1: Alexa.BrightnessController "Lamp.Level": takes no instance name: an endpoint has the interface once'],
[
() => lamp.add(BrightnessController, { friendlyNames: [{ "@type": "text", value: { text: "Level", locale: "en-US" } }] }),
"lamp-1: Alexa.BrightnessController: takes no friendly names",
],
];
for (const [declare, message] of cases) assert.equal(refused(declare).message, message);
assert.deepEqual(lamp.getCapabilities().map((capability) => capability.namespace), ["Alexa.PowerController"]);
const err = refused(() => lamp.add(BrightnessController, { instance: "Lamp.Level" }));
assert.deepEqual(
{ endpointId: err.endpointId, namespace: err.namespace, instance: err.instance, problem: err.problem },
{ endpointId: "lamp-1", namespace: "Alexa.BrightnessController", instance: "Lamp.Level", problem: "takes no instance name: an endpoint has the interface once" }
);
});
test("device.add refuses an option the interface does not have and a value that does not fit", () => {
const lamp = endpoint();
const cases = [
[() => lamp.add(PowerController, { verificationRequired: ["TurnOn"] }), "lamp-1: Alexa.PowerController: verificationRequired: unknown key, the known ones are verificationsRequired"],
[() => lamp.add(PowerController, { verificationsRequired: ["Toggle"] }), 'lamp-1: Alexa.PowerController: verificationsRequired[0]: expected TurnOn | TurnOff, got "Toggle"'],
[() => lamp.add(TemperatureSensor, { scale: "CELSIUS" }), "lamp-1: Alexa.TemperatureSensor: scale: not an option of the interface"],
[() => lamp.add(TemperatureSensor, { retrievable: "yes" }), 'lamp-1: Alexa.TemperatureSensor: retrievable: expected true or false, got "yes"'],
[() => lamp.add(TemperatureSensor, { instance: 7 }), "lamp-1: Alexa.TemperatureSensor: instance: expected a string, got 7"],
[() => lamp.add(TemperatureSensor, "retrievable"), "lamp-1: Alexa.TemperatureSensor: the options of a declaration are an object"],
];
for (const [declare, message] of cases) assert.equal(refused(declare).message, message);
assert.deepEqual(lamp.getCapabilities(), []);
});
test("an endpoint takes 100 capabilities, the ones the library adds among them", () => {
const panel = endpoint("panel-1", "Panel", ["OTHER"]);
for (let n = 1; n <= 98; n += 1) panel.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER, { instance: `Panel.Switch${n}` });
panel.add(PowerController);
assert.equal(panel.getJSON().capabilities.length, 100);
assert.deepEqual(panel.check(), []);
assert.equal(refused(() => panel.add(BrightnessController)).message, "panel-1: 101 capabilities, an endpoint takes 100");
assert.equal(panel.getCapabilities().length, 99);
// The 1.x call is not refused: check() says it
panel.addCapability(AlexaInterfaceType.BRIGHTNESS_CONTROLLER);
assert.deepEqual(panel.check(), ["panel-1: 101 capabilities, an endpoint takes 100"]);
// With Alexa.EndpointHealth added for the device there is room for 98
const health = endpoint("panel-2", "Panel", ["OTHER"]);
health.endpointHealth = true;
for (let n = 1; n <= 98; n += 1) health.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER, { instance: `Panel.Switch${n}` });
assert.equal(refused(() => health.add(PowerController)).message, "panel-2: 101 capabilities, an endpoint takes 100");
assert.doesNotThrow(() => health.add(EndpointHealth));
});
test("check() lists what is wrong with a device declared the 1.x way, one line for each", () => {
const lamp = endpoint("lamp/1", "Lamp #1", ["LIGHT"]);
assert.deepEqual(lamp.check(), ["lamp/1: the endpointId takes up to 256 letters, digits, spaces and _ - = # ; : ? @ &"]);
const fan = endpoint("fan-1", "Fan", ["FAN", "VEHICLE"]);
fan.addCapability(AlexaInterfaceType.POWER_CONTROLLER, { instance: "Fan.Power" });
fan.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER, { instance: "Fan.Oscillate" });
fan.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER, { instance: "Fan.Oscillate" });
assert.deepEqual(fan.check(), [
'fan-1: "VEHICLE" is not a display category',
'fan-1: Alexa.PowerController "Fan.Power": takes no instance name: an endpoint has the interface once',
'fan-1: Alexa.ToggleController "Fan.Oscillate": the instance is declared twice',
]);
assert.equal(fan.getJSON().capabilities.length, 4, "announced all the same");
});
test("a stub is declared like any interface and checked for nothing but being declared twice", () => {
const lock = endpoint("lock-1", "Front Door", ["SMARTLOCK"]);
const capability = lock.add(registry.get("Alexa.LockController"), { proactivelyReported: true });
assert.deepEqual(capability.toJSON(), {
type: "AlexaInterface",
interface: "Alexa.LockController",
version: "3",
properties: { supported: [], proactivelyReported: true, retrievable: true },
});
assert.equal(refused(() => lock.add(registry.get("Alexa.LockController"))).message, "lock-1: Alexa.LockController: the interface is declared twice");
});

View file

@ -1,11 +1,20 @@
"use strict";
// One entry per interface that is described in full: the page its examples were saved from (test/helpers/fixtures.js).
// test/registry/descriptors.test.js holds every entry against those examples and fails for a descriptor of tier 1 or
// 2 that has no entry here.
// One entry per interface that is described in full: the page its examples were saved from (test/helpers/fixtures.js)
// and declarations that give capability objects of those examples.
//
// namespace the interface
// page the page of the interface; test/fixtures/alexa-docs/<page>/ has its examples
// declared [{ options, as: [example, n] }]: device.add(descriptor, options) gives the n-th capability object of
// the interface in that discovery example (n counts from 0 and defaults to it)
//
// test/registry/descriptors.test.js and test/device/discovery.test.js run the entries. The first one fails for a
// descriptor of tier 1 or 2 that has no entry.
const reported = { retrievable: true, proactivelyReported: true };
module.exports = [
{ namespace: "Alexa", page: "alexa-interface" },
{ namespace: "Alexa.BrightnessController", page: "alexa-brightnesscontroller" },
{ namespace: "Alexa.EndpointHealth", page: "alexa-endpointhealth" },
{ namespace: "Alexa.PowerController", page: "alexa-powercontroller" },
{ namespace: "Alexa.TemperatureSensor", page: "alexa-temperaturesensor" },
{ namespace: "Alexa", page: "alexa-interface", declared: [{ options: {}, as: ["discovery"] }] },
{ namespace: "Alexa.BrightnessController", page: "alexa-brightnesscontroller", declared: [{ options: reported, as: ["discovery"] }] },
{ namespace: "Alexa.EndpointHealth", page: "alexa-endpointhealth", declared: [{ options: reported, as: ["discovery"] }] },
{ namespace: "Alexa.PowerController", page: "alexa-powercontroller", declared: [{ options: reported, as: ["discovery"] }] },
{ namespace: "Alexa.TemperatureSensor", page: "alexa-temperaturesensor", declared: [{ options: reported, as: ["discovery"] }] },
];

View file

@ -2,12 +2,12 @@
// dist/types, resolved through the package's "exports". A "@ts-expect-error" line fails the compile when the
// declaration stops rejecting what follows it.
import {
ActionMapping, AlexaActions, AlexaInterfaceType, Assets, DeclarationError, DisplayCategory, EndpointHealth, PowerController,
registry,
ActionMapping, AlexaActions, AlexaInterfaceType, Assets, BrightnessController, DeclarationError, DisplayCategory, EndpointHealth,
PowerController, PowerState, TemperatureSensor, asset, registry, text,
} from "alex2node";
import type {
Alex2MQTT, Alex2MQTTOptions, AlexaInterface, AlexaStatusMessage, AssetId, ChangeCause, Device, DisplayCategoryName, Infer,
InterfaceDescriptor, Schema, SupportedMode, Temperature, UnitOfMeasure,
Alex2MQTT, Alex2MQTTOptions, AlexaInterface, AlexaStatusMessage, AssetId, Capability, CapabilityJson, ChangeCause, Device,
DisplayCategoryName, EndpointJson, Infer, InterfaceDescriptor, Label, Schema, SupportedMode, Temperature, UnitOfMeasure,
} from "alex2node";
declare const bridge: Alex2MQTT;
@ -18,9 +18,12 @@ const options: Alex2MQTTOptions = { host: "mqtt://127.0.0.1:1883", mqtt: { recon
const device: Device = bridge.registerDevice("Lamp", "lamp-1", [DisplayCategory.LIGHT, DisplayCategory.SWITCH]);
const added: AlexaInterface = device.addCapability(AlexaInterfaceType.POWER_CONTROLLER, { proactivelyReported: true });
// ActionMapping: the payload is optional
// ActionMapping: the payload is optional, and an object
const close = new ActionMapping([AlexaActions.Close], "TurnOn");
capability.addActionMapping(close);
capability.addActionMapping(new ActionMapping([AlexaActions.Open], "SetRangeValue", { rangeValue: 100 }));
// @ts-expect-error a payload is an object or, as in 1.x, a string
capability.addActionMapping(new ActionMapping([AlexaActions.Open], "SetRangeValue", 100));
// addHealthProp: the enum or its string values, chainable
const chained: AlexaStatusMessage = message.addHealthProp(EndpointHealth.OK).addHealthProp("UNREACHABLE", 50);
@ -29,6 +32,10 @@ message.addHealthProp("ASLEEP");
// @ts-expect-error a power state is ON or OFF
message.addPowerControllerProp("ON ");
message.addPowerControllerProp(PowerController.ON);
// PowerController is the descriptor of the interface as well; the enum alone is PowerState
const on: PowerController = PowerState.ON;
const namespace: string = PowerController.namespace;
const reachable: EndpointHealth = EndpointHealth.OK;
// addSupportedModes: Mode objects, plain strings still accepted
const mode: SupportedMode = { value: "Fan.Auto", modeResources: { friendlyNames: [{ "@type": "text", value: { text: "Auto", locale: "en-US" } }] } };
@ -39,6 +46,34 @@ const sent: Promise<string> = device.getChangeReport(cause).addPowerControllerPr
// @ts-expect-error not a cause Alexa knows
device.getChangeReport("BUTTON");
// bridge.addDevice() and device.add(): the options of the interface and the ones every capability has
const blinds: Device = bridge.addDevice({
endpointId: "bedroom-blinds",
name: "Bedroom Blinds",
categories: ["INTERIOR_BLIND", DisplayCategory.OTHER],
cookie: { room: "bedroom" },
endpointHealth: false,
});
// @ts-expect-error an endpoint has categories
bridge.addDevice({ endpointId: "lamp-2", name: "Lamp" });
// @ts-expect-error not a display category
bridge.addDevice({ endpointId: "lamp-2", name: "Lamp", categories: ["LAMP"] });
const power: Capability = blinds.add(PowerController, { proactivelyReported: true, verificationsRequired: ["TurnOff"] });
blinds.add(BrightnessController);
blinds.add(TemperatureSensor, { retrievable: true, nonControllable: true });
// @ts-expect-error not a directive of the interface
blinds.add(PowerController, { verificationsRequired: ["Toggle"] });
// @ts-expect-error not an option of the interface
blinds.add(BrightnessController, { range: { min: 0, max: 100 } });
const announced: CapabilityJson = power.toJSON();
const endpoint: EndpointJson = blinds.getJSON();
const problems: string[] = blinds.check();
// Friendly names
const names: Label[] = [asset("Alexa.Setting.Opening"), text("Position"), text("Posición", "es-MX")];
// @ts-expect-error not in the global Alexa catalog
asset("Alexa.Setting.Openning");
// The registry: a descriptor by its namespace or by the 1.x enum member
const described: InterfaceDescriptor = registry.get("Alexa.PowerController");
const version: string = registry.get(AlexaInterfaceType.ENDPOINT_HEALTH).version;
@ -59,4 +94,7 @@ const measured: Infer<typeof temperature> = { value: 20, scale: "CELSIUS" };
// @ts-expect-error not a temperature scale
const rankine: Infer<typeof temperature> = { value: 20, scale: "RANKINE" };
export { options, added, chained, sent, version, refused, opening, percent, vacuum, misspelt, notAUnit, measured, rankine };
export {
options, added, chained, sent, on, namespace, reachable, announced, endpoint, problems, names, version, refused, opening,
percent, vacuum, misspelt, notAUnit, measured, rankine,
};

1098
test/fixtures/zoo/discovery.json vendored Normal file

File diff suppressed because it is too large Load diff

10
test/helpers/endpoint.js Normal file
View file

@ -0,0 +1,10 @@
"use strict";
// A device that is on no bridge. What a device declares and the discovery JSON it answers with need no broker.
const { Device } = require("alex2node");
/** The arguments Device takes before the name are the broker client and the root topic of its bridge. */
function endpoint(endpointId = "lamp-1", name = "Lamp", categories = ["LIGHT"]) {
return new Device(null, "root", name, endpointId, categories);
}
module.exports = { endpoint };

View file

@ -6,6 +6,7 @@ const fs = require("node:fs");
const path = require("node:path");
const DOCS = path.join(__dirname, "..", "fixtures", "alexa-docs");
const ZOO = path.join(__dirname, "..", "fixtures", "zoo", "discovery.json");
/** One example: doc("alexa-powercontroller", "TurnOn.directive"). */
function doc(page, name) {
@ -44,4 +45,15 @@ function reported(page, namespace) {
return found.filter(({ property }) => property.namespace === namespace);
}
module.exports = { doc, examples, capabilities, reported };
/**
* An endpoint of the zoo: the 22 test devices built on alex2node 1.5.2, as their discovery answer was on 2026-09-28
* when Alexa accepted all of them. Six had their capability JSON corrected by hand, because 1.5.2 had no way to
* declare it: zoo-blinds, zoo-blower, zoo-heater, zoo-lock, zoo-motion, and zoo-health-lamp-31 for its version.
*/
function zoo(endpointId) {
const endpoint = JSON.parse(fs.readFileSync(ZOO, "utf8")).find((each) => each.endpointId === endpointId);
if (!endpoint) throw new Error(`${endpointId} is not in the zoo`);
return endpoint;
}
module.exports = { doc, examples, capabilities, reported, zoo };

View file

@ -23,7 +23,7 @@ test("import { Alex2MQTT } from \"alex2node\": discovery, a directive and a chan
await until(() => alexa.on("root/discover_r").length === 1, 3000, "discovery reply");
const [endpoints] = alexa.on("root/discover_r");
assert.deepEqual(endpoints.map((e) => e.endpointId), ["lamp-1"]);
assert.deepEqual(endpoints[0].capabilities.map((c) => c.interface), ["Alexa.PowerController", "Alexa.EndpointHealth"]);
assert.deepEqual(endpoints[0].capabilities.map((c) => c.interface), ["Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"]);
alexa.send("root", directive("Alexa.PowerController", "TurnOn", "lamp-1", "ct1"));
await until(() => alexa.on("root/lamp-1/alexaResponce").length === 1, 3000, "directive response");