export type ExtendProviderCredential = { apiKey?: string | null; updatedAt?: Date | string | null; }; export type ExtendProvider = "vip98k" | "dashscope" | "fal"; export function resolveFalExtendApiKey(providers: Array) { for (const { apiKey, baseUrl } of providers) { if (!apiKey || !baseUrl) continue; const url = URL.canParse(baseUrl) ? new URL(baseUrl) : null; if (url?.protocol === "https:" && ["queue.fal.run", "fal.run", "fal.ai", "api.fal.ai"].includes(url.hostname)) { return apiKey.trim().replace(/^(?:Bearer|Key)\s+/i, ""); } } return null; } function getUpdatedAtTimestamp(value: Date | string | null | undefined): number { if (!value) return 0; const timestamp = value instanceof Date ? value.getTime() : Date.parse(value); return Number.isFinite(timestamp) ? timestamp : 0; } export function resolveAlibabaExtendApiKey( providers: ExtendProviderCredential[], legacyApiKey?: string | null, ): string | null { const currentProvider = providers .filter((provider) => Boolean(provider.apiKey?.trim())) .sort( (left, right) => getUpdatedAtTimestamp(right.updatedAt) - getUpdatedAtTimestamp(left.updatedAt), )[0]; return currentProvider?.apiKey?.trim() || legacyApiKey?.trim() || null; }