import {z} from 'zod' export type SwitchOptions = 'on' | 'off'; export type Toggle = {status: SwitchOptions}; export type Switch = {status: SwitchOptions}; export type RollerDirection = 'up' | 'down'; export type Roller = {status: SwitchOptions, direction: RollerDirection}; export type CleanerMode = 'dock' | 'clean'; export type FanStrengthOptions = 'low' | 'med' | 'high' | 'auto'; export type Cleaner = {status: SwitchOptions, mode: CleanerMode, fanSpeed: FanStrengthOptions}; export type ACModeOptions = 'hot' | 'cold' | 'dry' | 'auto'; export type AirConditioning = {status: SwitchOptions, temperature: number, mode: ACModeOptions, fanStrength: FanStrengthOptions}; export type Light = {status: SwitchOptions, brightness: number}; export type TemperatureLight = {status: SwitchOptions, brightness: number, temperature: number}; export type ColorLight = {status: SwitchOptions, brightness: number, temperature: number, red: number, green: number, blue: number}; export type TemperatureSensor = {status: SwitchOptions, temperature: number}; export type MinionStatus = {toggle?: Toggle | undefined, switch?: Switch | undefined, roller?: Roller | undefined, cleaner?: Cleaner | undefined, airConditioning?: AirConditioning | undefined, light?: Light | undefined, temperatureLight?: TemperatureLight | undefined, colorLight?: ColorLight | undefined, temperatureSensor?: TemperatureSensor | undefined}; export type ActionSet = {minionId: string, setStatus: MinionStatus}; export type ActionApply = 'statusChange' | 'permanent'; export type Action = {actionId: string, minionId: string, active: boolean, name?: string | undefined, ifStatus: MinionStatus, thenSet: Array, apply: ActionApply}; export type CreateApiActionsArgs = {body: Action}; export type CreateApiActionsOptions = {baseUrl: string, userAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const switchOptions = z.enum(["on", "off"]); export const toggle = z.object({status: switchOptions}); export const switch = z.object({status: switchOptions}); export const rollerDirection = z.enum(["up", "down"]); export const roller = z.object({status: switchOptions, direction: rollerDirection}); export const cleanerMode = z.enum(["dock", "clean"]); export const fanStrengthOptions = z.enum(["low", "med", "high", "auto"]); export const cleaner = z.object({status: switchOptions, mode: cleanerMode, fanSpeed: fanStrengthOptions}); export const aCModeOptions = z.enum(["hot", "cold", "dry", "auto"]); export const airConditioning = z.object({status: switchOptions, temperature: z.number().int().gte(16).lte(30), mode: aCModeOptions, fanStrength: fanStrengthOptions}); export const light = z.object({status: switchOptions, brightness: z.number().int().gte(1).lte(100)}); export const temperatureLight = z.object({status: switchOptions, brightness: z.number().int().gte(1).lte(100), temperature: z.number().int().gte(1).lte(100)}); export const colorLight = z.object({status: switchOptions, brightness: z.number().int().gte(1).lte(100), temperature: z.number().int().gte(1).lte(100), red: z.number().int().gte(0).lte(255), green: z.number().int().gte(0).lte(255), blue: z.number().int().gte(0).lte(255)}); export const temperatureSensor = z.object({status: switchOptions, temperature: z.number()}); export const minionStatus = z.object({toggle: toggle.optional(), switch: switch.optional(), roller: roller.optional(), cleaner: cleaner.optional(), airConditioning: airConditioning.optional(), light: light.optional(), temperatureLight: temperatureLight.optional(), colorLight: colorLight.optional(), temperatureSensor: temperatureSensor.optional()}); export const actionSet = z.object({minionId: z.string(), setStatus: minionStatus}); export const actionApply = z.enum(["statusChange", "permanent"]); export const action = z.object({actionId: z.string(), minionId: z.string(), active: z.boolean(), name: z.string().optional(), ifStatus: minionStatus, thenSet: z.array(actionSet), apply: actionApply}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Creates a new action. * * POST /actions * * Also accepts auth: adminAuth */ export const createApiActions = async (args: CreateApiActionsArgs, options: CreateApiActionsOptions) => { const {baseUrl, fetch: fetchFn = fetch, userAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (userAuth !== undefined) headers.set("authentication", userAuth) const url = `${baseUrl.replace(/\/+$/, '')}/actions${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(action, await res.json()) };