Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

3.7 KB
Raw Blame
import api from 'lib/api'
import { retryImport } from 'lib/utils/retryImport'

import type { WidgetFrameApi, WidgetStatusApiInputBindings } from 'products/notebooks/frontend/generated/api.schemas'

export type ReusableWidgetInputBinding = WidgetStatusApiInputBindings[string]

function frameRowsAsObjects(frame: WidgetFrameApi): Record<string, unknown>[] {
    return frame.rows.map((row) =>
        Object.fromEntries(frame.columns.map((column, index) => [column.name, row[index] ?? null]))
    )
}

const compiledBindings = new Map<string, Promise<unknown[]>>()

async function bindingBytecode(binding: ReusableWidgetInputBinding): Promise<unknown[] | undefined> {
    if (!binding.hog?.trim()) {
        return undefined
    }
    let compiled = compiledBindings.get(binding.hog)
    if (!compiled) {
        const hog = binding.hog
        compiled = api.hog
            .create(hog)
            .then((response) => response.bytecode as unknown[])
            .catch((error) => {
                compiledBindings.delete(hog)
                throw error
            })
        compiledBindings.set(binding.hog, compiled)
    }
    return await compiled
}

export async function applyReusableWidgetBinding(
    frame: WidgetFrameApi,
    logicalName: string,
    binding: ReusableWidgetInputBinding | undefined,
    expectedColumns: string[]
): Promise<WidgetFrameApi> {
    if (!binding) {
        return { ...frame, name: logicalName }
    }
    const bytecode = await bindingBytecode(binding)
    if (!bytecode) {
        return { ...frame, name: logicalName }
    }
    if (!Array.isArray(bytecode) || bytecode[0] !== '_H') {
        throw new Error(`The input mapping for "${logicalName}" has invalid compiled Hog code.`)
    }
    const sourceRows = frameRowsAsObjects(frame)
    const { convertHogToJS, execHog } = await retryImport(() => import('lib/hog'))
    const execution = execHog(bytecode, {
        globals: {
            columns: frame.columns,
            frame: { ...frame, rows: sourceRows },
            rows: sourceRows,
        },
        functions: {},
        maxAsyncSteps: 0,
        memoryLimit: 16 * 1024 * 1024,
        timeout: 100,
    })
    if (execution.error || !execution.finished) {
        throw new Error(`The input mapping for "${logicalName}" could not be evaluated.`)
    }
    const mapped = convertHogToJS(execution.result)
    if (!Array.isArray(mapped) || mapped.some((row) => !row || typeof row !== 'object' || Array.isArray(row))) {
        throw new Error(`The input mapping for "${logicalName}" must return a list of objects.`)
    }
    const records = mapped as Record<string, unknown>[]
    const missingColumn = expectedColumns.find((name) =>
        records.some((row) => !Object.prototype.hasOwnProperty.call(row, name))
    )
    if (missingColumn !== undefined) {
        throw new Error(`The input mapping for "${logicalName}" must return the contract column "${missingColumn}".`)
    }
    return {
        ...frame,
        name: logicalName,
        columns: expectedColumns.map((name) => ({ name, type: 'unknown' })),
        rows: records.map((row) => expectedColumns.map((name) => row[name] ?? null)),
        includedRowCount: records.length,
    }
}

export function getReusableWidgetInputBinding(
    inputBindings: Record<string, unknown>,
    logicalName: string
): ReusableWidgetInputBinding | undefined {
    const binding = inputBindings[logicalName]
    if (!binding || typeof binding !== 'object' || Array.isArray(binding)) {
        return undefined
    }
    const value = binding as Record<string, unknown>
    if (typeof value.source !== 'string') {
        return undefined
    }
    return {
        source: value.source,
        hog: typeof value.hog === 'string' ? value.hog : undefined,
    }
}