@git.zone/tsdoc 1.5.1 → 1.5.2

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.
@@ -3,7 +3,7 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@git.zone/tsdoc',
6
- version: '1.5.1',
6
+ version: '1.5.2',
7
7
  description: 'A comprehensive TypeScript documentation tool that leverages AI to generate and enhance project documentation, including dynamic README creation, API docs via TypeDoc, and smart commit message generation.'
8
8
  };
9
9
  //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMDBfY29tbWl0aW5mb19kYXRhLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvMDBfY29tbWl0aW5mb19kYXRhLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOztHQUVHO0FBQ0gsTUFBTSxDQUFDLE1BQU0sVUFBVSxHQUFHO0lBQ3hCLElBQUksRUFBRSxpQkFBaUI7SUFDdkIsT0FBTyxFQUFFLE9BQU87SUFDaEIsV0FBVyxFQUFFLDhNQUE4TTtDQUM1TixDQUFBIn0=
@@ -53,8 +53,8 @@ interface {
53
53
  For the recommendedNextVersionDetails, please only add a detail entries to the array if it has an obvious value to the reader.
54
54
 
55
55
  You are being given the files of the project. You should use them to create the commit message.
56
- Also you are given a diff
57
-
56
+ Also you are given a diff.
57
+ Never mention CLAUDE code, or codex.
58
58
  `,
59
59
  messageHistory: [],
60
60
  userMessage: contextString,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git.zone/tsdoc",
3
- "version": "1.5.1",
3
+ "version": "1.5.2",
4
4
  "private": false,
5
5
  "description": "A comprehensive TypeScript documentation tool that leverages AI to generate and enhance project documentation, including dynamic README creation, API docs via TypeDoc, and smart commit message generation.",
6
6
  "type": "module",
@@ -13,30 +13,29 @@
13
13
  "tsdoc": "cli.js"
14
14
  },
15
15
  "devDependencies": {
16
- "@git.zone/tsbuild": "^2.6.4",
16
+ "@git.zone/tsbuild": "^2.6.8",
17
17
  "@git.zone/tsrun": "^1.2.46",
18
- "@git.zone/tstest": "^2.3.2",
19
- "@push.rocks/tapbundle": "^6.0.3",
18
+ "@git.zone/tstest": "^2.3.6",
20
19
  "@types/node": "^22.15.17"
21
20
  },
22
21
  "dependencies": {
23
- "@git.zone/tspublish": "^1.10.1",
22
+ "@git.zone/tspublish": "^1.10.3",
24
23
  "@push.rocks/early": "^4.0.3",
25
- "@push.rocks/npmextra": "^5.3.1",
26
- "@push.rocks/qenv": "^6.1.2",
24
+ "@push.rocks/npmextra": "^5.3.3",
25
+ "@push.rocks/qenv": "^6.1.3",
27
26
  "@push.rocks/smartai": "^0.5.11",
28
27
  "@push.rocks/smartcli": "^4.0.11",
29
28
  "@push.rocks/smartdelay": "^3.0.5",
30
- "@push.rocks/smartfile": "^11.2.5",
29
+ "@push.rocks/smartfile": "^11.2.7",
31
30
  "@push.rocks/smartgit": "^3.2.1",
32
31
  "@push.rocks/smartinteract": "^2.0.15",
33
- "@push.rocks/smartlog": "^3.1.8",
32
+ "@push.rocks/smartlog": "^3.1.9",
34
33
  "@push.rocks/smartlog-destination-local": "^9.0.2",
35
34
  "@push.rocks/smartpath": "^6.0.0",
36
- "@push.rocks/smartshell": "^3.2.4",
35
+ "@push.rocks/smartshell": "^3.3.0",
37
36
  "@push.rocks/smarttime": "^4.0.6",
38
- "gpt-tokenizer": "^2.9.0",
39
- "typedoc": "^0.28.10",
37
+ "gpt-tokenizer": "^3.0.1",
38
+ "typedoc": "^0.28.12",
40
39
  "typescript": "^5.9.2"
41
40
  },
42
41
  "files": [
@@ -76,7 +75,7 @@
76
75
  },
77
76
  "homepage": "https://gitlab.com/gitzone/tsdoc#readme",
78
77
  "scripts": {
79
- "test": "(tstest test/) && npm run testCli",
78
+ "test": "(tstest test/ --verbose --logfile --timeout 600) && npm run testCli",
80
79
  "testCli": "(node ./cli.ts.js) && (node ./cli.ts.js aidocs)",
81
80
  "build": "(tsbuild --web --allowimplicitany)",
82
81
  "buildDocs": "tsdoc"
package/readme.md CHANGED
@@ -1,726 +1,285 @@
1
- # @git.zone/tsdoc
2
- An advanced TypeScript documentation tool using AI to generate and enhance documentation for TypeScript projects.
1
+ # @git.zone/tsdoc 🚀
2
+ **AI-Powered Documentation for TypeScript Projects**
3
3
 
4
- ## Install
4
+ > Stop writing documentation. Let AI understand your code and do it for you.
5
5
 
6
- To install @git.zone/tsdoc, you have two options. You can install it globally so that the CLI commands are available throughout your system, or you can use it with npx if you prefer to keep the installation local to your project.
6
+ ## What is tsdoc?
7
7
 
8
- ### Global Installation
8
+ `@git.zone/tsdoc` is a next-generation documentation tool that combines traditional TypeDoc generation with cutting-edge AI to create comprehensive, intelligent documentation for your TypeScript projects. It reads your code, understands it, and writes documentation that actually makes sense.
9
9
 
10
- To install the tool globally, run the following command in your terminal:
10
+ ### Key Features
11
11
 
12
- ```bash
13
- npm install -g @git.zone/tsdoc
14
- ```
12
+ - **🤖 AI-Enhanced Documentation** - Leverages GPT-5 and other models to generate contextual READMEs
13
+ - **📚 TypeDoc Integration** - Classic API documentation generation when you need it
14
+ - **💬 Smart Commit Messages** - AI analyzes your changes and suggests meaningful commit messages
15
+ - **🎯 Context Optimization** - Intelligent token management for efficient AI processing
16
+ - **📦 Zero Config** - Works out of the box with sensible defaults
17
+ - **🔧 Highly Configurable** - Customize every aspect when needed
15
18
 
16
- Installing globally ensures that the CLI commands (such as tsdoc, tsdoc typedoc, tsdoc aidoc, etc.) are available anywhere on your machine without the need to refer to the local node_modules folder.
17
-
18
- ### Usage with npx
19
-
20
- If you prefer not to install the tool globally, you can invoke it using npx directly from your project. This method works well if you intend to use the tool on a per-project basis:
19
+ ## Installation
21
20
 
22
21
  ```bash
23
- npx @git.zone/tsdoc <command>
24
- ```
25
-
26
- In the commands below, you will see how to use the various functionalities that @git.zone/tsdoc provides for generating intricate and enhanced documentation for your TypeScript projects.
27
-
28
- ## Usage
29
-
30
- The @git.zone/tsdoc module provides a very rich and interactive CLI interface together with a set of programmable classes that let you integrate documentation generation into your build processes or workflows. This section will walk you through every aspect of the module—from its basic CLI commands to its advanced internal API usage. All examples provided below use ESM syntax with TypeScript and are designed to be comprehensive. Every code snippet is written so you can easily copy, paste, and adapt to your project. The following guide is divided into several sections covering every major feature, tool integration, and customization options available in the module.
31
-
32
- -------------------------------------------------------------------
33
- ### Overview and Core Concepts
34
-
35
- At its heart, @git.zone/tsdoc is a CLI tool that blends classic documentation generation (using libraries such as TypeDoc) with AI-enhanced techniques. The tool reads your project files, uses a context builder to optimize file content based on token usage and configurable trimming strategies, and then leverages an AI engine to generate enhanced documentation. This complete solution is designed to integrate smoothly into your project pipeline.
36
-
37
- Key features include:
38
- - **Auto-detection of documentation format**: The CLI attempts to determine the best documentation strategy for your project.
39
- - **Support for TypeDoc generation**: Build TypeDoc-compatible documentation directly.
40
- - **AI-Enhanced Documentation (AiDoc)**: Generate a README and project description using artificial intelligence that analyzes your project’s code and context.
41
- - **Plugin Integration**: The module leverages a variety of plugins (smartfile, smartgit, smartcli, smartai, etc.) to streamline tasks such as file manipulation, CLI interaction, shell command execution, and logging.
42
- - **Context Trimming and Optimization**: To manage token usage (especially for AI input), the module includes advanced context-building strategies that trim and summarize code files intelligently.
43
- - **Robust Internal API**: While the primary user interface is through the CLI, the underlying classes (AiDoc, TypeDoc, Readme, etc.) can be used to build custom integrations or extend the tool’s functionality.
44
-
45
- Below, you will find detailed explanations along with ESM/TypeScript code examples for all core use cases.
46
-
47
- -------------------------------------------------------------------
48
- ### Command-Line Interface (CLI) Usage
49
-
50
- The most common way to interact with @git.zone/tsdoc is via its command-line interface (CLI). The CLI is designed to auto-detect your project’s context and trigger the appropriate commands based on your needs. Below is a guide on how to use the CLI commands.
51
-
52
- #### Basic Invocation
53
-
54
- When you run the command without any arguments, the tool attempts to determine the appropriate documentation generation mode:
22
+ # Global installation (recommended)
23
+ npm install -g @git.zone/tsdoc
55
24
 
56
- ```bash
57
- tsdoc
25
+ # Or use with npx
26
+ npx @git.zone/tsdoc
58
27
  ```
59
28
 
60
- This will scan the project directory and attempt to detect whether your project follows a TypeDoc convention or if it would benefit from an AI-enhanced documentation build. The auto-detection logic uses the project context (for example, the presence of a ts directory or specific configuration files) to decide the best course of action.
61
-
62
- ##### Example Scenario
63
-
64
- Imagine you have a TypeScript project with the following structure:
65
-
66
- ├── package.json
67
- ├── ts/
68
- │   └── index.ts
69
- └── readme.hints.md
29
+ ## Quick Start
70
30
 
71
- When you execute:
31
+ ### Generate AI-Powered Documentation
72
32
 
73
33
  ```bash
74
- tsdoc
34
+ # In your project root
35
+ tsdoc aidoc
75
36
  ```
76
37
 
77
- The tool will analyze the project directory, recognizing the ts/ folder, and it will route the command to the appropriate documentation generator, such as the TypeDoc generator if it detects valid structure.
78
-
79
- #### TypeDoc Command
38
+ That's it! tsdoc will analyze your entire codebase and generate:
39
+ - A comprehensive README.md
40
+ - Updated package.json description and keywords
41
+ - Smart documentation based on your actual code
80
42
 
81
- For projects that require a traditional documentation format, you can explicitly generate documentation using the TypeDoc integration:
43
+ ### Generate Traditional TypeDoc
82
44
 
83
45
  ```bash
84
46
  tsdoc typedoc --publicSubdir docs
85
47
  ```
86
48
 
87
- This command instructs the module to generate HTML documentation using TypeDoc, placing the output into a public directory (or a custom subdirectory as specified).
88
-
89
- **Inside a TypeScript file, this command can be mirrored by calling the TypeDoc class directly:**
90
-
91
- ```typescript
92
- import { TypeDoc } from '@git.zone/tsdoc';
93
- import * as path from 'path';
94
-
95
- const cwd = process.cwd();
96
- const typeDocInstance = new TypeDoc(cwd);
97
-
98
- const compileDocumentation = async (): Promise<void> => {
99
- try {
100
- // Specify the output subdirectory for documentation
101
- await typeDocInstance.compile({
102
- publicSubdir: 'docs'
103
- });
104
- console.log('Documentation successfully generated using TypeDoc.');
105
- } catch (error) {
106
- console.error('Error generating documentation with TypeDoc:', error);
107
- }
108
- };
109
-
110
- compileDocumentation();
111
- ```
112
-
113
- In this example, the script creates an instance of the TypeDoc class passing the current working directory. The compile method is then called with an options object, indicating that the public subdirectory should be named “docs.” The method spawns a shell command using the smart shell plugin to execute the TypeDoc binary.
114
-
115
- #### AI-Enhanced Documentation Command
116
-
117
- One of the standout features of this module is its AI-enhanced documentation capabilities. The `aidoc` command integrates with an OpenAI interface to produce a more contextual and detailed README and project description. This is particularly useful when your project codebase has evolved and requires documentation updates based on the current source code.
118
-
119
- To run the AI-enhanced documentation generation:
49
+ ### Get Smart Commit Messages
120
50
 
121
51
  ```bash
122
- tsdoc aidoc
52
+ tsdoc commit
123
53
  ```
124
54
 
125
- In an ESM/TypeScript project, you can use the AiDoc class to programmatically run the same functionality:
126
-
127
- ```typescript
128
- import { AiDoc } from '@git.zone/tsdoc';
129
-
130
- const buildEnhancedDocs = async (): Promise<void> => {
131
- const aiDoc = new AiDoc({ OPENAI_TOKEN: 'your-openai-token' });
132
- try {
133
- // Start the AI interface; this internally checks if the token is valid and persists it
134
- await aiDoc.start();
55
+ ## CLI Commands
135
56
 
136
- // Build the README file for the project directory
137
- console.log('Generating README file using AI...');
138
- await aiDoc.buildReadme(process.cwd());
57
+ | Command | Description |
58
+ |---------|-------------|
59
+ | `tsdoc` | Auto-detects and runs appropriate documentation |
60
+ | `tsdoc aidoc` | Generate AI-enhanced documentation |
61
+ | `tsdoc typedoc` | Generate TypeDoc documentation |
62
+ | `tsdoc commit` | Generate smart commit message |
63
+ | `tsdoc tokens` | Analyze token usage for AI context |
64
+ | `tsdoc context` | Display context information |
139
65
 
140
- // Build a new project description based on the codebase
141
- console.log('Generating updated project description...');
142
- await aiDoc.buildDescription(process.cwd());
66
+ ### Token Analysis
143
67
 
144
- console.log('AI-enhanced documentation generated successfully.');
145
- } catch (error) {
146
- console.error('Failed to generate AI-enhanced documentation:', error);
147
- }
148
- };
149
-
150
- buildEnhancedDocs();
151
- ```
152
-
153
- In the above snippet, we import the AiDoc class and create an instance with an OpenAI token. The methods start(), buildReadme(), and buildDescription() streamline the process of generating enhanced documentation by leveraging the underlying AI engine. This code example should serve as a blueprint for those wishing to integrate AI-driven documentation updates as part of their CI/CD pipelines.
154
-
155
- #### Testing Your Documentation Setup
156
-
157
- Before you commit changes to your project documentation, it is often worthwhile to run tests to ensure that your documentation generation process is behaving as expected. The module includes a `test` command:
68
+ Understanding token usage helps optimize AI costs:
158
69
 
159
70
  ```bash
160
- tsdoc test
161
- ```
162
-
163
- This command verifies that all components (CLI commands, TypeDoc compilation, AI integration, etc.) are properly configured.
164
-
165
- Here is an example test script written in TypeScript using a test bundle:
166
-
167
- ```typescript
168
- import { expect, tap } from '@push.rocks/tapbundle';
169
- import { AiDoc } from '@git.zone/tsdoc';
71
+ # Show token count for current project
72
+ tsdoc tokens
170
73
 
171
- tap.test('AiDoc instance creation', async () => {
172
- const aidoc = new AiDoc({ OPENAI_TOKEN: 'dummy-token' });
173
- expect(aidoc).toBeInstanceOf(AiDoc);
174
- });
74
+ # Show detailed stats for all task types
75
+ tsdoc tokens --all
175
76
 
176
- tap.test('Running AI documentation generation', async () => {
177
- const aidoc = new AiDoc({ OPENAI_TOKEN: 'dummy-token' });
178
- await aidoc.start();
179
-
180
- // Attempt buildReadme and buildDescription synchronously for test coverage
181
- await aidoc.buildReadme(process.cwd());
182
- await aidoc.buildDescription(process.cwd());
183
-
184
- // If no errors are thrown, we assume the process works as expected
185
- expect(true).toBe(true);
186
- });
187
-
188
- tap.start();
77
+ # Test with trimmed context
78
+ tsdoc tokens --trim
189
79
  ```
190
80
 
191
- This test script demonstrates how to automate the validation process by using the provided AiDoc class. Using a testing framework like tap ensures that your documentation generation remains robust even as new features are added or as the project evolves.
192
-
193
- -------------------------------------------------------------------
194
- ### Advanced Usage Scenarios
195
-
196
- Beyond using the CLI, @git.zone/tsdoc provides various classes and plugins that allow you to deeply integrate documentation generation within your project. The following sections document advanced usage scenarios where you programmatically interact with different components.
81
+ ## Programmatic Usage
197
82
 
198
- #### 1. Deep Dive into AiDoc Functionality
199
-
200
- The AiDoc class is the core of the AI-enhanced documentation generation. It manages interactions with the OpenAI API, handles token validations, and integrates with project-specific configurations.
201
-
202
- Consider the following advanced usage example:
83
+ ### Generate Documentation Programmatically
203
84
 
204
85
  ```typescript
205
86
  import { AiDoc } from '@git.zone/tsdoc';
206
- import * as path from 'path';
207
-
208
- const generateProjectDocs = async () => {
209
- // Create an instance of the AiDoc class with a configuration object
210
- // that includes your OpenAI token. This token will be used to query the AI.
211
- const aiDoc = new AiDoc({ OPENAI_TOKEN: 'your-openai-token' });
212
87
 
213
- // Initialize the AI documentation system.
88
+ const generateDocs = async () => {
89
+ const aiDoc = new AiDoc({ OPENAI_TOKEN: 'your-token' });
214
90
  await aiDoc.start();
215
-
216
- // Build the README file for the current project.
217
- console.log('Building README for the project...');
218
- await aiDoc.buildReadme(process.cwd());
219
-
220
- // Build an updated project description based on the analysis of the source files.
221
- console.log('Building project description...');
222
- await aiDoc.buildDescription(process.cwd());
223
-
224
- // You can also generate a commit message based on code changes by using the next commit object generation.
225
- try {
226
- console.log('Generating commit message based on your project changes...');
227
- const nextCommit = await aiDoc.buildNextCommitObject(process.cwd());
228
- console.log('Next commit message object:', nextCommit);
229
- } catch (error) {
230
- console.error('Error generating commit message:', error);
231
- }
91
+
92
+ // Generate README
93
+ await aiDoc.buildReadme('./');
94
+
95
+ // Update package.json description
96
+ await aiDoc.buildDescription('./');
97
+
98
+ // Get smart commit message
99
+ const commit = await aiDoc.buildNextCommitObject('./');
100
+ console.log(commit.recommendedNextVersionMessage);
232
101
  };
233
-
234
- generateProjectDocs();
235
102
  ```
236
103
 
237
- In this example, the AiDoc class handles multiple tasks:
238
-
239
- - It starts by validating and printing the sanitized token.
240
- - It generates and writes the README file based on dynamic analysis.
241
- - It updates the project description stored in your configuration files.
242
- - It even integrates with Git to produce a suggested commit message that factors in the current state of the project directory.
243
-
244
- Internally, methods such as buildReadme() interact with the ProjectContext class to gather files and determine the relevant context. This context is trimmed and processed based on token budgets, thus ensuring that the AI interface only receives the information it can effectively process.
245
-
246
- #### 2. Interacting with the TypeDoc Class Programmatically
247
-
248
- The TypeDoc class does not merely wrap the standard TypeDoc tool. It adds a layer of automation by preparing the TypeScript environment, generating a temporary tsconfig file, and invoking TypeDoc with the proper configuration. You can use this functionality to conditionally generate documentation or integrate it into your build steps.
249
-
250
- Below is another example demonstrating the integration:
104
+ ### TypeDoc Generation
251
105
 
252
106
  ```typescript
253
107
  import { TypeDoc } from '@git.zone/tsdoc';
254
- import * as path from 'path';
255
-
256
- const generateTypeDocDocs = async () => {
257
- // Assume you are in the root directory of your TypeScript project
258
- const cwd = process.cwd();
259
-
260
- // Create an instance of the TypeDoc class
261
- const typeDocInstance = new TypeDoc(cwd);
262
-
263
- // Prepare additional options if necessary (e.g., setting a public subdirectory for docs)
264
- const options = { publicSubdir: 'documentation' };
265
-
266
- // Compile your TypeScript project documentation.
267
- // The compile method handles creating the tsconfig file, running the shell command, and cleaning up afterward.
268
- try {
269
- console.log('Compiling TypeScript documentation using TypeDoc...');
270
- await typeDocInstance.compile(options);
271
- console.log('Documentation generated at:', path.join(cwd, 'public', 'documentation'));
272
- } catch (error) {
273
- console.error('Error compiling TypeDoc documentation:', error);
274
- }
275
- };
276
108
 
277
- generateTypeDocDocs();
109
+ const typeDoc = new TypeDoc(process.cwd());
110
+ await typeDoc.compile({ publicSubdir: 'docs' });
278
111
  ```
279
112
 
280
- This script clearly demonstrates how TypeDoc automation is structured inside the module. By invoking the compile() method, the class takes care of setting directory paths, preparing command arguments, and executing the underlying TypeDoc binary using the smart shell plugin.
113
+ ### Context Management
281
114
 
282
- #### 3. Customizing Context Building
283
-
284
- One of the critical functionalities within @git.zone/tsdoc is its ability to build a smart context for documentation generation. The module not only collects file content from your project (like package.json, readme.hints.md, and other source files) but also intelligently trims and summarizes these contents to fit within token limits for AI processing.
285
-
286
- Consider the following deep-dive example into the context building process:
115
+ Control how tsdoc processes your codebase:
287
116
 
288
117
  ```typescript
289
118
  import { EnhancedContext } from '@git.zone/tsdoc';
290
- import { ConfigManager } from '@git.zone/tsdoc/dist/ts/context/config-manager.js';
291
-
292
- const buildProjectContext = async () => {
293
- const projectDir = process.cwd();
294
-
295
- // Create an instance of the EnhancedContext class to optimize file content for AI use.
296
- const enhancedContext = new EnhancedContext(projectDir);
297
-
298
- // Initialize the context builder. This ensures that configuration (e.g., token budgets, trimming options) is loaded.
299
- await enhancedContext.initialize();
300
119
 
301
- // Optionally, you can choose to set a custom token budget and context mode.
302
- enhancedContext.setTokenBudget(100000); // for example, limit tokens to 100K
303
- enhancedContext.setContextMode('trimmed');
120
+ const context = new EnhancedContext('./');
121
+ await context.initialize();
304
122
 
305
- // Build the context string from selected files in your project.
306
- const contextResult = await enhancedContext.buildContext('readme');
123
+ // Set token budget
124
+ context.setTokenBudget(100000);
307
125
 
308
- console.log('Context generated with token count:', contextResult.tokenCount);
309
- console.log('Token savings due to trimming:', contextResult.tokenSavings);
126
+ // Choose context mode
127
+ context.setContextMode('trimmed'); // 'full' | 'trimmed' | 'summarized'
310
128
 
311
- // The context string includes file boundaries and token information.
312
- console.log('Generated Context:', contextResult.context);
313
- };
314
-
315
- buildProjectContext();
129
+ // Build optimized context
130
+ const result = await context.buildContext('readme');
131
+ console.log(`Tokens used: ${result.tokenCount}`);
316
132
  ```
317
133
 
318
- In this example:
319
- - The EnhancedContext class is initialized with the project directory.
320
- - Configuration is loaded via the ConfigManager, which reads parameters from npmextra.json.
321
- - The context builder then gathers files (such as package.json, readme hints, TypeScript sources, etc.), trims unnecessary content, and builds a context string.
322
- - Finally, it prints the overall token counts and savings, giving you valuable feedback on how the context was optimized for the AI input.
323
-
324
- This detailed context-building mechanism is essential for managing large TypeScript projects. It ensures that the AI engine can process relevant code data without being overwhelmed by too many tokens.
325
-
326
- #### 4. Working with the Readme Class for Automatic README Generation
327
-
328
- The Readme class in @git.zone/tsdoc takes the AI-enhanced documentation further by not only generating a project-level README but also iterating over submodules within your project. This ensures that every published module has its own complete, AI-generated README.
329
-
330
- Here is an advanced example demonstrating how to trigger README generation for the main project and its submodules:
331
-
332
- ```typescript
333
- import { AiDoc } from '@git.zone/tsdoc';
334
- import * as path from 'path';
335
- import { logger } from '@git.zone/tsdoc/dist/ts/logging.js';
336
- import { readFileSync } from 'fs';
337
-
338
- const buildProjectReadme = async () => {
339
- const projectDir = process.cwd();
340
-
341
- // Create an instance of the AiDoc class to handle AI-enhanced docs generation
342
- const aiDoc = new AiDoc({ OPENAI_TOKEN: 'your-openai-token' });
343
-
344
- // Start the AI interface
345
- await aiDoc.start();
346
-
347
- // Build the primary README for the project directory
348
- console.log('Generating primary README...');
349
- await aiDoc.buildReadme(projectDir);
350
-
351
- // Logging function to verify submodule processing
352
- logger.log('info', `Primary README generated in ${projectDir}`);
353
-
354
- // Assume that submodules are organized in distinct directories.
355
- // Here we simulate the process of scanning subdirectories and triggering README generation for each.
356
- const subModules = ['submodule1', 'submodule2'];
357
-
358
- // Loop through each submodule directory to generate its README.
359
- for (const subModule of subModules) {
360
- const subModuleDir = path.join(projectDir, subModule);
361
- logger.log('info', `Generating README for submodule: ${subModule}`);
362
-
363
- // Each submodule README is generated independently.
364
- await aiDoc.buildReadme(subModuleDir);
365
-
366
- // Optionally, read the generated README content for verification.
367
- const readmePath = path.join(subModuleDir, 'readme.md');
368
- try {
369
- const readmeContent = readFileSync(readmePath, 'utf8');
370
- logger.log('info', `Generated README for ${subModule}:\n${readmeContent.substring(0, 200)}...`);
371
- } catch (error) {
372
- logger.log('error', `Failed to read README for ${subModule}: ${error}`);
134
+ ## Configuration
135
+
136
+ Configure tsdoc via `npmextra.json`:
137
+
138
+ ```json
139
+ {
140
+ "tsdoc": {
141
+ "context": {
142
+ "maxTokens": 150000,
143
+ "contextMode": "trimmed",
144
+ "includePatterns": ["**/*.ts"],
145
+ "excludePatterns": ["**/*.test.ts"],
146
+ "trimming": {
147
+ "removeImplementations": true,
148
+ "preserveJSDoc": true,
149
+ "removeComments": true
150
+ }
373
151
  }
374
152
  }
375
- };
376
-
377
- buildProjectReadme();
153
+ }
378
154
  ```
379
155
 
380
- In this example, the script:
381
- - Starts by building the AI-enhanced README for the entire project.
382
- - Then iterates over a list of submodule directories and generates READMEs for each.
383
- - Uses the logging utility to provide immediate feedback on the generation process.
384
- - Optionally, reads back a snippet of the generated file to verify successful documentation generation.
156
+ ## How It Works
385
157
 
386
- This approach ensures that projects with multiple submodules or packages maintain a consistent and high-quality documentation standard across every component.
158
+ 1. **🔍 Code Analysis** - Scans your TypeScript files, package.json, and existing documentation
159
+ 2. **✂️ Smart Trimming** - Optimizes code context to fit within AI token limits
160
+ 3. **🧠 AI Processing** - Sends optimized context to AI for analysis
161
+ 4. **📝 Generation** - Creates documentation that understands your code's purpose and structure
387
162
 
388
- -------------------------------------------------------------------
389
- ### Plugin-Based Architecture and Integrations
163
+ ### Context Optimization
390
164
 
391
- Under the hood, @git.zone/tsdoc leverages a number of smaller, focused plugins that extend its functionality. These plugins facilitate file system operations, shell command execution, environment variable management, and logging. The modular design makes it easy to extend or customize the tool according to your needs.
392
-
393
- The relevant plugins include:
394
- - smartai: Provides the API integration with OpenAI.
395
- - smartcli: Handles CLI input parsing and command setup.
396
- - smartdelay: Manages asynchronous delays and debouncing.
397
- - smartfile: Offers an abstraction over file I/O operations.
398
- - smartgit: Facilitates integration with git repositories (e.g., retrieving diffs, commit status).
399
- - smartinteract: Eases interaction with the user (prompting for tokens, confirming actions).
400
- - smartlog and smartlogDestinationLocal: Provide comprehensive logging mechanisms.
401
- - smartpath, smartshell, and smarttime: Manage file paths, execute shell commands, and process time data respectively.
402
-
403
- Below is a sample snippet illustrating how you might directly interact with a few of these plugins to, for example, run a custom shell command or log events:
404
-
405
- ```typescript
406
- import * as plugins from '@git.zone/tsdoc/dist/ts/plugins.js';
407
- import { logger } from '@git.zone/tsdoc/dist/ts/logging.js';
408
-
409
- const runCustomCommand = async () => {
410
- // Create an instance of the smart shell utility
411
- const smartshellInstance = new plugins.smartshell.Smartshell({
412
- executor: 'bash',
413
- pathDirectories: [plugins.smartpath.join(process.cwd(), 'node_modules/.bin')]
414
- });
415
-
416
- try {
417
- // Execute a sample shell command, e.g., listing files in the current directory
418
- const output = await smartshellInstance.exec('ls -la');
419
- logger.log('info', `Shell command output:\n${output}`);
420
- } catch (error) {
421
- logger.log('error', 'Error executing custom shell command:', error);
422
- }
423
- };
165
+ tsdoc employs sophisticated strategies to maximize the value of every token:
424
166
 
425
- runCustomCommand();
426
- ```
167
+ - **Intelligent Trimming** - Removes implementation details while preserving signatures
168
+ - **Priority Sorting** - Most important files first
169
+ - **Smart Summarization** - Condenses large files while maintaining context
170
+ - **Token Budgeting** - Ensures optimal use of AI context windows
427
171
 
428
- This example shows how to:
429
- - Import the necessary plugins.
430
- - Set up a smartshell instance by specifying the shell executor and the directories where executables are located.
431
- - Execute a command (in this case, listing directory contents) and log the results using the provided logging plugin.
172
+ ## Environment Variables
432
173
 
433
- Such examples demonstrate the flexibility provided by the module’s internal API. They also illustrate that even if you choose not to use the CLI, you can still leverage the @git.zone/tsdoc functionality programmatically in a highly integrated fashion.
174
+ | Variable | Description |
175
+ |----------|-------------|
176
+ | `OPENAI_TOKEN` | Your OpenAI API key for AI features |
434
177
 
435
- -------------------------------------------------------------------
436
- ### Handling Git Commit Messages with AI
178
+ ## Use Cases
437
179
 
438
- A unique feature of this tool is its capacity to assist with creating smart commit messages based on code changes. The Commit class (found within the aidocs_classes directory) ties together output from smartgit and AiDoc to suggest commit messages that are both descriptive and formatted according to conventional commit guidelines.
180
+ ### 🚀 Continuous Integration
439
181
 
440
- Consider this example where you generate a commit message based on the diff from your git repository:
182
+ ```yaml
183
+ # .github/workflows/docs.yml
184
+ - name: Generate Documentation
185
+ run: |
186
+ npm install -g @git.zone/tsdoc
187
+ tsdoc aidoc
188
+ ```
441
189
 
442
- ```typescript
443
- import { AiDoc } from '@git.zone/tsdoc';
190
+ ### 🔄 Pre-Commit Hooks
444
191
 
445
- const generateCommitMessage = async () => {
446
- // Create an instance of AiDoc
447
- const aiDoc = new AiDoc({ OPENAI_TOKEN: 'your-openai-token' });
192
+ ```bash
193
+ # Generate commit message before each commit
194
+ tsdoc commit
195
+ ```
448
196
 
449
- // Initialize the AI service
450
- await aiDoc.start();
197
+ ### 📦 Package Publishing
451
198
 
452
- try {
453
- // Generate and retrieve the next commit object based on the uncommitted changes in the repository.
454
- const commitObject = await aiDoc.buildNextCommitObject(process.cwd());
455
- console.log('Recommended commit object:', commitObject);
456
-
457
- // The commit object is structured with the following fields:
458
- // - recommendedNextVersionLevel: Indicates whether the commit is a fix, feature, or breaking change.
459
- // - recommendedNextVersionScope: The scope of changes.
460
- // - recommendedNextVersionMessage: A short commit message.
461
- // - recommendedNextVersionDetails: A list of details explaining the changes.
462
- // - recommendedNextVersion: A computed version string.
463
- } catch (error) {
464
- console.error('Error generating commit message:', error);
199
+ ```javascript
200
+ // Ensure docs are updated before publish
201
+ {
202
+ "scripts": {
203
+ "prepublishOnly": "tsdoc aidoc"
465
204
  }
466
- };
467
-
468
- generateCommitMessage();
205
+ }
469
206
  ```
470
207
 
471
- The process works as follows:
472
- 1. The AiDoc instance is created and started.
473
- 2. The tool uses the smartgit plugin to fetch uncommitted changes from the repository.
474
- 3. It then builds a context string incorporating file diffs and project metadata.
475
- 4. Finally, the OpenAI API is queried to produce a commit message formatted as JSON. This JSON object is parsed and can be used directly in your git workflow.
476
-
477
- This advanced integration assists teams in maintaining consistent commit message standards while reducing the manual burden of summarizing code changes.
208
+ ## Advanced Features
478
209
 
479
- -------------------------------------------------------------------
480
- ### Detailed Explanation of Internal Mechanics
210
+ ### Multi-Module Projects
481
211
 
482
- If you are curious about the intricate inner workings of @git.zone/tsdoc and wish to extend or debug its behavior, here is an in-depth explanation of some internal mechanisms.
483
-
484
- #### Context Trimming Strategy
485
-
486
- Managing token count is critical when interfacing with APIs that have strict limits. The module uses a multi-step process:
487
- - It gathers various files (such as package.json, ts files, readme hints).
488
- - It sorts the files and calculates the token count using the GPT tokenizer.
489
- - It applies trimming strategies such as removing function implementations or comments in TypeScript files, based on a configurable set of parameters.
490
- - Finally, it constructs a unified context string that includes file boundaries for clarity.
491
-
492
- For example, the ContextTrimmer class carries out these transformations:
212
+ tsdoc automatically detects and documents multi-module projects:
493
213
 
494
214
  ```typescript
495
- import { ContextTrimmer } from '@git.zone/tsdoc/dist/ts/context/context-trimmer.js';
496
-
497
- const trimFileContent = (filePath: string, content: string): string => {
498
- // Create an instance of ContextTrimmer with default configuration
499
- const trimmer = new ContextTrimmer({
500
- removeImplementations: true,
501
- preserveJSDoc: true,
502
- maxFunctionLines: 5,
503
- removeComments: true,
504
- removeBlankLines: true
505
- });
506
-
507
- // Trim the content based on the file type and configured options
508
- const trimmedContent = trimmer.trimFile(filePath, content, 'trimmed');
509
- return trimmedContent;
510
- };
215
+ const aiDoc = new AiDoc();
216
+ await aiDoc.start();
511
217
 
512
- // Example usage with a TypeScript file
513
- const tsFileContent = `
514
- /**
515
- * This function calculates the sum of two numbers.
516
- */
517
- export const add = (a: number, b: number): number => {
518
- // Calculation logic
519
- return a + b;
520
- };
521
- `;
218
+ // Process main project
219
+ await aiDoc.buildReadme('./');
522
220
 
523
- const trimmedTSContent = trimFileContent('src/math.ts', tsFileContent);
524
- console.log('Trimmed TypeScript File Content:\n', trimmedTSContent);
221
+ // Process submodules
222
+ for (const module of ['packages/core', 'packages/cli']) {
223
+ await aiDoc.buildReadme(module);
224
+ }
525
225
  ```
526
226
 
527
- This process helps in reducing the number of tokens before sending the data to the AI API while preserving the essential context needed for documentation generation.
528
-
529
- #### Dynamic Configuration Management
227
+ ### Custom Context Building
530
228
 
531
- The module’s configuration is stored in the npmextra.json file and includes settings for context building, trimming strategies, and task-specific options. The ConfigManager class reads these settings and merges them with default values. This dynamic configuration system ensures that the behavior of the documentation tool can be easily adjusted without altering the source code.
229
+ Fine-tune what gets sent to AI:
532
230
 
533
231
  ```typescript
534
- import { ConfigManager } from '@git.zone/tsdoc/dist/ts/context/config-manager.js';
232
+ import { TaskContextFactory } from '@git.zone/tsdoc';
535
233
 
536
- const updateDocumentationConfig = async () => {
537
- const projectDir = process.cwd();
538
- const configManager = ConfigManager.getInstance();
539
-
540
- // Initialize the configuration manager with the project directory
541
- await configManager.initialize(projectDir);
542
-
543
- // Retrieve the current configuration
544
- let currentConfig = configManager.getConfig();
545
- console.log('Current context configuration:', currentConfig);
546
-
547
- // If you want to change some parameters (e.g., maxTokens), update and then save the new configuration
548
- const newConfig = { maxTokens: 150000 };
549
- await configManager.updateConfig(newConfig);
550
-
551
- console.log('Configuration updated successfully.');
552
- };
234
+ const factory = new TaskContextFactory('./');
235
+ await factory.initialize();
553
236
 
554
- updateDocumentationConfig();
237
+ // Get optimized context for specific tasks
238
+ const readmeContext = await factory.getContext('readme');
239
+ const commitContext = await factory.getContext('commit');
555
240
  ```
556
241
 
557
- In this snippet, the ConfigManager:
558
- - Loads current configuration from npmextra.json.
559
- - Allows updates to specific keys (such as token limits).
560
- - Persists these changes back to the file system using the smartfile plugin.
242
+ ## Performance
561
243
 
562
- #### Logging and Diagnostic Output
244
+ - **Fast** - Parallel file processing and smart caching
245
+ - 💾 **Efficient** - Minimal memory footprint with streaming
246
+ - 🎯 **Accurate** - Context optimization ensures AI gets the most relevant code
247
+ - 💰 **Cost-Effective** - Token optimization reduces AI API costs
563
248
 
564
- Throughout its execution, @git.zone/tsdoc logs important information such as token counts, file statistics, and shell command outputs. This logging is accomplished through a combination of the smartlog and smartlogDestinationLocal plugins. The following example illustrates how logging can help diagnose execution issues:
249
+ ## Requirements
565
250
 
566
- ```typescript
567
- import { logger } from '@git.zone/tsdoc/dist/ts/logging.js';
251
+ - Node.js >= 18.0.0
252
+ - TypeScript project
253
+ - OpenAI API key (for AI features)
568
254
 
569
- const logDiagnosticInfo = () => {
570
- logger.log('info', 'Starting documentation generation process...');
571
-
572
- // Log additional contextual information
573
- logger.log('debug', 'Project directory:', process.cwd());
574
- logger.log('debug', 'Token budget set for context building:', 150000);
575
-
576
- // Simulate a long-running process
577
- setTimeout(() => {
578
- logger.log('info', 'Documentation generation process completed successfully.');
579
- }, 2000);
580
- };
255
+ ## Troubleshooting
581
256
 
582
- logDiagnosticInfo();
583
- ```
584
-
585
- Using comprehensive logging, the tool provides feedback not only during normal execution but also in error scenarios, allowing developers to troubleshoot and optimize their documentation generation workflow.
586
-
587
- -------------------------------------------------------------------
588
- ### Integrating @git.zone/tsdoc into a Continuous Integration Pipeline
257
+ ### Token Limit Exceeded
589
258
 
590
- For teams looking to integrate documentation generation into their CI processes, @git.zone/tsdoc can be harnessed by scripting the CLI commands or by embedding the class-based API directly into your build scripts. Here’s an example of a CI script written in TypeScript that runs as part of a GitHub Action or similar workflow:
591
-
592
- ```typescript
593
- import { runCli } from '@git.zone/tsdoc';
594
- import { logger } from '@git.zone/tsdoc/dist/ts/logging.js';
595
-
596
- const runDocumentationPipeline = async () => {
597
- try {
598
- logger.log('info', 'Starting the documentation pipeline...');
599
-
600
- // Run the CLI which automatically detects the project context and generates docs.
601
- await runCli();
602
-
603
- logger.log('info', 'Documentation pipeline completed successfully.');
604
- } catch (error) {
605
- logger.log('error', 'Documentation pipeline encountered an error:', error);
606
- process.exit(1);
607
- }
608
- };
259
+ If you hit token limits, try:
260
+ ```bash
261
+ # Use trimmed mode
262
+ tsdoc aidoc --trim
609
263
 
610
- runDocumentationPipeline();
264
+ # Check token usage
265
+ tsdoc tokens --all
611
266
  ```
612
267
 
613
- In a CI environment, you can invoke this script to ensure that documentation is generated or updated as part of your deployment process. The process includes building the README, updating project descriptions, and generating TypeDoc documentation if the project structure warrants it.
614
-
615
- -------------------------------------------------------------------
616
- ### Comprehensive Workflow Example
617
-
618
- Below is a full-fledged example that combines many of the above functionalities into a single workflow. This script is intended to be run as part of your build process or as a standalone command, and it demonstrates how to initialize all parts of the module, generate documentation for the main project and its submodules, update configuration, and log key diagnostics.
619
-
620
- ```typescript
621
- import { AiDoc } from '@git.zone/tsdoc';
622
- import { TypeDoc } from '@git.zone/tsdoc';
623
- import { ConfigManager } from '@git.zone/tsdoc/dist/ts/context/config-manager.js';
624
- import { EnhancedContext } from '@git.zone/tsdoc/dist/ts/context/enhanced-context.js';
625
- import * as path from 'path';
626
- import { logger } from '@git.zone/tsdoc/dist/ts/logging.js';
627
-
628
- const runFullDocumentationWorkflow = async () => {
629
- const projectDir = process.cwd();
630
-
631
- // Initialize configuration management
632
- const configManager = ConfigManager.getInstance();
633
- await configManager.initialize(projectDir);
634
- logger.log('info', `Loaded configuration for project at ${projectDir}`);
635
-
636
- // Step 1: Generate conventional TypeDoc documentation
637
- const typeDocInstance = new TypeDoc(projectDir);
638
- try {
639
- logger.log('info', 'Starting TypeDoc documentation generation...');
640
- await typeDocInstance.compile({ publicSubdir: 'docs' });
641
- logger.log('info', `TypeDoc documentation generated in ${path.join(projectDir, 'public', 'docs')}`);
642
- } catch (error) {
643
- logger.log('error', 'Error during TypeDoc generation:', error);
644
- }
645
-
646
- // Step 2: Run AI-enhanced documentation generation
647
- const aiDoc = new AiDoc({ OPENAI_TOKEN: 'your-openai-token' });
648
- await aiDoc.start();
649
-
650
- // Generate main README and updated project description
651
- try {
652
- logger.log('info', 'Generating main README via AI-enhanced documentation...');
653
- await aiDoc.buildReadme(projectDir);
654
- logger.log('info', 'Main README generated successfully.');
655
-
656
- logger.log('info', 'Generating updated project description...');
657
- await aiDoc.buildDescription(projectDir);
658
- logger.log('info', 'Project description updated successfully.');
659
- } catch (error) {
660
- logger.log('error', 'Error generating AI-enhanced documentation:', error);
661
- }
662
-
663
- // Step 3: Generate contextual data using EnhancedContext
664
- const enhancedContext = new EnhancedContext(projectDir);
665
- await enhancedContext.initialize();
666
- enhancedContext.setContextMode('trimmed');
667
- enhancedContext.setTokenBudget(150000);
668
-
669
- const contextResult = await enhancedContext.buildContext('readme');
670
- logger.log('info', `Context built successfully. Total tokens: ${contextResult.tokenCount}. Savings: ${contextResult.tokenSavings}`);
671
-
672
- // Step 4: Process submodules (if any) and generate READMEs
673
- const subModules = ['submodule1', 'submodule2'];
674
- for (const subModule of subModules) {
675
- const subModuleDir = path.join(projectDir, subModule);
676
- logger.log('info', `Processing submodule: ${subModule}`);
677
- try {
678
- await aiDoc.buildReadme(subModuleDir);
679
- logger.log('info', `Submodule README generated for ${subModule}`);
680
- } catch (error) {
681
- logger.log('error', `Failed to generate README for ${subModule}:`, error);
682
- }
683
- }
684
-
685
- // Optional: Generate a commit message suggestion based on current changes
686
- try {
687
- logger.log('info', 'Generating commit message suggestion...');
688
- const commitObject = await aiDoc.buildNextCommitObject(projectDir);
689
- logger.log('info', 'Suggested commit message object:', commitObject);
690
- } catch (error) {
691
- logger.log('error', 'Error generating commit message suggestion:', error);
692
- }
693
-
694
- logger.log('info', 'Full documentation workflow completed successfully.');
695
- };
268
+ ### Missing API Key
696
269
 
697
- runFullDocumentationWorkflow();
270
+ Set your OpenAI key:
271
+ ```bash
272
+ export OPENAI_TOKEN="your-key-here"
273
+ tsdoc aidoc
698
274
  ```
699
275
 
700
- This comprehensive workflow showcases the integration of various facets of the @git.zone/tsdoc module:
701
- - Loading and updating configuration via the ConfigManager.
702
- - Generating static documentation using TypeDoc.
703
- - Enhancing documentation with AI through the AiDoc class.
704
- - Optimizing project context with the EnhancedContext class.
705
- - Iterating over submodules to ensure all parts of your project are documented.
706
- - Providing useful diagnostic logging for every step.
707
-
708
- -------------------------------------------------------------------
709
- ### Wrapping Up the Usage Guide
710
-
711
- The examples provided above demonstrate that @git.zone/tsdoc is not simply a CLI tool—it is a complete documentation framework designed to adapt to your workflow. Whether you are a developer looking to automate documentation updates in your CI pipeline or a team seeking an AI-powered enhancement for your project metadata, this module offers a wide range of interfaces and hooks for you to leverage.
712
-
713
- Key takeaways:
714
- - The CLI handles most routine tasks automatically while also exposing commands for specific documentation generation strategies.
715
- - Programmatic usage allows deep integration with your project’s build and commit processes.
716
- - The internal architecture—built on plugins, context optimization, and extensive logging—ensures that the tool can scale with project complexity.
717
- - Advanced users can customize context trimming, file inclusion rules, and even modify AI queries to better suit their project’s needs.
718
-
719
- Each code example provided here is written using modern ESM syntax and TypeScript to ensure compatibility with current development practices. Since the module is designed with extensibility in mind, developers are encouraged to explore the source code (especially the classes in the ts/ and ts/aidocs_classes directories) for further customization opportunities.
720
-
721
- By integrating @git.zone/tsdoc into your workflow, you ensure that your project documentation remains accurate, comprehensive, and reflective of your latest code changes—whether you are generating a simple README or a complex API documentation set enhanced by AI insights.
276
+ ## Why tsdoc?
722
277
 
723
- Happy documenting!
278
+ - **🎯 Actually Understands Your Code** - Not just parsing, but comprehension
279
+ - **⏱️ Saves Hours** - Generate complete documentation in seconds
280
+ - **🔄 Always Up-to-Date** - Regenerate documentation with every change
281
+ - **🎨 Beautiful Output** - Clean, professional documentation every time
282
+ - **🛠️ Developer-Friendly** - Built by developers, for developers
724
283
 
725
284
  ## License and Legal Information
726
285
 
@@ -739,4 +298,4 @@ Registered at District court Bremen HRB 35230 HB, Germany
739
298
 
740
299
  For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
741
300
 
742
- By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
301
+ By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@git.zone/tsdoc',
6
- version: '1.5.1',
6
+ version: '1.5.2',
7
7
  description: 'A comprehensive TypeScript documentation tool that leverages AI to generate and enhance project documentation, including dynamic README creation, API docs via TypeDoc, and smart commit message generation.'
8
8
  }
@@ -77,8 +77,8 @@ interface {
77
77
  For the recommendedNextVersionDetails, please only add a detail entries to the array if it has an obvious value to the reader.
78
78
 
79
79
  You are being given the files of the project. You should use them to create the commit message.
80
- Also you are given a diff
81
-
80
+ Also you are given a diff.
81
+ Never mention CLAUDE code, or codex.
82
82
  `,
83
83
  messageHistory: [],
84
84
  userMessage: contextString,