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

79
dist/esm/device/Capability.d.ts vendored Normal file
View file

@ -0,0 +1,79 @@
import type { Declared, Directives, InterfaceDescriptor, Label, Properties, Semantics } from "../registry/types.js";
/** What a declaration can set for any interface. */
export interface CommonOptions {
/** The name of the instance of a generic controller: "Blind.Lift", "Fan.Speed". */
instance?: string;
/** What the user calls the instance; the first name is the one the Alexa app shows. */
friendlyNames?: Label[];
/** The properties are in the answer to ReportState. Default: true. */
retrievable?: boolean;
/** A change of the properties is sent to Alexa as a ChangeReport. Default: false. */
proactivelyReported?: boolean;
/** The user can ask for the properties and cannot set them. Left out of discovery when not given. */
nonControllable?: boolean;
}
/** The same as a schema. The friendly names are checked with the instance, by the rules of the interface. */
export declare const commonOptions: import("../registry/schema.js").Schema<import("../registry/schema.js").InferShape<{
instance: import("../registry/schema.js").OptionalSchema<string>;
friendlyNames: import("../registry/schema.js").OptionalSchema<unknown[]>;
retrievable: import("../registry/schema.js").OptionalSchema<boolean>;
proactivelyReported: import("../registry/schema.js").OptionalSchema<boolean>;
nonControllable: import("../registry/schema.js").OptionalSchema<boolean>;
}>>;
type Naming<I extends boolean> = I extends true ? {
instance: string;
friendlyNames: Label[];
} : {
instance?: string;
friendlyNames?: Label[];
};
/** The options of device.add() for one interface: its own, and the ones every interface has. */
export type Declaration<O, I extends boolean> = O & Omit<CommonOptions, "instance" | "friendlyNames"> & Naming<I>;
/** A capability object of a discovery answer (alexa-discovery-objects.html, "Capability object"). */
export interface CapabilityJson {
type: "AlexaInterface";
interface: string;
instance?: string;
version: string;
properties?: {
supported: Array<{
name: string;
}>;
proactivelyReported: boolean;
retrievable: boolean;
nonControllable?: boolean;
};
capabilityResources?: {
friendlyNames: Label[];
};
configuration?: Record<string, unknown>;
configurations?: Record<string, unknown>;
semantics?: Semantics;
[field: string]: unknown;
}
/** One interface as an endpoint declares it: the descriptor, and what the declaration says about this endpoint. */
export declare class Capability<P extends Properties = Properties, D extends Directives = Directives, O = {}> implements Declared<O> {
readonly descriptor: InterfaceDescriptor<P, D, O, boolean>;
/** The endpoint the capability is declared on; the device sets it. */
endpointId: string;
/** "" for an interface without instances. */
instance: string;
friendlyNames: Label[];
retrievable: boolean;
proactivelyReported: boolean;
nonControllable?: boolean;
/** The options of the interface: a range, the supported modes, the semantics. */
options: O;
/** What the bridge logs about the declaration, once, when it answers a discovery. */
readonly notes: string[];
constructor(descriptor: InterfaceDescriptor<P, D, O, boolean>, declared: CommonOptions & {
options: O;
});
get namespace(): string;
/** Mappings of "open", "close", "raise", "lower" and of states, when the declaration has any. */
get semantics(): Semantics | undefined;
/** The capability object for discovery, its fields in the order of the example on alexa-discovery-objects.html. */
toJSON(): CapabilityJson;
}
export type AnyCapability = Capability<any, any, any>;
export {};

63
dist/esm/device/Capability.js vendored Normal file
View file

@ -0,0 +1,63 @@
import { s } from "../registry/schema.js";
/** The same as a schema. The friendly names are checked with the instance, by the rules of the interface. */
export const commonOptions = s.object({
instance: s.optional(s.string()),
friendlyNames: s.optional(s.array(s.unknown())),
retrievable: s.optional(s.boolean()),
proactivelyReported: s.optional(s.boolean()),
nonControllable: s.optional(s.boolean()),
});
/** One interface as an endpoint declares it: the descriptor, and what the declaration says about this endpoint. */
export class Capability {
constructor(descriptor, declared) {
this.descriptor = descriptor;
/** The endpoint the capability is declared on; the device sets it. */
this.endpointId = "";
/** What the bridge logs about the declaration, once, when it answers a discovery. */
this.notes = [];
this.instance = declared.instance ?? "";
this.friendlyNames = declared.friendlyNames ?? [];
this.retrievable = declared.retrievable ?? true;
this.proactivelyReported = declared.proactivelyReported ?? false;
this.nonControllable = declared.nonControllable;
this.options = declared.options;
}
get namespace() {
return this.descriptor.namespace;
}
/** Mappings of "open", "close", "raise", "lower" and of states, when the declaration has any. */
get semantics() {
const { semantics } = this.options;
const mapped = (semantics?.actionMappings?.length ?? 0) + (semantics?.stateMappings?.length ?? 0);
return mapped > 0 ? semantics : undefined;
}
/** The capability object for discovery, its fields in the order of the example on alexa-discovery-objects.html. */
toJSON() {
const { descriptor, semantics } = this;
const extras = descriptor.discovery ? descriptor.discovery(this) : {};
const json = {
type: "AlexaInterface",
interface: descriptor.namespace,
...(this.instance ? { instance: this.instance } : {}),
version: descriptor.version,
};
if (extras.properties !== false) {
json.properties = {
supported: Object.keys(descriptor.properties).map((name) => ({ name })),
proactivelyReported: this.proactivelyReported,
retrievable: this.retrievable,
};
if (this.nonControllable !== undefined)
json.properties.nonControllable = this.nonControllable;
}
if (this.friendlyNames.length > 0)
json.capabilityResources = { friendlyNames: this.friendlyNames };
if (extras.configuration)
json.configuration = extras.configuration;
if (extras.configurations)
json.configurations = extras.configurations;
if (semantics)
json.semantics = semantics;
return { ...json, ...extras.topLevel };
}
}

135
dist/esm/device/Device.d.ts vendored Normal file
View file

@ -0,0 +1,135 @@
import { EventEmitter } from "events";
import type { MqttClient } from "mqtt";
import { AlexaErrorResponse } from "../AlexaErrorResponse.js";
import { AlexaStatusMessage } from "../AlexaStatusMessage.js";
import type { ChangeCause } from "../AlexaStatusMessage.js";
import { AlexaInterface } from "../compat/AlexaInterface.js";
import { DisplayCategory } from "../compat/enums.js";
import type { AlexaInterfaceType } from "../compat/enums.js";
import type { DisplayCategoryName } from "../registry/catalog.js";
import type { Directives, InterfaceDescriptor, Properties } from "../registry/types.js";
import { Capability } from "./Capability.js";
import type { AnyCapability, CapabilityJson, Declaration } from "./Capability.js";
import type { EndpointFields } from "./validate.js";
/** An endpoint as bridge.addDevice() takes it. */
export interface EndpointDefinition {
/** Up to 256 letters, digits, spaces and _ - = # ; : ? @ &. The same id at every discovery. */
endpointId: string;
/** What the user calls the device: letters, digits and spaces. */
name: string;
/** The first one is the category the Alexa app shows the device under. */
categories: Array<DisplayCategoryName | DisplayCategory>;
/** Shown in the Alexa app, up to 128 characters. Default: "Alexa to Node.js bridge". */
description?: string;
/** Up to 128 characters. Default: "Alex2Node". */
manufacturerName?: string;
manufacturer?: string;
model?: string;
serialNumber?: string;
firmwareVersion?: string;
softwareVersion?: string;
customIdentifier?: string;
/** Returned with every directive to the endpoint. Up to 5000 bytes; not a place for state. */
cookie?: Record<string, string>;
/** false: the device gets no Alexa.EndpointHealth unless it declares one. */
endpointHealth?: boolean;
}
/** An endpoint object of a discovery answer (alexa-discovery-objects.html, "Endpoint object"). */
export interface EndpointJson extends EndpointFields {
capabilities: CapabilityJson[];
}
type DeclarationArguments<O, I extends boolean> = {} extends Declaration<O, I> ? [options?: Declaration<O, I>] : [options: Declaration<O, I>];
declare class Device extends EventEmitter {
private mqttClient;
private rootTopic;
name: string;
endpointId: string;
displayCategory: Array<DisplayCategory> | null;
description: string;
manufacturerName: string;
manufacturer: string;
model: string;
softwareVersion: string;
serialNumber: string;
firmwareVersion: string;
customIdentifier: string;
cookie?: Record<string, string>;
/**
* Discovery lists the Alexa interface on the endpoint (alexa-interface.html: "You must explicitly identify your
* support for the Alexa interface"). The bridge sets it from its alexaInterface option.
*/
alexaInterface: boolean;
/**
* Discovery lists Alexa.EndpointHealth when the device did not declare it and is not a scene. On for a device of
* bridge.addDevice(), off for one of registerDevice(), which is announced as 1.x announced it.
*/
endpointHealth: boolean;
private capabilities;
/** Where a failed publish from this device or a message it built is reported; Alex2MQTT sets it (1.5.2). */
onPublishError?: (err: Error) => void;
constructor(mqttClient: MqttClient, rootTopic: string, name: string, endpointId: string, displayCategory: Array<DisplayCategory> | null, description?: string, manufacturerName?: string, manufacturer?: string, model?: string);
/** Internal (1.5.2): Alex2MQTT.connect() re-binds every registered device to its new broker client after a disconnect(). */
setMqttClient(client: MqttClient): void;
getName(): string;
setName(name: string): void;
getEndpointId(): string;
setDisplayCategory(category: DisplayCategory | DisplayCategory[]): void;
getDisplayCategory(): Array<DisplayCategory>;
setDescription(description: string): void;
getDescription(): string;
getErrorMessage(correlationToken: string): AlexaErrorResponse;
getStatusMessage(correlationToken: string, isResponse?: boolean, isDeferred?: boolean): AlexaStatusMessage;
/**
* A proactive Alexa.ChangeReport (1.5.1): add the changed properties (the default target), optionally
* .unchanged() then the others, and .send() - it goes to <root>/changeReport, which Alex2MQTT forwards to the Alexa
* event gateway with the user's token. Alexa only accepts it for capabilities registered with proactivelyReported.
*/
getChangeReport(cause?: ChangeCause): AlexaStatusMessage;
/**
* Alexa.SceneController: answer an Activate / Deactivate directive with ActivationStarted / DeactivationStarted
* (1.5.1). Resolves with the topic published to, or "" when the publish failed (never rejects, 1.5.2).
*/
sendSceneResponse(correlationToken: string, activated: boolean, cause?: ChangeCause, sendAsync?: boolean): Promise<string>;
/** The capabilities the device declared, in the order it declared them. */
getCapabilities(): AnyCapability[];
setManufacturerName(name: string): void;
getManufacturerName(): string;
setManufacturer(manufacturer: string): void;
getManufacturer(): string;
setModel(model: string): void;
getModel(): string;
getSoftwareVersion(): string;
/**
* Declare an interface of the device:
*
* lamp.add(PowerController, { proactivelyReported: true });
* blinds.add(RangeController, { instance: "Blind.Lift", friendlyNames: [asset("Alexa.Setting.Opening")],
* range: { min: 0, max: 100, precision: 1 } });
*
* Throws a DeclarationError that names the endpoint, the interface and the instance when Alexa would reject the
* capability; the device is then as it was before the call.
*/
add<P extends Properties, D extends Directives, O, I extends boolean>(descriptor: InterfaceDescriptor<P, D, O, I>, ...[options]: DeclarationArguments<O, I>): Capability<P, D, O>;
/**
* Declare an interface the 1.x way, by its name: options.retrievable / proactivelyReported / instance, then the
* add and set methods of the capability that is returned. Throws for a name that is not an interface. Anything
* else Alexa would reject is not refused here: check() lists it.
*/
addCapability(type: AlexaInterfaceType | string, options?: {
retrievable?: boolean;
proactivelyReported?: boolean;
instance?: string;
}): AlexaInterface;
/**
* What Alexa would reject in the device as it is declared now, one line for each: a name with punctuation, an
* interface declared twice. Also what a capability noted about its declaration. Empty when there is nothing.
* The bridge logs the lines when it answers a discovery.
*/
check(): string[];
/** The endpoint object for discovery. */
getJSON(): EndpointJson;
private fields;
private view;
private announced;
}
export default Device;

268
dist/esm/device/Device.js vendored Normal file
View file

@ -0,0 +1,268 @@
import { EventEmitter } from "events";
import { randomUUID } from "crypto";
import { AlexaErrorResponse } from "../AlexaErrorResponse.js";
import { AlexaStatusMessage } from "../AlexaStatusMessage.js";
import { AlexaInterface } from "../compat/AlexaInterface.js";
import { DisplayCategory } from "../compat/enums.js";
import { Alexa } from "../registry/interfaces/Alexa.js";
import { EndpointHealth } from "../registry/interfaces/EndpointHealth.js";
import { SchemaError } from "../registry/schema.js";
import { DeclarationError } from "../registry/types.js";
import { Capability, commonOptions } from "./Capability.js";
import { checkCapability, checkCapabilityCount, checkEndpoint } from "./validate.js";
class Device extends EventEmitter {
constructor(mqttClient, rootTopic, name, endpointId, displayCategory, description = "Alexa to Node.js bridge", manufacturerName = "Alex2Node", manufacturer = "Alex2Node", model = "Alex2Node_v1.0.0") {
super();
this.mqttClient = mqttClient;
this.rootTopic = rootTopic;
this.name = name;
this.endpointId = endpointId;
this.displayCategory = displayCategory;
this.description = description;
this.manufacturerName = manufacturerName;
this.manufacturer = manufacturer;
this.model = model;
this.softwareVersion = "1.0.0";
this.serialNumber = "Alex2Node";
this.firmwareVersion = "1.0.0";
this.customIdentifier = "Alex2Node";
/**
* Discovery lists the Alexa interface on the endpoint (alexa-interface.html: "You must explicitly identify your
* support for the Alexa interface"). The bridge sets it from its alexaInterface option.
*/
this.alexaInterface = true;
/**
* Discovery lists Alexa.EndpointHealth when the device did not declare it and is not a scene. On for a device of
* bridge.addDevice(), off for one of registerDevice(), which is announced as 1.x announced it.
*/
this.endpointHealth = false;
this.capabilities = [];
}
/** Internal (1.5.2): Alex2MQTT.connect() re-binds every registered device to its new broker client after a disconnect(). */
setMqttClient(client) {
this.mqttClient = client;
}
getName() {
return this.name;
}
setName(name) {
this.name = name;
}
getEndpointId() {
return this.endpointId;
}
setDisplayCategory(category) {
this.displayCategory = Array.isArray(category) ? category : [category];
}
getDisplayCategory() {
return this.displayCategory || [DisplayCategory.LIGHT];
}
setDescription(description) {
this.description = description;
}
getDescription() {
return this.description;
}
getErrorMessage(correlationToken) {
const msg = new AlexaErrorResponse(correlationToken, this.rootTopic, this.endpointId, this.mqttClient);
msg.onPublishError = this.onPublishError;
return msg;
}
getStatusMessage(correlationToken, isResponse = false, isDeferred = false) {
const msg = new AlexaStatusMessage(correlationToken, this.rootTopic, this.endpointId, this.mqttClient, isResponse, isDeferred);
msg.onPublishError = this.onPublishError;
return msg;
}
/**
* A proactive Alexa.ChangeReport (1.5.1): add the changed properties (the default target), optionally
* .unchanged() then the others, and .send() - it goes to <root>/changeReport, which Alex2MQTT forwards to the Alexa
* event gateway with the user's token. Alexa only accepts it for capabilities registered with proactivelyReported.
*/
getChangeReport(cause = "PHYSICAL_INTERACTION") {
const msg = new AlexaStatusMessage("", this.rootTopic, this.endpointId, this.mqttClient, false, false, cause);
msg.onPublishError = this.onPublishError;
return msg;
}
/**
* Alexa.SceneController: answer an Activate / Deactivate directive with ActivationStarted / DeactivationStarted
* (1.5.1). Resolves with the topic published to, or "" when the publish failed (never rejects, 1.5.2).
*/
sendSceneResponse(correlationToken, activated, cause = "VOICE_INTERACTION", sendAsync = false) {
const payload = {
context: {},
event: {
header: { namespace: "Alexa.SceneController", name: activated ? "ActivationStarted" : "DeactivationStarted", messageId: randomUUID(), correlationToken, payloadVersion: "3" },
endpoint: { endpointId: this.endpointId },
payload: { cause: { type: cause }, timestamp: new Date().toISOString() },
},
};
const topic = `${this.rootTopic}/${this.endpointId}/${sendAsync ? "deferredResponse" : "alexaResponce"}`;
return new Promise((resolve) => {
this.mqttClient.publish(topic, JSON.stringify(payload), (err) => {
if (!err)
return resolve(topic);
if (this.onPublishError)
this.onPublishError(err); // -> the bridge's "error" event (when somebody listens)
resolve(""); // 1.5.1 rejected here, and an un-caught send() then killed the host on any broker hiccup
});
});
}
/** The capabilities the device declared, in the order it declared them. */
getCapabilities() {
return this.capabilities.slice();
}
setManufacturerName(name) {
this.manufacturerName = name;
}
getManufacturerName() {
return this.manufacturerName;
}
setManufacturer(manufacturer) {
this.manufacturer = manufacturer;
}
getManufacturer() {
return this.manufacturer;
}
setModel(model) {
this.model = model;
}
getModel() {
return this.model;
}
getSoftwareVersion() {
return this.softwareVersion;
}
/**
* Declare an interface of the device:
*
* lamp.add(PowerController, { proactivelyReported: true });
* blinds.add(RangeController, { instance: "Blind.Lift", friendlyNames: [asset("Alexa.Setting.Opening")],
* range: { min: 0, max: 100, precision: 1 } });
*
* Throws a DeclarationError that names the endpoint, the interface and the instance when Alexa would reject the
* capability; the device is then as it was before the call.
*/
add(descriptor, ...[options]) {
const where = { endpointId: this.endpointId, namespace: descriptor.namespace, instance: "" };
if (options !== undefined && (typeof options !== "object" || options === null)) {
throw new DeclarationError(where, "the options of a declaration are an object");
}
try {
const { instance, friendlyNames, retrievable, proactivelyReported, nonControllable, ...given } = commonOptions.parse(options ?? {});
where.instance = instance ?? "";
const common = { instance, friendlyNames: friendlyNames, retrievable, proactivelyReported, nonControllable };
const capability = new Capability(descriptor, { ...common, options: interfaceOptions(descriptor, given) });
capability.endpointId = this.endpointId;
checkCapability(capability, descriptor, this.view(this.capabilities));
checkCapabilityCount(this.endpointId, this.announced([...this.capabilities, capability]).length);
this.capabilities.push(capability);
return capability;
}
catch (err) {
throw err instanceof SchemaError ? new DeclarationError(where, err.message) : err;
}
}
/**
* Declare an interface the 1.x way, by its name: options.retrievable / proactivelyReported / instance, then the
* add and set methods of the capability that is returned. Throws for a name that is not an interface. Anything
* else Alexa would reject is not refused here: check() lists it.
*/
addCapability(type, options = {}) {
let capability;
try {
capability = new AlexaInterface(type, options.retrievable ?? true, options.proactivelyReported ?? false, options.instance ?? "");
}
catch (err) {
throw err instanceof DeclarationError ? new DeclarationError({ endpointId: this.endpointId }, err.problem) : err;
}
capability.endpointId = this.endpointId;
this.capabilities.push(capability);
return capability;
}
/**
* What Alexa would reject in the device as it is declared now, one line for each: a name with punctuation, an
* interface declared twice. Also what a capability noted about its declaration. Empty when there is nothing.
* The bridge logs the lines when it answers a discovery.
*/
check() {
const lines = [];
const attempt = (rule) => {
try {
rule();
}
catch (err) {
if (!(err instanceof DeclarationError))
throw err;
lines.push(err.message);
}
};
attempt(() => checkEndpoint(this.fields()));
this.capabilities.forEach((capability, i) => {
capability.endpointId = this.endpointId;
attempt(() => checkCapability(capability, capability.descriptor, this.view(this.capabilities.slice(0, i))));
const notes = [...capability.notes];
const { tier, properties } = capability.descriptor;
if (tier === 3 && Object.keys(properties).length === 0 && capability.toJSON().properties) {
notes.push("no property list known, discovery lists it with no supported properties");
}
for (const note of notes)
lines.push(new DeclarationError(capability, note).message);
});
attempt(() => checkCapabilityCount(this.endpointId, this.announced(this.capabilities).length));
return lines;
}
/** The endpoint object for discovery. */
getJSON() {
return { ...this.fields(), capabilities: this.announced(this.capabilities).map((capability) => capability.toJSON()) };
}
fields() {
return {
endpointId: this.endpointId,
friendlyName: this.name,
description: this.description,
manufacturerName: this.manufacturerName,
displayCategories: this.getDisplayCategory(),
additionalAttributes: {
manufacturer: this.manufacturer,
model: this.model,
serialNumber: this.serialNumber,
firmwareVersion: this.firmwareVersion,
softwareVersion: this.softwareVersion,
customIdentifier: this.customIdentifier,
},
...(this.cookie ? { cookie: this.cookie } : {}),
};
}
// The endpoint as the rules of a capability see it
view(declaredBefore) {
return {
endpointId: this.endpointId,
friendlyName: this.name,
description: this.description,
displayCategories: this.getDisplayCategory(),
capabilities: declaredBefore,
};
}
// What discovery lists: the declared capabilities, then the ones the library adds
announced(declared) {
const has = (namespace) => declared.some((capability) => capability.namespace === namespace);
const added = [];
// alexa-scenecontroller.html, "Discovery": a scene is not a physical device and has no Alexa.EndpointHealth
if (this.endpointHealth && !has(EndpointHealth.namespace) && !has("Alexa.SceneController")) {
added.push(new Capability(EndpointHealth, { options: {} }));
}
if (this.alexaInterface && !has(Alexa.namespace))
added.push(new Capability(Alexa, { options: {} }));
return [...declared, ...added];
}
}
// The options of the interface itself, checked by the schema of its descriptor
function interfaceOptions(descriptor, given) {
if (descriptor.options)
return descriptor.options.parse(given);
const [unknown] = Object.keys(given);
if (unknown !== undefined)
throw new SchemaError(unknown, "not an option of the interface");
return {};
}
export default Device;

20
dist/esm/device/validate.d.ts vendored Normal file
View file

@ -0,0 +1,20 @@
import type { AnyDescriptor, Declared, EndpointView } from "../registry/types.js";
/** An endpoint as discovery sends it, without its capabilities. */
export interface EndpointFields {
endpointId: string;
friendlyName: string;
description: string;
manufacturerName: string;
displayCategories: readonly string[];
additionalAttributes: Readonly<Record<string, string>>;
cookie?: Readonly<Record<string, string>>;
}
/** Throws the first rule of the Endpoint object that the fields break. */
export declare function checkEndpoint(endpoint: EndpointFields): void;
/** alexa-discovery.html, "Interface limits". count includes the capabilities the library adds. */
export declare function checkCapabilityCount(endpointId: string, count: number): void;
/**
* Throws the first rule that a capability breaks on its endpoint. endpoint.capabilities are the ones declared
* before it. A stub is checked for being declared twice and for nothing else: the library does not know its rules.
*/
export declare function checkCapability(capability: Declared<unknown>, descriptor: AnyDescriptor, endpoint: EndpointView): void;

123
dist/esm/device/validate.js vendored Normal file
View file

@ -0,0 +1,123 @@
// What Alexa rejects at discovery, checked where a device is declared. Alexa gives no reason when it drops an
// endpoint: the user hears "no new devices found". Each rule names the page it is from.
import { DISPLAY_CATEGORIES, LIMITS } from "../registry/catalog.js";
import { labels, shownAs } from "../registry/resources.js";
import { SchemaError } from "../registry/schema.js";
import { DeclarationError } from "../registry/types.js";
// alexa-discovery-objects.html, "Endpoint object details": "letters, numbers, spaces, and the following special
// characters: _ - = # ; : ? @ &"
const ENDPOINT_ID = /^[A-Za-z0-9 _\-=#;:?@&]+$/;
// Same table: "alphanumeric characters and spaces". Letters of any script: Alexa speaks Hindi and Japanese too.
const FRIENDLY_NAME = /^[\p{L}\p{M}\p{N} ]+$/u;
const isText = (value) => typeof value === "string" && value.length > 0;
/** Throws the first rule of the Endpoint object that the fields break. */
export function checkEndpoint(endpoint) {
const where = { endpointId: isText(endpoint.endpointId) ? endpoint.endpointId : undefined };
function refuse(problem) {
throw new DeclarationError(where, problem);
}
const { endpointId, friendlyName, description, manufacturerName, displayCategories, additionalAttributes, cookie } = endpoint;
if (!isText(endpointId))
refuse("an endpoint needs an endpointId");
if (endpointId.length > LIMITS.endpointIdLength || !ENDPOINT_ID.test(endpointId)) {
refuse(`the endpointId takes up to ${LIMITS.endpointIdLength} letters, digits, spaces and _ - = # ; : ? @ &`);
}
if (!isText(friendlyName))
refuse("an endpoint needs a name");
if (friendlyName.length > LIMITS.friendlyNameLength || !FRIENDLY_NAME.test(friendlyName)) {
refuse(`the name ${JSON.stringify(friendlyName)} takes up to ${LIMITS.friendlyNameLength} letters, digits and spaces, no punctuation`);
}
if (!isText(manufacturerName) || manufacturerName.length > LIMITS.manufacturerNameLength) {
refuse(`the manufacturerName takes 1 to ${LIMITS.manufacturerNameLength} characters`);
}
if (!isText(description) || description.length > LIMITS.descriptionLength) {
refuse(`the description takes 1 to ${LIMITS.descriptionLength} characters`);
}
if (!Array.isArray(displayCategories) || displayCategories.length === 0)
refuse("an endpoint needs a display category");
const known = DISPLAY_CATEGORIES;
for (const category of displayCategories) {
if (!known.includes(category))
refuse(`${JSON.stringify(category)} is not a display category`);
}
for (const [name, value] of Object.entries(additionalAttributes)) {
if (typeof value !== "string" || value.length > LIMITS.additionalAttributeLength) {
refuse(`${name} takes up to ${LIMITS.additionalAttributeLength} characters`);
}
}
if (cookie !== undefined) {
const bytes = Buffer.byteLength(JSON.stringify(cookie) ?? "");
if (bytes > LIMITS.cookieBytes)
refuse(`the cookie is ${bytes} bytes, ${LIMITS.cookieBytes} is the most`);
}
}
/** alexa-discovery.html, "Interface limits". count includes the capabilities the library adds. */
export function checkCapabilityCount(endpointId, count) {
if (count > LIMITS.capabilitiesPerEndpoint) {
throw new DeclarationError({ endpointId }, `${count} capabilities, an endpoint takes ${LIMITS.capabilitiesPerEndpoint}`);
}
}
// Two names are the same name when the app would show the same: the asset, or the text in one locale.
function nameKey(name) {
return name["@type"] === "asset" ? `asset ${name.value.assetId}` : `text ${name.value.locale} ${name.value.text.toLowerCase()}`;
}
function phrases(capability) {
const { semantics } = capability.options;
return (semantics?.actionMappings ?? []).flatMap((mapping) => mapping.actions);
}
/**
* Throws the first rule that a capability breaks on its endpoint. endpoint.capabilities are the ones declared
* before it. A stub is checked for being declared twice and for nothing else: the library does not know its rules.
*/
export function checkCapability(capability, descriptor, endpoint) {
function refuse(problem) {
throw new DeclarationError(capability, problem);
}
const { namespace, instance, friendlyNames } = capability;
// generic-controllers.html, "Multiple instances": one capability of an interface, or one per instance name
if (endpoint.capabilities.some((other) => other.namespace === namespace && other.instance === instance)) {
refuse(instance ? "the instance is declared twice" : "the interface is declared twice");
}
if (descriptor.tier === 3)
return;
if (descriptor.instanced) {
// alexa-rangecontroller.html, "Capabilities array": instance and capabilityResources are required
if (!isText(instance))
refuse("needs an instance name, like Blind.Lift");
try {
labels.parse(friendlyNames, "friendlyNames");
}
catch (err) {
refuse(err instanceof SchemaError && err.path === "friendlyNames" ? "needs a friendly name, from text() or asset()" : err.message);
}
// resources-and-assets.html, "CapabilityResources": "The first friendly name in the array must be unique for
// the endpoint."
const first = nameKey(friendlyNames[0]);
const taken = endpoint.capabilities.find((other) => other.friendlyNames.length > 0 && nameKey(other.friendlyNames[0]) === first);
if (taken) {
refuse(`the first friendly name, ${shownAs(friendlyNames[0])}, is the first of ${taken.namespace} ${JSON.stringify(taken.instance)} too`);
}
}
else {
if (instance)
refuse("takes no instance name: an endpoint has the interface once");
if (friendlyNames.length > 0)
refuse("takes no friendly names");
}
// generic-controllers.html, "Semantics for user utterances": "Each semantic phrase must be unique across all
// controller instances for each endpoint"
const used = new Map();
for (const other of endpoint.capabilities)
for (const phrase of phrases(other))
used.set(phrase, other);
for (const phrase of phrases(capability)) {
const owner = used.get(phrase);
if (owner) {
const place = owner === capability ? "twice" : `here and on ${owner.namespace} ${JSON.stringify(owner.instance)}`;
refuse(`${phrase} is mapped ${place}, an endpoint maps a phrase once`);
}
used.set(phrase, capability);
}
if (descriptor.validate)
descriptor.validate(capability, endpoint);
}