Files
test/packages/schema/src/canvas/variable.ts
2026-04-08 21:26:18 +08:00

89 lines
2.6 KiB
TypeScript

/**
* 变量绑定 Schema
* 定义变量和绑定相关类型
*/
import { z } from 'zod'
// ============================================
// 变量类型
// ============================================
/**
* 变量值类型
*/
export const variableValueTypeSchema = z.enum([
'analog', // 模拟量(数值)
'digital', // 数字量(布尔)
'string', // 字符串
'enum', // 枚举
])
export type VariableValueType = z.infer<typeof variableValueTypeSchema>
/**
* 变量定义 Schema
*/
export const variableSchema = z.object({
name: z.string().min(1, '变量名不能为空').describe('变量名'),
type: variableValueTypeSchema.describe('变量类型'),
description: z.string().optional().describe('变量描述'),
unit: z.string().optional().describe('单位'),
source: z.enum(['dynamic_project', 'manual', 'calculated']).optional().describe('数据来源'),
sourceId: z.string().optional().describe('来源 ID'),
defaultValue: z.unknown().optional().describe('默认值'),
})
export type Variable = z.infer<typeof variableSchema>
// ============================================
// 变量绑定
// ============================================
/**
* 绑定表达式 Schema
* 支持直接绑定变量名或计算表达式
*/
export const bindingExpressionSchema = z.object({
id: z.string().optional().describe('绑定规则 ID'),
type: z.enum(['variable', 'expression']).describe('绑定类型'),
value: z.string().describe('变量名或表达式'),
variables: z.array(z.string()).optional().describe('表达式中引用的变量列表'),
priority: z.number().optional().describe('权重,数值越大优先级越高'),
enabled: z.boolean().optional().describe('是否启用该绑定规则'),
})
export type BindingExpression = z.infer<typeof bindingExpressionSchema>
/**
* 组件变量绑定 Schema
*/
export const componentBindingsSchema = z.record(
z.string(), // 绑定属性名
z.union([
z.string(), // 简单绑定:直接使用变量名
bindingExpressionSchema, // 复杂绑定:表达式
z.array(z.union([
z.string(),
bindingExpressionSchema,
])).describe('同一属性的多条绑定规则'),
]),
)
export type ComponentBindings = z.infer<typeof componentBindingsSchema>
// ============================================
// 变量值(运行时)
// ============================================
/**
* 变量快照 Schema
*/
export const variableSnapshotSchema = z.object({
name: z.string(),
value: z.unknown(),
quality: z.enum(['good', 'bad', 'uncertain']).optional(),
timestamp: z.string().datetime().optional(),
})
export type VariableSnapshot = z.infer<typeof variableSnapshotSchema>