import {z} from 'zod' export type GetApiMinionsOptions = {baseUrl: string, userAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const deviceStatus = z.object({battery: z.number().optional(), charging: z.boolean().optional()}); export const localNetworkDevice = z.object({name: z.string().optional(), mac: z.string(), vendor: z.string().optional(), ip: z.string().optional(), deviceStatus: deviceStatus.optional()}); export const minionDevice = z.object({pysicalDevice: localNetworkDevice, brand: z.string(), model: z.string(), token: z.string().optional(), deviceId: z.string().optional()}); 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 minionTypes = z.enum(["toggle", "switch", "temperatureSensor", "roller", "cleaner", "airConditioning", "light", "temperatureLight", "colorLight"]); export const calibrationMode = z.enum(["LOCK_ON", "LOCK_OFF", "SHABBAT", "AUTO", "LOCK_DASHBOARD"]); export const minionCalibrate = z.object({calibrationCycleMinutes: z.number().int().gte(0), calibrationMode: calibrationMode}); export const restrictionType = z.enum(["BLOCK", "READ", "WRITE"]); export const restrictionItem = z.object({userEmail: z.string(), restrictionType: restrictionType}); export const minion = z.object({minionId: z.string().optional(), name: z.string(), device: minionDevice, isProperlyCommunicated: z.boolean().optional(), minionStatus: minionStatus, minionType: minionTypes, minionAutoTurnOffMS: z.number().optional(), calibration: minionCalibrate.optional(), room: z.string().optional(), statusChangedTime: z.number().optional(), restrictions: z.array(restrictionItem).optional()}); export const getApiMinionsResponse = z.array(minion); 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 }; /** * Get all minions in the system. * * GET /minions * * Also accepts auth: adminAuth */ export const getApiMinions = async (options: GetApiMinionsOptions) => { const {baseUrl, fetch: fetchFn = fetch, userAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (userAuth !== undefined) headers.set("authentication", userAuth) const url = `${baseUrl.replace(/\/+$/, '')}/minions${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiMinionsResponse, await res.json()) };