Alex2Node/src/device/Capability.ts
David feff828ec1 dispatch: typed handlers, respond/defer/error, automatic ErrorResponse, watchdog
src/dispatcher.ts routes a directive to capability.on(name | "*"), device.onDirective() or
device.onReportState(), with the payload checked by the descriptor of the interface. The
DirectiveContext answers with respond/report/defer/error; respond() and report() start from
device.state(). A handler or 1.x listener that throws or rejects is answered with INTERNAL_ERROR
(an AlexaError with itself) and reported through "error", never as an unhandled rejection.
Undeclared interface, unknown directive, AdjustMode on an unordered mode and a missing handler
get INVALID_DIRECTIVE, a bad payload INVALID_VALUE; a device with an "Event" or "ReportState"
listener keeps the answer to itself. Every answer passes the dispatcher: the first one per
correlationToken is published, a second is refused. No answer within answerWithinMs (6500,
0 = off, unref'd timer) sends INTERNAL_ERROR and emits "unanswered". A messageId that arrived
in the last 60 s is dropped. New: "unknownEndpoint", options answerUnknownEndpoints, publisher,
timers, and bridge.receive() to run a bridge without a broker. 168 tests pass (18 new).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 19:49:41 +00:00

147 lines
6.5 KiB
TypeScript

import type { DirectiveHandler } from "../dispatcher.js";
import { s } from "../registry/schema.js";
import type { Infer } from "../registry/schema.js";
import { DeclarationError } from "../registry/types.js";
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 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()),
});
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 class Capability<P extends Properties = Properties, D extends Directives = Directives, O = {}> implements Declared<O> {
/** The endpoint the capability is declared on; the device sets it. */
endpointId = "";
/** "" 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[] = [];
private readonly handlers = new Map<string, DirectiveHandler<any>>();
constructor(readonly descriptor: InterfaceDescriptor<P, D, O, boolean>, declared: CommonOptions & { options: O }) {
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(): string {
return this.descriptor.namespace;
}
/**
* What the device does on a directive of the interface:
*
* lift.on("SetRangeValue", async (ctx) => { await motor.moveTo(ctx.payload.rangeValue); return ctx.respond(); });
*
* "*" is the handler of every directive that has none of its own. A handler that throws answers the directive
* with an ErrorResponse: the AlexaError it threw, INTERNAL_ERROR for anything else. Throws a DeclarationError
* for a name that is not a directive of the interface.
*/
on<K extends keyof D & string>(name: K, handler: DirectiveHandler<Infer<D[K]["payload"]>>): this;
on(name: "*", handler: DirectiveHandler): this;
on(name: string, handler: DirectiveHandler<any>): this {
const names = Object.keys(this.descriptor.directives);
// An interface the library only names (tier 3) describes no directive: any name is taken
if (name !== "*" && this.descriptor.tier !== 3 && !names.includes(name)) {
throw new DeclarationError(this, `${name} is not a directive of the interface, which has ${names.join(", ") || "none"}`);
}
if (typeof handler !== "function") throw new DeclarationError(this, `the handler of ${name} is a function`);
this.handlers.set(name, handler);
return this;
}
/** The handler on(name) registered, or the one of "*". */
handlerFor(name: string): DirectiveHandler<any> | undefined {
return this.handlers.get(name) ?? this.handlers.get("*");
}
/** Mappings of "open", "close", "raise", "lower" and of states, when the declaration has any. */
get semantics(): Semantics | undefined {
const { semantics } = this.options as { semantics?: Semantics };
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(): CapabilityJson {
const { descriptor, semantics } = this;
const extras = descriptor.discovery ? descriptor.discovery(this) : {};
const json: CapabilityJson = {
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 };
}
}
export type AnyCapability = Capability<any, any, any>;