All files / dingtalk-openclaw-connector/src/config accounts.ts

70.07% Statements 96/137
25.71% Branches 9/35
81.81% Functions 9/11
70.07% Lines 96/137

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 2241x                       16x 16x 16x 16x 16x               1x 16x 16x   16x 16x             1x     16x 16x 16x 16x           16x 16x 16x 16x 16x 16x 16x     16x 16x 16x         1x             16x 16x 16x 16x 16x 16x 16x 16x               16x 16x     16x     16x     16x 16x                               1x 16x 16x       16x 16x 32x     32x     32x 32x 32x   16x 32x 32x 32x 32x       32x                       32x       32x   16x 16x   16x     16x 16x 16x 16x 16x         1x     16x 16x 16x 16x   16x 16x   16x 16x   16x 16x     16x     16x     16x 16x     16x 16x   16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x         1x          
import { DEFAULT_ACCOUNT_ID, normalizeAccountId , normalizeResolvedSecretInputString, normalizeSecretInputString } from "../sdk/helpers.ts";
import type { ClawdbotConfig } from "openclaw/plugin-sdk";
import type {
  DingtalkConfig,
  DingtalkAccountConfig,
  DingtalkDefaultAccountSelectionSource,
  ResolvedDingtalkAccount,
} from "../types/index.ts";
 
/**
 * List all configured account IDs from the accounts field.
 */
function listConfiguredAccountIds(cfg: ClawdbotConfig): string[] {
  const accounts = (cfg.channels?.["dingtalk-connector"] as DingtalkConfig)?.accounts;
  if (!accounts || typeof accounts !== "object") {
    return [];
  }
  return Object.keys(accounts).filter(Boolean);
}
 
/**
 * List all DingTalk account IDs.
 * If no accounts are configured, returns [DEFAULT_ACCOUNT_ID] for backward compatibility.
 */
export function listDingtalkAccountIds(cfg: ClawdbotConfig): string[] {
  const ids = listConfiguredAccountIds(cfg);
  if (ids.length === 0) {
    // Backward compatibility: no accounts configured, use default
    return [DEFAULT_ACCOUNT_ID];
  }
  return [...ids].toSorted((a, b) => a.localeCompare(b));
}
 
/**
 * Resolve the default account selection and its source.
 */
export function resolveDefaultDingtalkAccountSelection(cfg: ClawdbotConfig): {
  accountId: string;
  source: DingtalkDefaultAccountSelectionSource;
} {
  const preferredRaw = (cfg.channels?.["dingtalk-connector"] as DingtalkConfig | undefined)?.defaultAccount?.trim();
  const preferred = preferredRaw ? normalizeAccountId(preferredRaw) : undefined;
  if (preferred) {
    return {
      accountId: preferred,
      source: "explicit-default",
    };
  }
  const ids = listDingtalkAccountIds(cfg);
  if (ids.includes(DEFAULT_ACCOUNT_ID)) {
    return {
      accountId: DEFAULT_ACCOUNT_ID,
      source: "mapped-default",
    };
  }
  return {
    accountId: ids[0] ?? DEFAULT_ACCOUNT_ID,
    source: "fallback",
  };
}
 
/**
 * Resolve the default account ID.
 */
export function resolveDefaultDingtalkAccountId(cfg: ClawdbotConfig): string {
  return resolveDefaultDingtalkAccountSelection(cfg).accountId;
}
 
/**
 * Get the raw account-specific config.
 */
function resolveAccountConfig(
  cfg: ClawdbotConfig,
  accountId: string,
): DingtalkAccountConfig | undefined {
  const accounts = (cfg.channels?.["dingtalk-connector"] as DingtalkConfig)?.accounts;
  if (!accounts || typeof accounts !== "object") {
    return undefined;
  }
  return accounts[accountId];
}
 
/**
 * Merge top-level config with account-specific config.
 * Account-specific fields override top-level fields.
 */
function mergeDingtalkAccountConfig(cfg: ClawdbotConfig, accountId: string): DingtalkConfig {
  const dingtalkCfg = cfg.channels?.["dingtalk-connector"] as DingtalkConfig | undefined;
 
  // Extract base config (exclude accounts field to avoid recursion)
  const { accounts: _ignored, defaultAccount: _ignoredDefaultAccount, ...base } = dingtalkCfg ?? {};
 
  // Get account-specific overrides
  const account = resolveAccountConfig(cfg, accountId) ?? {};
 
  // Merge: account config overrides base config
  return { ...base, ...account } as DingtalkConfig;
}
 
/**
 * Resolve DingTalk credentials from a config.
 */
export function resolveDingtalkCredentials(cfg?: DingtalkConfig): {
  clientId: string;
  clientSecret: string;
} | null;
export function resolveDingtalkCredentials(
  cfg: DingtalkConfig | undefined,
  options: { allowUnresolvedSecretRef?: boolean },
): {
  clientId: string;
  clientSecret: string;
} | null;
export function resolveDingtalkCredentials(
  cfg?: DingtalkConfig,
  options?: { allowUnresolvedSecretRef?: boolean },
): {
  clientId: string;
  clientSecret: string;
} | null {
  const normalizeString = (value: unknown): string | undefined => {
    if (typeof value === "number") {
      return String(value);
    }
    if (typeof value !== "string") {
      return undefined;
    }
    const trimmed = value.trim();
    return trimmed ? trimmed : undefined;
  };
 
  const resolveSecretLike = (value: unknown, path: string): string | undefined => {
    const asString = normalizeString(value);
    if (asString) {
      return asString;
    }
 
    // In relaxed/onboarding paths only: allow direct env SecretRef reads for UX.
    // Default resolution path must preserve unresolved-ref diagnostics/policy semantics.
    if (options?.allowUnresolvedSecretRef && typeof value === "object" && value !== null) {
      const rec = value as Record<string, unknown>;
      const source = normalizeString(rec.source)?.toLowerCase();
      const id = normalizeString(rec.id);
      if (source === "env" && id) {
        const envValue = normalizeString(process.env[id]);
        if (envValue) {
          return envValue;
        }
      }
    }
 
    if (options?.allowUnresolvedSecretRef) {
      return normalizeSecretInputString(value);
    }
    return normalizeResolvedSecretInputString({ value, path });
  };
 
  const clientId = resolveSecretLike(cfg?.clientId, "channels.dingtalk-connector.clientId");
  const clientSecret = resolveSecretLike(cfg?.clientSecret, "channels.dingtalk-connector.clientSecret");
 
  if (!clientId || !clientSecret) {
    return null;
  }
  return {
    clientId,
    clientSecret,
  };
}
 
/**
 * Resolve a complete DingTalk account with merged config.
 */
export function resolveDingtalkAccount(params: {
  cfg: ClawdbotConfig;
  accountId?: string | null;
}): ResolvedDingtalkAccount {
  const hasExplicitAccountId =
    typeof params.accountId === "string" && params.accountId.trim() !== "";
  const defaultSelection = hasExplicitAccountId
    ? null
    : resolveDefaultDingtalkAccountSelection(params.cfg);
  const accountId = hasExplicitAccountId
    ? normalizeAccountId(params.accountId ?? "")
    : (defaultSelection?.accountId ?? DEFAULT_ACCOUNT_ID);
  const selectionSource = hasExplicitAccountId
    ? "explicit"
    : (defaultSelection?.source ?? "fallback");
  const dingtalkCfg = params.cfg.channels?.["dingtalk-connector"] as DingtalkConfig | undefined;
 
  // Base enabled state (top-level)
  const baseEnabled = dingtalkCfg?.enabled !== false;
 
  // Merge configs
  const merged = mergeDingtalkAccountConfig(params.cfg, accountId);
 
  // Account-level enabled state
  const accountEnabled = merged.enabled !== false;
  const enabled = baseEnabled && accountEnabled;
 
  // Resolve credentials from merged config
  const creds = resolveDingtalkCredentials(merged);
  const accountName = (merged as DingtalkAccountConfig).name;
 
  return {
    accountId,
    selectionSource,
    enabled,
    configured: Boolean(creds),
    name: typeof accountName === "string" ? accountName.trim() || undefined : undefined,
    clientId: creds?.clientId,
    clientSecret: creds?.clientSecret,
    config: merged,
  };
}
 
/**
 * List all enabled and configured accounts.
 */
export function listEnabledDingtalkAccounts(cfg: ClawdbotConfig): ResolvedDingtalkAccount[] {
  return listDingtalkAccountIds(cfg)
    .map((accountId) => resolveDingtalkAccount({ cfg, accountId }))
    .filter((account) => account.enabled && account.configured);
}