All files / realm/blong-commander/orchestrator/commander branchList.ts

80.24% Statements 130/162
37.5% Branches 12/32
72.72% Functions 8/11
80.24% Lines 130/162

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 1631x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 26x       26x 26x 26x 26x             13x 13x 1x 1x 1x 1x                       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 24x 24x 24x 1x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x   1x 1x   1x       1x 1x 1x 1x 1x 1x 1x 1x  
import {type IMeta, handler} from '@feasibleone/blong';
import {getPath} from '../../branch/getPath.ts';
import {levelRowsSelect} from '../../branch/levelRowsSelect.ts';
import {sources as defaultSources} from '../../config/sources.ts';
import type {ICommanderLevel, ICommanderSource} from '../../types.ts';
 
/**
 * One-level flatten: keep top-level scalar fields; promote the scalar leaves of
 * nested plain objects to dot-path keys. Arrays and deeper nesting are skipped.
 * Backends return heterogeneous rows (e.g. raw Kubernetes objects with
 * `metadata.name` / `status.phase`) — this makes every row displayable by the
 * generic commander table (which only shows scalar cells).
 */
function flattenItem(item: unknown): Record<string, unknown> {
    if (!item || typeof item !== 'object' || Array.isArray(item)) return {};
    const out: Record<string, unknown> = {};
    for (const [key, value] of Object.entries(item)) {
        if (value === null || value === undefined) {
            out[key] = value;
            continue;
        }
        if (typeof value !== 'object' || Array.isArray(value)) {
            if (typeof value !== 'object') out[key] = value;
            continue;
        }
        for (const [subKey, subValue] of Object.entries(value)) {
            if (subValue !== null && subValue !== undefined && typeof subValue !== 'object') {
                out[`${key}.${subKey}`] = subValue;
            }
        }
    }
    return out;
}
 
/** Resolve `{field}` / `{parent.field}` tokens against the parent node. */
function resolve(text: string, parent: Record<string, unknown> | null): string {
    return text.replace(/\{([^}]+)\}/g, (_match, expr: string) => {
        const raw = expr.trim();
        const path = raw.startsWith('parent.') ? raw.slice('parent.'.length) : raw;
        // Rows are flattened to literal dot-path keys (e.g. `metadata.name`), so
        // prefer a direct lookup; fall back to nested traversal for raw objects.
        const literal = parent ? parent[path] : undefined;
        const value =
            literal !== undefined && literal !== null
                ? literal
                : getPath(parent ?? undefined, path);
        return value === undefined || value === null ? '' : String(value);
    });
}
 
/**
 * Order one level's rows deterministically by the field the level displays —
 * `labelField`, falling back to `keyField` (both may be dot paths, e.g.
 * `metadata.name`). Backends such as Keycloak return collections in an
 * unspecified order that can differ between two calls, so the navigator tree
 * and the table would otherwise list the same rows in a different order from
 * one run to the next and a screenshot would never be stable. Sorting here, in
 * the single place every source's children come through, makes the response —
 * and therefore both views — reproducible; ties keep the backend's order.
 */
function sortRows(level: ICommanderLevel, rows: unknown[]): unknown[] {
    const field = level.labelField || level.keyField;
    if (!field) return rows;
    const valueOf = (row: unknown): string => {
        const raw = getPath(row as Record<string, unknown> | undefined, field);
        return raw === undefined || raw === null ? '' : String(raw);
    };
    return [...rows].sort((left, right) => {
        const a = valueOf(left);
        const b = valueOf(right);
        return a < b ? -1 : a > b ? 1 : 0;
    });
}
 
/**
 * commanderBranchList — generic children dispatch.
 *
 * `level: -1` lists the source root children (`levels[0].list`); `level: n`
 * lists the children of a node at depth n (`levels[n + 1].list`). The method
 * and params are resolved from the descriptor, templating `{field}` /
 * `{parent.field}` against the parent node.
 */
export default handler(
    ({config, handler: h}) =>
        async function commanderBranchList(
            params: {
                source: string;
                level?: number;
                parent?: Record<string, unknown>;
                paging?: {pageSize?: number; pageNumber?: number};
            },
            $meta: IMeta,
        ) {
            const sources = (config as {sources?: ICommanderSource[]}).sources ?? defaultSources;
            const levelIndex = params.level ?? -1;
            $meta.checkpoint?.('dispatch-started', {source: params.source, level: levelIndex});
            const source = sources.find(s => s.name === params.source);
            if (!source) throw new Error(`Unknown commander source: ${params.source}`);
            $meta.checkpoint?.('source-resolved', {
                source: source.name,
                levels: source.levels.length,
            });
            const next = levelIndex + 1;
            if (next >= source.levels.length) return {items: []};
            const level = source.levels[next];
            const parent = levelIndex >= 0 ? (params.parent ?? null) : null;
 
            const method = resolve(level.list.method, parent);
            const listParams: Record<string, unknown> = {};
            for (const [key, value] of Object.entries(level.list.params ?? {})) {
                listParams[key] = typeof value === 'string' ? resolve(value, parent) : value;
            }
            if (params.paging) listParams.paging = params.paging;
            // The outgoing leg: the method is a template resolved against the parent row, so a
            // drill draws `access.{tableName}.find` and its parameters come from the node the
            // reader selected — which is what makes the dispatched call the interesting half of
            // this flow (PRD R26/R27).
            $meta.checkpoint?.('level-resolved', {
                level: next,
                resourceType: level.resourceType,
                method,
            });
 
            const result = await h[method](listParams, $meta);
            const resultSet = level.list.resultSet;
            // What the backend answered with decides what is read out of it: the rows themselves,
            // or a named set inside an envelope. Naming the branch rather than testing it twice
            // keeps the drawing honest — the block is the dispatch that happened.
            const shape = await $meta.decide?.('result-shape', {resultSet: resultSet ?? null}, [
                {name: 'array', when: () => Array.isArray(result), run: () => 'array' as const},
                {
                    name: 'result-set',
                    when: () => resultSet !== undefined,
                    run: () => 'result-set' as const,
                },
                {name: 'empty', when: () => true, run: () => 'empty' as const},
            ]);
            const taken =
                shape ??
                (Array.isArray(result)
                    ? 'array'
                    : resultSet !== undefined
                      ? 'result-set'
                      : 'empty');
            const rows =
                taken === 'array'
                    ? (result as unknown[])
                    : taken === 'result-set' && result && typeof result === 'object'
                      ? (result as Record<string, unknown>)[resultSet as string]
                      : undefined;
            if (!Array.isArray(rows)) {
                $meta.checkpoint?.('rows-listed', {rows: 0});
                return {items: []};
            }
            $meta.checkpoint?.('rows-listed', {rows: rows.length});
            // What the level's own whitelist/blacklist admits, ordered the way the level
            // displays it: the row half of the declaration, beside the ordering below.
            return {
                items: sortRows(level, levelRowsSelect(level, rows)).map(flattenItem),
            };
        },
);