|
| 1 | +import { |
| 2 | + ClazzDto, |
| 3 | + FieldDto, |
| 4 | + FileDetailedDto, |
| 5 | + FunctionDto, |
| 6 | +} from 'explorviz-frontend/src/utils/landscape-schemes/file-detailed-data'; |
| 7 | +import { Building } from 'explorviz-frontend/src/utils/landscape-schemes/flat-landscape'; |
| 8 | +import { TypeOfAnalysis } from 'explorviz-frontend/src/utils/landscape-schemes/structure-data'; |
| 9 | + |
| 10 | +export const FILE_SECTIONS = ['imports', 'functions', 'dataStructures'] as const; |
| 11 | +export type FileSection = (typeof FILE_SECTIONS)[number]; |
| 12 | + |
| 13 | +/** Every file is a request to the landscape service. */ |
| 14 | +export const MAX_FILES = 10; |
| 15 | +export const DEFAULT_MAX_ENTRIES = 100; |
| 16 | + |
| 17 | +export interface FileQuery { |
| 18 | + ids: string[]; |
| 19 | + sections?: FileSection[]; |
| 20 | + search?: string; |
| 21 | + includeMetrics?: boolean; |
| 22 | + maxEntries?: number; |
| 23 | +} |
| 24 | + |
| 25 | +type Entry = Record<string, unknown>; |
| 26 | + |
| 27 | +/** Drops absent values and empty lists so they cost no tokens. */ |
| 28 | +function compact(entry: Entry): Entry { |
| 29 | + return Object.fromEntries( |
| 30 | + Object.entries(entry).filter( |
| 31 | + ([, value]) => value !== undefined && value !== null && !(Array.isArray(value) && value.length === 0) |
| 32 | + ) |
| 33 | + ); |
| 34 | +} |
| 35 | + |
| 36 | +/** The service returns these lists in no particular order, which would make equal results look different. */ |
| 37 | +function sortedByName<T extends { name: string }>(items: T[] | null | undefined): T[] { |
| 38 | + return [...(items ?? [])].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); |
| 39 | +} |
| 40 | + |
| 41 | +interface DataStructure { |
| 42 | + /** Includes the names of the data structures it is nested in. */ |
| 43 | + name: string; |
| 44 | + clazz: ClazzDto; |
| 45 | +} |
| 46 | + |
| 47 | +function flatten(classes: ClazzDto[] | null | undefined, prefix = ''): DataStructure[] { |
| 48 | + return sortedByName(classes).flatMap((clazz) => { |
| 49 | + const name = prefix + clazz.name; |
| 50 | + return [{ name, clazz }, ...flatten(clazz.innerClasses, `${name}.`)]; |
| 51 | + }); |
| 52 | +} |
| 53 | + |
| 54 | +/** Counts down how many entries may still be listed for a file. */ |
| 55 | +class Budget { |
| 56 | + omitted: Partial<Record<FileSection, number>> = {}; |
| 57 | + |
| 58 | + constructor(private remaining: number) {} |
| 59 | + |
| 60 | + take<T>(section: FileSection, items: T[]): T[] { |
| 61 | + const taken = items.slice(0, this.remaining); |
| 62 | + this.remaining -= taken.length; |
| 63 | + if (taken.length < items.length) { |
| 64 | + this.omitted[section] = (this.omitted[section] ?? 0) + items.length - taken.length; |
| 65 | + } |
| 66 | + return taken; |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +/** Selects the requested data of one file. The same function serves functions of files and of data structures. */ |
| 71 | +export function describeFile(file: FileDetailedDto, query: Omit<FileQuery, 'ids'>): Entry { |
| 72 | + const sections = new Set<FileSection>(query.sections?.length ? query.sections : FILE_SECTIONS); |
| 73 | + const search = query.search?.trim().toLowerCase() ?? ''; |
| 74 | + const matches = (...texts: (string | null | undefined)[]) => |
| 75 | + !search || texts.some((text) => text?.toLowerCase().includes(search)); |
| 76 | + const maxEntries = query.maxEntries; |
| 77 | + const budget = new Budget( |
| 78 | + typeof maxEntries === 'number' && maxEntries >= 0 ? Math.floor(maxEntries) : DEFAULT_MAX_ENTRIES |
| 79 | + ); |
| 80 | + |
| 81 | + const toFunction = ({ name, returnType, metrics }: FunctionDto) => { |
| 82 | + const signature = returnType ? `${name}: ${returnType}` : name; |
| 83 | + return query.includeMetrics ? { function: signature, metrics } : signature; |
| 84 | + }; |
| 85 | + const toField = ({ name, type }: FieldDto) => (type ? `${name}: ${type}` : name); |
| 86 | + const listFunctions = (functions: FunctionDto[] | null | undefined, takeAll = false) => |
| 87 | + sections.has('functions') |
| 88 | + ? budget |
| 89 | + .take( |
| 90 | + 'functions', |
| 91 | + sortedByName(functions).filter(({ name, returnType }) => takeAll || matches(name, returnType)) |
| 92 | + ) |
| 93 | + .map(toFunction) |
| 94 | + : []; |
| 95 | + |
| 96 | + const imports = sections.has('imports') |
| 97 | + ? budget.take( |
| 98 | + 'imports', |
| 99 | + [...(file.importNames ?? [])].sort().filter((name) => matches(name)) |
| 100 | + ) |
| 101 | + : []; |
| 102 | + const functions = listFunctions(file.functions); |
| 103 | + |
| 104 | + const dataStructures = flatten(file.classes).flatMap(({ name, clazz }) => { |
| 105 | + // A data structure that is searched for is returned with everything in it. |
| 106 | + const isMatch = matches(name); |
| 107 | + const superclasses = clazz.superclassFqns ?? []; |
| 108 | + const hasMatchingSuperclass = sections.has('dataStructures') && matches(...superclasses); |
| 109 | + const matchingFields = sections.has('dataStructures') |
| 110 | + ? sortedByName(clazz.fields).filter((field) => isMatch || matches(field.name, field.type)) |
| 111 | + : []; |
| 112 | + const hasMatchingFunction = |
| 113 | + sections.has('functions') && (clazz.functions ?? []).some((fn) => isMatch || matches(fn.name, fn.returnType)); |
| 114 | + const isListed = |
| 115 | + (isMatch && sections.has('dataStructures')) || |
| 116 | + (search !== '' && hasMatchingSuperclass) || |
| 117 | + matchingFields.length > 0 || |
| 118 | + hasMatchingFunction; |
| 119 | + if (!isListed || budget.take('dataStructures', [clazz]).length === 0) { |
| 120 | + return []; |
| 121 | + } |
| 122 | + return [ |
| 123 | + compact({ |
| 124 | + name, |
| 125 | + type: clazz.type, |
| 126 | + ...(sections.has('dataStructures') && { |
| 127 | + superclasses: [...superclasses].sort(), |
| 128 | + fields: budget.take('dataStructures', matchingFields).map(toField), |
| 129 | + metrics: query.includeMetrics ? clazz.metrics : undefined, |
| 130 | + }), |
| 131 | + functions: listFunctions(clazz.functions, isMatch), |
| 132 | + }), |
| 133 | + ]; |
| 134 | + }); |
| 135 | + |
| 136 | + return compact({ |
| 137 | + language: file.language, |
| 138 | + package: file.packageName || undefined, |
| 139 | + metrics: query.includeMetrics ? file.metrics : undefined, |
| 140 | + // Totals, so that the chatbot can tell "none" from "none that match". |
| 141 | + counts: { |
| 142 | + imports: file.importNames?.length ?? 0, |
| 143 | + topLevelFunctions: file.functions?.length ?? 0, |
| 144 | + dataStructures: flatten(file.classes).length, |
| 145 | + }, |
| 146 | + imports, |
| 147 | + functions, |
| 148 | + dataStructures, |
| 149 | + omitted: Object.keys(budget.omitted).length > 0 ? budget.omitted : undefined, |
| 150 | + }); |
| 151 | +} |
| 152 | + |
| 153 | +function hasFileData({ originOfData }: Building) { |
| 154 | + return originOfData === TypeOfAnalysis.Static || originOfData === TypeOfAnalysis.StaticAndRuntime; |
| 155 | +} |
| 156 | + |
| 157 | +/** |
| 158 | + * Loads and describes files. A file that cannot be inspected is reported in its |
| 159 | + * place, so it does not keep the chatbot from getting the others. |
| 160 | + */ |
| 161 | +export async function queryFiles( |
| 162 | + query: FileQuery, |
| 163 | + getBuilding: (id: string) => Building | undefined, |
| 164 | + requestFile: (id: string) => Promise<FileDetailedDto> |
| 165 | +): Promise<{ files: Entry[]; omittedIds?: string[] }> { |
| 166 | + const ids = [...new Set(query.ids)]; |
| 167 | + const files = await Promise.all( |
| 168 | + ids.slice(0, MAX_FILES).map(async (id) => { |
| 169 | + const building = getBuilding(id); |
| 170 | + if (!building) { |
| 171 | + return { id, error: 'Not the id of a building. Look up the id with query-landscape-data.' }; |
| 172 | + } |
| 173 | + const name = building.fqn ?? building.name; |
| 174 | + if (!hasFileData(building)) { |
| 175 | + return { id, name, error: 'Has no file data: it does not come from static analysis.' }; |
| 176 | + } |
| 177 | + try { |
| 178 | + return { id, name, ...describeFile(await requestFile(id), query) }; |
| 179 | + } catch (error) { |
| 180 | + return { id, name, error: error instanceof Error ? error.message : String(error) }; |
| 181 | + } |
| 182 | + }) |
| 183 | + ); |
| 184 | + return { files, ...(ids.length > MAX_FILES && { omittedIds: ids.slice(MAX_FILES) }) }; |
| 185 | +} |
0 commit comments