scan-sources.js 24.9 KB
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
const fs = require("node:fs");
const path = require("node:path");
const traverse = require("@babel/traverse").default;
const vueCompiler = require("vue-template-compiler");

const {
	arrayValues,
	findProperty,
	locationOf,
	objectEntries,
	parseJavaScript,
	propertyName,
	staticPrimitive,
} = require("./ast-utils");
const {
	isDocumentFile,
	isTestFile,
	relativePath,
	resolveModule,
	toPosix,
} = require("./path-utils");

function fileNodeType(filePath, context) {
	if (isTestFile(filePath)) {
		return "test";
	}
	if (isDocumentFile(filePath)) {
		return "document";
	}
	if (filePath.endsWith(".vue")) {
		return context.routeViewPaths.has(filePath) ? "view" : "component";
	}
	return "module";
}

function fileNodeId(filePath, context) {
	return `${fileNodeType(filePath, context)}:${filePath}`;
}

function ensureFileNode(store, filePath, context) {
	const type = fileNodeType(filePath, context);
	return store.addNode({
		id: `${type}:${filePath}`,
		type,
		name: path.posix.basename(filePath),
		path: filePath,
	});
}

function importedName(specifier) {
	if (specifier.type === "ImportDefaultSpecifier") {
		return "default";
	}
	if (specifier.type === "ImportNamespaceSpecifier") {
		return "*";
	}
	return specifier.imported?.name || specifier.imported?.value || specifier.local.name;
}

function collectImports(ast, rootDir, filePath, store, context, sourceId) {
	const bindings = new Map();
	function addResolvedImport(specifier, node, localBindings = []) {
		const targetPath = resolveModule(rootDir, filePath, specifier);
		if (!targetPath) {
			return;
		}
		const targetId = ensureFileNode(store, targetPath, context);
		store.addEdge({
			from: sourceId,
			to: targetId,
			type: "imports",
			evidence: locationOf(node, filePath),
		});
		if (isTestFile(filePath)) {
			store.addEdge({
				from: targetId,
				to: sourceId,
				type: "coveredBy",
				evidence: locationOf(node, filePath),
			});
		}
		localBindings.forEach(binding => bindings.set(binding.local, {
			path: targetPath,
			imported: binding.imported,
		}));
	}
	traverse(ast, {
		ImportDeclaration(importPath) {
			addResolvedImport(importPath.node.source.value, importPath.node, importPath.node.specifiers.map(specifier => ({
				local: specifier.local.name,
				imported: importedName(specifier),
			})));
		},
		CallExpression(callPath) {
			const chain = memberChain(callPath.node.callee).join(".");
			const isRequire = callPath.node.callee.type === "Identifier" && callPath.node.callee.name === "require";
			const isDynamicImport = callPath.node.callee.type === "Import";
			const isJestMock = ["jest.mock", "jest.doMock"].includes(chain);
			if (!isRequire && !isDynamicImport && !isJestMock) {
				return;
			}
			const localBindings = [];
			const declarator = callPath.findParent(parent => parent.isVariableDeclarator());
			if (isRequire && declarator?.node.id.type === "Identifier") {
				localBindings.push({ local: declarator.node.id.name, imported: "default" });
			}
			addResolvedImport(staticPrimitive(callPath.node.arguments[0]), callPath.node, localBindings);
		},
	});
	return bindings;
}

function collectConstants(ast) {
	const constants = new Map();
	traverse(ast, {
		VariableDeclarator(variablePath) {
			if (variablePath.node.id.type !== "Identifier") {
				return;
			}
			const value = staticPrimitive(variablePath.node.init, constants);
			if (value !== null) {
				constants.set(variablePath.node.id.name, value);
			}
		},
	});
	return constants;
}

function findExportDefaultObject(ast) {
	let result = null;
	traverse(ast, {
		ExportDefaultDeclaration(exportPath) {
			if (exportPath.node.declaration.type === "ObjectExpression") {
				result = exportPath.node.declaration;
			}
		},
	});
	return result;
}

function collectApiOperations(ast, filePath, store, constants, sourceId) {
	const operations = [];
	const isApiFile = /(?:^|\/)api(?:\/|\.js$)/.test(filePath);
	if (!isApiFile) {
		return operations;
	}

	function addOperation(name, node) {
		if (!name || !node) {
			return;
		}
		const operationId = `api:${filePath}#${name}`;
		store.addNode({
			id: operationId,
			type: "apiOperation",
			name,
			path: filePath,
		});
		store.addEdge({
			from: sourceId,
			to: operationId,
			type: "definesApi",
			evidence: locationOf(node, filePath),
		});
		operations.push({ id: operationId, name, start: node.start, end: node.end });
	}

	traverse(ast, {
		FunctionDeclaration(functionPath) {
			if (functionPath.node.id && functionPath.parentPath.isExportNamedDeclaration()) {
				addOperation(functionPath.node.id.name, functionPath.node);
			}
		},
		VariableDeclarator(variablePath) {
			if (variablePath.node.id.type !== "Identifier") {
				return;
			}
			if (["ArrowFunctionExpression", "FunctionExpression"].includes(variablePath.node.init?.type)) {
				addOperation(variablePath.node.id.name, variablePath.node.init);
			}
		},
	});

	function addEndpoint(operation, endpoint, node) {
		if (!operation || typeof endpoint !== "string"
			|| !/^[\w-]+(?:\.[\w-]+){2,}$/.test(endpoint)) {
			return;
		}
		const endpointId = `endpoint:${endpoint}`;
		store.addNode({ id: endpointId, type: "endpoint", name: endpoint });
		store.addEdge({
			from: operation.id,
			to: endpointId,
			type: "callsEndpoint",
			evidence: locationOf(node, filePath),
		});
	}

	function enclosingOperation(node) {
		return operations
			.filter(item => item.start <= node.start && item.end >= node.end)
			.sort((leftItem, rightItem) => (leftItem.end - leftItem.start) - (rightItem.end - rightItem.start))[0];
	}

	traverse(ast, {
		AssignmentExpression(assignmentPath) {
			const left = assignmentPath.node.left;
			if (left.type !== "MemberExpression" || left.computed || propertyName({ key: left.property }) !== "method") {
				return;
			}
			addEndpoint(enclosingOperation(assignmentPath.node), staticPrimitive(assignmentPath.node.right, constants), assignmentPath.node);
		},
		ObjectProperty(propertyPath) {
			if (propertyName(propertyPath.node) !== "method") {
				return;
			}
			addEndpoint(enclosingOperation(propertyPath.node), staticPrimitive(propertyPath.node.value, constants), propertyPath.node);
		},
	});
	return operations;
}

function inferVuexNamespace(filePath) {
	const normalized = toPosix(filePath);
	const d2adminMatch = normalized.match(/^src\/store\/modules\/d2admin\/modules\/([^/]+)\.js$/);
	if (d2adminMatch) {
		return `d2admin/${d2adminMatch[1]}`;
	}
	const directMatch = normalized.match(/^src\/store\/modules\/([^/]+)(?:\/index)?\.js$/);
	return directMatch ? directMatch[1] : null;
}

function scanVuexModule(ast, filePath, store, sourceId) {
	const namespace = inferVuexNamespace(filePath);
	if (!namespace) {
		return;
	}
	const options = findExportDefaultObject(ast);
	if (!options) {
		return;
	}
	const definitions = [
		["state", "vuexState"],
		["getters", "vuexGetter"],
		["actions", "vuexAction"],
		["mutations", "vuexMutation"],
	];
	definitions.forEach(([section, type]) => {
		const sectionNode = findProperty(options, section)?.value;
		for (const entry of objectEntries(sectionNode)) {
			const separator = type === "vuexState" || type === "vuexGetter" ? "." : "/";
			const name = `${namespace}${separator}${entry.name}`;
			const nodeId = `${type}:${name}`;
			store.addNode({ id: nodeId, type, name, path: filePath });
			store.addEdge({
				from: sourceId,
				to: nodeId,
				type: "declares",
				evidence: locationOf(entry.node, filePath),
			});
		}
	});
}

function memberChain(node) {
	const parts = [];
	let current = node;
	while (current?.type === "MemberExpression" && !current.computed) {
		parts.unshift(current.property.name || current.property.value);
		current = current.object;
	}
	if (current?.type === "Identifier") {
		parts.unshift(current.name);
	} else if (current?.type === "ThisExpression") {
		parts.unshift("this");
	}
	return parts;
}

function functionForNode(functions, node) {
	return functions
		.filter(item => item.start <= node.start && item.end >= node.end)
		.sort((left, right) => (left.end - left.start) - (right.end - right.start))[0] || null;
}

function addVuexReference(store, type, name, fromId, filePath, node) {
	const config = {
		state: ["vuexState", "readsState"],
		getter: ["vuexGetter", "readsGetter"],
		action: ["vuexAction", "dispatchesAction"],
		mutation: ["vuexMutation", "commitsMutation"],
	}[type];
	const nodeId = `${config[0]}:${name}`;
	store.addNode({ id: nodeId, type: config[0], name });
	store.addEdge({
		from: fromId,
		to: nodeId,
		type: config[1],
		evidence: locationOf(node, filePath),
	});
}

function scanVueScript(ast, filePath, store, context, sourceId, bindings) {
	const options = findExportDefaultObject(ast);
	const functions = [];
	const componentBindings = new Map();
	if (options) {
		const propsNode = findProperty(options, "props")?.value;
		const propNames = propsNode?.type === "ArrayExpression"
			? arrayValues(propsNode)
			: objectEntries(propsNode).map(entry => entry.name);
		propNames.forEach((name) => {
			const propId = `function:${filePath}#prop:${name}`;
			store.addNode({
				id: propId,
				type: "function",
				name: String(name),
				path: filePath,
				meta: { kind: "prop" },
			});
			store.addEdge({
				from: sourceId,
				to: propId,
				type: "declares",
				evidence: locationOf(propsNode, filePath),
			});
		});
		const componentsNode = findProperty(options, "components")?.value;
		for (const entry of objectEntries(componentsNode)) {
			const localName = entry.value.type === "Identifier" ? entry.value.name : entry.name;
			const binding = bindings.get(localName);
			if (binding) {
				const targetId = ensureFileNode(store, binding.path, context);
				componentBindings.set(entry.name, binding.path);
				store.addEdge({
					from: sourceId,
					to: targetId,
					type: "usesComponent",
					evidence: locationOf(entry.node, filePath),
				});
			}
		}

		const sections = ["methods", "computed", "watch"];
		sections.forEach((section) => {
			const sectionNode = findProperty(options, section)?.value;
			for (const entry of objectEntries(sectionNode)) {
				const functionId = `function:${filePath}#${entry.name}`;
				store.addNode({ id: functionId, type: "function", name: entry.name, path: filePath });
				store.addEdge({
					from: sourceId,
					to: functionId,
					type: "declares",
					evidence: locationOf(entry.node, filePath),
				});
				functions.push({ id: functionId, name: entry.name, start: entry.node.start, end: entry.node.end });
			}
		});
		["beforeCreate", "created", "beforeMount", "mounted", "beforeUpdate", "updated", "beforeDestroy", "destroyed"].forEach((name) => {
			const lifecycle = findProperty(options, name);
			if (!lifecycle) {
				return;
			}
			const functionId = `function:${filePath}#${name}`;
			store.addNode({ id: functionId, type: "function", name, path: filePath });
			store.addEdge({
				from: sourceId,
				to: functionId,
				type: "declares",
				evidence: locationOf(lifecycle, filePath),
			});
			functions.push({ id: functionId, name, start: lifecycle.start, end: lifecycle.end });
		});
	}

	traverse(ast, {
		CallExpression(callPath) {
			const node = callPath.node;
			const currentFunction = functionForNode(functions, node);
			const fromId = currentFunction?.id || sourceId;
			if (node.callee.type === "Identifier" && bindings.has(node.callee.name)) {
				const binding = bindings.get(node.callee.name);
				if (/(?:^|\/)api(?:\/|\.js$)/.test(binding.path)) {
					const operationName = binding.imported === "default" ? node.callee.name : binding.imported;
					const operationId = `api:${binding.path}#${operationName}`;
					store.addNode({ id: operationId, type: "apiOperation", name: operationName, path: binding.path });
					store.addEdge({
						from: fromId,
						to: operationId,
						type: "callsApi",
						evidence: locationOf(node, filePath),
					});
				}
			}
			const chain = memberChain(node.callee);
			if (chain[0] === "this" && chain.length === 2 && !chain[1].startsWith("$")) {
				const targetId = `function:${filePath}#${chain[1]}`;
				store.addNode({ id: targetId, type: "function", name: chain[1], path: filePath });
				store.addEdge({
					from: fromId,
					to: targetId,
					type: "calls",
					evidence: locationOf(node, filePath),
				});
			}
			if (chain.join(".") === "this.$router.push" || chain.join(".") === "this.$router.replace") {
				const argument = node.arguments[0];
				let target = null;
				let staticReference = null;
				let sameRouteUpdate = false;
				if (argument?.type === "ObjectExpression") {
					const nameNode = findProperty(argument, "name")?.value;
					const pathNode = findProperty(argument, "path")?.value;
					const name = staticPrimitive(nameNode);
					const routePath = staticPrimitive(pathNode);
					sameRouteUpdate = (!nameNode && !pathNode)
						|| (memberChain(pathNode).join(".") === "this.$route.path");
					staticReference = name || routePath;
					target = (name && context.routesByName.get(String(name)))
						|| (routePath && (context.routesByPath.get(String(routePath))
							|| context.routesByPath.get(`/${String(routePath).replace(/^\//, "")}`)));
				} else {
					const routePath = staticPrimitive(argument);
					staticReference = routePath;
					target = routePath && context.routesByPath.get(String(routePath));
				}
				if (target) {
					store.addEdge({
						from: fromId,
						to: target,
						type: "navigatesTo",
						evidence: locationOf(node, filePath),
					});
				} else if (!sameRouteUpdate) {
					store.addUnresolved({
						kind: "route",
						path: filePath,
						line: node.loc?.start.line,
						column: node.loc?.start.column,
						reason: staticReference ? "missing-target" : "dynamic-expression",
						expressionKind: argument?.type || "Unknown",
					});
				}
			}
			if (chain.join(".") === "this.$store.dispatch" || chain.join(".") === "this.$store.commit") {
				const reference = staticPrimitive(node.arguments[0]);
				if (typeof reference === "string") {
					addVuexReference(store, chain[2] === "dispatch" ? "action" : "mutation", reference, fromId, filePath, node);
				}
			}
			if (chain.join(".") === "this.$emit") {
				const eventName = staticPrimitive(node.arguments[0]);
				if (typeof eventName === "string") {
					const eventId = `event:${eventName}`;
					store.addNode({ id: eventId, type: "event", name: eventName });
					store.addEdge({
						from: sourceId,
						to: eventId,
						type: "emitsEvent",
						evidence: locationOf(node, filePath),
					});
				}
			}

			if (["mapState", "mapGetters", "mapActions", "mapMutations"].includes(node.callee.name)) {
				const namespace = staticPrimitive(node.arguments[0]);
				const names = arrayValues(node.arguments[1]);
				if (typeof namespace === "string") {
					names.forEach((name) => {
						const type = {
							mapState: "state",
							mapGetters: "getter",
							mapActions: "action",
							mapMutations: "mutation",
						}[node.callee.name];
						const separator = ["state", "getter"].includes(type) ? "." : "/";
						addVuexReference(store, type, `${namespace}${separator}${name}`, sourceId, filePath, node);
					});
				}
			}
		},
		MemberExpression(memberPath) {
			const chain = memberChain(memberPath.node);
			if (chain.slice(0, 3).join(".") === "this.$store.state" && chain.length >= 5) {
				addVuexReference(store, "state", `${chain[3]}.${chain[4]}`, sourceId, filePath, memberPath.node);
			}
			if (memberPath.node.computed
				&& memberChain(memberPath.node.object).join(".") === "this.$store.getters") {
				const getterName = staticPrimitive(memberPath.node.property);
				if (typeof getterName === "string") {
					addVuexReference(store, "getter", getterName, sourceId, filePath, memberPath.node);
				}
			}
		},
	});
	return componentBindings;
}

function scanTemplate(template, filePath, store, sourceId, componentBindings, context) {
	if (!template) {
		return;
	}
	const tagPattern = /<([A-Z][\w-]*)(?:\s([^>]*))?>/gi;
	for (let match = tagPattern.exec(template); match; match = tagPattern.exec(template)) {
		const tagName = match[1];
		const normalizedTag = tagName.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
		const bindingEntry = [...componentBindings.entries()].find(([name]) => name.toLowerCase() === normalizedTag.toLowerCase());
		if (bindingEntry) {
			const targetId = ensureFileNode(store, bindingEntry[1], context);
			store.addEdge({
				from: sourceId,
				to: targetId,
				type: "usesComponent",
				evidence: { path: filePath, line: template.slice(0, match.index).split("\n").length, column: 0 },
			});
		}
		const eventPattern = /(?:@|v-on:)([\w-]+)(?:\.[\w-]+)*=["']([^"']+)["']/g;
		for (let eventMatch = eventPattern.exec(match[2] || ""); eventMatch;
			eventMatch = eventPattern.exec(match[2] || "")) {
			const eventId = `event:${eventMatch[1]}`;
			store.addNode({ id: eventId, type: "event", name: eventMatch[1] });
			store.addEdge({
				from: sourceId,
				to: eventId,
				type: "listensEvent",
				evidence: { path: filePath, line: template.slice(0, match.index).split("\n").length, column: 0 },
			});
			const handlerName = eventMatch[2].match(/^[A-Z_$][\w$]*/i)?.[0];
			if (handlerName) {
				store.addEdge({
					from: eventId,
					to: `function:${filePath}#${handlerName}`,
					type: "calls",
					evidence: { path: filePath, line: template.slice(0, match.index).split("\n").length, column: 0 },
				});
			}
		}
	}
}

function scanVueFile(rootDir, filePath, store, context) {
	const source = fs.readFileSync(path.join(rootDir, filePath), "utf8");
	const descriptor = vueCompiler.parseComponent(source, { pad: "line" });
	const sourceId = ensureFileNode(store, filePath, context);
	if (!descriptor.script?.content) {
		return;
	}
	let ast;
	try {
		ast = parseJavaScript(descriptor.script.content, filePath);
	} catch (error) {
		store.addUnresolved({
			kind: "parse",
			path: filePath,
			reason: error.reasonCode || "syntax-error",
			expressionKind: "SFC-script",
		});
		return;
	}
	const bindings = collectImports(ast, rootDir, filePath, store, context, sourceId);
	const componentBindings = scanVueScript(ast, filePath, store, context, sourceId, bindings);
	scanTemplate(descriptor.template?.content, filePath, store, sourceId, componentBindings, context);
}

function scanJavaScriptFile(rootDir, filePath, store, context) {
	const source = fs.readFileSync(path.join(rootDir, filePath), "utf8");
	let ast;
	try {
		ast = parseJavaScript(source, filePath);
	} catch (error) {
		store.addUnresolved({
			kind: "parse",
			path: filePath,
			reason: error.reasonCode || "syntax-error",
			expressionKind: "Program",
		});
		return;
	}
	const sourceId = ensureFileNode(store, filePath, context);
	const bindings = collectImports(ast, rootDir, filePath, store, context, sourceId);
	const constants = collectConstants(ast);
	collectApiOperations(ast, filePath, store, constants, sourceId);
	scanVuexModule(ast, filePath, store, sourceId);
	const genericFunctions = [];
	traverse(ast, {
		CallExpression(callPath) {
			const chain = memberChain(callPath.node.callee).join(".");
			if (["router.beforeEach", "router.afterEach"].includes(chain)) {
				const callback = callPath.node.arguments[0];
				if (["ArrowFunctionExpression", "FunctionExpression"].includes(callback?.type)) {
					const name = chain.endsWith("beforeEach") ? "beforeEachGuard" : "afterEachHook";
					const functionId = `function:${filePath}#${name}`;
					store.addNode({
						id: functionId,
						type: "function",
						name,
						path: filePath,
						meta: { kind: "router-guard" },
					});
					store.addEdge({
						from: sourceId,
						to: functionId,
						type: "declares",
						evidence: locationOf(callPath.node, filePath),
					});
					genericFunctions.push({ id: functionId, start: callback.start, end: callback.end });
				}
			}
		},
	});
	traverse(ast, {
		CallExpression(callPath) {
			const node = callPath.node;
			const chain = memberChain(node.callee).join(".");
			const currentFunction = functionForNode(genericFunctions, node);
			const fromId = currentFunction?.id || sourceId;
			const storeOperation = chain === "store.dispatch" || chain === "store.commit"
				|| node.callee.name === "dispatch" || node.callee.name === "commit";
			if (storeOperation) {
				const reference = staticPrimitive(node.arguments[0], constants);
				if (typeof reference === "string") {
					const isDispatch = chain === "store.dispatch" || node.callee.name === "dispatch";
					addVuexReference(store, isDispatch ? "action" : "mutation", reference, fromId, filePath, node);
				}
			}
			if (["router.addRoutes", "router.addRoute"].includes(chain)) {
				const targetId = `function:${filePath}#dynamicRouteRegistration`;
				store.addNode({
					id: targetId,
					type: "function",
					name: "dynamicRouteRegistration",
					path: filePath,
					meta: { kind: "dynamic-route" },
				});
				store.addEdge({
					from: fromId,
					to: targetId,
					type: "calls",
					evidence: locationOf(node, filePath),
				});
				store.addUnresolved({
					kind: "dynamic-route",
					path: filePath,
					line: node.loc?.start.line,
					column: node.loc?.start.column,
					reason: "runtime-registration",
					expressionKind: node.arguments[0]?.type || "Unknown",
				});
			}
			if (chain === "require.context") {
				const directory = staticPrimitive(node.arguments[0], constants);
				if (typeof directory === "string") {
					const absoluteDirectory = path.resolve(rootDir, path.dirname(filePath), directory);
					if (fs.existsSync(absoluteDirectory) && fs.statSync(absoluteDirectory).isDirectory()) {
						fs.readdirSync(absoluteDirectory, { withFileTypes: true })
							.filter(entry => entry.isFile() && entry.name.endsWith(".js"))
							.forEach((entry) => {
								const targetPath = relativePath(rootDir, path.join(absoluteDirectory, entry.name));
								const targetId = ensureFileNode(store, targetPath, context);
								store.addEdge({
									from: sourceId,
									to: targetId,
									type: "imports",
									confidence: 0.9,
									evidence: locationOf(node, filePath),
								});
							});
					}
				}
			}
		},
	});
	if (isTestFile(filePath)) {
		traverse(ast, {
			CallExpression(callPath) {
				if (!["mount", "shallowMount"].includes(callPath.node.callee.name)) {
					return;
				}
				const componentName = callPath.node.arguments[0]?.name;
				const binding = bindings.get(componentName);
				if (!binding) {
					return;
				}
				const targetId = ensureFileNode(store, binding.path, context);
				store.addEdge({
					from: targetId,
					to: sourceId,
					type: "coveredBy",
					evidence: locationOf(callPath.node, filePath),
				});
			},
		});
	}
	const contractPattern = /@see\s+([^\s*]+\.contract\.md)/g;
	for (let contractMatch = contractPattern.exec(source); contractMatch;
		contractMatch = contractPattern.exec(source)) {
		const contractSpecifier = contractMatch[1].startsWith(".")
			? contractMatch[1]
			: `./${contractMatch[1]}`;
		const contractPath = resolveModule(rootDir, filePath, contractSpecifier);
		if (!contractPath) {
			continue;
		}
		const contractId = ensureFileNode(store, contractPath, context);
		store.addEdge({
			from: sourceId,
			to: contractId,
			type: "documentedBy",
			evidence: {
				path: filePath,
				line: source.slice(0, contractMatch.index).split("\n").length,
				column: 0,
			},
		});
	}
}

function scanContractFile(rootDir, filePath, store, context) {
	const documentId = ensureFileNode(store, filePath, context);
	let contract;
	try {
		contract = JSON.parse(fs.readFileSync(path.join(rootDir, filePath), "utf8"));
	} catch (error) {
		store.addUnresolved({
			kind: "parse",
			path: filePath,
			reason: "invalid-json",
			expressionKind: "Contract",
		});
		return;
	}
	if (typeof contract.method !== "string") {
		store.addUnresolved({
			kind: "contract",
			path: filePath,
			reason: "missing-method",
			expressionKind: "Contract",
		});
		return;
	}
	const endpointId = `endpoint:${contract.method}`;
	store.addNode({ id: endpointId, type: "endpoint", name: contract.method, path: filePath });
	store.addEdge({
		from: endpointId,
		to: documentId,
		type: "documentedBy",
		evidence: { path: filePath, line: 2, column: 2 },
	});
}

function scanDocument(rootDir, filePath, store, context) {
	const source = fs.readFileSync(path.join(rootDir, filePath), "utf8");
	const documentId = ensureFileNode(store, filePath, context);
	const linkPattern = /\[[^\]]+\]\(([^)]+)\)/g;
	for (let match = linkPattern.exec(source); match; match = linkPattern.exec(source)) {
		const target = match[1].split("#")[0];
		if (!target || /^[a-z]+:/i.test(target)) {
			continue;
		}
		const absoluteTarget = path.resolve(rootDir, path.dirname(filePath), target);
		if (!fs.existsSync(absoluteTarget)) {
			store.addUnresolved({
				kind: "document-link",
				path: filePath,
				line: source.slice(0, match.index).split("\n").length,
				column: 0,
				reason: "missing-target",
				expressionKind: "MarkdownLink",
			});
			continue;
		}
		if (!fs.statSync(absoluteTarget).isFile()) {
			continue;
		}
		const targetPath = relativePath(rootDir, absoluteTarget);
		const targetId = ensureFileNode(store, targetPath, context);
		store.addEdge({
			from: targetId,
			to: documentId,
			type: "documentedBy",
			evidence: {
				path: filePath,
				line: source.slice(0, match.index).split("\n").length,
				column: 0,
			},
		});
	}
}

module.exports = {
	ensureFileNode,
	fileNodeId,
	scanDocument,
	scanContractFile,
	scanJavaScriptFile,
	scanVueFile,
};