import type { InterfaceRevision, ValueType } from "../capability-model/types.js"; import type { CheckedQuery, QuerySelection } from "./types.js"; /** Browser presentation is separate from the portable query value contract. */ export function queryPresentation(query: CheckedQuery, interfaces: readonly InterfaceRevision[]) { const result: { path: string[]; selectionId: string; interfaceRevisionId: string; getOperationId: string; setOperationId?: string; watchOperationId?: string; inputKind: "value" | "fields"; valueType: ValueType; conditions: (QuerySelection["conditions"][number] & { defaultValue?: boolean })[]; }[] = []; const visit = (type: ValueType, selections: QuerySelection[], path: string[]) => { if (type.kind === "optional") return visit(type.value, selections, path); if (type.kind === "list") return visit(type.value, selections, [...path, "*"]); if (type.kind !== "record") return; for (const [name, field] of Object.entries(type.fields)) { const matches = selections.filter((entry) => entry.key === name); if (matches.some((entry) => entry.liveSelectionId) && matches.some((entry) => !entry.liveSelectionId)) throw new Error(`QUERY_LIVE_CONFLICT: ${[...path, name].join(".")} mixes live and plain selections`); for (const entry of matches) { if (entry.liveSelectionId) { const iface = interfaces.find((iface) => iface.revisionId === entry.interfaceRevisionId)!; const member = iface.members.find((member) => member.id === entry.memberId)!; if (member.kind !== "value") throw new Error("QUERY_LIVE_UNSUPPORTED"); const get = member.operations.find((op) => op.displayName === "get")!; const set = member.operations.find((op) => op.displayName === "set"); result.push({ path: [...path, name], selectionId: entry.liveSelectionId, interfaceRevisionId: iface.revisionId, getOperationId: get.id, setOperationId: set?.id, watchOperationId: member.operations.find((op) => op.displayName === "watch-start")?.id, inputKind: set?.inputType.kind === "record" ? "fields" : "value", valueType: get.outputType, conditions: entry.conditions.map((condition) => { const fallback = condition.value.kind === "variable" ? query.variableDefaults[condition.value.name] : undefined; return { ...condition, ...(fallback?.kind === "literal" && typeof fallback.value === "boolean" ? { defaultValue: fallback.value } : {}), }; }), }); } else visit(field, entry.selection, [...path, name]); } } }; visit(query.output, query.selection, []); return result; }