import {z} from 'zod' export type CalculatedFieldId = {id: string, entityType: 'CALCULATED_FIELD'}; export type TenantId = {id: string, entityType: 'TENANT'}; export type EntityId = {id: string, entityType: 'TENANT' | 'CUSTOMER' | 'USER' | 'DASHBOARD' | 'ASSET' | 'DEVICE' | 'ALARM' | 'RULE_CHAIN' | 'RULE_NODE' | 'ENTITY_VIEW' | 'WIDGETS_BUNDLE' | 'WIDGET_TYPE' | 'TENANT_PROFILE' | 'DEVICE_PROFILE' | 'ASSET_PROFILE' | 'API_USAGE_STATE' | 'TB_RESOURCE' | 'OTA_PACKAGE' | 'EDGE' | 'RPC' | 'QUEUE' | 'NOTIFICATION_TARGET' | 'NOTIFICATION_TEMPLATE' | 'NOTIFICATION_REQUEST' | 'NOTIFICATION' | 'NOTIFICATION_RULE' | 'QUEUE_STATS' | 'OAUTH2_CLIENT' | 'DOMAIN' | 'MOBILE_APP' | 'MOBILE_APP_BUNDLE' | 'CALCULATED_FIELD' | 'JOB' | 'ADMIN_SETTINGS' | 'AI_MODEL' | 'API_KEY'}; export type DebugSettings = {failuresEnabled?: boolean | undefined, allEnabled?: boolean | undefined, allEnabledUntil?: number | undefined}; export type CurrentOwnerDynamicSourceConfiguration = {type: string}; export type RelationPathLevel = {direction: 'FROM' | 'TO', relationType: string}; export type RelationPathQueryDynamicSourceConfiguration = {type: string, levels?: Array | undefined}; export type ReferencedEntityKey = {key?: string | undefined, type?: ('TS_LATEST' | 'ATTRIBUTE' | 'TS_ROLLING') | undefined, scope?: ('CLIENT_SCOPE' | 'SERVER_SCOPE' | 'SHARED_SCOPE') | undefined}; export type Argument = {refEntityId?: EntityId | undefined, refDynamicSourceConfiguration?: (CurrentOwnerDynamicSourceConfiguration | RelationPathQueryDynamicSourceConfiguration) | undefined, refEntityKey?: ReferencedEntityKey | undefined, defaultValue?: string | undefined, limit?: number | undefined, timeWindow?: number | undefined}; export type AttributesImmediateOutputStrategy = {type: string, sendAttributesUpdatedNotification?: boolean | undefined, updateAttributesOnlyOnValueChange?: boolean | undefined, saveAttribute?: boolean | undefined, sendWsUpdate?: boolean | undefined, processCfs?: boolean | undefined}; export type AttributesRuleChainOutputStrategy = {type: string}; export type AttributesOutput = {name?: string | undefined, scope?: ('CLIENT_SCOPE' | 'SERVER_SCOPE' | 'SHARED_SCOPE') | undefined, decimalsByDefault?: number | undefined, strategy?: (AttributesImmediateOutputStrategy | AttributesRuleChainOutputStrategy) | undefined, type: string}; export type TimeSeriesImmediateOutputStrategy = {type: string, ttl?: number | undefined, saveTimeSeries?: boolean | undefined, saveLatest?: boolean | undefined, sendWsUpdate?: boolean | undefined, processCfs?: boolean | undefined}; export type TimeSeriesRuleChainOutputStrategy = {type: string}; export type TimeSeriesOutput = {name?: string | undefined, scope?: ('CLIENT_SCOPE' | 'SERVER_SCOPE' | 'SHARED_SCOPE') | undefined, decimalsByDefault?: number | undefined, strategy?: (TimeSeriesImmediateOutputStrategy | TimeSeriesRuleChainOutputStrategy) | undefined, type: string}; export type SimpleCalculatedFieldConfiguration = {arguments: {[key: string]: Argument}, expression?: string | undefined, output: AttributesOutput | TimeSeriesOutput, useLatestTs?: boolean | undefined}; export type CalculatedField = {id?: CalculatedFieldId | undefined, createdTime?: number | undefined, tenantId?: TenantId | undefined, entityId?: EntityId | undefined, type?: ('SIMPLE' | 'SCRIPT' | 'GEOFENCING' | 'ALARM' | 'PROPAGATION' | 'RELATED_ENTITIES_AGGREGATION' | 'ENTITY_AGGREGATION') | undefined, name?: string | undefined, debugMode?: boolean | undefined, debugSettings?: DebugSettings | undefined, configurationVersion?: number | undefined, configuration: SimpleCalculatedFieldConfiguration, version?: number | undefined}; export type CreateApiApiCalculatedFieldArgs = {body: CalculatedField}; export type CreateApiApiCalculatedFieldOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const calculatedFieldId = z.object({id: z.string(), entityType: z.literal("CALCULATED_FIELD")}); export const tenantId = z.object({id: z.string(), entityType: z.literal("TENANT")}); export const entityId = z.object({id: z.string(), entityType: z.enum(["TENANT", "CUSTOMER", "USER", "DASHBOARD", "ASSET", "DEVICE", "ALARM", "RULE_CHAIN", "RULE_NODE", "ENTITY_VIEW", "WIDGETS_BUNDLE", "WIDGET_TYPE", "TENANT_PROFILE", "DEVICE_PROFILE", "ASSET_PROFILE", "API_USAGE_STATE", "TB_RESOURCE", "OTA_PACKAGE", "EDGE", "RPC", "QUEUE", "NOTIFICATION_TARGET", "NOTIFICATION_TEMPLATE", "NOTIFICATION_REQUEST", "NOTIFICATION", "NOTIFICATION_RULE", "QUEUE_STATS", "OAUTH2_CLIENT", "DOMAIN", "MOBILE_APP", "MOBILE_APP_BUNDLE", "CALCULATED_FIELD", "JOB", "ADMIN_SETTINGS", "AI_MODEL", "API_KEY"])}); export const debugSettings = z.object({failuresEnabled: z.boolean().optional(), allEnabled: z.boolean().optional(), allEnabledUntil: z.number().int().optional()}); export const currentOwnerDynamicSourceConfiguration = z.object({type: z.string()}); export const relationPathLevel = z.object({direction: z.enum(["FROM", "TO"]), relationType: z.string().min(1)}); export const relationPathQueryDynamicSourceConfiguration = z.object({type: z.string(), levels: z.array(relationPathLevel).optional()}); export const referencedEntityKey = z.object({key: z.string().optional(), type: z.enum(["TS_LATEST", "ATTRIBUTE", "TS_ROLLING"]).optional(), scope: z.enum(["CLIENT_SCOPE", "SERVER_SCOPE", "SHARED_SCOPE"]).optional()}); export const argument = z.object({refEntityId: entityId.optional(), refDynamicSourceConfiguration: z.union([currentOwnerDynamicSourceConfiguration, relationPathQueryDynamicSourceConfiguration]).optional(), refEntityKey: referencedEntityKey.optional(), defaultValue: z.string().optional(), limit: z.number().int().optional(), timeWindow: z.number().int().optional()}); export const attributesImmediateOutputStrategy = z.object({type: z.string(), sendAttributesUpdatedNotification: z.boolean().optional(), updateAttributesOnlyOnValueChange: z.boolean().optional(), saveAttribute: z.boolean().optional(), sendWsUpdate: z.boolean().optional(), processCfs: z.boolean().optional()}); export const attributesRuleChainOutputStrategy = z.object({type: z.string()}); export const attributesOutput = z.object({name: z.string().optional(), scope: z.enum(["CLIENT_SCOPE", "SERVER_SCOPE", "SHARED_SCOPE"]).optional(), decimalsByDefault: z.number().int().optional(), strategy: z.union([attributesImmediateOutputStrategy, attributesRuleChainOutputStrategy]).optional(), type: z.string()}); export const timeSeriesImmediateOutputStrategy = z.object({type: z.string(), ttl: z.number().int().optional(), saveTimeSeries: z.boolean().optional(), saveLatest: z.boolean().optional(), sendWsUpdate: z.boolean().optional(), processCfs: z.boolean().optional()}); export const timeSeriesRuleChainOutputStrategy = z.object({type: z.string()}); export const timeSeriesOutput = z.object({name: z.string().optional(), scope: z.enum(["CLIENT_SCOPE", "SERVER_SCOPE", "SHARED_SCOPE"]).optional(), decimalsByDefault: z.number().int().optional(), strategy: z.union([timeSeriesImmediateOutputStrategy, timeSeriesRuleChainOutputStrategy]).optional(), type: z.string()}); export const simpleCalculatedFieldConfiguration = z.object({arguments: z.record(z.string(), argument), expression: z.string().optional(), output: z.union([attributesOutput, timeSeriesOutput]), useLatestTs: z.boolean().optional()}); export const calculatedField = z.object({id: calculatedFieldId.optional(), createdTime: z.number().int().optional(), tenantId: tenantId.optional(), entityId: entityId.optional(), type: z.enum(["SIMPLE", "SCRIPT", "GEOFENCING", "ALARM", "PROPAGATION", "RELATED_ENTITIES_AGGREGATION", "ENTITY_AGGREGATION"]).optional(), name: z.string().optional(), debugMode: z.boolean().optional(), debugSettings: debugSettings.optional(), configurationVersion: z.number().int().optional(), configuration: simpleCalculatedFieldConfiguration, version: z.number().int().optional()}); 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 }; /** * Create Or Update Calculated Field (saveCalculatedField) * * POST /api/calculatedField */ export const createApiApiCalculatedField = async (args: CreateApiApiCalculatedFieldArgs, options?: CreateApiApiCalculatedFieldOptions) => { const {baseUrl = "https://demo.thingsboard.io", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/api/calculatedField${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(calculatedField, await res.json()) };