From b29e6b4f3eeb77110ff2a149a94a82ccdb525307 Mon Sep 17 00:00:00 2001 From: MCR-3 Date: Tue, 22 Sep 2026 09:15:47 +0200 Subject: [PATCH] feat: add TypeScript and JavaScript support via a single language plugin TS and JS share syntax and routinely import each other, so one Language plugin (backend/languages/typescript.py) reads both, using tree-sitter- typescript. Each file and function keeps its own Language, typescript or javascript, stamped by extension, which drives its badge and highlighting; the dispatcher now lets a plugin set this per file instead of only per plugin. Splitting them into two plugins would have silently dropped every call edge crossing a .ts/.js boundary, since the dispatcher only hands a plugin its own extensions. The plugin extracts function declarations, class members (methods, constructors, static methods, getters/setters, field arrows), named function/arrow expressions, object-literal methods, and anonymous default exports (named .default so two files' defaults stay distinct). It resolves ESM and basic CommonJS imports/exports, and calls through plain references, this.m(), Class.staticM(), namespace access, and typed variables/constructors - documented in the plugin's own docstring, along with what stays out of reach (dynamic calls, JSX, inheritance, deep member chains). "Untyped" is not a separate mode: a missing annotation is just a None annotation, exactly as it already is for an untyped TypeScript parameter, and the card omits the return arrow for JS/TS rather than claiming None. Also: SKIP_DIRS gains dist/build, .d.ts and minified files are skipped in both the picker and the plugin, and CONTEXT.md gets a Language term plus a widened Language plugin definition to cover a family of related languages. Closes #18 --- CLAUDE.md | 4 +- CONTEXT.md | 5 +- README.md | 8 +- backend/analyzer.py | 6 +- backend/languages/__init__.py | 3 +- backend/languages/base.py | 8 +- backend/languages/typescript.py | 789 +++++++++++++++++++++++ backend/requirements.txt | 1 + frontend/src/components/FunctionNode.tsx | 19 +- frontend/src/languages.ts | 24 + frontend/src/localFiles.ts | 19 +- sample_typescript_project/Report.tsx | 5 + sample_typescript_project/formatting.jsx | 8 + sample_typescript_project/main.ts | 16 + sample_typescript_project/models.ts | 16 + sample_typescript_project/processing.ts | 14 + sample_typescript_project/storage.js | 27 + 17 files changed, 957 insertions(+), 15 deletions(-) create mode 100644 backend/languages/typescript.py create mode 100644 sample_typescript_project/Report.tsx create mode 100644 sample_typescript_project/formatting.jsx create mode 100644 sample_typescript_project/main.ts create mode 100644 sample_typescript_project/models.ts create mode 100644 sample_typescript_project/processing.ts create mode 100644 sample_typescript_project/storage.js diff --git a/CLAUDE.md b/CLAUDE.md index c936e47..96ad0ac 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -28,7 +28,7 @@ There is **no test suite**. Verify by hand: - Frontend: `npm run build` and `npm run lint` in `frontend/`. - Backend: start uvicorn and `GET /api/health`. -- Analyzer or language-plugin changes: run `python -m backend.analyzer` on `sample_project` and `sample_rust_project` before and after, and compare function and edge counts. An unexplained drop in edges is a regression. +- Analyzer or language-plugin changes: run `python -m backend.analyzer` on `sample_project`, `sample_rust_project` and `sample_typescript_project` before and after, and compare function and edge counts. An unexplained drop in edges is a regression. CI (`.github/workflows/pr-checks.yml`) only runs the frontend build and the backend health check. It does not lint and does not exercise the analyzer, so green CI says little about analysis correctness. @@ -36,7 +36,7 @@ CI (`.github/workflows/pr-checks.yml`) only runs the frontend build and the back - **The server never reads the visitor's filesystem.** The browser reads picked files and POSTs `{root, files: [{path, content}]}` to `/api/analyze`. `analyze_path()` and the disk walk in `analyzer.py` exist for the CLI only. - **The wire format is a two-sided contract.** Backend `FunctionInfo.to_dict()` (`backend/languages/base.py`) emits camelCase; `frontend/src/types.ts` mirrors it by hand. Change one, change the other. -- **`SKIP_DIRS` is duplicated** in `backend/languages/base.py` and `frontend/src/localFiles.ts`. Keep them in sync. +- **`SKIP_DIRS` is duplicated** in `backend/languages/base.py` and `frontend/src/localFiles.ts`. Keep them in sync. So is the rule that drops `.d.ts` and `*.min.js` (`_is_skipped_file` in `typescript.py`, `SKIP_FILE` in `localFiles.ts`). - **The theme is applied in two places.** The inline script in `frontend/index.html` sets `data-theme` before first paint, and `frontend/src/theme.ts` owns it afterwards. They share the storage key and the resolution rules; keep them in sync. Colors belong in the tokens at the top of `index.css`, never as literals (the function card header and the language badge text are the deliberately theme-independent surfaces). - **Paths must be relative to the picked folder's contents**, with the folder's own name stripped (`localFiles.ts`). Module-name derivation and import resolution in the plugins depend on it. - **Vocabulary lives in `CONTEXT.md`; use its terms.** The code hasn't caught up on two of them: **File mode** is still `"folder"` in the code (`OrgMode`, `FolderFrame`, `layoutFolderGraph`), and **Trace up / Trace down** is still `showFlow`. Don't rename these as a drive-by; use the glossary term in prose and the code name in code. diff --git a/CONTEXT.md b/CONTEXT.md index db88168..fd2f4f8 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -21,8 +21,11 @@ _Avoid_: Link, dependency The function activated automatically when a project loads: the project's top-level `main`, if it has one. _Avoid_: Start function, root function +**Language**: +What a source file is written in, as shown by its badge, its Explorer icon and its syntax highlighting. A file has exactly one Language. + **Language plugin**: -The support for one programming language: the piece that knows how to read that language's functions and their calls. +The support for one programming language, or for a family of closely related ones whose files import each other (TypeScript and JavaScript share one): the piece that knows how to read those languages' functions and their calls. One plugin may read several Languages; each file keeps its own. _Avoid_: Parser ### Roots diff --git a/README.md b/README.md index b19e25b..2ace2b2 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,8 @@ The goal is to make the flow of a codebase visible instead of jumping between fi | --- | --- | | Python | `.py` | | Rust | `.rs` | +| TypeScript | `.ts`, `.tsx`, `.mts`, `.cts` | +| JavaScript | `.js`, `.jsx`, `.mjs`, `.cjs` | More languages can be added without touching the frontend - see [Backend](#backend) below. @@ -43,7 +45,7 @@ npm install npm run dev ``` -Open http://localhost:5173 and load a folder or file from the sidebar. Try `sample_project` (Python) or `sample_rust_project` (Rust) for a quick demo. +Open http://localhost:5173 and load a folder or file from the sidebar. Try `sample_project` (Python), `sample_rust_project` (Rust) or `sample_typescript_project` (TypeScript and JavaScript) for a quick demo. ## Codebase @@ -52,6 +54,7 @@ backend/ FastAPI + a per-language plugin architecture, static analysi frontend/src/ React 19 + React Flow + Zustand, the UI sample_project/ Python demo fixture used for manual testing sample_rust_project/ Rust demo fixture used for manual testing +sample_typescript_project/ TypeScript + JavaScript demo fixture used for manual testing ``` ### Backend @@ -60,6 +63,7 @@ sample_rust_project/ Rust demo fixture used for manual testing - `languages/`: one module per language, each implementing the same `LanguagePlugin` contract (`languages/base.py`) - parse every file, extract each function's signature/docstring/source lines, and resolve which loaded functions it calls (direct calls, `module.func()`, `self.method()`, constructors/associated functions). Only calls between functions that were actually loaded get resolved. Adding a language means adding one new module here and registering it in `languages/__init__.py`; nothing else changes. - `python.py`: parses with the stdlib `ast`. - `rust.py`: parses with `tree-sitter` + `tree-sitter-rust` (functions, `impl` methods, `use`-based and bare-path module resolution). Calls made inside a macro invocation (`println!`, `format!`, ...) aren't visible to it - macro arguments are an opaque token stream, not parsed expressions. + - `typescript.py`: one plugin for TypeScript and JavaScript, parsed with `tree-sitter` + `tree-sitter-typescript` (the `typescript` grammar for `.ts`, `.tsx` for everything else). It stamps each file with its own language, so a `.ts` file and a `.js` file get their own badge but can call each other. Reads ESM and basic CommonJS imports, resolves relative specifiers and (by unique path suffix) aliases, and ignores `.d.ts` and minified files. There's no separate "JS mode": a missing annotation is just a missing annotation. Its docstring lists exactly what it resolves and what it can't (JSX elements, inheritance, dynamic calls, ...). - `main.py`: the FastAPI app. `GET /api/browse` powers the server-side folder picker, `POST /api/analyze` runs the analyzer and returns the graph as JSON. Also serves the built frontend in production. ### Frontend @@ -72,7 +76,7 @@ sample_rust_project/ Rust demo fixture used for manual testing - `components/FolderFrame.tsx`: the folder style group frame used in folder mode. - `components/Sidebar.tsx`, `FileTree.tsx`, `SearchBar.tsx`, `PathBrowser.tsx`: import controls, a nested directory tree, search, and the server-side folder browser. - `components/LanguageIcon.tsx`: the small per-file language badge shown in the Explorer. -- `languages.ts`: the frontend's mirror of the backend's language registry - id, label, extensions, icon color per language. Adding a language to the backend also means adding one entry here. +- `languages.ts`: the frontend's mirror of the backend's language registry - id, label, extensions, icon color per language, plus two optional settings (`prism`, a highlighting grammar not named like the id; `unannotatedReturn`, what a card shows when a return type is missing). Adding a language to the backend also means adding one entry here. - `api.ts`, `types.ts`, `colors.ts`: fetch wrapper, wire format types, and per file color hashing. - `theme.ts`, `components/ThemeToggle.tsx`: the theme preference (System, Light or Dark), the System theme tracking, and the topbar toggle. The resolved theme is set as `data-theme` on ``, and every color in `index.css` is a token that the Light theme overrides. diff --git a/backend/analyzer.py b/backend/analyzer.py index 6ed8870..a004d89 100644 --- a/backend/analyzer.py +++ b/backend/analyzer.py @@ -51,11 +51,13 @@ def analyze_sources(sources: dict[str, str], root: str = "") -> dict: if not lang_sources: continue result = lang.analyze(lang_sources) + # A plugin that reads several languages stamps each file/function itself; + # otherwise everything it returned is in the plugin's own language. for file_entry in result["files"]: - file_entry["language"] = lang.id + file_entry.setdefault("language", lang.id) files.append(file_entry) for func_id, func in result["functions"].items(): - func["language"] = lang.id + func.setdefault("language", lang.id) functions[func_id] = func edges.extend(result["edges"]) diff --git a/backend/languages/__init__.py b/backend/languages/__init__.py index 25e28a6..6ae33ed 100644 --- a/backend/languages/__init__.py +++ b/backend/languages/__init__.py @@ -11,8 +11,9 @@ from .base import SKIP_DIRS, LanguagePlugin from .python import PythonLanguage from .rust import RustLanguage +from .typescript import TypeScriptLanguage -LANGUAGES: list[LanguagePlugin] = [PythonLanguage(), RustLanguage()] +LANGUAGES: list[LanguagePlugin] = [PythonLanguage(), RustLanguage(), TypeScriptLanguage()] EXTENSION_TO_LANGUAGE: dict[str, LanguagePlugin] = {ext: lang for lang in LANGUAGES for ext in lang.extensions} diff --git a/backend/languages/base.py b/backend/languages/base.py index fb23037..4fddc56 100644 --- a/backend/languages/base.py +++ b/backend/languages/base.py @@ -13,7 +13,7 @@ # Directories skipped while walking a disk tree, shared across all languages # (build/dependency/vcs dirs a source scan should never descend into). -SKIP_DIRS = {"__pycache__", "node_modules", ".git", ".venv", "venv", ".tox", ".mypy_cache", "target"} +SKIP_DIRS = {"__pycache__", "node_modules", ".git", ".venv", "venv", ".tox", ".mypy_cache", "target", "dist", "build"} @dataclass @@ -55,7 +55,7 @@ def to_dict(self) -> dict: class LanguagePlugin(ABC): """One entry in the language registry (see languages/__init__.py).""" - id: str # "python", "rust" - also stamped onto each file/function in the response + id: str # "python", "rust" - stamped onto each file/function unless the plugin sets its own label: str # "Python", "Rust" extensions: frozenset[str] # {".py"}, {".rs"} - dot-prefixed, lowercase @@ -66,4 +66,8 @@ def analyze(self, sources: dict[str, str]) -> dict: Returns {"files": [...], "functions": {...}, "edges": [...]} - the same shape the top-level analyzer.py dispatcher returns, scoped to just this language's files. + + A plugin that reads a family of related languages (TypeScript and + JavaScript) sets "language" on each file and function entry itself; + the dispatcher only fills it in, with `id`, where it is missing. """ diff --git a/backend/languages/typescript.py b/backend/languages/typescript.py new file mode 100644 index 0000000..eb5ce02 --- /dev/null +++ b/backend/languages/typescript.py @@ -0,0 +1,789 @@ +"""TypeScript / JavaScript language plugin: tree-sitter-based analysis. + +One plugin reads both languages. TypeScript's syntax is a superset of +JavaScript's and the two import each other freely, so splitting them would +lose every call edge that crosses a `.ts`/`.js` boundary (the dispatcher +hands a plugin only its own extensions). Each file is still stamped with its +own Language, `typescript` or `javascript`, by extension, which drives its +badge and highlighting. + +"Untyped" is not a mode: a parameter without an annotation simply has +`annotation: None`, exactly as an unannotated TypeScript parameter does. + +Functions are module-level declarations: functions; class methods, +constructors, static methods, getters and setters (named `get x` / `set x`); +arrow and function expressions bound to a name, class-field arrows included; +object-literal methods (`obj.method`); and anonymous default exports, named +`.default` so two files' defaults stay apart. Bodiless overload, +abstract and interface signatures are not Functions. Anonymous callbacks and +nested closures aren't Functions either: their calls are attributed to the +enclosing function. A leading `/** */` block is the docstring (its types are +not read), and decorators stay part of a member's code. + +Imports: ESM (relative, named, default, namespace, `export { } from`, +`export *`) and CommonJS (`require`, `module.exports`, `exports.x`). A +relative specifier resolves against the importing file, leaving off the +extension or naming a directory's `index`, and `./x.js` finds `x.ts`. Nothing +else is read (no tsconfig or package.json), so any other specifier resolves +only when exactly one loaded file's path ends with it; packages never do. + +Calls resolved: `foo()`, `new Foo()`, `this.m()`, `Class.staticM()`, `ns.f()` +and `variable.m()` when the variable's class is known from a parameter +annotation, `const x: Foo` or `const x = new Foo()` - so annotated code +yields more edges than untyped code, but through the same path. + +Real limits, in the spirit of the other plugins' resolvers: one object and +one member only (no `this.a.b()`); no inheritance (`super`, inherited +methods); no dynamic calls (`obj[key]()`, `.call`, `.apply`); a function +passed as a value (`items.map(fn)`) isn't a call; JSX elements (``) +aren't calls; a getter or setter runs on property access, which isn't a call; +`export * as ns` isn't followed; and top-level statements belong to no Function. +""" + +from __future__ import annotations + +import posixpath +import tree_sitter_typescript +from dataclasses import dataclass, field +from tree_sitter import Language, Node, Parser + +from .base import FunctionInfo, LanguagePlugin + +_TS_GRAMMAR = Language(tree_sitter_typescript.language_typescript()) +_TSX_GRAMMAR = Language(tree_sitter_typescript.language_tsx()) + +# `.ts`/`.mts`/`.cts` use the plain TypeScript grammar (angle-bracket casts are +# legal there, JSX is not). Everything else, plain JavaScript included, uses +# TSX: a superset that also parses JSX, and JS never needs the casts. +_TS_GRAMMAR_EXTENSIONS = frozenset({".ts", ".mts", ".cts"}) +_TYPESCRIPT_EXTENSIONS = frozenset({".ts", ".tsx", ".mts", ".cts"}) +_JAVASCRIPT_EXTENSIONS = frozenset({".js", ".jsx", ".mjs", ".cjs"}) + +# Overload, abstract and interface signatures have no body and are separate +# node types (function_signature, method_signature, ...), so they never match. +_FUNCTION_NODE_TYPES = frozenset( + { + "function_declaration", + "generator_function_declaration", + "function_expression", + "function", # the same node under older grammar versions + "generator_function", + "arrow_function", + } +) +_CLASS_NODE_TYPES = frozenset({"class_declaration", "abstract_class_declaration", "class"}) +_VARIABLE_STATEMENT_TYPES = frozenset({"lexical_declaration", "variable_declaration"}) + +# What a specifier may leave off, tried in this order (TypeScript wins over a +# compiled `.js` sitting beside it). +_RESOLVE_EXTENSIONS = (".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs") +# `import "./x.js"` in TypeScript ESM code means the source file x.ts. +_TS_SOURCE_FOR_JS_SPECIFIER = {".js": (".ts", ".tsx"), ".jsx": (".tsx",), ".mjs": (".mts",), ".cjs": (".cts",)} + + +@dataclass +class _Import: + specifier: str # the module string exactly as written + original: str | None # the exported name imported; "default" for a default import; None for a namespace import + + +@dataclass +class _ModuleInfo: + rel_path: str # forward slashes + module: str # rel_path without its extension + top_level: dict[str, str] = field(default_factory=dict) # fn name -> function id + # class (or object literal) name -> {member name -> function id} + classes: dict[str, dict[str, str]] = field(default_factory=dict) + imports: dict[str, _Import] = field(default_factory=dict) # local name -> import + export_aliases: dict[str, str] = field(default_factory=dict) # `export { local as name }`: name -> local + default_export: str | None = None # local name behind `export default` + reexports: dict[str, tuple[str, str]] = field(default_factory=dict) # `export { o as n } from`: n -> (specifier, o) + star_reexports: list[str] = field(default_factory=list) # specifiers of `export * from` + + +def _is_skipped_file(rel_path: str) -> bool: + """Type declaration files (no function bodies) and minified bundles (build output). + + Mirrors SKIP_FILE in frontend/src/localFiles.ts; here it also covers the CLI's disk walk. + """ + name = posixpath.basename(rel_path) + return name.endswith((".d.ts", ".d.mts", ".d.cts", ".min.js", ".min.mjs", ".min.cjs")) + + +def _extension(rel_path: str) -> str: + return posixpath.splitext(rel_path)[1] + + +def _language_id(rel_path: str) -> str: + return "typescript" if _extension(rel_path) in _TYPESCRIPT_EXTENSIONS else "javascript" + + +def _module_name(rel_path: str) -> str: + return posixpath.splitext(rel_path)[0] + + +def _text(node: Node | None, source: bytes) -> str: + if node is None: + return "" + return source[node.start_byte : node.end_byte].decode("utf-8", "replace") + + +def _annotation_text(node: Node | None, source: bytes) -> str | None: + """`: string` / `: Promise` -> the type text without its leading colon.""" + text = _text(node, source).lstrip(":").strip() + return text or None + + +def _string_value(node: Node | None, source: bytes) -> str: + return _text(node, source).strip("'\"`") + + +def _clean_jsdoc(comment: str) -> str | None: + """`/** ... */` -> its text, without the delimiters and the leading `*` of each line.""" + body = comment[3:] + if body.endswith("*/"): + body = body[:-2] + lines = [] + for raw in body.split("\n"): + line = raw.strip() + if line.startswith("*"): + line = line[1:] + if line.startswith(" "): + line = line[1:] + lines.append(line.rstrip()) + return "\n".join(lines).strip() or None + + +def _leading_decorators_and_jsdoc(span_node: Node, source: bytes) -> tuple[int, str | None]: + """Returns (code start line, docstring). + + Decorators directly above a member stay part of its code (the analog of a + Python decorator) and pull the start line up to them. A `/** */` block on + the line above that becomes the docstring and is never part of the code. + """ + start_line = span_node.start_point[0] + 1 + node = span_node.prev_sibling + while node is not None and node.type == "decorator" and 0 <= start_line - (node.end_point[0] + 1) <= 1: + start_line = node.start_point[0] + 1 + node = node.prev_sibling + if node is not None and node.type == "comment" and start_line - (node.end_point[0] + 1) == 1: + text = _text(node, source) + if text.startswith("/**"): + return start_line, _clean_jsdoc(text) + return start_line, None + + +def _require_specifier(node: Node | None, source: bytes) -> str | None: + """`require("./x")` -> "./x"; anything else -> None.""" + if node is None or node.type != "call_expression": + return None + func = node.child_by_field_name("function") + args = node.child_by_field_name("arguments") + first = next((c for c in args.children if c.is_named), None) if args is not None else None + if func is None or func.type != "identifier" or _text(func, source) != "require": + return None + return _string_value(first, source) if first is not None and first.type == "string" else None + + +def _is_module_exports(node: Node | None, source: bytes) -> bool: + if node is None or node.type != "member_expression": + return False + obj = node.child_by_field_name("object") + return ( + obj is not None + and obj.type == "identifier" + and _text(obj, source) == "module" + and _text(node.child_by_field_name("property"), source) == "exports" + ) + + +def _member_name(node: Node | None, source: bytes) -> str | None: + """A class member / object key as a plain name; computed keys (`[expr]`) have none.""" + if node is None: + return None + if node.type in ("property_identifier", "private_property_identifier", "identifier", "number"): + return _text(node, source) + if node.type == "string": + return _text(node, source).strip("'\"`") + return None + + +def _type_name(node: Node | None, source: bytes) -> str | None: + """`Foo`, `Foo` and `Foo | null` -> "Foo". Anything less plain has no single class to resolve against.""" + if node is None: + return None + if node.type == "type_annotation": + inner = next((c for c in node.children if c.is_named), None) + return _type_name(inner, source) + if node.type == "type_identifier": + return _text(node, source) + if node.type == "generic_type": + return _type_name(node.child_by_field_name("name"), source) + if node.type == "union_type": + names = {_type_name(c, source) for c in node.children if c.is_named} - {None} + return next(iter(names)) if len(names) == 1 else None + return None + + +def _collect_local_types(fn_node: Node, source: bytes) -> dict[str, str]: + """Variable -> class name, from parameter annotations, `const x: Foo`, and `const x = new Foo()`. + + Walks the whole function, nested callbacks included, and ignores shadowing. + """ + types: dict[str, str] = {} + + def walk(node: Node) -> None: + if node.type in ("required_parameter", "optional_parameter"): + pattern = node.child_by_field_name("pattern") + type_name = _type_name(node.child_by_field_name("type"), source) + if pattern is not None and pattern.type == "identifier" and type_name: + types[_text(pattern, source)] = type_name + elif node.type == "variable_declarator": + name = node.child_by_field_name("name") + if name is not None and name.type == "identifier": + type_name = _type_name(node.child_by_field_name("type"), source) + value = node.child_by_field_name("value") + if type_name is None and value is not None and value.type == "new_expression": + ctor = value.child_by_field_name("constructor") + type_name = _text(ctor, source) if ctor is not None and ctor.type == "identifier" else None + if type_name: + types[_text(name, source)] = type_name + for child in node.children: + walk(child) + + walk(fn_node) + return types + + +def _is_async(fn_node: Node) -> bool: + return any(child.type == "async" for child in fn_node.children) + + +def _extract_params(fn_node: Node, source: bytes) -> list[dict]: + params_node = fn_node.child_by_field_name("parameters") + if params_node is None: + # `x => ...`: a lone unparenthesized arrow parameter + single = fn_node.child_by_field_name("parameter") + return [{"name": _text(single, source), "annotation": None, "default": None}] if single is not None else [] + params: list[dict] = [] + for child in params_node.children: + if child.type not in ("required_parameter", "optional_parameter"): + continue + pattern = child.child_by_field_name("pattern") + name = _text(pattern, source) if pattern is not None else _text(child, source) + if child.type == "optional_parameter": + name += "?" + value = child.child_by_field_name("value") + params.append( + { + "name": name, + "annotation": _annotation_text(child.child_by_field_name("type"), source), + "default": _text(value, source) or None, + } + ) + return params + + +class _CallCollector: + """Collects (lineno, callee-id) pairs inside one function body. + + Descends into everything, nested functions and callbacks included: their + calls are folded into the enclosing function's flow. + """ + + def __init__(self, resolver): + self.resolver = resolver + self.found: list[tuple[int, str]] = [] + + def visit(self, node: Node) -> None: + if node.type in ("call_expression", "new_expression"): + is_new = node.type == "new_expression" + func = node.child_by_field_name("constructor" if is_new else "function") + if func is not None: + target = self.resolver(func, is_new) + if target: + # a method name on a later line than its object (a chain) is where the wire should leave from + anchor = func.child_by_field_name("property") if func.type == "member_expression" else None + self.found.append(((anchor or func).start_point[0] + 1, target)) + for child in node.children: + self.visit(child) + + +class _TypeScriptAnalyzer: + def __init__(self, sources: dict[str, str]): + self.sources = sources + self.sources_bytes: dict[str, bytes] = {} + self.modules: dict[str, _ModuleInfo] = {} # rel_path -> module + self.functions: dict[str, FunctionInfo] = {} + self.file_errors: dict[str, str] = {} + self.file_functions: dict[str, list[str]] = {} + self._specifier_cache: dict[tuple[str, str], _ModuleInfo | None] = {} + + def analyze(self) -> dict: + self._parse_files() + self._resolve_calls() + return self._to_response() + + # -- pass 1: parse everything, register functions -- + + def _parse_files(self) -> None: + ts_parser = Parser(_TS_GRAMMAR) + tsx_parser = Parser(_TSX_GRAMMAR) + for rel_path, source in sorted(self.sources.items()): + self.file_functions.setdefault(rel_path, []) + source_bytes = source.encode("utf-8") + self.sources_bytes[rel_path] = source_bytes + parser = ts_parser if _extension(rel_path) in _TS_GRAMMAR_EXTENSIONS else tsx_parser + tree = parser.parse(source_bytes) + if tree.root_node.has_error: + self.file_errors[rel_path] = "SyntaxError: source has one or more parse errors" + + mod = _ModuleInfo(rel_path=rel_path, module=_module_name(rel_path)) + self.modules[rel_path] = mod + # tree-sitter rows count only "\n", so split on exactly that (not str.splitlines) + source_lines = [line.rstrip("\r") for line in source.split("\n")] + self._walk_module_body(mod, tree.root_node, source_bytes, source_lines) + + def _walk_module_body(self, mod: _ModuleInfo, node: Node, source: bytes, source_lines: list[str]) -> None: + for stmt in node.children: + if stmt.type == "import_statement": + self._register_import(mod, stmt, source) + continue + if stmt.type == "export_statement": + decl = stmt.child_by_field_name("declaration") or stmt.child_by_field_name("value") + self._register_export(mod, stmt, decl, source) + else: + decl = stmt + if decl is not None: + self._register_declaration(mod, decl, stmt, source, source_lines) + if stmt.type == "expression_statement": + self._register_commonjs_export(mod, stmt, source, source_lines) + + def _register_require(self, mod: _ModuleInfo, name_node: Node, value: Node, source: bytes) -> bool: + """`const x = require(..)`, `const { a, b: c } = require(..)`, `const f = require(..).f`. False if it isn't one.""" + prop = None + call = value + if value.type == "member_expression": + call = value.child_by_field_name("object") + prop = _member_name(value.child_by_field_name("property"), source) + specifier = _require_specifier(call, source) + if specifier is None: + return False + if name_node.type == "identifier": + mod.imports[_text(name_node, source)] = _Import(specifier, prop) # no prop: the whole module + elif name_node.type == "object_pattern" and prop is None: + for item in name_node.children: + if item.type == "shorthand_property_identifier_pattern": + name = _text(item, source) + mod.imports[name] = _Import(specifier, name) + elif item.type == "pair_pattern": + key = _member_name(item.child_by_field_name("key"), source) + local = item.child_by_field_name("value") + if key and local is not None and local.type == "identifier": + mod.imports[_text(local, source)] = _Import(specifier, key) + return True + + def _register_commonjs_export(self, mod: _ModuleInfo, stmt: Node, source: bytes, source_lines: list[str]) -> None: + """`module.exports = ...`, `exports.x = ...` and `module.exports.x = ...`.""" + assign = next((c for c in stmt.children if c.type == "assignment_expression"), None) + left = assign.child_by_field_name("left") if assign is not None else None + right = assign.child_by_field_name("right") if assign is not None else None + if left is None or right is None or left.type != "member_expression": + return + obj = left.child_by_field_name("object") + prop = _member_name(left.child_by_field_name("property"), source) + + if _is_module_exports(left, source): # module.exports = + if right.type == "object": + self._register_exported_object(mod, right, source, source_lines) + elif right.type == "identifier": + mod.default_export = _text(right, source) + elif right.type in _FUNCTION_NODE_TYPES or right.type in _CLASS_NODE_TYPES: + mod.default_export = self._register_exported_value(mod, None, right, stmt, source, source_lines) + elif prop and obj is not None and ( + (obj.type == "identifier" and _text(obj, source) == "exports") or _is_module_exports(obj, source) + ): # exports.prop = + if right.type == "identifier": + mod.export_aliases[prop] = _text(right, source) + elif right.type in _FUNCTION_NODE_TYPES or right.type in _CLASS_NODE_TYPES: + self._register_exported_value(mod, prop, right, stmt, source, source_lines) + + def _register_exported_value( + self, mod: _ModuleInfo, name: str | None, value: Node, span: Node, source: bytes, source_lines: list[str] + ) -> str: + """Registers a function or class assigned to module.exports / exports.name; returns the name it is known by.""" + name = name or _text(value.child_by_field_name("name"), source) or self._default_name(mod) + if value.type in _CLASS_NODE_TYPES: + self._register_members(mod, name, value.child_by_field_name("body"), source, source_lines) + else: + info = self._register_function(mod, value, span, name, None, source, source_lines) + mod.top_level[name] = info.id + return name + + def _register_exported_object(self, mod: _ModuleInfo, obj: Node, source: bytes, source_lines: list[str]) -> None: + """`module.exports = { a, b: fn, c: function () {}, d() {} }`: each entry is an export of the module.""" + for member in obj.children: + if member.type == "method_definition": + name = _member_name(member.child_by_field_name("name"), source) + if name and member.child_by_field_name("body") is not None: + info = self._register_function(mod, member, member, name, None, source, source_lines) + mod.top_level[name] = info.id + elif member.type == "pair": + key = _member_name(member.child_by_field_name("key"), source) + value = member.child_by_field_name("value") + if not key or value is None: + continue + if value.type == "identifier": + mod.export_aliases[key] = _text(value, source) + elif value.type in _FUNCTION_NODE_TYPES: + info = self._register_function(mod, value, member, key, None, source, source_lines) + mod.top_level[key] = info.id + # shorthand `a` needs nothing: a top-level `a` is already importable by that name + + def _register_import(self, mod: _ModuleInfo, stmt: Node, source: bytes) -> None: + specifier = _string_value(stmt.child_by_field_name("source"), source) + for clause in stmt.children: + if clause.type == "import_require_clause": # import x = require("./x") + ident = next((c for c in clause.children if c.type == "identifier"), None) + spec = _string_value(clause.child_by_field_name("source"), source) + if ident is not None: + mod.imports[_text(ident, source)] = _Import(spec, None) + elif clause.type == "import_clause": + for part in clause.children: + if part.type == "identifier": # import def from + mod.imports[_text(part, source)] = _Import(specifier, "default") + elif part.type == "namespace_import": # import * as ns from + ident = next((c for c in part.children if c.type == "identifier"), None) + if ident is not None: + mod.imports[_text(ident, source)] = _Import(specifier, None) + elif part.type == "named_imports": # import { a, b as c } from + for item in part.children: + if item.type != "import_specifier": + continue + name = _text(item.child_by_field_name("name"), source) + alias = _text(item.child_by_field_name("alias"), source) + mod.imports[alias or name] = _Import(specifier, name) + + def _register_export(self, mod: _ModuleInfo, stmt: Node, decl: Node | None, source: bytes) -> None: + """Records what this module exports beyond declarations it makes itself: `export { }`, re-exports, `export default`.""" + src = stmt.child_by_field_name("source") + specifier = _string_value(src, source) + clause = next((c for c in stmt.children if c.type == "export_clause"), None) + if clause is not None: + for item in clause.children: + if item.type != "export_specifier": + continue + name = _text(item.child_by_field_name("name"), source) + alias = _text(item.child_by_field_name("alias"), source) or name + if src is not None: + mod.reexports[alias] = (specifier, name) # export { name as alias } from "..." + else: + mod.export_aliases[alias] = name # export { name as alias } + elif src is not None and not any(c.type == "namespace_export" for c in stmt.children): + mod.star_reexports.append(specifier) # export * from "..." (`export * as ns` is not followed) + + if decl is not None and any(c.type == "default" for c in stmt.children): + if decl.type == "identifier": + mod.default_export = _text(decl, source) + elif decl.type in _FUNCTION_NODE_TYPES or decl.type in _CLASS_NODE_TYPES: + mod.default_export = _text(decl.child_by_field_name("name"), source) or self._default_name(mod) + + @staticmethod + def _default_name(mod: _ModuleInfo) -> str: + """`export default` with no name of its own: `Button.default` for Button.tsx, so two files' defaults differ.""" + return f"{posixpath.basename(mod.module)}.default" + + def _register_declaration( + self, mod: _ModuleInfo, decl: Node, stmt: Node, source: bytes, source_lines: list[str] + ) -> None: + """decl is the declaration proper; stmt is the whole statement (an `export` wrapper included), shown as code.""" + if decl.type in _FUNCTION_NODE_TYPES: + name = _text(decl.child_by_field_name("name"), source) or self._default_name(mod) + info = self._register_function(mod, decl, stmt, name, None, source, source_lines) + mod.top_level[name] = info.id + elif decl.type in _CLASS_NODE_TYPES: + name = _text(decl.child_by_field_name("name"), source) or self._default_name(mod) + self._register_members(mod, name, decl.child_by_field_name("body"), source, source_lines) + elif decl.type in _VARIABLE_STATEMENT_TYPES: + declarators = [c for c in decl.children if c.type == "variable_declarator"] + for declarator in declarators: + name_node = declarator.child_by_field_name("name") + value = declarator.child_by_field_name("value") + if name_node is None or value is None: + continue + if self._register_require(mod, name_node, value, source): + continue + if name_node.type != "identifier": + continue + name = _text(name_node, source) + span = stmt if len(declarators) == 1 else declarator + if value.type in _FUNCTION_NODE_TYPES: + info = self._register_function(mod, value, span, name, None, source, source_lines) + mod.top_level[name] = info.id + elif value.type in _CLASS_NODE_TYPES: + self._register_members(mod, name, value.child_by_field_name("body"), source, source_lines) + elif value.type == "object": + self._register_members(mod, name, value, source, source_lines) + + def _register_members( + self, mod: _ModuleInfo, owner: str, container: Node | None, source: bytes, source_lines: list[str] + ) -> None: + """Registers a class body's or object literal's function members as `owner.member`.""" + members = mod.classes.setdefault(owner, {}) + if container is None: + return + for member in container.children: + fn_node = member + if member.type == "method_definition": + name = _member_name(member.child_by_field_name("name"), source) + if name is None or member.child_by_field_name("body") is None: + continue + accessor = next((c.type for c in member.children if c.type in ("get", "set")), None) + if accessor: + name = f"{accessor} {name}" # a getter and setter can share a name, so keep them apart + elif member.type in ("public_field_definition", "pair"): + key = member.child_by_field_name("name" if member.type == "public_field_definition" else "key") + name = _member_name(key, source) + value = member.child_by_field_name("value") + if name is None or value is None or value.type not in _FUNCTION_NODE_TYPES: + continue + fn_node = value + else: + continue + info = self._register_function(mod, fn_node, member, name, owner, source, source_lines) + members[name] = info.id + + def _register_function( + self, + mod: _ModuleInfo, + fn_node: Node, + span_node: Node, + name: str, + class_name: str | None, + source: bytes, + source_lines: list[str], + ) -> FunctionInfo: + """fn_node holds the params and body; span_node is the whole statement shown as the card's code.""" + qualname = f"{class_name}.{name}" if class_name else name + func_id = f"{mod.rel_path}::{qualname}" + + start_line, docstring = _leading_decorators_and_jsdoc(span_node, source) + end_line = span_node.end_point[0] + 1 + raw = source_lines[start_line - 1 : end_line] + indent = len(raw[0]) - len(raw[0].lstrip()) if raw else 0 + code_lines = [] + for i, line in enumerate(raw): + text = line[indent:] if line[:indent].strip() == "" else line + code_lines.append({"lineno": start_line + i, "text": text, "calls": []}) + + info = FunctionInfo( + id=func_id, + name=name, + qualname=qualname, + file=mod.rel_path, + module=mod.module, + class_name=class_name, + lineno=start_line, + end_lineno=end_line, + params=_extract_params(fn_node, source), + returns=_annotation_text(fn_node.child_by_field_name("return_type"), source), + docstring=docstring, + is_async=_is_async(fn_node), + code_lines=code_lines, + ) + self.functions[func_id] = info + self.file_functions[mod.rel_path].append(func_id) + info._node = fn_node # type: ignore[attr-defined] + return info + + # -- pass 2: resolve calls -- + + def _resolve_calls(self) -> None: + for info in self.functions.values(): + mod = self.modules[info.file] + node = info._node # type: ignore[attr-defined] + body = node.child_by_field_name("body") + + resolver = self._make_resolver(mod, info.class_name, _collect_local_types(node, self.sources_bytes[mod.rel_path])) + collector = _CallCollector(resolver) + if body is not None: + collector.visit(body) + + line_index = {cl["lineno"]: cl for cl in info.code_lines} + seen: set[str] = set() + for lineno, target in collector.found: + if lineno in line_index and target not in line_index[lineno]["calls"]: + line_index[lineno]["calls"].append(target) + if target not in seen: + seen.add(target) + info.calls.append(target) + del info._node # type: ignore[attr-defined] + + # -- module and export resolution -- + + def _resolve_specifier(self, mod: _ModuleInfo, specifier: str) -> _ModuleInfo | None: + """The loaded module a specifier names, or None (a package, or a file that wasn't picked).""" + key = (posixpath.dirname(mod.rel_path) if specifier.startswith(".") else "", specifier) + if key not in self._specifier_cache: + found = self._resolve_relative(mod, specifier) if specifier.startswith(".") else self._resolve_bare(specifier) + self._specifier_cache[key] = found + return self._specifier_cache[key] + + def _resolve_relative(self, mod: _ModuleInfo, specifier: str) -> _ModuleInfo | None: + base = posixpath.normpath(posixpath.join(posixpath.dirname(mod.rel_path), specifier)) + if base == ".." or base.startswith("../"): + return None # climbs out of the picked folder + stem, ext = posixpath.splitext(base) + candidates = [base] + candidates += [stem + e for e in _TS_SOURCE_FOR_JS_SPECIFIER.get(ext, ())] + candidates += [base + e for e in _RESOLVE_EXTENSIONS] + candidates += [posixpath.join(base, "index" + e) for e in _RESOLVE_EXTENSIONS] + return next((self.modules[c] for c in candidates if c in self.modules), None) + + def _resolve_bare(self, specifier: str) -> _ModuleInfo | None: + """Aliases (`@/lib/x`) and root-relative paths (`src/lib/x`): no config is read, so a + specifier resolves only when exactly one loaded file's path ends with it.""" + path = specifier + for prefix in ("@/", "~/", "#/"): + if path.startswith(prefix): + path = path[len(prefix) :] + stem, ext = posixpath.splitext(path) + if ext in _RESOLVE_EXTENSIONS: + path = stem + if not path: + return None + matches = [] + for candidate in self.modules.values(): + names = {candidate.module} + if posixpath.basename(candidate.module) == "index": + names.add(posixpath.dirname(candidate.module)) + if any(n == path or n.endswith("/" + path) for n in names): + matches.append(candidate) + return matches[0] if len(matches) == 1 else None + + def _lookup_export(self, mod: _ModuleInfo, name: str, seen: set[str] | None = None) -> tuple[_ModuleInfo, str] | None: + """(defining module, local name) of what `mod` exports as `name`, following re-exports. + + The local name is a key of that module's `top_level` (a function) and/or `classes` (a class or object). + """ + seen = set() if seen is None else seen + if mod.rel_path in seen: + return None # circular re-exports + seen.add(mod.rel_path) + + if name == "default": + if mod.default_export is not None: + return mod, mod.default_export + else: + local = mod.export_aliases.get(name, name) + if local in mod.top_level or local in mod.classes: + return mod, local + if name in mod.reexports: + specifier, original = mod.reexports[name] + target = self._resolve_specifier(mod, specifier) + found = self._lookup_export(target, original, seen) if target else None + if found: + return found + if name != "default": # `export *` never re-exports a default + for specifier in mod.star_reexports: + target = self._resolve_specifier(mod, specifier) + found = self._lookup_export(target, name, seen) if target else None + if found: + return found + return None + + def _imported_symbol(self, mod: _ModuleInfo, name: str) -> tuple[_ModuleInfo, str] | None: + """Where the import bound to `name` is defined. A whole-module import (`import * as`, or a + CommonJS `require`) stands for the module's default export, i.e. `module.exports = thing`.""" + imp = mod.imports.get(name) + if imp is None: + return None + target = self._resolve_specifier(mod, imp.specifier) + return self._lookup_export(target, imp.original or "default") if target else None + + def _method_of(self, mod: _ModuleInfo, class_name: str, method: str) -> str | None: + """A method of the class (or object literal) `class_name` names in `mod`, declared there or imported.""" + if class_name in mod.classes: + return mod.classes[class_name].get(method) + symbol = self._imported_symbol(mod, class_name) + return symbol[0].classes.get(symbol[1], {}).get(method) if symbol else None + + def _make_resolver(self, mod: _ModuleInfo, class_name: str | None, local_types: dict[str, str]): + source = self.sources_bytes[mod.rel_path] + + def resolve(func_node: Node, is_new: bool = False) -> str | None: + # foo(...) / new Foo(...) + if func_node.type == "identifier": + name = _text(func_node, source) + if is_new: + return self._method_of(mod, name, "constructor") + if name in mod.top_level: + return mod.top_level[name] + symbol = self._imported_symbol(mod, name) + return symbol[0].top_level.get(symbol[1]) if symbol else None + + # this.m(...) / ns.f(...) / Class.staticM(...) / variable.m(...) / new ns.Foo(...) + # - one object, one member: no deeper chains (`this.a.b()`), like the other plugins. + if func_node.type == "member_expression": + obj = func_node.child_by_field_name("object") + member = _member_name(func_node.child_by_field_name("property"), source) + if obj is None or member is None: + return None + if obj.type == "this": + return self._method_of(mod, class_name, member) if class_name and not is_new else None + if obj.type != "identifier": + return None + name = _text(obj, source) + + imp = mod.imports.get(name) + if imp is not None and imp.original is None: # import * as ns + target = self._resolve_specifier(mod, imp.specifier) + found = self._lookup_export(target, member) if target else None + if found: + if is_new: + return found[0].classes.get(found[1], {}).get("constructor") + return found[0].top_level.get(found[1]) + # else `module.exports = class/object`: its members are reached through the default export below + if is_new: + return None + + if name in local_types: # a variable whose class is known + return self._method_of(mod, local_types[name], member) + return self._method_of(mod, name, member) # Class.staticMethod() / object.method() + return None + + return resolve + + # -- output -- + + def _to_response(self) -> dict: + edges = [] + for info in self.functions.values(): + for cl in info.code_lines: + for target in cl["calls"]: + edges.append({"source": info.id, "target": target, "line": cl["lineno"]}) + files = [ + { + "path": rel_path, + "functions": ids, + "error": self.file_errors.get(rel_path), + "language": _language_id(rel_path), + } + for rel_path, ids in sorted(self.file_functions.items()) + ] + functions = {} + for fid, info in self.functions.items(): + entry = info.to_dict() + entry["language"] = _language_id(info.file) + functions[fid] = entry + return {"files": files, "functions": functions, "edges": edges} + + +class TypeScriptLanguage(LanguagePlugin): + id = "typescript" # fallback only: each file and function carries its own `language` + label = "TypeScript/JavaScript" + extensions = _TYPESCRIPT_EXTENSIONS | _JAVASCRIPT_EXTENSIONS + + def analyze(self, sources: dict[str, str]) -> dict: + readable = {path: content for path, content in sources.items() if not _is_skipped_file(path)} + return _TypeScriptAnalyzer(readable).analyze() diff --git a/backend/requirements.txt b/backend/requirements.txt index 80cfdcb..99c471b 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -2,3 +2,4 @@ fastapi>=0.110 uvicorn[standard]>=0.29 tree-sitter>=0.23 tree-sitter-rust>=0.23 +tree-sitter-typescript>=0.23 diff --git a/frontend/src/components/FunctionNode.tsx b/frontend/src/components/FunctionNode.tsx index 5296379..83fd8ed 100644 --- a/frontend/src/components/FunctionNode.tsx +++ b/frontend/src/components/FunctionNode.tsx @@ -3,7 +3,11 @@ import { Handle, Position, type NodeProps, type Node } from "@xyflow/react"; import Prism from "prismjs"; import "prismjs/components/prism-python"; import "prismjs/components/prism-rust"; +import "prismjs/components/prism-typescript"; +import "prismjs/components/prism-jsx"; +import "prismjs/components/prism-tsx"; import { fileColor } from "../colors"; +import { languageForId } from "../languages"; import { useViewer } from "../store"; import type { FunctionInfo } from "../types"; @@ -39,6 +43,8 @@ function Docstring({ text }: { text: string }) { } function Signature({ fn }: { fn: FunctionInfo }) { + const unannotated = languageForId(fn.language)?.unannotatedReturn; + const returns = fn.returns ?? (unannotated === undefined ? "None" : unannotated); return ( ( @@ -50,7 +56,13 @@ function Signature({ fn }: { fn: FunctionInfo }) { {p.default && = {p.default}} ))} - ) → {fn.returns ?? "None"} + ) + {returns !== null && ( + <> + {" "} + → {returns} + + )} ); } @@ -64,8 +76,9 @@ function FunctionNodeInner({ data, selected }: NodeProps) { const color = fileColor(fn.file); const highlighted = useMemo(() => { - const grammar = Prism.languages[fn.language] ?? Prism.languages.python; - return fn.codeLines.map((line) => Prism.highlight(line.text, grammar, fn.language)); + const grammarName = languageForId(fn.language)?.prism ?? fn.language; + const grammar = Prism.languages[grammarName] ?? Prism.languages.python; + return fn.codeLines.map((line) => Prism.highlight(line.text, grammar, grammarName)); }, [fn.codeLines, fn.language]); const dotTitle = isActive ? "Active, click to disable" : "Inactive, click to enable"; diff --git a/frontend/src/languages.ts b/frontend/src/languages.ts index 315bea4..312d953 100644 --- a/frontend/src/languages.ts +++ b/frontend/src/languages.ts @@ -5,11 +5,35 @@ export interface LanguageDef { extensions: string[]; color: string; mono: string; + /** Prism grammar to highlight with, when it isn't named like the language id. */ + prism?: string; + /** What a card shows after `→` for a function with no return annotation ("None" when unset); null hides the arrow. */ + unannotatedReturn?: string | null; } export const LANGUAGES: LanguageDef[] = [ { id: "python", label: "Python", extensions: [".py"], color: "#3776ab", mono: "PY" }, { id: "rust", label: "Rust", extensions: [".rs"], color: "#dea584", mono: "RS" }, + // The superset grammars: they also cover JSX/TSX markup, and highlight plain code the same. + // A missing return annotation there means "not stated", not "returns nothing". + { + id: "typescript", + label: "TypeScript", + extensions: [".ts", ".tsx", ".mts", ".cts"], + color: "#3178c6", + mono: "TS", + prism: "tsx", + unannotatedReturn: null, + }, + { + id: "javascript", + label: "JavaScript", + extensions: [".js", ".jsx", ".mjs", ".cjs"], + color: "#f7df1e", + mono: "JS", + prism: "jsx", + unannotatedReturn: null, + }, ]; /** Flat extension list, also used as the file picker's `accept` attribute. */ diff --git a/frontend/src/localFiles.ts b/frontend/src/localFiles.ts index f11530a..4409072 100644 --- a/frontend/src/localFiles.ts +++ b/frontend/src/localFiles.ts @@ -2,7 +2,22 @@ import type { FileUpload } from "./api"; import { SUPPORTED_EXTENSIONS } from "./languages"; // Mirrors backend/languages/base.py's SKIP_DIRS so junk trees (venvs, caches, build output) never get uploaded. -const SKIP_DIRS = new Set(["__pycache__", "node_modules", ".git", ".venv", "venv", ".tox", ".mypy_cache", "target"]); +const SKIP_DIRS = new Set([ + "__pycache__", + "node_modules", + ".git", + ".venv", + "venv", + ".tox", + ".mypy_cache", + "target", + "dist", + "build", +]); + +// Files that match a supported extension but hold no code worth reading: type declarations (no bodies) +// and minified bundles (build output). Mirrors _is_skipped_file in backend/languages/typescript.py. +const SKIP_FILE = /\.(d\.[mc]?ts|min\.[mc]?js)$/; function relativePath(file: File): string { const raw = (file.webkitRelativePath || file.name).replace(/\\/g, "/"); @@ -27,7 +42,7 @@ export async function collectSourceFiles(fileList: FileList): Promise<{ root: st // still fires a change event), which clears this same live FileList once // we hit the first `await` below. const picked = Array.from(fileList).filter( - (f) => SUPPORTED_EXTENSIONS.some((ext) => f.name.endsWith(ext)) && !isSkipped(relativePath(f)), + (f) => SUPPORTED_EXTENSIONS.some((ext) => f.name.endsWith(ext)) && !SKIP_FILE.test(f.name) && !isSkipped(relativePath(f)), ); const first = picked[0]; const root = first?.webkitRelativePath ? first.webkitRelativePath.split("/")[0] : (first?.name ?? ""); diff --git a/sample_typescript_project/Report.tsx b/sample_typescript_project/Report.tsx new file mode 100644 index 0000000..9844686 --- /dev/null +++ b/sample_typescript_project/Report.tsx @@ -0,0 +1,5 @@ +import { renderRow } from "./formatting"; + +export default function (results: { item: { name: string }; score: number }[]) { + return
    {results.map((result) => renderRow(result))}
; +} diff --git a/sample_typescript_project/formatting.jsx b/sample_typescript_project/formatting.jsx new file mode 100644 index 0000000..72c1e55 --- /dev/null +++ b/sample_typescript_project/formatting.jsx @@ -0,0 +1,8 @@ +function label(result) { + return `${result.item.name}: ${result.score}`; +} + +/** Renders one result as a list item. */ +export function renderRow(result) { + return
  • {label(result)}
  • ; +} diff --git a/sample_typescript_project/main.ts b/sample_typescript_project/main.ts new file mode 100644 index 0000000..8ae5594 --- /dev/null +++ b/sample_typescript_project/main.ts @@ -0,0 +1,16 @@ +import { createItem, Item } from "./models"; +import { processAll } from "./processing"; +import { save, load } from "./storage"; +import Report from "./Report"; + +/** Entry point: build a few items, process them, persist them and report. */ +export function main(): void { + const items = [createItem("alpha", 3), createItem("beta", 5)]; + const first: Item = items[0]; + console.log(first.describe()); + + save(processAll(items)); + console.log(Report(load())); +} + +main(); diff --git a/sample_typescript_project/models.ts b/sample_typescript_project/models.ts new file mode 100644 index 0000000..1cab383 --- /dev/null +++ b/sample_typescript_project/models.ts @@ -0,0 +1,16 @@ +export class Item { + constructor(public name: string, public weight: number) {} + + /** Human-readable label for the item. */ + describe(): string { + return `${this.name} (${this.weight})`; + } + + heavier(other: Item): boolean { + return this.weight > other.weight; + } +} + +export function createItem(name: string, weight: number): Item { + return new Item(name, weight); +} diff --git a/sample_typescript_project/processing.ts b/sample_typescript_project/processing.ts new file mode 100644 index 0000000..3777084 --- /dev/null +++ b/sample_typescript_project/processing.ts @@ -0,0 +1,14 @@ +import { Item } from "./models"; + +const scoreOf = (item: Item) => item.weight * 2; + +/** Orders two items, heaviest first. */ +export function compare(a: Item, b: Item): number { + return a.heavier(b) ? -1 : 1; +} + +/** Scores every item, then sorts them by weight. */ +export function processAll(items: Item[]) { + const sorted = [...items].sort((a, b) => compare(a, b)); + return sorted.map((item) => ({ item, score: scoreOf(item) })); +} diff --git a/sample_typescript_project/storage.js b/sample_typescript_project/storage.js new file mode 100644 index 0000000..0a7b7b3 --- /dev/null +++ b/sample_typescript_project/storage.js @@ -0,0 +1,27 @@ +// The untyped, CommonJS side of the project: no annotations anywhere. +const { Item } = require("./models"); + +const rows = []; + +function put(row) { + rows.push(row); +} + +function serialize(result) { + return { name: result.item.name, weight: result.item.weight, score: result.score }; +} + +function restore(row) { + return { item: new Item(row.name, row.weight), score: row.score }; +} + +/** Stores every result as a plain row. */ +function save(results) { + results.forEach((result) => put(serialize(result))); +} + +function load() { + return rows.map((row) => restore(row)); +} + +module.exports = { save, load };