import { groupBy, uniq } from "es-toolkit"; import { collectColumnReferences, isColumnUniversalId, isColumnUniversalKey, isColumnValueId, type BlockColumnLinks, type BlockOutput, type ColumnLink, type ColumnUniversalId, type ColumnValue, type LinkCheck, } from "@platforma-sdk/model"; /** * Which way a link goes: `usedBy` — another block's args reference an output of this block; * `uses` — this block's args reference an output of another block. */ export type LinkSide = "usedBy" | "uses"; /** * What one other block uses of one output, or what this block uses of one output of another * block. All references of that block to the output that pick values are merged into one row, * with their distinct picked values and the check that needs attention most; its use of the * output as a whole is a row of its own. */ export type LinkRow = Pick & { key: string; /** The other block: the one using this block's output, or the one producing the output. */ blockId: string; /** The output. Its name is not meant for reading, so it is shown only as a hint. */ column: BlockOutput; }; /** The links of one side. */ export type LinkSection = { side: LinkSide; rows: LinkRow[] }; /** * A line about links that need attention: the other block's name, then a space and `text`. The * name is kept apart so it can be shown as a way to open that block. A line is about one link, * about every link to that block whose output is not exported and has no known label: such * outputs have no name a reader can tell apart, or about every link to a block that has not been * run yet: they all wait for its run. `outputs` names the outputs the line is about, * for a hint. */ export type LinkIssue = { key: string; blockId: string; text: string; outputs: string[]; }; /** The links of one side that need attention, shown as its {@link ALERTS} entry says. */ export type LinkAlert = { side: LinkSide; issues: LinkIssue[] }; /** * How the alert of each side shows. `error` on the `uses` side: this block cannot run against * the links. `warn` on the `usedBy` side: the other blocks are the ones to fix, by getting the * data back here or by being reconfigured; `hint` says so. */ export const ALERTS = { uses: { type: "error", label: "Links to blocks this block takes data from are broken", hint: null, }, usedBy: { type: "warn", label: "Some blocks are missing data from this block", hint: "Checked against the last run of this block. Add the missing data and run it, or " + "reconfigure those blocks.", }, } as const satisfies Record< LinkSide, { type: "error" | "warn"; label: string; hint: null | string } >; /** The links of both sides: `usedBy`, then `uses`. */ export function linkSections( links: Pick, ): LinkSection[] { const { dependents, dependencies } = links; return [ { side: "usedBy", rows: groupRows(dependents.map((link) => toRow(link, link.holderBlockId))), }, { side: "uses", rows: groupRows(dependencies.map((link) => toRow(link, link.producer.blockId))), }, ]; } /** * One alert per side whose links need attention, in the order of the sections: * - `uses` — an output this block uses is not available or lacks picked values; * - `usedBy` — another block uses an output this block does not export, or picked values this * block's output lacks. The links are checked against this block's last run, as the hint says. */ export function linkAlerts(sections: LinkSection[]): LinkAlert[] { return sections.flatMap((section): LinkAlert[] => { const links = section.rows.flatMap((row) => attentionLink(row) ?? []); if (links.length === 0) return []; const issues = groupIssues(links).map((group) => toIssue(section.side, group)); return [{ side: section.side, issues }]; }); } /** The label of a block, or a short form of its id when it has no label. */ export function blockName(labels: Record, blockId: string): string { return labels[blockId] ?? `Block ${blockId.slice(0, 8)}`; } /** * Why a selected column or column value is missing. `source`: the block meant to provide it, and * what went wrong, as a sentence that follows the block's name. `waiting`: its column is provided, * while other inputs of the block are not, and the options of one input may be made from another. * `name`: what the selection is called — the picked value, or the label of a column selected as a * whole; `null` when the column has no known label. */ export type MissingValueCause = | { type: "source"; name: string | null; blockId: string; text: string } | { type: "waiting"; name: string | null; text: string }; /** * Why `value` is missing from its options, by the dependencies of the block: a column value id, * or a column — as an id or a ref. When its column is provided, with the value, while other * inputs of the block are not, the block offers it once they are: the options of one input may * be made from another. `undefined` for any other value, and for one whose column has nothing * wrong with it while every other input is provided too. */ export function describeMissingValue( dependencies: readonly ColumnLink[], value: unknown, ): MissingValueCause | undefined { const reference = selectedReference(value); if (reference === undefined) return undefined; const entry = dependencies.find((link) => link.ref === reference.ref); if (entry === undefined) return undefined; const column = entry.columnLabel === null ? "the column" : `“${entry.columnLabel}”`; const text = missingValueCauseText(entry.check, column, reference.picked); const name = reference.picked ?? entry.columnLabel; if (text !== undefined) { return { type: "source", name, blockId: entry.producer.blockId, text }; } return waitsForOtherInputs(dependencies, entry, reference.picked) ? { type: "waiting", name, text: "Waiting for the other inputs of this block." } : undefined; } // Internals /** The column `value` selects, with the value of it a column value id picks. */ function selectedReference( value: unknown, ): { ref: ColumnUniversalId; picked: ColumnValue | undefined } | undefined { const isColumn = isColumnUniversalId(value) || isColumnUniversalKey(value); if (!isColumnValueId(value) && !isColumn) return undefined; const [reference] = collectColumnReferences(value); if (reference === undefined) return undefined; if (reference.values === null) return isColumn ? { ref: reference.ref, picked: undefined } : undefined; return { ref: reference.ref, picked: reference.values[0] }; } function missingValueCauseText( check: LinkCheck, column: string, picked: ColumnValue | undefined, ): string | undefined { switch (check.type) { case "ok": case "unreadable": return undefined; case "pending": return `is still computing ${column}.`; case "notRun": case "unavailable": return `does not provide ${column}.`; case "missingValues": return picked !== undefined && check.values.includes(picked) ? `has no “${picked}” in ${column}.` : undefined; } } /** Whether a selected column is provided, with the picked value, while another input is not. */ function waitsForOtherInputs( dependencies: readonly ColumnLink[], entry: ColumnLink, picked: ColumnValue | undefined, ): boolean { if (!providesPick(entry.check, picked)) return false; return dependencies.some( (link) => link.ref !== entry.ref && link.check.type !== "ok" && link.check.type !== "unreadable", ); } /** Whether a column is provided with the picked value, as far as it was checked. */ function providesPick(check: LinkCheck, picked: ColumnValue | undefined): boolean { switch (check.type) { case "ok": return true; case "missingValues": return picked === undefined || !check.values.includes(picked); case "unreadable": case "pending": case "notRun": case "unavailable": return false; } } /** A link as a row, seen from the side whose other block is `blockId`. */ function toRow(link: ColumnLink, blockId: string): LinkRow { const { producer: column, columnLabel, values, check } = link; return { key: JSON.stringify([blockId, column.name, values === null]), blockId, column, columnLabel, values: values === null ? null : uniq(values), check, }; } /** Rows of one key merged into one, in the place of the first. */ function groupRows(rows: LinkRow[]): LinkRow[] { return Object.values(groupBy(rows, (row) => row.key)).map((group) => group.reduce(mergeRows)); } /** Two rows of one key: references to one output of one block, picking values or not. */ function mergeRows(a: LinkRow, b: LinkRow): LinkRow { return { ...a, columnLabel: a.columnLabel ?? b.columnLabel, values: a.values !== null && b.values !== null ? uniq([...a.values, ...b.values]) : a.values, check: mergeCheck(a.check, b.check), }; } /** The check of merged references: the one that needs attention most. */ function mergeCheck(a: LinkCheck, b: LinkCheck): LinkCheck { if (a.type === "missingValues" && b.type === "missingValues") { return { type: "missingValues", values: uniq([...a.values, ...b.values]) }; } return CHECK_RANK[b.type] > CHECK_RANK[a.type] ? b : a; } const CHECK_RANK: Record = { ok: 0, unreadable: 1, pending: 2, missingValues: 3, notRun: 4, unavailable: 4, }; /** A link whose check needs attention: it breaks a block, or lacks picked values. */ type AttentionLink = { row: LinkRow; check: AttentionCheck }; type AttentionCheck = Extract; /** The row as a link needing attention; `undefined` when it does not. */ function attentionLink(row: LinkRow): undefined | AttentionLink { const { check } = row; switch (check.type) { case "notRun": case "unavailable": case "missingValues": return { row, check }; case "ok": case "pending": case "unreadable": return undefined; } } /** One link an alert line is about. */ type SingleIssue = { type: "single"; link: AttentionLink }; /** Every link to one block whose output is not exported and has no known label. */ type UnlabeledIssue = { type: "unlabeled"; blockId: string; outputs: string[] }; type Issue = SingleIssue | UnlabeledIssue; /** Groups links into alert lines, each line in the place of its first link. */ function groupIssues(links: AttentionLink[]): Issue[] { const keyed = links.map((link, index) => ({ link, key: issueKey(link, index) })); return Object.values(groupBy(keyed, ({ key }) => key)).map((group): Issue => { const [{ link }] = group; if (!isUnlabeled(link)) return { type: "single", link }; const outputs = uniq(group.map((item) => item.link.row.column.name)); return { type: "unlabeled", blockId: link.row.blockId, outputs }; }); } function issueKey(link: AttentionLink, index: number): string { const blockId = JSON.stringify(link.row.blockId); return isUnlabeled(link) ? `unlabeled/${blockId}` : `single/${index}`; } /** A link to an output that is not exported and has no known label. */ function isUnlabeled(link: AttentionLink): boolean { const { type } = link.check; return link.row.columnLabel === null && (type === "notRun" || type === "unavailable"); } function toIssue(side: LinkSide, group: Issue): LinkIssue { if (group.type === "unlabeled") { return { key: `${side}/${JSON.stringify([group.blockId])}`, blockId: group.blockId, text: describeUnlabeled(side, group.outputs.length), outputs: group.outputs, }; } const { row } = group.link; return { key: `${side}/${row.key}`, blockId: row.blockId, text: describeIssue(side, group.link), outputs: [row.column.name], }; } /** * Outputs of one block that are not exported and have no known label, as words that follow the * other block's name and a space. One such output is the data in question; several are counted. */ function describeUnlabeled(side: LinkSide, count: number): string { const what = count === 1 ? "data" : `${count} outputs`; return side === "uses" ? `does not provide ${what} this block uses` : `uses ${what} this block does not export`; } /** * What is wrong with one link, as words that follow the other block's name and a space. The * column is named by its label, quoted; a column with no known label is named by its role. */ function describeIssue(side: LinkSide, { row, check }: AttentionLink): string { const column = row.columnLabel === null ? null : `"${row.columnLabel}"`; switch (check.type) { case "notRun": case "unavailable": if (column === null) return describeUnlabeled(side, 1); return side === "uses" ? `does not provide ${column}` : `uses ${column}, which this block does not export`; case "missingValues": { const values = quoteValues(check.values); if (side === "uses") return `has no ${values} in ${column ?? "data this block uses"}`; return column === null ? `uses ${values}, which this block's data no longer has` : `uses ${values} of ${column}, which this block no longer has`; } } } /** Picked values for display: quoted, comma-separated. */ function quoteValues(values: string[]): string { return values.map((value) => `"${value}"`).join(", "); }