Files

182 lines
7.3 KiB
TypeScript

/**
* Every relation the corpus holds, loaded once, validated together, indexed
* both ways.
*
* Four producers, one shape:
* 1. hand-written rows and candidate rows — `config/substrata-relations.ts`
* (candidates folded in from `config/candidates/relations.json`);
* 2. rows the corpus already states — `./from-corpus.ts` (ownership holders,
* facility operators);
* 3. the USGS facility tables — `research/usgs-relations.json`, generated by
* `scripts/research/build-usgs-relations.ts`;
* 4. rule proposals — `research/derived-relations.json`, generated by
* `scripts/research/build-derived-relations.ts` from the first three
* (lib/coverage/rules.ts). Only `derived` and `lead`, never counted, and
* held apart in `proposals`: they are validated with the rest but are not
* walked by traversal, counted by a dossier or indexed for search until a
* person promotes one into a producer above.
*
* The same relation from two producers is one relation with both sources: two
* independent counted sources make it `corroborated`. Two producers that give
* it different shares are a conflict, kept from the more reviewed producer
* (hand-written, then candidate, then research) and listed in `graphStats()`.
*
* Validation runs on load and throws (./validate.ts): a relation that breaks a
* rule stops the build rather than reaching a page.
*/
import { RELATIONS } from '@/config/substrata-relations';
import { resolveDirectoryEntity } from '@/lib/entities/directory';
import type { EntityId } from '@/lib/entities/types';
import usgsFile from '@/research/usgs-relations.json';
import derivedFile from '@/research/derived-relations.json';
import { withCanonicalEnds } from './aliases';
import { corpusRelations } from './from-corpus';
import { COUNTED_GRADES, type Relation, type RelationOrigin } from './types';
import type { UsgsNode, UsgsReport } from './usgs-operators';
import { validateRelations } from './validate';
interface UsgsRelationsFile {
source: string;
readOn: string;
report: UsgsReport;
nodes: Record<string, UsgsNode>;
relations: Relation[];
}
/** A minted endpoint: what a page can say about a node that has no entity of its own. */
export interface GraphNode {
id: EntityId;
name: string;
/** The directory entity, when there is one. A stub (lib/entities/sources/company-stubs.ts) is not. */
inDirectory: boolean;
kind: string;
/** Countries whose tables printed it (USGS nodes). */
iso2: string[];
commodities?: string[];
}
export interface GraphStore {
all: Relation[];
/** Rule proposals (origin `rule`), validated against `all`, never in `byId`/`from`/`to`. */
proposals: Relation[];
byId: Map<string, Relation>;
from: Map<string, Relation[]>;
to: Map<string, Relation[]>;
nodes: Map<string, Omit<GraphNode, 'id' | 'inDirectory' | 'kind'>>;
conflicts: string[];
skipped: Record<string, number>;
usgs: UsgsReport;
}
const PRECEDENCE: RelationOrigin[] = ['curated', 'candidate', 'research', 'rule'];
const rankOf = (r: Relation) => PRECEDENCE.indexOf(r.origin ?? 'curated');
/** The same relation from a second producer: union the evidence, keep the stronger reading. */
function merge(kept: Relation, other: Relation, conflicts: string[]): Relation {
const [first, second] = rankOf(other) < rankOf(kept) ? [other, kept] : [kept, other];
if ((first.share?.value ?? null) !== (second.share?.value ?? null)) {
conflicts.push(
`${first.id}: ${first.origin ?? 'curated'} says ${first.share?.value ?? 'no share'}, ` +
`${second.origin ?? 'curated'} says ${second.share?.value ?? 'no share'}`,
);
return first;
}
const evidence = [...first.evidence];
for (const e of second.evidence)
if (!evidence.some((x) => x.source === e.source)) evidence.push(e);
const counted = [first, second].filter((r) => COUNTED_GRADES.includes(r.grade));
const countedSources = new Set(counted.flatMap((r) => r.evidence.map((e) => e.source)));
const grade =
countedSources.size >= 2 ? 'corroborated' : counted.length ? counted[0].grade : first.grade;
return { ...first, grade, evidence };
}
export function buildStore(
inputs: {
hand?: readonly Relation[];
corpus?: ReturnType<typeof corpusRelations>;
usgs?: UsgsRelationsFile;
/** Rule proposals; pass `{ relations: [] }` to build the graph the rules read. */
derived?: { relations: readonly Relation[] };
} = {},
today = new Date(),
): GraphStore {
const corpus = inputs.corpus ?? corpusRelations();
const usgs = inputs.usgs ?? (usgsFile as unknown as UsgsRelationsFile);
const hand = inputs.hand ?? RELATIONS;
// The proposals were made from the committed producers, so they are only
// loaded with them: a store built from other inputs (a test's fixture) gets
// none unless it passes its own, or their chains would point at nothing.
const derived =
inputs.derived ??
(inputs.hand || inputs.corpus || inputs.usgs
? { relations: [] }
: (derivedFile as unknown as { relations: Relation[] }));
const conflicts: string[] = [];
const byId = new Map<string, Relation>();
for (const raw of [...hand, ...corpus.relations, ...usgs.relations]) {
// A reviewed alias moves every edge to one id, whichever producer wrote it.
const r = withCanonicalEnds(raw);
const seen = byId.get(r.id);
byId.set(r.id, seen ? merge(seen, r, conflicts) : r);
}
const all = [...byId.values()].sort((a, b) => a.id.localeCompare(b.id));
// A proposal the producers now state themselves is dropped: the stated row wins.
const proposals = derived.relations
.map(withCanonicalEnds)
.filter((r) => !byId.has(r.id))
.sort((a, b) => a.id.localeCompare(b.id));
validateRelations([...all, ...proposals], today);
const from = new Map<string, Relation[]>();
const to = new Map<string, Relation[]>();
for (const r of all) {
(from.get(r.from) ?? from.set(r.from, []).get(r.from)!).push(r);
(to.get(r.to) ?? to.set(r.to, []).get(r.to)!).push(r);
}
const nodes: GraphStore['nodes'] = new Map();
for (const [id, node] of Object.entries(usgs.nodes))
nodes.set(id, { name: node.name, iso2: node.iso2, commodities: node.commodities });
for (const [id, name] of Object.entries(corpus.names))
if (!nodes.has(id)) nodes.set(id, { name, iso2: [] });
return {
all,
proposals,
byId,
from,
to,
nodes,
conflicts,
skipped: corpus.skipped,
usgs: usgs.report,
};
}
let store: GraphStore | null = null;
/** The corpus's graph, built on first use. Static files, so it cannot change within a process. */
export function graphStore(): GraphStore {
if (!store) store = buildStore();
return store;
}
/**
* A node as the directory alone can name it: the profiled entity, else the name
* its source printed. The derived company sources use this while they build,
* so they never need the full registry (lib/graph/node.ts has that one).
*/
export function directoryNode(id: string, s: GraphStore = graphStore()): GraphNode {
const minted = s.nodes.get(id);
const profiled = resolveDirectoryEntity(id);
const kind = id.slice(0, id.indexOf(':'));
return {
id: id as EntityId,
name: profiled?.name ?? minted?.name ?? id.slice(id.indexOf(':') + 1),
inDirectory: Boolean(profiled),
kind,
iso2: minted?.iso2 ?? (kind === 'country' ? [id.slice(id.indexOf(':') + 1)] : []),
...(minted?.commodities ? { commodities: minted.commodities } : {}),
};
}