Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

7.2 KB
Raw Blame
import { deepmerge } from 'deepmerge-ts'

export function isString(str: unknown): str is string {
    return str != null && typeof str === 'string'
}

export function truncateString({ value, maxLength, suffix = '…' }: { value: string, maxLength: number, suffix?: string }): string {
    if (value.length <= maxLength) {
        return value
    }
    let end = maxLength
    const lastKeptCodeUnit = value.charCodeAt(end - 1)
    const splitsSurrogatePair = lastKeptCodeUnit >= 0xD800 && lastKeptCodeUnit <= 0xDBFF
    if (splitsSurrogatePair) {
        end -= 1
    }
    return value.slice(0, end) + suffix
}

export function isNil<T>(value: T | null | undefined): value is null | undefined {
    return value === null || value === undefined
}

export function stringifyNullOrUndefined(data: undefined | null): string {
    if (data === undefined) {
        return 'undefined'
    }
    return 'null'
}

export function ensureTrailingSlash(url: string): string {
    return url.endsWith('/') ? url : `${url}/`
}


// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function setAtPath<T, K extends keyof any>(obj: T, path: K | K[], value: any): void {
    const pathArray = Array.isArray(path) ? path : (path as string).match(/([^[.\]])+/g) as unknown as K[]

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    pathArray.reduce((acc: any, key: K, i: number) => {
        if (acc[key] === undefined) acc[key] = {}
        if (i === pathArray.length - 1) acc[key] = value
        return acc[key]
    }, obj)
}


export function insertAt<T>(array: T[], index: number, item: T): T[] {
    return [...array.slice(0, index), item, ...array.slice(index)]
}

export function debounce<T>(func: (...args: T[]) => void, wait: number): (key?: string, ...args: T[]) => void {
    let timeout: NodeJS.Timeout
    let currentKey: string | undefined
    return function (key?: string, ...args: T[]) {
        const later = () => {
            func(...args)
        }
        if (currentKey === key) {
            clearTimeout(timeout)
        }
        currentKey = key
        timeout = setTimeout(later, wait)
    }
}


type DeepPartial<T> = {
    [P in keyof T]?: T[P] extends Record<string, unknown> ? DeepPartial<T[P]> : T[P];
}

/**
 * This function also merges arrays, x = [1, 2], y = [3, 4], z = deepMergeAndCast(x, y) -> [1, 2, 3, 4]
**/
export function deepMergeAndCast<T>(target: DeepPartial<T>, source: DeepPartial<T>): T {
    return deepmerge(target as Partial<T>, source as Partial<T>) as T
}


export function kebabCase(str: string): string {
    return str
        .replace(/([a-z])([A-Z])/g, '$1-$2') // Handle camelCase by adding hyphen between lowercase and uppercase letters
        .replace(/\s+/g, '-')                // Replace spaces with hyphens
        .replace(/_/g, '-')                  // Replace underscores with hyphens
        .toLowerCase()                       // Convert to lowercase
        .replace(/^-+|-+$/g, '')            // Remove leading and trailing hyphens
}

export function slugify(value: string): string {
    return value
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '')
}


export function isEmpty<T>(value: T | null | undefined): boolean {
    if (value == null) {
        return true
    }

    if (typeof value === 'string' || Array.isArray(value)) {
        return value.length === 0
    }

    if (typeof value === 'object') {
        return Object.keys(value).length === 0
    }

    return false
}

export function startCase(str: string): string {
    return str
        .replace(/([a-z])([A-Z])/g, '$1 $2')
        .replace(/[_-]+/g, ' ')
        .replace(/\s+/g, ' ')
        .replace(/^[a-z]/, match => match.toUpperCase())
        .replace(/\b[a-z]/g, match => match.toUpperCase())
}

export function camelCase(str: string): string {
    return str
        .replace(/([-_][a-z])/g, group => group.toUpperCase()
            .replace('-', '')
            .replace('_', ''))
}

export function parseToJsonIfPossible(str: unknown): unknown {
    try {
        return JSON.parse(str as string)
    }
    catch (e) {
        return str
    }
}



export function pickBy<T extends Record<string, unknown>>(
    object: T,
    predicate: (value: T[keyof T], key: keyof T) => boolean,
): Partial<T> {
    return Object.keys(object).reduce((result: Partial<T>, key: keyof T) => {
        if (predicate(object[key], key)) {
            result[key] = object[key]
        }
        return result
    }, {})
}


export function chunk<T>(records: T[], size: number) {
    const chunks: T[][] = []
    for (let i = 0; i < records.length; i += size) {
        chunks.push(records.slice(i, i + size))
    }
    return chunks
}

export function partition<T>(array: T[], predicate: (item: T, index: number, arr: T[]) => boolean): [T[], T[]] {
    const truthy: T[] = []
    const falsy: T[] = []
    array.forEach((item, idx) => {
        if (predicate(item, idx, array)) {
            truthy.push(item)
        }
        else {
            falsy.push(item)
        }
    })
    return [truthy, falsy]
}

export function unique<T>(array: T[]): T[] {
    const seen = new Set<string | undefined>()
    return array.filter((item) => {
        const key = JSON.stringify(item)
        if (seen.has(key)) {
            return false
        }
        seen.add(key)
        return true
    })
}

export function mapsAreSame<K, V>(a: Map<K, V>, b: Map<K, V>): boolean {
    if (a.size !== b.size) return false
    for (const [key, value] of a) {
        if (!b.has(key)) return false
        if (b.get(key) !== value) return false
    }
    return true
}

export function validateIndexBound({
    index, limit,
}: { index: number, limit: number }) {
    if (index < 0) {
        return 0
    }
    if (index >= limit) {
        return limit - 1
    }
    return index
}

export function isManualPieceTrigger({ pieceName, triggerName }: { pieceName: string, triggerName: string }) {
    return pieceName === '@activepieces/piece-manual-trigger' && triggerName === 'manual_trigger'
}

export function isEnumValue<T extends { [key: string]: string | number }>(
    enumObj: T,
    value: string | number,
): value is T[keyof T] {
    return Object.values(enumObj).includes(value as T[keyof T])
}

export type IsBase64Options = {
    allowMime?: boolean
}

const INVALID_BASE64_CHARS = /[^A-Za-z0-9+/=]/

export function isBase64(value: string, options?: IsBase64Options): boolean {
    if (!isString(value) || value.length === 0) {
        return false
    }

    if (options?.allowMime) {
        const base64MarkerIndex = value.indexOf(';base64,')
        if (base64MarkerIndex !== -1 && value.startsWith('data:')) {
            const base64Part = value.slice(base64MarkerIndex + 8) // 8 = ';base64,'.length
            return _isValidBase64String(base64Part)
        }
    }

    return _isValidBase64String(value)
}

function _isValidBase64String(str: string): boolean {
    const len = str.length
    if (len === 0 || len % 4 !== 0 || INVALID_BASE64_CHARS.test(str)) {
        return false
    }
    // Validate that '=' only appears at the end (padding), at most 2 chars
    const firstPaddingIndex = str.indexOf('=')
    return firstPaddingIndex === -1 ||
        firstPaddingIndex === len - 1 ||
        (firstPaddingIndex === len - 2 && str[len - 1] === '=')
}