| 981 | }; |
| 982 | |
| 983 | const link = ( |
| 984 | from: StepRecord, |
| 985 | to: StepRecord, |
| 986 | kind: WireStepLinkKind, |
| 987 | chain: Node[], |
| 988 | whens: string[], |
| 989 | site: WireStepSite, |
| 990 | edge: Edge | null, |
| 991 | trigger: WireStepTrigger | null = null, |
| 992 | within: string | null = null |
| 993 | ): string => { |
| 994 | const meta = (edge?.metadata ?? {}) as Record<string, unknown>; |
| 995 | const synthesized = edge?.provenance === 'heuristic'; |
| 996 | const confidence = typeof meta.confidence === 'number' ? meta.confidence : null; |
| 997 | const via = chain.map(toNodeRef); |
| 998 | const viaKey = via.map((v) => v.id).join('>'); |
| 999 | const id = `${from.id} ${to.id} ${viaKey}`; |
| 1000 | const when = whens.filter((w, i) => w && whens.indexOf(w) === i).join(' && '); |
| 1001 | const stamped: WireStepSite = { ...site, when, ...(trigger ? { trigger } : {}) }; |
| 1002 | // A `contains` edge is how a nested handler is FOUND, not a place it is |
| 1003 | // called from: its row stays only while no call site has been seen. |
| 1004 | const structural = (s: WireStepSite) => s.text.startsWith('defines '); |
| 1005 | const existing = links.get(id); |
| 1006 | if (existing) { |
| 1007 | if (structural(stamped) && existing.sites.some((s) => !structural(s))) return id; |
| 1008 | if (!structural(stamped) && existing.sites.every(structural)) existing.sites.length = 0; |
| 1009 | // One statement, two references (`res.status(201)` and its `.json(…)`): |
| 1010 | // the outer call is the site, the inner one folds into it. |
| 1011 | const sameLine = existing.sites.findIndex((s) => s.file === site.file && s.line === site.line); |
| 1012 | if (sameLine < 0) existing.sites.push(stamped); |
| 1013 | else if (stamped.text.startsWith(existing.sites[sameLine]!.text) && stamped.text.length > existing.sites[sameLine]!.text.length) { |
| 1014 | existing.sites[sameLine] = stamped; |
| 1015 | } |
| 1016 | if (!existing.trigger && trigger) existing.trigger = trigger; |
| 1017 | if (!existing.within && within) existing.within = within; |
| 1018 | if (when !== existing.when) { |
| 1019 | if (!when || !existing.when) existing.when = ''; |
| 1020 | else if (!existing.when.split(' || ').includes(when)) existing.when = `${existing.when} || ${when}`; |
| 1021 | } |
| 1022 | return id; |
| 1023 | } |
| 1024 | links.set(id, { |
| 1025 | id, |
| 1026 | from: from.id, |
| 1027 | to: to.id, |
| 1028 | kind, |
| 1029 | via, |
| 1030 | when, |
| 1031 | label: hopLabel(meta, synthesized), |
| 1032 | synthesized, |
| 1033 | uncertain: confidence !== null && confidence < UNCERTAIN_BELOW, |
| 1034 | sites: [stamped], |
| 1035 | ...(trigger ? { trigger } : {}), |
| 1036 | ...(within ? { within } : {}), |
| 1037 | }); |
| 1038 | if (trigger && to.kind === 'trigger' && !to.trigger) to.trigger = trigger; |
| 1039 | return id; |
| 1040 | }; |