All files / dingtalk-openclaw-connector/src/sdk helpers.ts

8.98% Statements 15/167
100% Branches 0/0
0% Functions 0/14
8.98% Lines 15/167

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318                              1x         1x                             1x                                     1x                                   1x                                                               1x                                         1x                                                                                                         1x                       1x                                                 1x                                                 1x                                                                           1x                             1x             1x                     1x            
/**
 * DingTalk Connector SDK Helpers
 * 
 * 完全独立的辅助函数,不依赖任何外部 SDK。
 */
 
import type { SecretInput, SecretInputRef } from "./types/index.ts";
 
// ============================================================================
// 账号 ID 处理
// ============================================================================
 
/**
 * 默认账号 ID
 */
export const DEFAULT_ACCOUNT_ID = "default" as const;
 
/**
 * 规范化账号 ID
 */
export function normalizeAccountId(accountId: string): string {
  const trimmed = accountId.trim().toLowerCase();
  if (trimmed === "default" || trimmed === "") {
    return DEFAULT_ACCOUNT_ID;
  }
  return trimmed;
}
 
// ============================================================================
// SecretInput 处理
// ============================================================================
 
/**
 * 判断是否为 SecretInput 引用
 */
export function isSecretInputRef(value: unknown): value is SecretInputRef {
  if (!value || typeof value !== "object") {
    return false;
  }
  const ref = value as SecretInputRef;
  return (
    typeof ref.source === "string" &&
    ["env", "file", "exec"].includes(ref.source) &&
    typeof ref.provider === "string" &&
    ref.provider.length > 0 &&
    typeof ref.id === "string" &&
    ref.id.length > 0
  );
}
 
/**
 * 规范化 SecretInput 字符串
 * 用于显示和日志,会隐藏敏感信息
 */
export function normalizeSecretInputString(value: unknown): string | undefined {
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed || undefined;
  }
  
  if (isSecretInputRef(value)) {
    const ref = value as SecretInputRef;
    return `<${ref.source}:${ref.provider}:${ref.id}>`;
  }
  
  return undefined;
}
 
/**
 * 解析 SecretInput 为实际值
 * 用于运行时获取实际的敏感信息
 */
export function resolveSecretInputValue(
  value: unknown,
  options?: { allowEnvRead?: boolean },
): string | undefined {
  // 直接字符串
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed || undefined;
  }
  
  // SecretInput 引用
  if (isSecretInputRef(value)) {
    const ref = value as SecretInputRef;
    
    // 环境变量
    if (ref.source === "env" && options?.allowEnvRead) {
      const envValue = process.env[ref.id];
      if (typeof envValue === "string") {
        return envValue.trim() || undefined;
      }
    }
    
    // 文件或执行 - 返回引用字符串
    return `<${ref.source}:${ref.provider}:${ref.id}>`;
  }
  
  return undefined;
}
 
/**
 * 检查 SecretInput 是否已配置
 */
export function hasConfiguredSecretInput(value: unknown): boolean {
  if (typeof value === "string") {
    return value.trim().length > 0;
  }
  
  if (isSecretInputRef(value)) {
    const ref = value as SecretInputRef;
    if (ref.source === "env") {
      return typeof process.env[ref.id] === "string" && process.env[ref.id]!.trim().length > 0;
    }
    // file 和 exec 总是认为已配置(运行时会验证)
    return true;
  }
  
  return false;
}
 
/**
 * 规范化已解析的 SecretInput 字符串
 * 用于配置验证和错误提示
 */
export function normalizeResolvedSecretInputString(params: {
  value: unknown;
  path: string;
}): string | undefined {
  const { value, path } = params;
  
  // 直接字符串
  if (typeof value === "string") {
    const trimmed = value.trim();
    if (trimmed) {
      return trimmed;
    }
    throw new Error(`${path} must be a non-empty string`);
  }
  
  // SecretInput 引用
  if (isSecretInputRef(value)) {
    const ref = value as SecretInputRef;
    
    // 验证引用格式
    if (!["env", "file", "exec"].includes(ref.source)) {
      throw new Error(`${path}.source must be one of: env, file, exec`);
    }
    if (typeof ref.provider !== "string" || !ref.provider.trim()) {
      throw new Error(`${path}.provider must be a non-empty string`);
    }
    if (typeof ref.id !== "string" || !ref.id.trim()) {
      throw new Error(`${path}.id must be a non-empty string`);
    }
    
    // 环境变量特殊处理
    if (ref.source === "env") {
      const envValue = process.env[ref.id];
      if (!envValue || !envValue.trim()) {
        throw new Error(`${path}: environment variable ${ref.id} is not set`);
      }
      return envValue.trim();
    }
    
    // file 和 exec 返回引用字符串
    return `<${ref.source}:${ref.provider}:${ref.id}>`;
  }
  
  throw new Error(`${path} must be a string or SecretInput object`);
}
 
// ============================================================================
// 群组策略处理
// ============================================================================
 
/**
 * 解析默认群组策略
 */
export function resolveDefaultGroupPolicy(cfg: {
  channels?: { [key: string]: unknown };
}): "open" | "allowlist" | "disabled" {
  const dingtalkCfg = cfg.channels?.["dingtalk-connector"] as {
    groupPolicy?: "open" | "allowlist" | "disabled";
  } | undefined;
  return dingtalkCfg?.groupPolicy ?? "open";
}
 
/**
 * 解析允许列表提供者运行时群组策略
 */
export function resolveAllowlistProviderRuntimeGroupPolicy(params: {
  providerConfigPresent: boolean;
  groupPolicy?: "open" | "allowlist" | "disabled";
  defaultGroupPolicy: "open" | "allowlist" | "disabled";
}): { groupPolicy: "open" | "allowlist" | "disabled" } {
  const { providerConfigPresent, groupPolicy, defaultGroupPolicy } = params;
  
  if (groupPolicy) {
    return { groupPolicy };
  }
  
  if (providerConfigPresent) {
    return { groupPolicy: defaultGroupPolicy };
  }
  
  return { groupPolicy: "disabled" };
}
 
// ============================================================================
// 通道状态处理
// ============================================================================
 
/**
 * 创建默认通道运行时状态
 */
export function createDefaultChannelRuntimeState(
  accountId: string,
  extras?: Record<string, unknown>,
): {
  running: boolean;
  lastStartAt: string | null;
  lastStopAt: string | null;
  lastError: string | null;
  port: number | null;
  accountId: string;
} {
  return {
    running: false,
    lastStartAt: null,
    lastStopAt: null,
    lastError: null,
    port: null,
    accountId,
    ...extras,
  };
}
 
/**
 * 构建基础通道状态摘要
 */
export function buildBaseChannelStatusSummary(snapshot: {
  accountId: string;
  enabled: boolean;
  configured: boolean;
  name?: string;
  running?: boolean;
  lastStartAt?: string | null;
  lastStopAt?: string | null;
  lastError?: string | null;
}): {
  accountId: string;
  enabled: boolean;
  configured: boolean;
  name?: string;
  running: boolean;
  lastStartAt: string | null;
  lastStopAt: string | null;
  lastError: string | null;
} {
  return {
    accountId: snapshot.accountId,
    enabled: snapshot.enabled,
    configured: snapshot.configured,
    name: snapshot.name,
    running: snapshot.running ?? false,
    lastStartAt: snapshot.lastStartAt ?? null,
    lastStopAt: snapshot.lastStopAt ?? null,
    lastError: snapshot.lastError ?? null,
  };
}
 
// ============================================================================
// 其他辅助函数
// ============================================================================
 
/**
 * 添加通配符到 allowFrom
 */
export function addWildcardAllowFrom(
  existing?: (string | number)[],
): (string | number)[] {
  if (!existing || existing.length === 0) {
    return ["*"];
  }
  if (existing.includes("*")) {
    return existing;
  }
  return [...existing, "*"];
}
 
/**
 * 格式化文档链接
 */
export function formatDocsLink(path: string, label: string): string {
  return `https://docs.openclaw.ai${path}`;
}
 
/**
 * 规范化字符串
 */
export function normalizeString(value: unknown): string | undefined {
  if (typeof value !== "string") {
    return undefined;
  }
  const trimmed = value.trim();
  return trimmed || undefined;
}
 
/**
 * 解析 allowFrom 输入
 */
export function parseAllowFromInput(raw: string): string[] {
  return raw
    .split(/[\n,;]+/g)
    .map((entry) => entry.trim())
    .filter(Boolean);
}