Skip to content

Commit 7a6bd6d

Browse files
author
codegen-bot
committed
.
1 parent 8232528 commit 7a6bd6d

File tree

3 files changed

+351
-3
lines changed

3 files changed

+351
-3
lines changed
Lines changed: 180 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,180 @@
1-
1+
---
2+
title: "The Export API"
3+
sidebarTitle: "Exports"
4+
icon: "file-export"
5+
iconType: "solid"
6+
---
7+
8+
The [Export](/api-reference/core/Export) API provides tools for managing exports and module boundaries in TypeScript codebases.
9+
10+
## Export Statements vs Exports
11+
12+
Similar to imports, Codegen provides two levels of abstraction for working with exports:
13+
14+
- [ExportStatement](/api-reference/core/ExportStatement) - Represents a complete export statement
15+
- [Export](/api-reference/core/Export) - Represents individual exported symbols
16+
17+
```typescript
18+
// One ExportStatement containing multiple Export objects
19+
export { foo, bar as default, type User };
20+
// Creates:
21+
// - Export for 'foo'
22+
// - Export for 'bar' as default
23+
// - Export for 'User' as a type
24+
25+
// Direct exports create one ExportStatement per export
26+
export const value = 42;
27+
export function process() {}
28+
```
29+
30+
You can access these through your file's collections:
31+
32+
```python
33+
# Access all export statements
34+
for stmt in file.export_statements:
35+
print(f"Statement: {stmt.source}")
36+
37+
# Access individual exports in the statement
38+
for exp in stmt.exports:
39+
print(f" Export: {exp.name}")
40+
```
41+
42+
<Note>
43+
ExportStatement inherits from [Statement](/building-with-codegen/statements-and-code-blocks), providing operations like `remove()` and `insert_before()`. This is particularly useful when you want to manipulate the entire export declaration.
44+
</Note>
45+
46+
## Export Types
47+
48+
Codegen supports several types of exports:
49+
50+
```typescript
51+
// Direct exports
52+
export const value = 42; // Value export
53+
export function myFunction() {} // Function export
54+
export class MyClass {} // Class export
55+
export type MyType = string; // Type export
56+
export interface MyInterface {} // Interface export
57+
export enum MyEnum {} // Enum export
58+
59+
// Re-exports
60+
export { foo, bar } from './other-file'; // Named re-exports
61+
export type { Type } from './other-file'; // Type re-exports
62+
export * from './other-file'; // Wildcard re-exports
63+
export * as utils from './other-file'; // Namespace re-exports
64+
65+
// Aliased exports
66+
export { foo as foop }; // Basic alias
67+
export { foo as default }; // Default export alias
68+
export { bar as baz } from './other-file'; // Re-export with alias
69+
```
70+
71+
## Working with Exports
72+
73+
The Export API provides methods to identify and filter exports:
74+
75+
```python
76+
# Check export types
77+
for exp in file.exports:
78+
if exp.is_type_export():
79+
print(f"Type export: {exp.name}")
80+
elif exp.is_default_export():
81+
print(f"Default export: {exp.name}")
82+
elif exp.is_wildcard_export():
83+
print(f"Wildcard export from: {exp.from_file.filepath}")
84+
85+
# Work with re-exports
86+
for exp in file.exports:
87+
if exp.is_reexport():
88+
if exp.is_external_export:
89+
print(f"External re-export: {exp.name} from {exp.from_file.filepath}")
90+
else:
91+
print(f"Internal re-export: {exp.name}")
92+
```
93+
94+
## Export Resolution
95+
96+
You can trace exports to their original symbols:
97+
98+
```python
99+
for exp in file.exports:
100+
if exp.is_reexport():
101+
# Get original and current symbols
102+
current = exp.exported_symbol
103+
original = exp.resolved_symbol
104+
105+
print(f"Re-exporting {original.name} from {exp.from_file.filepath}")
106+
print(f"Through: {' -> '.join(e.file.filepath for e in exp.export_chain)}")
107+
```
108+
109+
## Common Operations
110+
111+
Here are common operations for working with exports:
112+
113+
```python
114+
# Add new export
115+
file.add_export("MyComponent")
116+
117+
# Add export with alias
118+
file.add_export("MyComponent", alias="default")
119+
120+
# Convert to type export
121+
export = file.get_export("MyType")
122+
export.make_type_export()
123+
124+
# Remove export
125+
export.remove() # Removes export but keeps symbol
126+
127+
# Update export properties
128+
export.update(
129+
name="NewName",
130+
is_type=True,
131+
is_default=False
132+
)
133+
```
134+
135+
## Managing Re-exports
136+
137+
Common patterns for working with re-exports:
138+
139+
```python
140+
# Create public API
141+
index_file = codebase.get_file("index.ts")
142+
143+
# Re-export from internal files
144+
for internal_file in codebase.files:
145+
if internal_file.name != "index":
146+
for symbol in internal_file.symbols:
147+
if symbol.is_public:
148+
index_file.add_export(
149+
symbol,
150+
from_file=internal_file
151+
)
152+
153+
# Convert default to named exports
154+
for exp in file.exports:
155+
if exp.is_default_export():
156+
exp.make_named_export()
157+
158+
# Consolidate re-exports
159+
from collections import defaultdict
160+
161+
file_exports = defaultdict(list)
162+
for exp in file.exports:
163+
if exp.is_reexport():
164+
file_exports[exp.from_file].append(exp)
165+
166+
for from_file, exports in file_exports.items():
167+
if len(exports) > 1:
168+
# Create consolidated re-export
169+
names = [exp.name for exp in exports]
170+
file.add_export_from_source(
171+
f"export {{ {', '.join(names)} }} from '{from_file.filepath}'"
172+
)
173+
# Remove individual exports
174+
for exp in exports:
175+
exp.remove()
176+
```
177+
178+
<Note>
179+
When managing exports, consider the impact on your module's public API. Not all symbols that can be exported should be exported.
180+
</Note>
Lines changed: 170 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,170 @@
1-
1+
---
2+
title: "The Import API"
3+
sidebarTitle: "Imports"
4+
icon: "file-import"
5+
iconType: "solid"
6+
---
7+
8+
The [Import](/api-reference/core/Import) API provides tools for working with imports and managing dependencies between files.
9+
10+
## Accessing Imports
11+
12+
You can access these through [File.imports](/api-reference/core/File#imports) and [File.import_statements](/api-reference/core/File#import-statements):
13+
14+
```python
15+
# Direct access to imports via file
16+
for imp in file.imports:
17+
...
18+
19+
# Grab by name of symbol being imported
20+
imp = file.get_import('math')
21+
22+
# Grab and filter from a codebase
23+
from codegen.sdk import ExternalModule
24+
25+
external_imports = [i for i in codebase.imports if isinstance(i, ExternalModule)]
26+
```
27+
28+
## Common Operations
29+
30+
The Import API provides several methods for modifying imports:
31+
32+
```python
33+
# Get a specific import
34+
import_stmt = file.get_import("MyComponent")
35+
36+
# Change import source
37+
import_stmt.set_module("./new/path")
38+
39+
# Add/update alias
40+
import_stmt.set_alias("MyAlias") # import X as MyAlias
41+
42+
# TypeScript-specific operations
43+
import_stmt.make_type_import() # Convert to 'import type'
44+
import_stmt.make_value_import() # Remove 'type' modifier
45+
46+
# Update multiple properties
47+
import_stmt.update(
48+
module="./new/path",
49+
alias="NewAlias",
50+
is_type=True
51+
)
52+
```
53+
54+
## Import Resolution
55+
56+
Imports can be traced to their original symbols:
57+
58+
```python
59+
# Follow import chain to source
60+
import_stmt = file.get_import("MyComponent")
61+
original = import_stmt.resolved_symbol
62+
63+
if original:
64+
print(f"Defined in: {original.file.filepath}")
65+
print(f"Original name: {original.name}")
66+
67+
# Get file relationships
68+
print(f"From file: {import_stmt.from_file.filepath}")
69+
print(f"To file: {import_stmt.to_file.filepath}")
70+
```
71+
72+
## Working with External Modules
73+
74+
You can determine if an import references an [ExternalModule](/api-reference/core/ExternalModule) by checking the type of [Import.imported_symbol](/api-reference/core/Import#imported-symbol), like so:
75+
76+
```python
77+
# Check if import is from external package
78+
for imp in file.imports:
79+
if isinstance(imp.imported_symbol, ExternalModule):
80+
print(f"External import: {imp.name} from {imp.module}")
81+
else:
82+
print(f"Local import: {imp.name}")
83+
```
84+
85+
<Tip>Learn more about [external modules here](/building-with-codegen/external-modules)</Tip>
86+
87+
88+
## Bulk Operations
89+
90+
Here are patterns for working with multiple imports:
91+
92+
```python
93+
# Update imports from a specific module
94+
old_path = "./old/path"
95+
new_path = "./new/path"
96+
97+
for imp in file.imports:
98+
if imp.module == old_path:
99+
imp.set_module(new_path)
100+
101+
# Remove unused imports (excluding external)
102+
for imp in file.imports:
103+
if not imp.usages and not isinstance(imp.resolved_symbol, ExternalModule):
104+
print(f"Removing: {imp.name}")
105+
imp.remove()
106+
107+
# Consolidate duplicate imports
108+
from collections import defaultdict
109+
110+
module_imports = defaultdict(list)
111+
for imp in file.imports:
112+
module_imports[imp.module].append(imp)
113+
114+
for module, imports in module_imports.items():
115+
if len(imports) > 1:
116+
# Create combined import
117+
symbols = [imp.name for imp in imports]
118+
file.add_import_from_import_string(
119+
f"import {{ {', '.join(symbols)} }} from '{module}'"
120+
)
121+
# Remove old imports
122+
for imp in imports:
123+
imp.remove()
124+
```
125+
126+
<Note>
127+
Always check if imports resolve to external modules before modification to avoid breaking third-party package imports.
128+
</Note>
129+
130+
## Import Statements vs Imports
131+
132+
Codegen provides two levels of abstraction for working with imports:
133+
134+
- [ImportStatement](/api-reference/core/ImportStatement) - Represents a complete import statement
135+
- [Import](/api-reference/core/Import) - Represents individual imported symbols
136+
137+
<CodeGroup>
138+
```python Python
139+
# One ImportStatement containing multiple Import objects
140+
from math import sin, cos as cosine
141+
# Creates:
142+
# - Import for 'sin'
143+
# - Import for 'cos' with alias 'cosine'
144+
```
145+
146+
```typescript Typescript
147+
// One ImportStatement containing multiple Import objects
148+
import { sin, cos as cosine } from 'math';
149+
// Creates:
150+
// - Import for 'sin'
151+
// - Import for 'cos' with alias 'cosine'
152+
```
153+
</CodeGroup>
154+
155+
You can access these through [File.imports](/api-reference/core/File#imports) and [File.import_statements](/api-reference/core/File#import-statements):
156+
157+
```python
158+
# Direct access to imports
159+
for imp in file.imports:
160+
...
161+
162+
# Access to imports via statements
163+
for stmt in file.import_statements:
164+
for imp in stmt.imports:
165+
...
166+
```
167+
168+
<Note>
169+
ImportStatement inherits from [Statement](/building-with-codegen/statements-and-code-blocks), providing operations like `remove()` and `insert_before()`.
170+
</Note>

docs/introduction/how-it-works.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ Codegen's graph construction happens in two stages:
4040

4141
1. **AST Parsing**: We use [Tree-sitter](https://tree-sitter.github.io/tree-sitter/) as our foundation for parsing code into Abstract Syntax Trees. Tree-sitter provides fast, reliable parsing across multiple languages.
4242

43-
2. **Multi-file Graph Construction**: Custom parsing logic, implemented in [rustworkx](https://github.com/Qiskit/rustworkx) and Python, analyzes these ASTs to construct a more sophisticated graph structure. This graph captures relationships between [symbols](/api-reference/core/Symbol), [files](/api-reference/core/SourceFile), [imports](/api-reference/core/Import), and more.
43+
2. **Multi-file Graph Construction**: Custom parsing logic, implemented in [rustworkx](https://github.com/Qiskit/rustworkx) and Python, analyzes these ASTs to construct a more sophisticated graph structure. This graph captures relationships between [symbols](/building-with-codegen/symbol-api), [files](/building-with-codegen/files-and-directories), [imports](/building-with-codegen/imports), and more.
4444

4545
### Performance Through Pre-computation
4646

0 commit comments

Comments
 (0)