import { Message } from '@aigxion/isdk' import { clsx, type ClassValue } from 'clsx' import { customAlphabet } from 'nanoid' import { twMerge } from 'tailwind-merge' export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } export const nanoid = customAlphabet( '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 7 ) // 7-character random string export function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } export function pause(duration: number): Promise { return new Promise((res) => setTimeout(res, duration * 1000)); } export function truncateString(str: string, maxLength?: number): string { const length = maxLength || 100; // 如果没有传入 maxLength 参数,则默认为 100 if (str.length > length) { // return str.substring(0, 100) + '...'; return str.substring(0, length); } else { return str; } } export async function fetcher( input: RequestInfo, init?: RequestInit ): Promise { const res = await fetch(input, init) if (!res.ok) { const json = await res.json() if (json.error) { const error = new Error(json.error) as Error & { status: number } error.status = res.status throw error } else { throw new Error('An unexpected error occurred') } } return res.json() } export function formatDate(input: string | number | Date): string { const date = new Date(Number(input)) return date.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) } export function isValidEmail(email: string): boolean { const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ return regex.test(email) } export function filterMessages(messages: Message[]): Message[] { return messages.filter( message => message.role !== 'system' && message.role !== 'function' ) } export const formatNumber = (value: number) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(value) export const runAsyncFnWithoutBlocking = ( fn: (...args: any) => Promise ) => { fn() } export const getStringFromBuffer = (buffer: ArrayBuffer) => Array.from(new Uint8Array(buffer)) .map(b => b.toString(16).padStart(2, '0')) .join('') export enum ResultCode { InvalidCredentials = 'INVALID_CREDENTIALS', InvalidSubmission = 'INVALID_SUBMISSION', UserAlreadyExists = 'USER_ALREADY_EXISTS', UnknownError = 'UNKNOWN_ERROR', UserCreated = 'USER_CREATED', UserLoggedIn = 'USER_LOGGED_IN' } export const getMessageFromCode = (resultCode: string) => { switch (resultCode) { case ResultCode.InvalidCredentials: return 'Invalid credentials!' case ResultCode.InvalidSubmission: return 'Invalid submission, please try again!' case ResultCode.UserAlreadyExists: return 'User already exists, please log in!' case ResultCode.UserCreated: return 'User created, welcome!' case ResultCode.UnknownError: return 'Something went wrong, please try again!' case ResultCode.UserLoggedIn: return 'Logged in!' } }