Skip to content

Commit 71291fd

Browse files
committed
chore: wip
1 parent afa595a commit 71291fd

File tree

15 files changed

+245
-24
lines changed

15 files changed

+245
-24
lines changed

src/generator.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ export async function processFile(
135135
}
136136

137137
// Process declarations to generate DTS
138-
const dtsContent = processDeclarations(declarations, context)
138+
const dtsContent = processDeclarations(declarations, context, config.keepComments)
139139

140140
return dtsContent
141141
}

src/processor.ts

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ import type { Declaration, ProcessingContext } from './types'
44
/**
55
* Format comments for DTS output
66
*/
7-
function formatComments(comments: string[] | undefined): string {
8-
if (!comments || comments.length === 0) {
7+
function formatComments(comments: string[] | undefined, keepComments: boolean = true): string {
8+
if (!keepComments || !comments || comments.length === 0) {
99
return ''
1010
}
1111

@@ -148,6 +148,7 @@ function extractAllImportedItems(importText: string): string[] {
148148
export function processDeclarations(
149149
declarations: Declaration[],
150150
context: ProcessingContext,
151+
keepComments: boolean = true,
151152
): string {
152153
const output: string[] = []
153154

@@ -471,25 +472,25 @@ export function processDeclarations(
471472
let processed = ''
472473
switch (decl.kind) {
473474
case 'function':
474-
processed = processFunctionDeclaration(decl)
475+
processed = processFunctionDeclaration(decl, keepComments)
475476
break
476477
case 'variable':
477-
processed = processVariableDeclaration(decl)
478+
processed = processVariableDeclaration(decl, keepComments)
478479
break
479480
case 'interface':
480-
processed = processInterfaceDeclaration(decl)
481+
processed = processInterfaceDeclaration(decl, keepComments)
481482
break
482483
case 'type':
483-
processed = processTypeDeclaration(decl)
484+
processed = processTypeDeclaration(decl, keepComments)
484485
break
485486
case 'class':
486-
processed = processClassDeclaration(decl)
487+
processed = processClassDeclaration(decl, keepComments)
487488
break
488489
case 'enum':
489-
processed = processEnumDeclaration(decl)
490+
processed = processEnumDeclaration(decl, keepComments)
490491
break
491492
case 'module':
492-
processed = processModuleDeclaration(decl)
493+
processed = processModuleDeclaration(decl, keepComments)
493494
break
494495
}
495496

@@ -517,9 +518,9 @@ export function processDeclarations(
517518
/**
518519
* Process function declaration to DTS format
519520
*/
520-
export function processFunctionDeclaration(decl: Declaration): string {
521+
export function processFunctionDeclaration(decl: Declaration, keepComments: boolean = true): string {
521522
// Add comments if present
522-
const comments = formatComments(decl.leadingComments)
523+
const comments = formatComments(decl.leadingComments, keepComments)
523524

524525
// The extractor already provides the correct DTS signature, just return it
525526
return comments + decl.text
@@ -557,9 +558,9 @@ function isGenericType(typeAnnotation: string): boolean {
557558
/**
558559
* Process variable declaration to DTS format
559560
*/
560-
export function processVariableDeclaration(decl: Declaration): string {
561+
export function processVariableDeclaration(decl: Declaration, keepComments: boolean = true): string {
561562
// Add comments if present
562-
const comments = formatComments(decl.leadingComments)
563+
const comments = formatComments(decl.leadingComments, keepComments)
563564

564565
let result = ''
565566

@@ -614,9 +615,9 @@ export function processVariableDeclaration(decl: Declaration): string {
614615
/**
615616
* Process interface declaration to DTS format
616617
*/
617-
export function processInterfaceDeclaration(decl: Declaration): string {
618+
export function processInterfaceDeclaration(decl: Declaration, keepComments: boolean = true): string {
618619
// Add comments if present
619-
const comments = formatComments(decl.leadingComments)
620+
const comments = formatComments(decl.leadingComments, keepComments)
620621

621622
let result = ''
622623

@@ -656,9 +657,9 @@ export function processInterfaceDeclaration(decl: Declaration): string {
656657
/**
657658
* Process type alias declaration to DTS format
658659
*/
659-
export function processTypeDeclaration(decl: Declaration): string {
660+
export function processTypeDeclaration(decl: Declaration, keepComments: boolean = true): string {
660661
// Add comments if present
661-
const comments = formatComments(decl.leadingComments)
662+
const comments = formatComments(decl.leadingComments, keepComments)
662663

663664
// For type exports like export type { Foo }
664665
if (decl.text.includes('{') && decl.text.includes('}') && decl.text.includes('from')) {
@@ -699,9 +700,9 @@ export function processTypeDeclaration(decl: Declaration): string {
699700
/**
700701
* Process class declaration to DTS format
701702
*/
702-
export function processClassDeclaration(decl: Declaration): string {
703+
export function processClassDeclaration(decl: Declaration, keepComments: boolean = true): string {
703704
// Add comments if present
704-
const comments = formatComments(decl.leadingComments)
705+
const comments = formatComments(decl.leadingComments, keepComments)
705706

706707
// The extractor already provides the correct DTS signature, just return it
707708
return comments + decl.text
@@ -710,9 +711,9 @@ export function processClassDeclaration(decl: Declaration): string {
710711
/**
711712
* Process enum declaration to DTS format
712713
*/
713-
export function processEnumDeclaration(decl: Declaration): string {
714+
export function processEnumDeclaration(decl: Declaration, keepComments: boolean = true): string {
714715
// Add comments if present
715-
const comments = formatComments(decl.leadingComments)
716+
const comments = formatComments(decl.leadingComments, keepComments)
716717

717718
let result = ''
718719

@@ -775,9 +776,9 @@ export function processExportDeclaration(decl: Declaration): string {
775776
/**
776777
* Process module/namespace declaration to DTS format
777778
*/
778-
export function processModuleDeclaration(decl: Declaration): string {
779+
export function processModuleDeclaration(decl: Declaration, keepComments: boolean = true): string {
779780
// Add comments if present
780-
const comments = formatComments(decl.leadingComments)
781+
const comments = formatComments(decl.leadingComments, keepComments)
781782

782783
// Check if this is an ambient module (quoted name)
783784
const isAmbientModule = decl.source || (decl.name.startsWith('"') || decl.name.startsWith('\'') || decl.name.startsWith('`'))

test/fixtures/output/edge-cases.d.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,33 @@
1+
// Function with complex overloads
12
export declare function complexOverload(value: string): string;
23
export declare function complexOverload(value: number): number;
34
export declare function complexOverload(value: boolean): boolean;
45
export declare function complexOverload<T extends object>(value: T): T;
56
export declare function complexOverload(value: any): any;
7+
// Async generator function
68
export declare function asyncGenerator<T>(items: T[]): AsyncGenerator<T, void, unknown>;
9+
// Test edge cases for type inference
10+
// BigInt literals
711
export declare const bigIntLiteral: 123n;
812
export declare const bigIntExpression: bigint;
13+
// Symbol types
914
export declare const symbolUnique: symbol;
1015
export declare const symbolFor: symbol;
16+
// Template literals
1117
export declare const templateSimple: `Hello World`;
1218
export declare const templateWithExpression: `Count: ${42}`;
1319
export declare const templateTagged: string;
20+
// Promise types
1421
export declare const promiseResolved: Promise<42>;
1522
export declare const promiseRejected: Promise<never>;
1623
export declare const promiseAll: Promise<[1, 'two']>;
24+
// Date and built-in types
1725
export declare const dateInstance: Date;
1826
export declare const mapInstance: Map<any, any>;
1927
export declare const setInstance: Set<any>;
2028
export declare const regexInstance: RegExp;
2129
export declare const errorInstance: Error;
30+
// Complex nested structures
2231
export declare const deeplyNested: {
2332
level1: {
2433
level2: {
@@ -29,23 +38,30 @@ export declare const deeplyNested: {
2938
}
3039
}
3140
};
41+
// Mixed type arrays
3242
export declare const mixedTypeArray: readonly ['string', 123, true, null, undefined, {
3343
key: 'value'
3444
}, readonly [1, 2, 3], (() => unknown), Date, Promise<'async'>];
45+
// Type with conditional and infer
3546
export type ExtractPromise<T> = T extends Promise<infer U> ? U : never
3647
export type ExtractArray<T> = T extends (infer U)[] ? U : never
48+
// Mapped type with template literal
3749
export type Getters<T> = {
3850
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
3951
}
52+
// Discriminated union
4053
export type Result<T, E = Error> = | { success: true; data: T; error?: never }
4154
| { success: false; data?: never; error: E }
55+
// Recursive type with constraints
4256
export type DeepReadonly<T> = T extends any[] ? DeepReadonlyArray<T[number]> :
4357
T extends object ? DeepReadonlyObject<T> :
4458
T
4559
declare type DeepReadonlyArray<T> = ReadonlyArray<DeepReadonly<T>>
4660
declare type DeepReadonlyObject<T> = {
4761
readonly [P in keyof T]: DeepReadonly<T[P]>
4862
}
63+
// Class with decorators (as comments for now)
64+
// @sealed
4965
export declare class DecoratedClass {
5066
name: string;
5167
oldMethod(): void;

test/fixtures/output/example/0004.d.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
/**
2+
* DtsGenerationConfig
3+
*
4+
* This is the configuration object for the DTS generation process.
5+
*/
16
export declare interface DtsGenerationConfig {
27
cwd: string
38
root: string
@@ -8,6 +13,9 @@ export declare interface DtsGenerationConfig {
813
tsconfigPath: string
914
verbose: boolean
1015
}
16+
/**
17+
* Regular expression patterns used throughout the module
18+
*/
1119
export declare interface RegexPatterns {
1220
typeImport: RegExp
1321
regularImport: RegExp
@@ -79,19 +87,28 @@ export declare interface MethodSignature {
7987
params: string
8088
returnType: string
8189
}
90+
/**
91+
* Represents property type information with support for nested structures
92+
*/
8293
export declare interface PropertyInfo {
8394
key: string
8495
value: string
8596
type: string
8697
nested?: PropertyInfo[]
8798
method?: MethodSignature
8899
}
100+
/**
101+
* Import statement metadata and tracking
102+
*/
89103
export declare interface ImportInfo {
90104
kind: 'type' | 'value' | 'mixed'
91105
usedTypes: Set<string>
92106
usedValues: Set<string>
93107
source: string
94108
}
109+
/**
110+
* Function signature components
111+
*/
95112
export declare interface FunctionSignature {
96113
name: string
97114
params: string
@@ -102,5 +119,15 @@ export declare interface ProcessedMethod {
102119
name: string
103120
signature: string
104121
}
122+
/**
123+
* DtsGenerationOption
124+
*
125+
* This is the configuration object for the DTS generation process.
126+
*/
105127
export type DtsGenerationOption = Partial<DtsGenerationConfig>
128+
/**
129+
* DtsGenerationOptions
130+
*
131+
* This is the configuration object for the DTS generation process.
132+
*/
106133
export type DtsGenerationOptions = DtsGenerationOption | DtsGenerationOption[]
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,21 @@
11
import type { ProcessingState } from './types';
2+
/**
3+
* Extracts types from a TypeScript file and generates corresponding .d.ts content
4+
* @param filePath - Path to source TypeScript file
5+
*/
26
export declare function extract(filePath: string): Promise<string>;
7+
/**
8+
* Processes TypeScript source code and generates declaration types
9+
* @param sourceCode - TypeScript source code
10+
*/
311
export declare function extractDtsTypes(sourceCode: string): string;
12+
/**
13+
* Check if a given type string represents a function type
14+
*/
415
export declare function isFunctionType(type: string): boolean;
16+
/**
17+
* Check if a declaration is complete by examining its content
18+
* @param content - Content to check, either as a string or array of lines
19+
*/
520
export declare function isDeclarationComplete(content: string | string[]): boolean;
621
export declare function processSpecificDeclaration(declarationWithoutComments: string, fullDeclaration: string, state: ProcessingState): void;

test/fixtures/output/example/0007.d.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import forge, { pki, tls } from 'node-forge';
22
import type { CAOptions, CertificateOptions, GenerateCertReturn, TlsOption } from './types';
3+
/**
4+
* Generate a random serial number for the Certificate
5+
* @returns The serial number for the Certificate
6+
*/
37
export declare function generateRandomSerial(verbose?: boolean): string;
48
export declare function calculateValidityDates(options: {
59
validityDays?: number
@@ -9,8 +13,21 @@ export declare function calculateValidityDates(options: {
913
}): { notBefore: Date, notAfter: Date };
1014
export declare function createRootCA(options?: CAOptions): Promise<GenerateCertReturn>;
1115
export declare function generateCertificate(options: CertificateOptions): Promise<GenerateCertReturn>;
16+
/**
17+
* Add a certificate to the system trust store and save the certificate to a file
18+
* @param cert
19+
* @param caCert
20+
* @param options
21+
* @returns The path to the stored certificate
22+
*/
1223
export declare function addCertToSystemTrustStoreAndSaveCert(cert: Cert, caCert: string, options?: TlsOption): Promise<string>;
1324
export declare function storeCertificate(cert: Cert, options?: TlsOption): string;
25+
/**
26+
* Store the CA Certificate
27+
* @param caCert - The CA Certificate
28+
* @param options - The options for storing the CA Certificate
29+
* @returns The path to the CA Certificate
30+
*/
1431
export declare function storeCACertificate(caCert: string, options?: TlsOption): string;
1532
export declare interface Cert {
1633
certificate: string

test/fixtures/output/example/0008.d.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,43 @@
11
import { pki } from 'node-forge';
22
import type { CertDetails } from './types';
3+
/**
4+
* Checks if a certificate is valid for a given domain.
5+
* @param certPemOrPath - The certificate in PEM format or the path to the certificate file.
6+
* @param domain - The domain to check.
7+
* @returns {boolean} - True if the certificate is valid for the domain, false otherwise.
8+
*/
39
export declare function isCertValidForDomain(certPemOrPath: string, domain: string): boolean;
10+
/**
11+
* Reads a certificate from a file.
12+
* @param certPath - Path to the certificate file.
13+
* @returns {string} - The certificate content.
14+
*/
415
export declare function readCertFromFile(certPath: string): string;
16+
/**
17+
* Parses and extracts details from a certificate.
18+
* @param certPemOrPath - The certificate in PEM format or the path to the certificate file.
19+
* @returns {CertDetails} - An object containing certificate details.
20+
*/
521
export declare function parseCertDetails(certPemOrPath: string): CertDetails;
22+
/**
23+
* Checks if a certificate is expired.
24+
* @param certPemOrPath - The certificate in PEM format or the path to the certificate file.
25+
* @returns {boolean} - True if the certificate is expired, false otherwise.
26+
*/
627
export declare function isCertExpired(certPemOrPath: string): boolean;
28+
/**
29+
* Gets a certificate from a PEM string or a path to a certificate file.
30+
* @param certPemOrPath - The certificate in PEM format or the path to the certificate file.
31+
* @returns {pki.Certificate} - The certificate object.
32+
*/
733
export declare function getCertificateFromCertPemOrPath(certPemOrPath: string): pki.Certificate;
34+
/**
35+
* Lists all certificates in a directory.
36+
* By default, it returns the certificates stored in their default locations on each operating system.
37+
* If no certificates are found in the default paths, it checks the fallback path.
38+
* @param dirPath - Path to the directory. If not provided, the default directory for the OS will be used.
39+
* @returns {string[]} - An array of certificate file paths.
40+
*/
841
export declare function listCertsInDirectory(dirPath?: string): string[];
942
export declare function makeNumberPositive(hexString: string): string;
1043
export declare function findFoldersWithFile(rootDir: string, fileName: string): string[];

test/fixtures/output/example/0009.d.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,23 @@
11
import type { Config } from './types';
2+
/**
3+
* Load Config
4+
*
5+
* @param {object} options - The configuration options.
6+
* @param {string} options.name - The name of the configuration file.
7+
* @param {string} [options.cwd] - The current working directory.
8+
* @param {string} [options.endpoint] - The API endpoint to fetch config from in browser environments.
9+
* @param {string} [options.headers] - The headers to send with the request in browser environments.
10+
* @param {T} options.defaultConfig - The default configuration.
11+
* @returns {Promise<T>} The merged configuration.
12+
* @example ```ts
13+
* // Merges arrays if both configs are arrays, otherwise does object deep merge
14+
* await loadConfig({
15+
* name: 'example',
16+
* endpoint: '/api/my-custom-config/endpoint',
17+
* defaultConfig: [{ foo: 'bar' }]
18+
* })
19+
* ```
20+
*/
221
export declare function loadConfig<T>({
322
name,
423
cwd,

0 commit comments

Comments
 (0)