/** * A declarative framework for building Home Assistant automations * * @remarks * This package contains everything you needed to get started building a hass-blocks automation * * @packageDocumentation */ import { Block as Block_2 } from '../index.ts'; import type { CallServiceCommand } from '@hass-blocks/hass-ts'; import type { HassArea } from '@hass-blocks/hass-ts'; import type { HassConfig } from '@hass-blocks/hass-ts'; import { IHomeAssistant } from '@hass-blocks/hass-ts'; import type { IMQTTConnection } from '@hass-blocks/hass-mqtt'; import type { Service } from '@hass-blocks/hass-ts'; import type { State } from '@hass-blocks/hass-ts'; import type { StateChangedEvent } from '@hass-blocks/hass-ts'; import z from 'zod/v4'; /** * @public * * A generic block that represents some kind of action * * @example * ```TypeScript * * import { action } from "@hass-blocks/core" * * const turnOnLivingRoomLights = action({ * name: `Turn on lights`, * callback: async (hass) => { * await hass.callService({ * domain: 'light', * service: 'turn_on', * target: { * entity_id: 'light.living_room' * } * }) * }, * }); * ``` * * @param config - configuration for the action */ export declare const action: (config: IActionConfig) => Block; /** * @public * * Make a HTTP request * * @param props - request configuration */ export declare const apiRequest: , TInputProps extends Partial>(props: TProps) => Block_2>>; /** * @public * * HTTP Request configuration */ export declare interface ApiRequestProps { /** * HTTP Verb to use */ method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'; /** * Headers to be sent along with the request */ headers: Record; /** * The base URL for the request */ baseUrl: string; /** * The path segment for the request */ path: string; /** * Body of the request */ body?: Record; /** * Zod schema for the response */ responseSchema?: z.core.$ZodType; } /** * @public * * An area target * @param id - One or more area ids */ export declare const area: (id: I, name?: string) => IArea; /** * @public * * An assertion is a block which can decide whether or not * an automation should continue based on the result of a predicate */ export declare const assertion: (config: IAssertionConfig) => Block; /** * @public * * An automation represents a sequence of actions that can either be executed in sequence * or in parallel. When passed into */ export declare const automation: [], TInput = GetSequenceInput, TOutput = GetSequenceOutput>(config: IAutomationConfig) => Block; /** * @public * * An event that is emitted when an automation has been registered */ export declare interface AutomationRegistered extends BaseHassBlocksEvent<'automation-registered'> { /** * The name of the automation that was registered */ name: string; /** * A serialised version of the block that was registered */ block: IBlocksNode; } /** * @public * * The base event that all events fired by the framework inherit from */ export declare interface BaseHassBlocksEvent { /** * The type of the event that was fired - used for discriminating unions */ eventType: T; /** * The id of the individual event - generated at the time of emit */ id: string; /** * The time that the event was emitted */ timestamp: string; } /** * @public * * The core Hass Blocks abstraction! - all Blocks must extend from this class for * the framework to be able to execute them */ export declare abstract class Block implements IBlock, IMutableNode { /** * String to identify this particular instance of a block. Must be unique */ readonly id: string; private targets; /** * All child nodes of this block */ private _trigger?; /** * Child nodes */ readonly children: IMutableNode[]; constructor( /** * String to identify this particular instance of a block. Must be unique */ id: string, targets: ITarget[] | undefined, /** * All child nodes of this block */ _trigger?: (ITrigger | ITrigger[]) | undefined); /** * Add a child node * * @param node - node to be added */ addChild(...node: IMutableNode[]): void; /** * Returns true if this node has a trigger attached */ protected hasTrigger(): boolean; /** * A JSON representation of the block. Used for websocket and rest serialisation */ toJson(): IBlocksNode; /** * Adds the next sequence node. The default implementation * simply adds the node as a child of this node, however * subclasses can override this to ensure that any children they need * to connect up in between are connected * * @param node - node to be added */ addNext(node?: IMutableNode): void; /** * Triggers that are currently registered with this block */ get trigger(): ITrigger | ITrigger[]; set trigger(trigger: ITrigger | ITrigger[]); /** * Friendly name for the block - for use in user interfaces */ abstract readonly name: string; /** * If defined, this method will be called when the parent automation is registered. * If any configuration is invalid, an error should be thrown */ initialise(client: IFullBlocksClient, mqtt: IMQTTConnection): Promise; /** * Iterate through a sequence of nodes and connect them together * * @param nodes - the nodes to link */ linkNodes(...nodes: IMutableNode[]): void; /** * String that identifies the kind of block */ abstract readonly type: string; /** * Called by the framework when the block is executed * * @param client - An initialised blocks client, * @param input - The input for this block - usually the output from the last one * @param events - An initialised event bus * @param triggerId - a uuid trigger id, unique to this particular trigger sequence */ abstract run(context: IRunContext): Promise> | BlockOutput; } /** * @public * * An event that is emitted when a block fails for some reason */ export declare interface BlockFailed extends LifeCycleEvent<'block-failed'> { /** * The type of block that failed */ type: string; /** * The message that explains why the block failed */ message: string; /** * The original error object */ error: Error; /** * The parent block (often this will be the automation that triggered the block execution) */ parent?: IBlocksNode; } /** * @public * * An event that is emitted when a block finishes successfully */ export declare interface BlockFinished extends LifeCycleEvent<'block-finished'> { /** * The type of block that has started */ type: string; /** * The output that was returned by the block callback */ output: BlockOutput; /** * The parent block (often this will be the automation that triggered the block execution) */ parent?: IBlocksNode; } /** * @public * * Results that can be returned by blocks */ export declare type BlockOutput = ContinueOutput | StopOutput | ConditionResult; /** * @public * * An event that is emitted when a block is queued for execution */ export declare interface BlockPending extends LifeCycleEvent<'block-pending'> { /** * The type of block that was queued */ type: string; /** * The parent block (often this will be the automation that triggered the block execution) */ parent?: IBlocksNode; /** * The trigger object that started this execution sequence */ triggeredBy?: ITrigger; } /** * @public * * Rehydrate a sequence of blocks with its input and output types */ export declare type BlockRetainType[]> = A extends readonly [ infer First extends Block, ...infer Rest extends readonly Block[] ] ? readonly [ Block, OutputTypeKeepPromise>, ...BlockRetainType ] : readonly []; /** * @public * * An event that is emitted when a block starts executing */ export declare interface BlockStarted extends LifeCycleEvent<'block-started'> { /** * The type of block that has started */ type: string; /** * The parent block (often this will be the automation that triggered the block execution) */ parent?: IBlocksNode; /** * The trigger object that started this execution sequence */ triggeredBy?: ITrigger; } /** * @public * * Compares a block with a sequence and determins of the inputs and outputs * are compatible */ export declare type BlockTypeIsCompatibleWithSequence = [ Exclude ] extends [ TSequenceInput extends void ? MustIncludeUndefined : Partial ] ? true : false; /** * @public * * The output of CheckScenarios - a list of either blocks, errors, or instructions * to recurse again */ export declare type CheckOutput = readonly Block[] | DoRecurse[], readonly Block[]> | SequenceCompatibilityError[], readonly Block[], string>; /** * @public * * Sequence validator phase one - check a number of scenarios and generate error messages or * instructions to recurse again if needed */ export declare type CheckScenarios[], TBefore extends readonly Block[]> = SinglePassBlock extends never ? SingleGeneralBlock extends never ? TwoPassBlocks extends never ? MultiPassSequence extends never ? NonPassSequence extends never ? SequenceCompatibilityError : NonPassSequence : MultiPassSequence : TwoPassBlocks : SingleGeneralBlock : SinglePassBlock; /** * @public * Combine a list of targets * * @returns */ export declare const combine: | ReadonlyArray | ReadonlyArray>(...items: T) => T[number]; /** * @public * * When executed, this block will execute all the blocks passed in as the first argument concurrently. Once complete * the outputs from all the blocks will be returned as an array */ export declare const concurrently: []>(...actions: TCollectionOfBlocks) => Block, GetSequenceOutput[]>; /** * @public * * Output returned when a conditional block signals to continue */ export declare interface ConditionResult { /** * Whether execution should continue */ continue: true; /** * Whether the output originates from a core block or a conditional block */ outputType: 'conditional'; /** * The condition result returned by the block */ conditionResult: boolean; /** * The output returned by the blocks callback */ output: O; } /** * @public * * Output returned when a block signals to continue */ export declare interface ContinueOutput { /** * Whether execution should continue */ continue: true; /** * Whether the output originates from a core block or a conditional block */ outputType: 'block'; /** * The output returned by the blocks callback */ output: O; } /** * @public * * Instruct the sequence recursor to perform a recursion */ export declare type DoRecurse[], TBefore extends readonly Block[]> = { __recurse: true; in: TInput; out: TOutput; sequence: TSequence; before: TBefore; }; /** * @public * * An entity target * * @param targets - One or more entity or other targets */ export declare const entity: (id: I, friendlyName?: string) => IEntity; /** * @public * * Assertion will pass if the entity exists in Home Assistant * * @param entity - The entity to examine */ export declare const entityExists: (entity: IEntity) => Block_2; /** * @public * * Blocks can throw this error at any time to abort the currently running * execution sequence */ export declare class ExecutionAbortedError extends HassBlocksError { constructor(name: string); } /** * @public * * The execution mode for an automation */ export declare enum ExecutionMode { /** * If a previous execution is in progress when triggered, that execution will be cancelled */ Restart = "Restart", /** * If a previous execution is in progress when triggered, the new execution will continue regardless */ Parallel = "Parallel", /** * If a previous execution was in progress, the new execution will execute when that execution has finished */ Queue = "Queue" } /** * @public * * Given the return type of a block, extract its output type */ export declare type ExtractOutput = TAny extends Promise ? ExtractOutput : TAny extends Exclude, StopOutput> ? TBlockType : never; /** * @public * * A factory function that keeps track of whether a gate is open or closed. * Returns an object containing actions to open and close the gate and an assertion * that checks if the gate is open * * @param name - The name of the gate */ export declare const gate: (name: string) => { ifGateIsOpen: Block_2; ifGateIsClosed: Block_2; open: Block_2; close: Block_2; }; /** * @public * * An event that is emitted when there is some kind of error */ export declare interface GeneralFailure extends BaseHassBlocksEvent<'generalFailure'> { /** * The message string that was generated by the error */ message: string; /** * The original error object */ error: Error; } /** * Get all of the outputs of a sequence of blocks * * @public */ export declare type GetOutputs[]> = T extends readonly [ infer First extends Block, ...infer Rest extends Block[] ] ? readonly [OutputType, ...GetOutputs] : readonly []; /** * Given an array of blocks, get the input type from the first block * * @public */ export declare type GetSequenceInput> = T extends readonly [Block] ? Pass : T extends readonly [infer Only extends Block] ? InputType : T extends readonly [infer First, ...infer Rest] ? First extends Block ? GetSequenceInput : First extends Block ? InputType : ['Item wasnt a block'] : ['No valid array remaining']; /** * Given an array of blocks, get the output type from the last block * * @public */ export declare type GetSequenceOutput> = T extends readonly [Block] ? Pass : T extends readonly [infer Only extends Block] ? OutputType : T extends readonly [...infer Rest, infer Last] ? Last extends Block ? GetSequenceOutput : Last extends Block ? OutputType : ['Item wasnt a block'] : ['No valid arrray remaining']; /** * @public * * Base class for all errors thrown by this framework */ export declare class HassBlocksError extends Error { constructor(message: string, cause?: unknown); } /** * @public * * Events published by the framework on the event bus */ export declare type HassBlocksEvent = AutomationRegistered | GeneralFailure | LogEvent | StateChanged | BlockFailed | BlockFinished | BlockPending | BlockStarted | SequenceAborted | LoadPluginsStart | LoadPluginStart | LoadPluginsFinished | LoadPluginFinished; /** * @public * * The Home Assistant context (See {@link https://data.home-assistant.io/docs/context/}) */ export declare type HassContext = { id: string; user_id: string | null; parent_id: string | null; }; /** * @public * * A Home Assistant entity */ export declare type HassEntity = HassEntityBase & { attributes: { [key: string]: any; }; }; /** * @public * * The core entity attributes shared by all Home Assistant entities */ export declare type HassEntityAttributeBase = { friendly_name?: string; unit_of_measurement?: string; icon?: string; entity_picture?: string; supported_features?: number; hidden?: boolean; assumed_state?: boolean; device_class?: string; state_class?: string; restored?: boolean; }; /** * @public * * The core attributes shared by all Home Assistant entities */ export declare type HassEntityBase = { entity_id: string; state: string; last_changed: string; last_updated: string; attributes: HassEntityAttributeBase; context: HassContext; }; /** * @public * * The base Home Assistant event */ export declare type HassEventBase = { origin: string; time_fired: string; context: HassContext; }; /** * @public * * Configuration object for action blocks */ export declare interface IActionConfig extends IBaseBlockConfig { /** * This callback will be executed when an automation runs this block */ callback: ((context: IRunContext) => TOutput) | ((context: IRunContext) => Promise); } /** * A node that can be connected to other nodes * * @public */ export declare interface IAddable { /** * Add a child to this node in the tree * * @param node - node to be added */ addChild(...node: IMutableNode[]): void; /** * Add the next node in a sequence * * @param node - node to be added */ addNext(...node: IMutableNode[]): void; } /** * @public * * Any Home Assistant area */ export declare interface IArea extends ITarget { /** * The ids that will actually be supplied to the service call */ targetIds: { area_id: I[]; }; } /** * @public * * Configuration object for an assertion block */ export declare interface IAssertionConfig extends IBaseBlockConfig { /** * When this block is executed by an automation it should return a boolean * either as the direct return value, or as the 'result' property on an object. * * If that value is false, it will indicate to the execution engine that the automation * should finish */ readonly predicate: (context: IRunContext) => Promise | boolean | { result: boolean; output: TOutput; } | Promise<{ result: boolean; output: TOutput; }>; } /** * @public * * Configuration object for automation blocks */ export declare interface IAutomationConfig[], TInput = GetSequenceInput, TOutput = GetSequenceOutput> extends IBaseBlockConfig { /** * Sequence of blocks to execute when the trigger is fired */ then: (BlockRetainType & TSequence & ValidateSequence) | Block; /** * Trigger will result in this block being executed */ when?: ITrigger | ITrigger[]; /** * Whether to execute the blocks in sequnce or in parallel */ mode?: ExecutionMode; } /** * @public * Configuration that is common for all blocks */ export declare interface IBaseBlockConfig { /** * Name of the block */ readonly name: string; /** * Unique ID of the block - if this is not supplied, an md5 hash of the name * will be used. Must be unique */ readonly id?: string; /** * A list of targets used by this block. The framework will validate they exist on boot * and at regular intervals */ readonly targets?: ITarget[]; } /** * @public * * The abstract base class that all blocks inherit from */ export declare interface IBlock extends IBlocksNode { /** * Triggers that are currently registered with this block */ trigger: ITrigger | ITrigger[]; /** * String that identifies the kind of block */ type: string; /** * Called by the framework when the block is executed * * @param client - An initialised blocks client, * @param input - The input for this block - usually the output from the last one * @param events - An initialised event bus * @param triggerId - a uuid trigger id, unique to this particular trigger sequence */ run(context: IRunContext): Promise> | BlockOutput; } /** * @public * * Configuration object for Hass Blocks */ export declare interface IBlocksConfig { /** * A list of plugins to be loaded by Hass Blocks */ plugins?: IBlocksPlugin[]; /** * A logger - if not supplied, will fall back to a default logger that uses console.log * and doesn't log trace or debug messages */ logger?: ILogger; /** * An already instantiated version of the Hass client. Used for testing */ client?: IHomeAssistant; } /** * @public * * An initialied Hass Blocks connection */ export declare interface IBlocksConnection { /** * A Hass Blocks registry object that automations can be registered with */ registry: IBlocksRegistry; } /** * @public * * Any node on the Hass Blocks graph */ export declare interface IBlocksNode { /** * String to identify this particular instance of a block. Must be unique */ id: string; /** * Friendly name for the node - for use in user interfaces */ name: string; /** * Nodes that descend from this one on the tree */ children: IBlocksNode[]; /** * String that identifies the kind of block */ type: string; /** * The parameters that were passed with the block */ params?: Record; } /** * @public * * An object that implements this interface can be passed into the 'plugins' property * of the {@link initialiseBlocks} config object. */ export declare interface IBlocksPlugin { /** * The name of the plugin - used for logging */ readonly name: string; /** * This method will be called once during Hass Blocks initialisation * * @param args - hass blocks internals passed in by the framework * @returns */ load(args: IPluginArgs): Promise; } /** * @public * * A blocks registery object - this is where you start registering automations */ export declare interface IBlocksRegistry { /** * Register an automation with Hass Blocks * * @param automation - The automation to be registered */ registerAutomation(...automation: (IMutableNode & ITriggerable)[]): Promise; } /** * @public * * Parameters for calling Home Assistant services */ export declare interface ICallServiceParams { /** * The service domain (e.g. 'light') */ domain: string; /** * The service action (e.g. 'turn_on') */ service: string; /** * The target of the service call */ target?: { entity_id?: string | string[]; area_id?: string | string[]; device_id?: string | string[]; }; /** * Any additional data specific to the individual service call */ data?: Record; } /** * @public * * Any Home Assistant device */ export declare interface IDevice extends ITarget { /** * The ids that will actually be supplied to the service call */ targetIds: { device_id: string[]; }; } /** * @public * * Configuration for loop block (do-while variant) */ export declare interface IDoWhileConfig extends IBaseBlockConfig { /** * Will execute this assertion for each iteration of the loop. If it succeeds, the 'then' block is executed */ while: Block; /** * Block to be executed */ do: Block; } /** * @public * * Any Home Assistant entity */ export declare interface IEntity extends ITarget { /** * The ids that will actually be supplied to the service call */ targetIds: { entity_id: I[]; }; /** * If this entity has been initialised with a registered automation, this will return the current state * of the entity within Home Assistant */ currentState: HassEntity; } /** * @public * * The Hass Blocks internal event bus */ export declare interface IEventBus { /** * Emit an event on the bus * * @param event - the event to be emitted */ emit(type: ET, event?: Omit): void; /** * Subscribe to the event bus * * @param callback - callback that is executed when an event is received */ subscribe(callback: (event: HassBlocksEvent) => void): void; } /** * @public * * Configuration object for a condition block */ export declare interface IfThenElseConditionConfig extends IBaseBlockConfig { /** * The result of this assertion decides which branch to take */ readonly assertion: Block | Block; /** * Execute this block if the predicate passes */ readonly then: Block; /** * Execute this block if the predicate fails */ readonly else: Block; } /** * @public * * The full version of the blocks client - only available to plugins */ export declare interface IFullBlocksClient extends IHass { /** * Reload the home assistant state cache */ loadStates(): Promise; /** * Register a trigger with Home Assistant * * @param trigger - the trigger details - see {@link https://www.home-assistant.io/docs/automation/trigger/} for more details * @param callback - callback that will be executed when the trigger fires */ registerTrigger(trigger: Record, callback: (event: unknown) => void | Promise): Promise; /** * Get a list of automations currently registered */ getAutomations(): (IBlocksNode & ISerialisable)[]; /** * Register an automation */ registerAutomation(...automation: (IMutableNode & ITriggerable)[]): Promise; /** * Register a callback that fires when a particular entity changes state * * @param id - The id to listen for * @param callback - Callback that will fire when the state changess */ onStateChanged(id: string, callback: (event: StateChangedEvent) => void): Promise; } /** * @public * * An initialised Home Assistant connection that blocks can used to inspect state * or make calls to services */ export declare interface IHass { /** * Get all states currently loaded into the Hass Blocks cache */ getStates(): Map; /** * Get the current state of a given entity * * @param id - The entity id */ getState(id: string): string; /** * Get the current state of a given entity * * @param entity - the entity to inspect */ getState(entity: IEntity<`${string}.${string}>`>): string; /** * Get the full entity description of a given entity * * @param id - The entity id */ getEntity(id: string): HassEntity; /** * Get the full entity description of a given entity * * @param entity - the entity to inspect */ getEntity(entity: IEntity<`${string}.${string}`>): HassEntity; /** * Get a list of registered services from Home Assistant */ getServices(): Promise>>; /** * Get a list of registered areas */ getAreas(): Promise; /** * Call a service on the Home Assistant API * * @param params - Service parameters */ callService(params: Omit): Promise; } /** * A node that can be initialised by Hass Blocks on boot * * @public */ export declare interface IInitialisable { /** * If defined, this method will be called when the parent automation is registered. * If any configuration is invalid, an error should be thrown */ initialise(client: IHass, mqtt: IMQTTConnection): Promise; } /** * @public * * Logger interface for logging messages */ export declare interface ILogger { /** * An extreme level of detail - often used for tracing flow control and * api calls * * @param message - log message */ trace(message: string): void; /** * A level of detail that is useful for debugging * * @param message - log message */ debug(message: string): void; /** * Log messages about the normal operation of the framework * * @param message - log message */ info(message: string): void; /** * Warnings about potential issues * * @param message - log message */ warn(message: string): void; /** * Something has gone wrong * * @param message - log message */ error(message: string): void; /** * Fatal errors normally result in termination of the application * * @param message - log message */ fatal: (message: string) => void; } /** * @public * * Configuration for loop block */ export declare interface ILoopConfig extends IBaseBlockConfig { /** * Will execute this assertion for each iteration of the loop. If it succeeds, the 'then' block is executed */ while: Block; /** * Block to be executed */ then: Block; } /** * @public * * A node in the blocks graph that is not read only */ export declare type IMutableNode = IBlocksNode & ISerialisable & IInitialisable & IAddable; /** * @public * * Bootstrap the connection with Home Assistant and initialise Hass Blocks * * @remarks * Uses {@link hass-ts#getConfig} under the hood, so will read the same environment variables * * @example * ```TypeScript * * const { registry } = await initialiseBlocks() * ``` */ export declare const initialiseBlocks: (args?: IBlocksConfig) => Promise; /** * Given a block, extract the input type and remove undefined from void * * @public */ export declare type InputType> = void extends RawInputType ? RemoveVoidIfNotOnlyVoid ? Exclude, undefined> : RawInputType> : RawInputType; /** * @public * * This object will be passed into the load method once during Hass Blocks * initialisation, plugins can use it to interact with home assistant and listen * to hass blocks event */ export declare interface IPluginArgs { /** * An initialised Hass Blocks clients which includes methods that * can be used by plugins to make calls to Home Assistant */ client: IFullBlocksClient; /** * The internal Hass Blocks event bus */ events: IEventBus; /** * The configuration that was used to connect to Home assistant */ config: HassConfig; /** * A logger */ logger: ILogger; } /** * @public * * Execution context and utilities supplied to each running block */ export declare interface IRunContext { /** * An initialised blocks client, */ hass: IHass; /** * The input for this block - usually the output from the last one */ input: I; /** * An initialised event bus */ events?: IEventBus; /** * uuid trigger id, unique to this particular trigger sequence */ triggerId?: string; /** * When called with a block, it will return a function that can be used * to execute that block */ runner: (block: Block) => (input: TInput) => Promise>; } /** * @public * * A node that can be serialised to JSON */ export declare interface ISerialisable { /** * Return a JSON representation of this block */ toJson(): IBlocksNode; } /** * @public * * Anything that can be a target for a service call */ export declare interface ITarget { /** * The ids that will actually be supplied to the service call */ targetIds: ITargetIds; /** * * Called by the framework to validate that this target exists * and is operational * @param hass - an initialised Home Assistant instance * @param mqtt - an initialised connection to the Home Assistant MQTT broker */ initialise(hass: IFullBlocksClient, mqtt: IMQTTConnection): Promise; /** * Render a string version of this target */ toString(): string; } /** * @public * * An object representing a set of ids for either entities, * areaas or devices */ export declare interface ITargetIds { /** * An entity id or list of ids */ entity_id?: string[]; /** * An area id or list of ids */ area_id?: string[]; /** * A device id or list of ids */ device_id?: string[]; } /** * @public * * An object representing a Home Assistant trigger */ export declare interface ITrigger extends IMutableNode { /** * Register the trigger with a Home Assistant client so that it actually fires when * the conditions are met * * @param client - An initialied blocks client * @param block - The block that will be executed when the trigger is fired * @param events - The internal event bus */ attachToClient(client: IFullBlocksClient, block: IMutableNode & ITriggerable, events: IEventBus): Promise; } /** * A node that can be triggered * * @public */ export declare interface ITriggerable { /** * The trigger for this node */ trigger: ITrigger | ITrigger[]; } /** * @public * * The configuration object for a trigger */ export declare interface ITriggerConfig { /** * The name of the trigger */ name: string; /** * A id string for the trigger (must be unique) */ id?: string; /** * The Home Assistant trigger parameters (See {@link https://www.home-assistant.io/docs/automation/trigger/}) */ trigger: Record; /** * A list of targets used by the trigger. The framework will validate the targets on boot and * at regular intervals */ targets?: ITarget[]; } /** * @public * * All events that relate to the lifecycle of a block inherit from this event */ declare interface LifeCycleEvent extends BaseHassBlocksEvent { /** * A unique uuid generated each time a trigger is fired. All blocks that are executed * as a result of that trigger will get the same triggerId */ triggerId: string; /** * A unique uuid that is generated for all events associated with a single execution of a given * block. This uuid is different every time the block is executed but the same for all of the lifecycle * events associated with that execution */ executeId: string; /** * The name of the block being executed */ name: string; /** * A serialised version of the block being executed */ block: IBlocksNode; } export { LifeCycleEvent as BaseHassEvent } export { LifeCycleEvent } /** * @public * * An event that is emitted just after a specific plugin finishes loading */ export declare interface LoadPluginFinished extends BaseHassBlocksEvent<'load-plugin-finished'> { /** * The name of the plugin that finished loading */ name: string; } /** * @public * * An event that is emitted after all plugins have finished loading */ export declare interface LoadPluginsFinished extends BaseHassBlocksEvent<'load-plugins-finished'> { /** * A loist of plugins that were loaded */ plugins: string[]; } /** * @public * * An event that is emitted just before all plugins start loading */ export declare type LoadPluginsStart = BaseHassBlocksEvent<'load-plugins-started'>; /** * @public * * An event that is emitted just before a specific plugin starts loading */ export declare interface LoadPluginStart extends BaseHassBlocksEvent<'load-plugin-started'> { /** * The name of the plugin that is about to start loading */ name: string; } /** * @public * * An event emitted whenever you want to log information. Will be picked up by * logging clients */ export declare interface LogEvent extends BaseHassBlocksEvent<'log-event'> { /** * The log message */ message: string; /** * The module that emitted the log message */ module: string; /** * The log level */ level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'; } /** * @public * Continues to execute a block until an assertion fails * * @param config - Configuration for loop */ export declare function loop(config: ILoopConfig): Block; /** * @public * Continues to execute a block until an assertion fails (do-while variant) * * @param config - Configuration for loop */ export declare function loop(config: IDoWhileConfig): Block; /** * @public * * Match sequences that contain pass multiple passes. */ export declare type MultiPassSequence[], TBefore extends readonly Block[], TInput, TOutput> = TSequence extends readonly [ infer First extends Block, infer Next extends Block, ...infer Rest extends readonly Block[] ] ? BlockTypeIsCompatibleWithSequence, TInput> extends true ? DoRecurse, TOutput, Rest, [...TBefore, First, Next]> : Next extends Block ? DoRecurse : SequenceCompatibilityError : never; /** * @public * * Returns never unless a type includes undefine * d */ export declare type MustIncludeUndefined = undefined extends T ? T : never; /** * @public * * This is the general case - where there are two blocks that aren't passthrough blocks * it checks there input and output compatibility and either returns an error a direction * to recurse */ export declare type NonPassSequence[], TBefore extends readonly Block[], TInput, TOutput> = TSequence extends readonly [ infer First extends Block, ...infer Rest extends readonly Block[] ] ? BlockTypeIsCompatibleWithSequence, TInput> extends true ? DoRecurse, TOutput, Rest, [...TBefore, First]> : SequenceCompatibilityError : never; /** * Given a block, extract the output type * * @public */ export declare type OutputType> = ExtractOutput>; /** * @public * * Block output type without undefined */ export declare type OutputTypeKeepPromise> = ExtractOutput>; /** * @public * * Assign to the input and output paramters of a block to indicate a passthrough block */ export declare interface Pass { /** * Indicates that this really is a pass block */ __pass: 'pass'; } /** * @public * * Prettify a type */ export declare type Prettify = { [K in keyof T]: T[K]; } & {}; /** * @public * * Given a block, extract the input type */ export declare type RawInputType> = Parameters[0]['input']; /** * @public * * Sequence validator phase two - once all the checking has been done, iterate through the check results * and recurse back on the sequence validator if a recurse instruction is found */ export declare type RecurseSequence = TCheckOutput extends infer Error extends { __error: true; } ? Omit : TCheckOutput extends infer Recurse extends { __recurse: true; in: unknown; out: unknown; before: readonly Block[]; sequence: readonly Block[]; } ? SequenceValidatorRecursive : TCheckOutput; /** * @public * * Removes void from a union type, unless void is the only constituent of that type */ export declare type RemoveVoidIfNotOnlyVoid = Exclude extends never ? void : Exclude; /** * @public * * Sends a list of commands to a media remote * * @param target - The targeted remote * @param commands - A list of commands to send */ export declare const sendRemoteCommands: (target: ITarget, commands: string[]) => Block_2 | undefined, void>; /** * @public * * Block that takes a series of blocks and executes them either in sequence or * in parallel */ export declare const sequence: [], TInput = GetSequenceInput, TOutput = GetSequenceOutput>(...actions: BlockRetainType & TSequence & ValidateSequence) => Block; /** * @public * * An event that is emitted when a sequence is aborted for some reason */ export declare interface SequenceAborted extends LifeCycleEvent<'sequence-aborted'> { /** * The type of block that was aborted */ type: string; /** * A serialised version of the block that caused the sequence to be aborted */ block: IBlocksNode; /** * The name of the block that caused the sequence to be aborted */ name: string; } /** * @public * * Detail about a sequence compatibility issue */ export declare type SequenceCompatibilityError[], TBefore extends readonly Block[], TMessage extends string> = { message: TMessage; sequence: { input: TInput; output: TOutput; }; context: { head: TBefore; tail: TSequence; }; __error: true; }; /** * Validates a sequence of blocks recursively * * @public */ export declare type SequenceValidatorRecursive[], TBefore extends readonly Block[] = []> = TSequence extends [] ? TBefore : RecurseSequence>; /** * @public * * A specialised action block that will call a service on your configured Home Assistant * instance */ export declare const serviceCall:

(serviceConfig: { name: string; target?: ITarget; params: Omit, "id" | "type">; }) => Block | undefined, void>; /** * @public * * Arguments for a service call action */ export declare type ServiceCallArgs

= { target?: ITarget; params: Omit, 'id' | 'type' | 'target'>; }; /** * @public * * Match the input and outputs of a sequence containing a single, normal block */ export declare type SingleGeneralBlock[], TBefore extends readonly Block[], TInput, TOutput> = TSequence extends readonly [infer Only extends Block] ? BlockTypeIsCompatibleWithSequence, TInput> extends true ? BlockTypeIsCompatibleWithSequence, TOutput> extends true ? readonly [...TBefore, Only] : SequenceCompatibilityError : SequenceCompatibilityError : never; /** * @public * * If a sequence of length one is a pass block, just return it */ export declare type SinglePassBlock[], TBefore extends readonly Block[]> = TSequence extends readonly [infer Only extends Block] ? readonly [...TBefore, Only] : never; /** * @public * * An event that is emitted when the websocket client recieves a state change from Hass */ export declare interface StateChanged extends BaseHassBlocksEvent<'hass-state-changed'> { /** * The entity that changed state */ entity: string; /** * The raw event data from Home Assistant */ hassEvent: StateChangedEvent; } /** * @public * * An assertion that passes if an entity has a given state * * @param entityId - the target to get the state from * @param state - whether we want the state to be */ export declare const stateIs: (target: ITarget, state: string) => Block_2; /** * @public * * An assertion that passes if an entity does not have a given state * * @param target - the target to get the state from * @param state - whether we want the state to be */ export declare const stateIsNot: (target: ITarget, state: string) => Block_2; /** * @public * * Output returned when a block signals to stop */ export declare interface StopOutput { /** * Whether execution should continue */ continue: false; } /** * @public * * Configuration for switch entity. When 'create' is false, this simply * refers to an existing switch entity */ export declare interface SwitchConfig { /** * The entity id */ id: TId; /** * Whether or not to create the entity */ create: false; } /** * @public * * When the 'create' parameter is supplied as true, this entity * will try to create a new switch in Home Assisstant so long as there is * an initialised MQTT connection */ export declare interface SwitchConfigForCreation { /** * The entity id */ id: TId; /** * Whether or not to create the entity */ create: true; /** * The friendly name for the Entity in Home Assistant */ friendlyName: string; } /** * @public * * A switch entity * * @param config - switch config */ export declare function toggle(config: SwitchConfig | SwitchConfigForCreation): IEntity; /** * @public * * A switch entity * * @param id - An entity id */ export declare function toggle(id: TId): IEntity; /** * @public * * Associate the automation with a Home Assistant trigger. For more details, see {@link https://www.home-assistant.io/docs/automation/trigger/ | the Home Assistant docs} */ export declare const trigger: (config: ITriggerConfig) => ITrigger; /** * @public * * Matches a two‐element sequence where the *first* block is `Block`, * and the *second* is anything. This is a base case, so returns the final sequence */ export declare type TwoPassBlocks[], TBefore extends readonly Block[]> = TSequence extends readonly [ infer First extends Block, infer Next extends Block ] ? readonly [...TBefore, First, Next] : never; /** * Given an Input and Ouput type and an array of block types, this type * validates that they are a compatible sequence of blocks. * * So for input I, output O and blocks A and B, this type will produce compiler * errors unless I is compatible with A, A is compatible with B and B * is compatible with O * * @public */ export declare type ValidateSequence[], TBefore extends Block[] = []> = Prettify>; /** * @public * * An action that will cause a currently executing automation * to wait for a given number of minutes * * @param minutes - how many minutes to wait for */ export declare const waitMinutes: (minutes: number) => Block_2; /** * @public * * An action that will cause a currently executing automation * to wait for a given number of seconds * * @param minutes - how many minutes to wait for */ export declare const waitSeconds: (seconds: number) => Block_2; /** * @public * * Given an entity id and a state value, this block will pause * execution of a given sequence until the entity id has that state. * * @param target - The entity to monitor * @param state - The targeted state * @param timeout - Wait timeout */ export declare const waitUntilState: (target: ITarget, state: string, timeout?: number) => Block_2; /** * @public * * Given an entity id and a state value, this block will pause * execution of a given sequence until the entity id no * longer has that state * * @param target - The entity id to monitor * @param state - The targeted state * @param timeout - Wait timeout */ export declare const waitUntilStateIsNot: (target: ITarget, state: string, timeout?: number) => Block_2; /** * @public * * Use in combination with an {@link assertion} block to implement branching logic in your automations. * Supply two blocks and execute either one of them depending on the result of the assertion */ export declare const when: (assertion: IfThenElseConditionConfig["assertion"], config: Omit, "assertion" | "name">) => Block; export { }