0
# Utility Functions
1
2
Utility functions for NPM package handling, temporary directory management, and common operations. These functions provide lower-level functionality used internally by jsii-diff and can be useful for building custom tools.
3
4
## Capabilities
5
6
### NPM Package Download
7
8
Download and process NPM packages in temporary environments for analysis.
9
10
```typescript { .api }
11
/**
12
* Download an NPM package and execute a processing function in its directory
13
* @param pkg - NPM package specifier (e.g., "package@version")
14
* @param block - Function to execute in the package directory
15
* @returns Promise resolving to download result with success/failure status
16
*/
17
function downloadNpmPackage<T>(
18
pkg: string,
19
block: (dir: string) => Promise<T>
20
): Promise<NpmDownloadResult<T>>;
21
```
22
23
**Usage Examples:**
24
25
```typescript
26
import { downloadNpmPackage } from "jsii-diff/lib/util";
27
import * as reflect from "jsii-reflect";
28
29
// Download and load a package for analysis
30
const result = await downloadNpmPackage("my-package@1.0.0", async (pkgDir) => {
31
const ts = new reflect.TypeSystem();
32
return ts.loadModule(pkgDir);
33
});
34
35
if (result.success) {
36
const assembly = result.result;
37
console.log(`Loaded assembly: ${assembly.name}@${assembly.version}`);
38
} else {
39
console.error(`Download failed: ${showDownloadFailure(result.reason)}`);
40
}
41
```
42
43
### Download Failure Handling
44
45
Convert download failure codes to human-readable messages.
46
47
```typescript { .api }
48
/**
49
* Convert download failure code to human-readable message
50
* @param f - Download failure code
51
* @returns Human-readable error message or undefined for unknown failures
52
*/
53
function showDownloadFailure(f: DownloadFailure): string | undefined;
54
```
55
56
### Temporary Directory Management
57
58
Execute operations in isolated temporary directories with automatic cleanup.
59
60
```typescript { .api }
61
/**
62
* Execute a block of code in a temporary directory with automatic cleanup
63
* @param block - Function to execute in temporary directory
64
* @returns Promise resolving to block return value
65
*/
66
function inTempDir<T>(block: () => T | Promise<T>): Promise<T>;
67
```
68
69
**Usage Examples:**
70
71
```typescript
72
import { inTempDir } from "jsii-diff/lib/util";
73
import * as fs from "fs-extra";
74
75
// Perform work in isolated temporary directory
76
const result = await inTempDir(async () => {
77
// Current working directory is now a temp dir
78
await fs.writeFile("test.txt", "temporary data");
79
const content = await fs.readFile("test.txt", "utf8");
80
return content;
81
}); // Temp directory is automatically cleaned up
82
83
console.log(result); // "temporary data"
84
```
85
86
### Array Utilities
87
88
Functional programming utilities for array manipulation.
89
90
```typescript { .api }
91
/**
92
* Map each element to an array and flatten the results
93
* @param xs - Input array
94
* @param fn - Function that maps elements to arrays
95
* @returns Flattened array of all mapped results
96
*/
97
function flatMap<T, U>(xs: T[], fn: (x: T) => U[]): U[];
98
```
99
100
**Usage Examples:**
101
102
```typescript
103
import { flatMap } from "jsii-diff/lib/util";
104
105
// Split strings and flatten results
106
const words = flatMap(["hello world", "foo bar"], (str) => str.split(" "));
107
console.log(words); // ["hello", "world", "foo", "bar"]
108
109
// Extract nested properties
110
const data = [
111
{ items: [1, 2] },
112
{ items: [3, 4, 5] }
113
];
114
const allItems = flatMap(data, (obj) => obj.items);
115
console.log(allItems); // [1, 2, 3, 4, 5]
116
```
117
118
### Recursion Protection
119
120
Prevent infinite recursion in algorithms that process potentially circular data structures.
121
122
```typescript { .api }
123
/**
124
* Utility class to prevent infinite recursion by tracking visited elements
125
*/
126
class RecursionBreaker<A> {
127
/**
128
* Execute block only if key hasn't been seen before in current call stack
129
* @param key - Unique identifier for the operation
130
* @param block - Function to execute if not already in progress
131
*/
132
do(key: A, block: () => void): void;
133
}
134
```
135
136
**Usage Examples:**
137
138
```typescript
139
import { RecursionBreaker } from "jsii-diff/lib/util";
140
141
// Prevent infinite recursion when processing circular references
142
const breaker = new RecursionBreaker<string>();
143
144
function processType(type: any): void {
145
breaker.do(type.name, () => {
146
// Process type properties
147
for (const prop of type.properties) {
148
if (prop.type) {
149
processType(prop.type); // Won't infinitely recurse
150
}
151
}
152
});
153
}
154
```
155
156
## Types
157
158
### Download Result Types
159
160
```typescript { .api }
161
/**
162
* Possible failure reasons for NPM package downloads
163
*/
164
type DownloadFailure = 'no_such_package';
165
166
/**
167
* Result type for NPM package download operations
168
*/
169
type NpmDownloadResult<T> =
170
| { success: true; result: T }
171
| { success: false; reason: DownloadFailure };
172
```
173
174
### Load Options
175
176
```typescript { .api }
177
/**
178
* Options for loading assemblies from the filesystem
179
*/
180
interface LoadOptions {
181
/** Whether to validate assembly format during loading */
182
validate: boolean;
183
}
184
```
185
186
## Implementation Notes
187
188
### NPM Package Download
189
190
- Downloads packages to temporary directories using `npm install`
191
- Automatically handles package dependencies required by jsii-reflect
192
- Supports both simple package names and version-specific specifiers
193
- Includes package existence validation before download attempts
194
- Provides detailed error information for troubleshooting
195
196
### Temporary Directory Usage
197
198
- Creates unique temporary directories under system temp location
199
- Automatically changes working directory during block execution
200
- Guarantees cleanup even if block throws exceptions
201
- Maintains original working directory after completion
202
- Uses system-appropriate temporary directory locations
203
204
### Recursion Breaking
205
206
- Thread-safe tracking of visited elements during recursive operations
207
- Automatic cleanup when recursive calls complete
208
- Generic implementation supports any comparable key type
209
- Prevents stack overflow in algorithms processing circular data structures
210
- Essential for safe traversal of jsii type hierarchies