fp-generate 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +203 -2
- package/bin/index.js +8 -0
- package/package.json +32 -4
- package/src/cli.js +167 -0
- package/src/formatters/json.js +18 -0
- package/src/formatters/markdown.js +74 -0
- package/src/formatters/routes.js +40 -0
- package/src/formatters/tree.js +30 -0
- package/src/index.js +8 -0
- package/src/scanner.js +228 -0
- package/src/utils.js +71 -0
- package/src/watcher.js +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,204 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 🚀 fp-generate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> **Instant AI-Ready Folder Structure & File Route Generator for Node.js.**
|
|
4
|
+
> Generate normalized directory trees, file path routes, and comprehensive project maps in milliseconds. Zero external dependencies.
|
|
5
|
+
|
|
6
|
+
[](https://www.npmjs.com/package/fp-generate)
|
|
7
|
+
[](LICENSE)
|
|
8
|
+
[]()
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 💡 Why `fp-generate`?
|
|
13
|
+
|
|
14
|
+
When providing context to AI models (Antigravity, Gemini, Claude, ChatGPT, Cursor), giving the AI a clear, normalized project structure is essential for accurate code generation, debugging, and file navigation.
|
|
15
|
+
|
|
16
|
+
However:
|
|
17
|
+
- Standard OS directory dumps are cluttered with `node_modules`, `.git`, build caches, and binary files.
|
|
18
|
+
- Manual directory maps become outdated the moment you add, rename, or delete files.
|
|
19
|
+
|
|
20
|
+
**`fp-generate` solves this instantly:**
|
|
21
|
+
- ⚡ **Instant Regeneration**: Scans your repository and writes a structured `PROJECT_STRUCTURE.md` in less than 30ms.
|
|
22
|
+
- 🔄 **Real-Time Watch Mode**: Automatically regenerates the file map the second any file or folder changes.
|
|
23
|
+
- 🧭 **Normalized Routes**: Normalizes all paths to clean `/` routes (`src/controllers/user.js`) across Windows, macOS, and Linux.
|
|
24
|
+
- 🛡️ **Smart Ignore Engine**: Automatically respects `.gitignore` and default excludes (`node_modules`, `.git`, `dist`, `.env*`, etc.).
|
|
25
|
+
- 📦 **Zero Dependencies**: Weighs less than 25 KB unpacked; runs instantaneously via `npx` with zero installation delay.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## ⚡ Quickstart
|
|
30
|
+
|
|
31
|
+
No installation required! Run directly with `npx`:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
npx fp-generate
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
This immediately creates `PROJECT_STRUCTURE.md` in your project root.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## 🔄 Real-Time Watch Mode
|
|
42
|
+
|
|
43
|
+
Need the file structure to stay updated automatically as you code? Run in watch mode:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npx fp-generate --watch
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Whenever a file or folder is added, deleted, or renamed, `fp-generate` immediately regenerates the map.
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## 📖 CLI Usage & Options
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
npx fp-generate [options] [target-directory]
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
| Flag | Short | Description | Default |
|
|
60
|
+
| :--- | :--- | :--- | :--- |
|
|
61
|
+
| `--output <file>` | `-o` | Output file path (`none` to disable file writing) | `PROJECT_STRUCTURE.md` |
|
|
62
|
+
| `--format <format>`| `-f` | Format: `markdown`, `tree`, `routes`, `json` | `markdown` |
|
|
63
|
+
| `--watch` | `-w` | Automatically regenerate on file/folder changes | `false` |
|
|
64
|
+
| `--stdout` | `-s` | Print output to terminal console | `false` |
|
|
65
|
+
| `--depth <n>` | `-d` | Max folder depth level to scan | unlimited |
|
|
66
|
+
| `--routes-only` | | Output a flat list of normalized relative paths | `false` |
|
|
67
|
+
| `--json` | | Output structured JSON | `false` |
|
|
68
|
+
| `--ignore <glob>` | `-i` | Comma-separated additional ignore patterns | |
|
|
69
|
+
| `--all` | `-a` | Include hidden files and folders | `false` |
|
|
70
|
+
| `--no-stats` | | Exclude file count and size summary | `false` |
|
|
71
|
+
| `--help` | `-h` | Display help screen | |
|
|
72
|
+
| `--version` | `-v` | Display version | |
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## 🎯 Common Examples
|
|
77
|
+
|
|
78
|
+
### 1. Generate clean route list for AI prompts
|
|
79
|
+
```bash
|
|
80
|
+
npx fp-generate --routes-only --stdout --output none
|
|
81
|
+
```
|
|
82
|
+
*Output:*
|
|
83
|
+
```text
|
|
84
|
+
bin/index.js
|
|
85
|
+
package.json
|
|
86
|
+
src/cli.js
|
|
87
|
+
src/formatters/markdown.js
|
|
88
|
+
src/scanner.js
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### 2. Print visual ASCII tree directly to terminal
|
|
92
|
+
```bash
|
|
93
|
+
npx fp-generate -f tree --stdout -o none
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### 3. Scan a specific subfolder up to 2 levels deep
|
|
97
|
+
```bash
|
|
98
|
+
npx fp-generate ./src -d 2 -o SRC_STRUCTURE.md
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### 4. Custom ignore rules
|
|
102
|
+
```bash
|
|
103
|
+
npx fp-generate --ignore "*.spec.js,docs/**"
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## 📄 Sample Generated Markdown (`PROJECT_STRUCTURE.md`)
|
|
109
|
+
|
|
110
|
+
```markdown
|
|
111
|
+
# Project Structure & File Routes
|
|
112
|
+
|
|
113
|
+
> Automatically generated by `fp-generate` on 2026-11-16T10:00:00.000Z.
|
|
114
|
+
> Root Directory: `/your/project`
|
|
115
|
+
|
|
116
|
+
## 📊 Overview
|
|
117
|
+
|
|
118
|
+
- **Total Files**: 12
|
|
119
|
+
- **Total Directories**: 3
|
|
120
|
+
- **Total Size**: 24.5 KB
|
|
121
|
+
|
|
122
|
+
### File Types
|
|
123
|
+
|
|
124
|
+
| Extension | Count |
|
|
125
|
+
| :--- | :--- |
|
|
126
|
+
| `.js` | 10 |
|
|
127
|
+
| `.json` | 1 |
|
|
128
|
+
| `.md` | 1 |
|
|
129
|
+
|
|
130
|
+
## 🌳 Directory Tree
|
|
131
|
+
|
|
132
|
+
```text
|
|
133
|
+
my-project/
|
|
134
|
+
├── bin/
|
|
135
|
+
│ └── index.js
|
|
136
|
+
├── src/
|
|
137
|
+
│ ├── cli.js
|
|
138
|
+
│ ├── index.js
|
|
139
|
+
│ └── scanner.js
|
|
140
|
+
├── package.json
|
|
141
|
+
└── README.md
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## 🧭 File Routes Index
|
|
145
|
+
|
|
146
|
+
| # | Route / Relative Path | Size |
|
|
147
|
+
| :--- | :--- | :--- |
|
|
148
|
+
| 1 | `bin/index.js` | 164 B |
|
|
149
|
+
| 2 | `package.json` | 660 B |
|
|
150
|
+
| 3 | `src/cli.js` | 5.8 KB |
|
|
151
|
+
| 4 | `src/index.js` | 434 B |
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
---
|
|
155
|
+
|
|
156
|
+
## 💻 Programmatic JavaScript API
|
|
157
|
+
|
|
158
|
+
You can also use `fp-generate` as a library in your own Node.js applications:
|
|
159
|
+
|
|
160
|
+
```javascript
|
|
161
|
+
import { scanDirectory, formatTree, formatRoutes, formatMarkdown } from 'fp-generate';
|
|
162
|
+
|
|
163
|
+
// Scan directory
|
|
164
|
+
const result = await scanDirectory('./src', {
|
|
165
|
+
maxDepth: 3,
|
|
166
|
+
customIgnores: ['*.test.js']
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
console.log(formatRoutes(result));
|
|
170
|
+
// -> src/app.js, src/index.js, ...
|
|
171
|
+
|
|
172
|
+
console.log(formatMarkdown(result));
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
---
|
|
176
|
+
|
|
177
|
+
## 🚢 Publishing to NPM
|
|
178
|
+
|
|
179
|
+
1. **Test locally**:
|
|
180
|
+
```bash
|
|
181
|
+
npm test
|
|
182
|
+
npm pack --dry-run
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
2. **Login to npm** (if not already logged in):
|
|
186
|
+
```bash
|
|
187
|
+
npm login
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
3. **Publish**:
|
|
191
|
+
```bash
|
|
192
|
+
npm publish --access public
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Once published, anyone can run your tool immediately with:
|
|
196
|
+
```bash
|
|
197
|
+
npx fp-generate
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
---
|
|
201
|
+
|
|
202
|
+
## 📄 License
|
|
203
|
+
|
|
204
|
+
MIT © 2026
|
package/bin/index.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fp-generate",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Generate clean, AI-optimized folder structures and file path routes for any codebase instantaneously.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"fp-generate": "bin/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"src",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"start": "node bin/index.js",
|
|
18
|
+
"test": "node --test test/*.test.js"
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"cli",
|
|
22
|
+
"file-tree",
|
|
23
|
+
"folder-structure",
|
|
24
|
+
"ai-context",
|
|
25
|
+
"file-routes",
|
|
26
|
+
"directory-scanner",
|
|
27
|
+
"npx"
|
|
28
|
+
],
|
|
29
|
+
"author": "",
|
|
30
|
+
"license": "MIT",
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=18.0.0"
|
|
33
|
+
}
|
|
34
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import { scanDirectory } from './scanner.js';
|
|
5
|
+
import { formatTree } from './formatters/tree.js';
|
|
6
|
+
import { formatRoutes } from './formatters/routes.js';
|
|
7
|
+
import { formatJson } from './formatters/json.js';
|
|
8
|
+
import { formatMarkdown } from './formatters/markdown.js';
|
|
9
|
+
import { watchDirectory } from './watcher.js';
|
|
10
|
+
import { colors, formatBytes } from './utils.js';
|
|
11
|
+
|
|
12
|
+
const HELP_TEXT = `
|
|
13
|
+
${colors.bold(colors.cyan('fp-generate'))} - Instant AI-Ready Folder Structure & File Route Generator
|
|
14
|
+
|
|
15
|
+
${colors.bold('USAGE:')}
|
|
16
|
+
npx fp-generate [options] [target-directory]
|
|
17
|
+
|
|
18
|
+
${colors.bold('OPTIONS:')}
|
|
19
|
+
-o, --output <file> Output file path (default: "PROJECT_STRUCTURE.md", pass "none" to disable)
|
|
20
|
+
-f, --format <format> Output format: markdown | tree | routes | json (default: "markdown")
|
|
21
|
+
-d, --depth <number> Max directory depth to scan (default: unlimited)
|
|
22
|
+
-w, --watch Watch for file/folder changes and regenerate immediately
|
|
23
|
+
-s, --stdout Print the output directly to the terminal
|
|
24
|
+
-i, --ignore <patterns> Additional comma-separated ignore patterns (e.g. "*.tmp,docs/**")
|
|
25
|
+
-a, --all Include hidden files and folders
|
|
26
|
+
--no-stats Omit overview statistics from output
|
|
27
|
+
--routes-only Shortcut for format=routes
|
|
28
|
+
--json Shortcut for format=json
|
|
29
|
+
-h, --help Show this help message
|
|
30
|
+
-v, --version Show version number
|
|
31
|
+
|
|
32
|
+
${colors.bold('EXAMPLES:')}
|
|
33
|
+
${colors.dim('# Generate PROJECT_STRUCTURE.md in the current directory')}
|
|
34
|
+
npx fp-generate
|
|
35
|
+
|
|
36
|
+
${colors.dim('# Print folder tree directly to terminal')}
|
|
37
|
+
npx fp-generate --stdout --output none
|
|
38
|
+
|
|
39
|
+
${colors.dim('# Generate clean routes list for LLM context prompts')}
|
|
40
|
+
npx fp-generate --routes-only -o ROUTES.txt
|
|
41
|
+
|
|
42
|
+
${colors.dim('# Keep running and auto-regenerate whenever files change')}
|
|
43
|
+
npx fp-generate --watch
|
|
44
|
+
|
|
45
|
+
${colors.dim('# Scan specific folder with max depth 3')}
|
|
46
|
+
npx fp-generate ./src -d 3 -o SRC_STRUCTURE.md
|
|
47
|
+
`;
|
|
48
|
+
|
|
49
|
+
export async function runCLI(argv = process.argv.slice(2)) {
|
|
50
|
+
const optionsConfig = {
|
|
51
|
+
output: { type: 'string', short: 'o', default: 'PROJECT_STRUCTURE.md' },
|
|
52
|
+
format: { type: 'string', short: 'f', default: 'markdown' },
|
|
53
|
+
depth: { type: 'string', short: 'd' },
|
|
54
|
+
watch: { type: 'boolean', short: 'w', default: false },
|
|
55
|
+
stdout: { type: 'boolean', short: 's', default: false },
|
|
56
|
+
ignore: { type: 'string', short: 'i' },
|
|
57
|
+
all: { type: 'boolean', short: 'a', default: false },
|
|
58
|
+
'no-stats': { type: 'boolean', default: false },
|
|
59
|
+
'routes-only': { type: 'boolean', default: false },
|
|
60
|
+
json: { type: 'boolean', default: false },
|
|
61
|
+
help: { type: 'boolean', short: 'h', default: false },
|
|
62
|
+
version: { type: 'boolean', short: 'v', default: false }
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
let parsed;
|
|
66
|
+
try {
|
|
67
|
+
parsed = parseArgs({
|
|
68
|
+
args: argv,
|
|
69
|
+
options: optionsConfig,
|
|
70
|
+
allowPositionals: true
|
|
71
|
+
});
|
|
72
|
+
} catch (err) {
|
|
73
|
+
console.error(colors.yellow(`Error: ${err.message}`));
|
|
74
|
+
console.log(`Run ${colors.cyan('fp-generate --help')} for available options.`);
|
|
75
|
+
process.exit(1);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const { values, positionals } = parsed;
|
|
79
|
+
|
|
80
|
+
if (values.help) {
|
|
81
|
+
console.log(HELP_TEXT);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (values.version) {
|
|
86
|
+
// Read package.json version
|
|
87
|
+
try {
|
|
88
|
+
const pkgPath = new URL('../package.json', import.meta.url);
|
|
89
|
+
const pkg = JSON.parse(await fs.readFile(pkgPath, 'utf8'));
|
|
90
|
+
console.log(`fp-generate v${pkg.version}`);
|
|
91
|
+
} catch {
|
|
92
|
+
console.log('fp-generate v1.0.0');
|
|
93
|
+
}
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const targetDir = positionals[0] ? path.resolve(positionals[0]) : process.cwd();
|
|
98
|
+
const maxDepth = values.depth ? parseInt(values.depth, 10) : Infinity;
|
|
99
|
+
const includeHidden = Boolean(values.all);
|
|
100
|
+
const customIgnores = values.ignore ? values.ignore.split(',').map(s => s.trim()) : [];
|
|
101
|
+
|
|
102
|
+
let format = values.format.toLowerCase();
|
|
103
|
+
if (values['routes-only']) format = 'routes';
|
|
104
|
+
if (values.json) format = 'json';
|
|
105
|
+
|
|
106
|
+
let outputFile = values.output;
|
|
107
|
+
if (outputFile === 'none' || outputFile === '-' || outputFile === 'false') {
|
|
108
|
+
outputFile = null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function generate() {
|
|
112
|
+
const startTime = performance.now();
|
|
113
|
+
const scanResult = await scanDirectory(targetDir, {
|
|
114
|
+
maxDepth,
|
|
115
|
+
includeHidden,
|
|
116
|
+
customIgnores
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
let rendered = '';
|
|
120
|
+
switch (format) {
|
|
121
|
+
case 'tree':
|
|
122
|
+
rendered = formatTree(scanResult.rootNode);
|
|
123
|
+
break;
|
|
124
|
+
case 'routes':
|
|
125
|
+
rendered = formatRoutes(scanResult);
|
|
126
|
+
break;
|
|
127
|
+
case 'json':
|
|
128
|
+
rendered = formatJson(scanResult, true);
|
|
129
|
+
break;
|
|
130
|
+
case 'markdown':
|
|
131
|
+
default:
|
|
132
|
+
rendered = formatMarkdown(scanResult, {
|
|
133
|
+
includeStats: !values['no-stats'],
|
|
134
|
+
includeTable: true
|
|
135
|
+
});
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (outputFile) {
|
|
140
|
+
const outPath = path.isAbsolute(outputFile) ? outputFile : path.join(targetDir, outputFile);
|
|
141
|
+
await fs.writeFile(outPath, rendered, 'utf8');
|
|
142
|
+
const duration = (performance.now() - startTime).toFixed(1);
|
|
143
|
+
console.log(
|
|
144
|
+
`${colors.green('✔')} Structure generated: ${colors.bold(colors.cyan(path.relative(process.cwd(), outPath) || outPath))} ` +
|
|
145
|
+
colors.dim(`(${scanResult.stats.totalFiles} files, ${scanResult.stats.totalFolders} folders, ${formatBytes(scanResult.stats.totalBytes)} in ${duration}ms)`)
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (values.stdout || !outputFile) {
|
|
150
|
+
if (outputFile) console.log('\n--- Output Preview ---');
|
|
151
|
+
console.log(rendered);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return scanResult;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Initial immediate generation
|
|
158
|
+
await generate();
|
|
159
|
+
|
|
160
|
+
// Watch mode if enabled
|
|
161
|
+
if (values.watch) {
|
|
162
|
+
console.log(colors.cyan(`\n👀 Watching for changes in: ${targetDir} (Press Ctrl+C to stop)...\n`));
|
|
163
|
+
watchDirectory(targetDir, async () => {
|
|
164
|
+
await generate();
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Formats scan result as structured JSON string.
|
|
3
|
+
* @param {object} scanResult
|
|
4
|
+
* @param {boolean} [pretty=true]
|
|
5
|
+
* @returns {string}
|
|
6
|
+
*/
|
|
7
|
+
export function formatJson(scanResult, pretty = true) {
|
|
8
|
+
return JSON.stringify(
|
|
9
|
+
{
|
|
10
|
+
rootDir: scanResult.rootDir,
|
|
11
|
+
generatedAt: new Date().toISOString(),
|
|
12
|
+
stats: scanResult.stats,
|
|
13
|
+
tree: scanResult.rootNode
|
|
14
|
+
},
|
|
15
|
+
null,
|
|
16
|
+
pretty ? 2 : 0
|
|
17
|
+
);
|
|
18
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { formatTree } from './tree.js';
|
|
2
|
+
import { extractRoutes } from './routes.js';
|
|
3
|
+
import { formatBytes } from '../utils.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Formats scan result into an AI-optimized Markdown file.
|
|
7
|
+
* @param {object} scanResult
|
|
8
|
+
* @param {object} [options]
|
|
9
|
+
* @param {boolean} [options.includeStats=true]
|
|
10
|
+
* @param {boolean} [options.includeTable=true]
|
|
11
|
+
* @returns {string}
|
|
12
|
+
*/
|
|
13
|
+
export function formatMarkdown(scanResult, options = {}) {
|
|
14
|
+
const includeStats = options.includeStats !== false;
|
|
15
|
+
const includeTable = options.includeTable !== false;
|
|
16
|
+
|
|
17
|
+
const { rootNode, stats, rootDir } = scanResult;
|
|
18
|
+
const treeString = formatTree(rootNode).trim();
|
|
19
|
+
const allRoutes = extractRoutes(rootNode, false);
|
|
20
|
+
|
|
21
|
+
let md = `# Project Structure & File Routes\n\n`;
|
|
22
|
+
md += `> Automatically generated by \`fp-generate\` on ${new Date().toISOString()}.\n`;
|
|
23
|
+
md += `> Root Directory: \`${rootDir}\`\n\n`;
|
|
24
|
+
|
|
25
|
+
if (includeStats) {
|
|
26
|
+
md += `## 📊 Overview\n\n`;
|
|
27
|
+
md += `- **Total Files**: ${stats.totalFiles}\n`;
|
|
28
|
+
md += `- **Total Directories**: ${stats.totalFolders}\n`;
|
|
29
|
+
md += `- **Total Size**: ${formatBytes(stats.totalBytes)}\n\n`;
|
|
30
|
+
|
|
31
|
+
const exts = Object.entries(stats.extensionCounts).sort((a, b) => b[1] - a[1]);
|
|
32
|
+
if (exts.length > 0) {
|
|
33
|
+
md += `### File Types\n\n`;
|
|
34
|
+
md += `| Extension | Count |\n`;
|
|
35
|
+
md += `| :--- | :--- |\n`;
|
|
36
|
+
for (const [ext, count] of exts) {
|
|
37
|
+
md += `| \`${ext}\` | ${count} |\n`;
|
|
38
|
+
}
|
|
39
|
+
md += `\n`;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
md += `## 🌳 Directory Tree\n\n`;
|
|
44
|
+
md += `\`\`\`text\n${treeString}\n\`\`\`\n\n`;
|
|
45
|
+
|
|
46
|
+
if (includeTable && allRoutes.length > 0) {
|
|
47
|
+
md += `## 🧭 File Routes Index\n\n`;
|
|
48
|
+
md += `This index contains all normalized relative file paths for AI navigation:\n\n`;
|
|
49
|
+
md += `| # | Route / Relative Path | Size |\n`;
|
|
50
|
+
md += `| :--- | :--- | :--- |\n`;
|
|
51
|
+
|
|
52
|
+
let fileMap = new Map();
|
|
53
|
+
function collectFileDetails(node) {
|
|
54
|
+
if (node.type === 'file') {
|
|
55
|
+
fileMap.set(node.path, node);
|
|
56
|
+
} else if (node.children) {
|
|
57
|
+
for (const child of node.children) {
|
|
58
|
+
collectFileDetails(child);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
collectFileDetails(rootNode);
|
|
63
|
+
|
|
64
|
+
for (let i = 0; i < allRoutes.length; i++) {
|
|
65
|
+
const route = allRoutes[i];
|
|
66
|
+
const fileInfo = fileMap.get(route);
|
|
67
|
+
const sizeStr = fileInfo ? formatBytes(fileInfo.size) : '-';
|
|
68
|
+
md += `| ${i + 1} | \`${route}\` | ${sizeStr} |\n`;
|
|
69
|
+
}
|
|
70
|
+
md += `\n`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return md;
|
|
74
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extracts a flat list of all normalized file routes from the scanned node tree.
|
|
3
|
+
* @param {object} node
|
|
4
|
+
* @param {boolean} [includeDirs=false]
|
|
5
|
+
* @returns {string[]}
|
|
6
|
+
*/
|
|
7
|
+
export function extractRoutes(node, includeDirs = false) {
|
|
8
|
+
const routes = [];
|
|
9
|
+
|
|
10
|
+
function traverse(currentNode) {
|
|
11
|
+
if (currentNode.type === 'file') {
|
|
12
|
+
if (currentNode.path) {
|
|
13
|
+
routes.push(currentNode.path);
|
|
14
|
+
}
|
|
15
|
+
} else if (currentNode.type === 'directory') {
|
|
16
|
+
if (includeDirs && currentNode.path) {
|
|
17
|
+
routes.push(`${currentNode.path}/`);
|
|
18
|
+
}
|
|
19
|
+
if (currentNode.children) {
|
|
20
|
+
for (const child of currentNode.children) {
|
|
21
|
+
traverse(child);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
traverse(node);
|
|
28
|
+
return routes.sort();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Formats routes as a plain text newline-delimited string.
|
|
33
|
+
* @param {object} scanResult
|
|
34
|
+
* @param {boolean} [includeDirs=false]
|
|
35
|
+
* @returns {string}
|
|
36
|
+
*/
|
|
37
|
+
export function formatRoutes(scanResult, includeDirs = false) {
|
|
38
|
+
const routes = extractRoutes(scanResult.rootNode, includeDirs);
|
|
39
|
+
return routes.join('\n');
|
|
40
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renders a directory tree into an ASCII/Unicode branch tree string.
|
|
3
|
+
* @param {object} node
|
|
4
|
+
* @param {string} [prefix='']
|
|
5
|
+
* @param {boolean} [isLast=true]
|
|
6
|
+
* @param {boolean} [isRoot=true]
|
|
7
|
+
* @returns {string}
|
|
8
|
+
*/
|
|
9
|
+
export function formatTree(node, prefix = '', isLast = true, isRoot = true) {
|
|
10
|
+
let output = '';
|
|
11
|
+
|
|
12
|
+
if (isRoot) {
|
|
13
|
+
output += `${node.name}/\n`;
|
|
14
|
+
} else {
|
|
15
|
+
const branch = isLast ? '└── ' : '├── ';
|
|
16
|
+
const displayName = node.type === 'directory' ? `${node.name}/` : node.name;
|
|
17
|
+
output += `${prefix}${branch}${displayName}\n`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (node.children && node.children.length > 0) {
|
|
21
|
+
const newPrefix = isRoot ? '' : prefix + (isLast ? ' ' : '│ ');
|
|
22
|
+
for (let i = 0; i < node.children.length; i++) {
|
|
23
|
+
const child = node.children[i];
|
|
24
|
+
const lastChild = i === node.children.length - 1;
|
|
25
|
+
output += formatTree(child, newPrefix, lastChild, false);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
return output;
|
|
30
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { scanDirectory } from './scanner.js';
|
|
2
|
+
export { formatTree } from './formatters/tree.js';
|
|
3
|
+
export { formatRoutes, extractRoutes } from './formatters/routes.js';
|
|
4
|
+
export { formatJson } from './formatters/json.js';
|
|
5
|
+
export { formatMarkdown } from './formatters/markdown.js';
|
|
6
|
+
export { watchDirectory } from './watcher.js';
|
|
7
|
+
export { normalizeRoute, formatBytes, DEFAULT_IGNORES } from './utils.js';
|
|
8
|
+
export { runCLI } from './cli.js';
|
package/src/scanner.js
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { normalizeRoute, DEFAULT_IGNORES } from './utils.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Converts a gitignore-style glob pattern into a RegExp.
|
|
7
|
+
* @param {string} pattern
|
|
8
|
+
* @returns {{ regex: RegExp, isDirOnly: boolean, isNegative: boolean }}
|
|
9
|
+
*/
|
|
10
|
+
export function compilePattern(pattern) {
|
|
11
|
+
let isNegative = false;
|
|
12
|
+
let p = pattern.trim();
|
|
13
|
+
|
|
14
|
+
if (p.startsWith('!')) {
|
|
15
|
+
isNegative = true;
|
|
16
|
+
p = p.slice(1);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const isDirOnly = p.endsWith('/');
|
|
20
|
+
if (isDirOnly) {
|
|
21
|
+
p = p.slice(0, -1);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const hasSlash = p.includes('/');
|
|
25
|
+
let regexStr = '';
|
|
26
|
+
|
|
27
|
+
let i = 0;
|
|
28
|
+
while (i < p.length) {
|
|
29
|
+
const char = p[i];
|
|
30
|
+
if (char === '*' && p[i + 1] === '*') {
|
|
31
|
+
if (p[i + 2] === '/') {
|
|
32
|
+
regexStr += '(?:.*/)?';
|
|
33
|
+
i += 3;
|
|
34
|
+
} else {
|
|
35
|
+
regexStr += '.*';
|
|
36
|
+
i += 2;
|
|
37
|
+
}
|
|
38
|
+
} else if (char === '*') {
|
|
39
|
+
regexStr += '[^/]*';
|
|
40
|
+
i++;
|
|
41
|
+
} else if (char === '?') {
|
|
42
|
+
regexStr += '[^/]';
|
|
43
|
+
i++;
|
|
44
|
+
} else if ('./\\+^$()[]{}|'.includes(char)) {
|
|
45
|
+
regexStr += '\\' + char;
|
|
46
|
+
i++;
|
|
47
|
+
} else {
|
|
48
|
+
regexStr += char;
|
|
49
|
+
i++;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// If anchored to root or has slash
|
|
54
|
+
if (hasSlash) {
|
|
55
|
+
if (regexStr.startsWith('\\/')) {
|
|
56
|
+
regexStr = regexStr.slice(2);
|
|
57
|
+
}
|
|
58
|
+
regexStr = `^${regexStr}(?:\\/.*)?$`;
|
|
59
|
+
} else {
|
|
60
|
+
// If not anchored, matches this name anywhere, or any child under it
|
|
61
|
+
regexStr = `(?:^|\\/)${regexStr}(?:\\/.*)?$`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
regex: new RegExp(regexStr),
|
|
66
|
+
isDirOnly,
|
|
67
|
+
isNegative
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Creates an ignore filter function from rules and gitignore files.
|
|
73
|
+
* @param {string[]} patterns
|
|
74
|
+
* @returns {(relativePath: string, isDirectory: boolean) => boolean} returns true if ignored
|
|
75
|
+
*/
|
|
76
|
+
export function createIgnoreFilter(patterns) {
|
|
77
|
+
const compiled = patterns
|
|
78
|
+
.map(line => line.trim())
|
|
79
|
+
.filter(line => line && !line.startsWith('#'))
|
|
80
|
+
.map(compilePattern);
|
|
81
|
+
|
|
82
|
+
return function isIgnored(relativePath, isDirectory) {
|
|
83
|
+
const normalized = normalizeRoute(relativePath);
|
|
84
|
+
if (!normalized) return false;
|
|
85
|
+
|
|
86
|
+
let ignored = false;
|
|
87
|
+
for (const rule of compiled) {
|
|
88
|
+
if (rule.isDirOnly && !isDirectory && !normalized.includes('/')) {
|
|
89
|
+
// e.g. rule is "dist/" but target is root-level file "dist"
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (rule.regex.test(normalized)) {
|
|
93
|
+
ignored = !rule.isNegative;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return ignored;
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Loads .gitignore patterns from root directory if present.
|
|
102
|
+
* @param {string} rootDir
|
|
103
|
+
* @returns {Promise<string[]>}
|
|
104
|
+
*/
|
|
105
|
+
export async function loadGitignore(rootDir) {
|
|
106
|
+
const gitignorePath = path.join(rootDir, '.gitignore');
|
|
107
|
+
try {
|
|
108
|
+
const content = await fs.readFile(gitignorePath, 'utf8');
|
|
109
|
+
return content.split(/\r?\n/);
|
|
110
|
+
} catch {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Scans a directory recursively and builds a structured tree of files and directories.
|
|
117
|
+
* @param {string} rootDir
|
|
118
|
+
* @param {object} options
|
|
119
|
+
* @param {number} [options.maxDepth]
|
|
120
|
+
* @param {string[]} [options.customIgnores]
|
|
121
|
+
* @param {boolean} [options.includeHidden]
|
|
122
|
+
* @returns {Promise<ScanResult>}
|
|
123
|
+
*/
|
|
124
|
+
export async function scanDirectory(rootDir, options = {}) {
|
|
125
|
+
const maxDepth = options.maxDepth !== undefined ? options.maxDepth : Infinity;
|
|
126
|
+
const includeHidden = options.includeHidden || false;
|
|
127
|
+
const customIgnores = options.customIgnores || [];
|
|
128
|
+
|
|
129
|
+
const gitignoreRules = await loadGitignore(rootDir);
|
|
130
|
+
const allPatterns = [...DEFAULT_IGNORES, ...gitignoreRules, ...customIgnores];
|
|
131
|
+
const isIgnored = createIgnoreFilter(allPatterns);
|
|
132
|
+
|
|
133
|
+
const stats = {
|
|
134
|
+
totalFiles: 0,
|
|
135
|
+
totalFolders: 0,
|
|
136
|
+
totalBytes: 0,
|
|
137
|
+
extensionCounts: {}
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Recursive scanner
|
|
142
|
+
*/
|
|
143
|
+
async function walk(currentDir, currentDepth) {
|
|
144
|
+
const relDir = path.relative(rootDir, currentDir);
|
|
145
|
+
const normalizedRelDir = normalizeRoute(relDir);
|
|
146
|
+
|
|
147
|
+
const dirNode = {
|
|
148
|
+
name: path.basename(currentDir) || path.basename(rootDir) || '.',
|
|
149
|
+
path: normalizedRelDir,
|
|
150
|
+
type: 'directory',
|
|
151
|
+
children: []
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
if (currentDepth > maxDepth) {
|
|
155
|
+
return dirNode;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
let entries;
|
|
159
|
+
try {
|
|
160
|
+
entries = await fs.readdir(currentDir, { withFileTypes: true });
|
|
161
|
+
} catch {
|
|
162
|
+
return dirNode;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Sort entries: directories first, then alphabetical
|
|
166
|
+
entries.sort((a, b) => {
|
|
167
|
+
if (a.isDirectory() && !b.isDirectory()) return -1;
|
|
168
|
+
if (!a.isDirectory() && b.isDirectory()) return 1;
|
|
169
|
+
return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
for (const entry of entries) {
|
|
173
|
+
if (!includeHidden && entry.name.startsWith('.') && entry.name !== '.gitignore') {
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const fullPath = path.join(currentDir, entry.name);
|
|
178
|
+
const relPath = path.relative(rootDir, fullPath);
|
|
179
|
+
const normalizedPath = normalizeRoute(relPath);
|
|
180
|
+
|
|
181
|
+
if (entry.isDirectory()) {
|
|
182
|
+
if (isIgnored(normalizedPath, true)) {
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
stats.totalFolders++;
|
|
187
|
+
const subDirNode = await walk(fullPath, currentDepth + 1);
|
|
188
|
+
dirNode.children.push(subDirNode);
|
|
189
|
+
} else if (entry.isFile()) {
|
|
190
|
+
if (isIgnored(normalizedPath, false)) {
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
stats.totalFiles++;
|
|
195
|
+
let size = 0;
|
|
196
|
+
try {
|
|
197
|
+
const fileStat = await fs.stat(fullPath);
|
|
198
|
+
size = fileStat.size;
|
|
199
|
+
stats.totalBytes += size;
|
|
200
|
+
} catch {
|
|
201
|
+
// ignore stat errors
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const ext = path.extname(entry.name).toLowerCase() || '(no ext)';
|
|
205
|
+
stats.extensionCounts[ext] = (stats.extensionCounts[ext] || 0) + 1;
|
|
206
|
+
|
|
207
|
+
dirNode.children.push({
|
|
208
|
+
name: entry.name,
|
|
209
|
+
path: normalizedPath,
|
|
210
|
+
type: 'file',
|
|
211
|
+
size,
|
|
212
|
+
extension: ext,
|
|
213
|
+
depth: currentDepth
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return dirNode;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const rootNode = await walk(rootDir, 1);
|
|
222
|
+
|
|
223
|
+
return {
|
|
224
|
+
rootDir: path.resolve(rootDir),
|
|
225
|
+
rootNode,
|
|
226
|
+
stats
|
|
227
|
+
};
|
|
228
|
+
}
|
package/src/utils.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Normalizes a path to use forward slashes (Unix style), suitable for route matching & AI prompts.
|
|
5
|
+
* @param {string} p
|
|
6
|
+
* @returns {string}
|
|
7
|
+
*/
|
|
8
|
+
export function normalizeRoute(p) {
|
|
9
|
+
if (!p) return '';
|
|
10
|
+
return p.split(path.sep).join('/').replace(/^\.\//, '');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Human readable file size formatter.
|
|
15
|
+
* @param {number} bytes
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/
|
|
18
|
+
export function formatBytes(bytes) {
|
|
19
|
+
if (bytes === 0) return '0 B';
|
|
20
|
+
const k = 1024;
|
|
21
|
+
const sizes = ['B', 'KB', 'MB', 'GB'];
|
|
22
|
+
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
23
|
+
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Built-in default ignore patterns (common bloat, caches, secrets, and VCS folders).
|
|
28
|
+
*/
|
|
29
|
+
export const DEFAULT_IGNORES = [
|
|
30
|
+
'.git',
|
|
31
|
+
'.svn',
|
|
32
|
+
'.hg',
|
|
33
|
+
'node_modules',
|
|
34
|
+
'dist',
|
|
35
|
+
'build',
|
|
36
|
+
'out',
|
|
37
|
+
'.next',
|
|
38
|
+
'.nuxt',
|
|
39
|
+
'.turbo',
|
|
40
|
+
'.cache',
|
|
41
|
+
'coverage',
|
|
42
|
+
'.nyc_output',
|
|
43
|
+
'.idea',
|
|
44
|
+
'.vscode',
|
|
45
|
+
'.DS_Store',
|
|
46
|
+
'Thumbs.db',
|
|
47
|
+
'.env',
|
|
48
|
+
'.env.*',
|
|
49
|
+
'*.log',
|
|
50
|
+
'npm-debug.log*',
|
|
51
|
+
'yarn-debug.log*',
|
|
52
|
+
'yarn-error.log*',
|
|
53
|
+
'package-lock.json',
|
|
54
|
+
'pnpm-lock.yaml',
|
|
55
|
+
'yarn.lock'
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Basic ANSI colors without external dependencies
|
|
60
|
+
*/
|
|
61
|
+
export const colors = {
|
|
62
|
+
reset: (text) => `\x1b[0m${text}\x1b[0m`,
|
|
63
|
+
bold: (text) => `\x1b[1m${text}\x1b[0m`,
|
|
64
|
+
dim: (text) => `\x1b[2m${text}\x1b[0m`,
|
|
65
|
+
cyan: (text) => `\x1b[36m${text}\x1b[0m`,
|
|
66
|
+
green: (text) => `\x1b[32m${text}\x1b[0m`,
|
|
67
|
+
yellow: (text) => `\x1b[33m${text}\x1b[0m`,
|
|
68
|
+
blue: (text) => `\x1b[34m${text}\x1b[0m`,
|
|
69
|
+
magenta: (text) => `\x1b[35m${text}\x1b[0m`,
|
|
70
|
+
gray: (text) => `\x1b[90m${text}\x1b[0m`
|
|
71
|
+
};
|
package/src/watcher.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { colors } from './utils.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Watches a directory for changes and invokes a callback with debouncing.
|
|
6
|
+
* @param {string} dirToWatch
|
|
7
|
+
* @param {Function} onChange
|
|
8
|
+
* @param {object} [options]
|
|
9
|
+
* @param {number} [options.debounceMs=250]
|
|
10
|
+
* @returns {{ close: () => void }}
|
|
11
|
+
*/
|
|
12
|
+
export function watchDirectory(dirToWatch, onChange, options = {}) {
|
|
13
|
+
const debounceMs = options.debounceMs || 300;
|
|
14
|
+
let timer = null;
|
|
15
|
+
|
|
16
|
+
function trigger(eventType, filename) {
|
|
17
|
+
if (timer) clearTimeout(timer);
|
|
18
|
+
timer = setTimeout(async () => {
|
|
19
|
+
try {
|
|
20
|
+
console.log(colors.gray(`[watcher] Change detected (${eventType}: ${filename || 'file'}). Regenerating...`));
|
|
21
|
+
await onChange();
|
|
22
|
+
} catch (err) {
|
|
23
|
+
console.error(colors.yellow(`[watcher] Error during regeneration:`), err.message);
|
|
24
|
+
}
|
|
25
|
+
}, debounceMs);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
let watcher;
|
|
29
|
+
try {
|
|
30
|
+
watcher = fs.watch(dirToWatch, { recursive: true }, (eventType, filename) => {
|
|
31
|
+
// Ignore updates to output markdown itself or common ignore targets
|
|
32
|
+
if (filename) {
|
|
33
|
+
const norm = filename.replace(/\\/g, '/');
|
|
34
|
+
if (
|
|
35
|
+
norm.endsWith('PROJECT_STRUCTURE.md') ||
|
|
36
|
+
norm.includes('.git/') ||
|
|
37
|
+
norm.includes('node_modules/') ||
|
|
38
|
+
norm.startsWith('.git') ||
|
|
39
|
+
norm.startsWith('node_modules')
|
|
40
|
+
) {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
trigger(eventType, filename);
|
|
45
|
+
});
|
|
46
|
+
} catch (err) {
|
|
47
|
+
console.warn(colors.yellow(`[watcher] Recursive watch not fully supported on this OS; falling back to non-recursive.`));
|
|
48
|
+
watcher = fs.watch(dirToWatch, (eventType, filename) => {
|
|
49
|
+
trigger(eventType, filename);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
close() {
|
|
55
|
+
if (timer) clearTimeout(timer);
|
|
56
|
+
if (watcher) watcher.close();
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|