Skip to content

Commit

Permalink
chore: wip
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisbbreuer committed Oct 21, 2024
1 parent 414908d commit 65638e7
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 20 deletions.
8 changes: 4 additions & 4 deletions fixtures/output/example-0001.d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
/**
* Example of const declaration
*/
export declare const config: { [key: string]: string }

export declare const config: {
apiUrl: 'https://api.example.com',
timeout: '5000'
}
/**
* Example of interface declaration
*/
Expand All @@ -11,15 +13,13 @@ export interface User {
name: string
email: string
}

/**
* Example of type declaration
*/
export interface ResponseData {
success: boolean
data: User[]
}

/**
* Example of function declaration
*/
Expand Down
3 changes: 0 additions & 3 deletions fixtures/output/example-0005.d.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
export declare const defaultHeaders: {
'Content-Type': 'application/json',
}

export interface Comment {
id: number
postId: number
body: string
}

export interface CommentsResponse {
comments: Comment[]
}

export declare function fetchComments(postId: number): Promise<CommentsResponse>
23 changes: 10 additions & 13 deletions src/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,14 @@ export async function extractTypeFromSource(filePath: string): Promise<string> {
// Function to parse object literal
function parseObjectLiteral(str: string) {
const obj: Record<string, string> = {}
str.split(',').forEach((pair) => {
const trimmedPair = pair.trim()
if (trimmedPair) {
const colonIndex = trimmedPair.indexOf(':')
if (colonIndex !== -1) {
const key = trimmedPair.slice(0, colonIndex).trim().replace(/['"]/g, '')
const value = trimmedPair.slice(colonIndex + 1).trim()
obj[key] = value
}
}
})
const regex = /(['"]?)([^\s'":]+)\1\s*:\s*(['"]?)([^\s'"]+)\3/g
let match

while ((match = regex.exec(str)) !== null) {
const [, , key, , value] = match
obj[key] = value
}

return obj
}

Expand All @@ -79,8 +76,8 @@ export async function extractTypeFromSource(filePath: string): Promise<string> {
// Parse the object literal
const parsedValue = parseObjectLiteral(constValue.slice(1, -1))
const formattedValue = Object.entries(parsedValue)
.map(([key, value]) => ` ${key}: ${value.includes('/') || value.includes('\'') ? value : `'${value}'`}`)
.join('\n')
.map(([key, value]) => ` ${key}: ${value.includes('/') || value.includes('\'') ? `'${value}'` : value}`)
.join(',\n')

if (pendingComment) {
declarations += `${pendingComment}\n`
Expand Down

0 comments on commit 65638e7

Please sign in to comment.