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

100% Statements 31/31
100% Branches 14/14
100% Functions 3/3
100% Lines 31/31

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 321x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 81x 30x 30x 3x 3x 3x 24x 24x 24x 3x 3x 1x  
import {handler} from '@feasibleone/blong';
import type {ICommanderSource} from '../../types.ts';
import {sources as defaultSources} from '../../config/sources.ts';
 
/** Normalise a triple to the gateway methodId (dots stripped, lowercased). */
const methodId = (name: string): string => name.replace(/\./g, '').toLowerCase();
 
/**
 * commanderSourceList — return the configured commander sources, filtered by
 * the caller's granted actions (`$meta.auth.actions`, populated by the gateway
 * authorize handler). Sources/levels without a `permission` are always shown.
 */
export default handler(
    ({config}) =>
        async function commanderSourceList(_params, $meta) {
            const sources = (config as {sources?: ICommanderSource[]}).sources ?? defaultSources;
            const actions = ($meta as {auth?: {actions?: string[]}}).auth?.actions;
            const allowed = actions?.length ? new Set(actions.map(methodId)) : null;
            const canShow = (permission?: string): boolean => {
                if (!permission || !allowed) return true;
                return allowed.has(methodId(permission));
            };
            const items = sources
                .filter(source => canShow(source.permission))
                .map(source => ({
                    ...source,
                    levels: source.levels.filter(level => canShow(level.permission)),
                }));
            return {items};
        },
);