Skip to content

Commit a54c03b

Browse files
committed
Counting TotalNumberOfCodeBlocks using marked library instead of regex
1 parent de8bf7a commit a54c03b

File tree

1 file changed

+12
-6
lines changed
  • packages/core/src/codewhispererChat/controllers/chat/messenger

1 file changed

+12
-6
lines changed

packages/core/src/codewhispererChat/controllers/chat/messenger/messenger.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import { OnboardingPageInteraction } from '../../../../amazonq/onboardingPage/mo
3030
import { FeatureAuthState } from '../../../../codewhisperer/util/authUtil'
3131
import { AuthFollowUpType, expiredText, enableQText, reauthenticateText } from '../../../../amazonq/auth/model'
3232
import { userGuideURL } from '../../../../amazonq/webview/ui/texts/constants'
33+
import { marked } from 'marked'
3334

3435
export type StaticTextResponseType = 'quick-action-help' | 'onboarding-help' | 'transform' | 'help'
3536

@@ -89,13 +90,18 @@ export class Messenger {
8990
)
9091
}
9192

92-
public countTotalNumberOfCodeBlocks(message: string): number {
93+
public async countTotalNumberOfCodeBlocks(message: string): Promise<number> {
9394
if (message === undefined) {
9495
return 0
9596
}
96-
const countOfCodeBlocks = message.match(/^```/gm)
97-
const numberOfTripleBackTicksInMarkdown = countOfCodeBlocks ? countOfCodeBlocks.length : 0
98-
return Math.floor(numberOfTripleBackTicksInMarkdown / 2)
97+
98+
// To Convert Markdown text to HTML using marked library
99+
const html = await marked(message)
100+
101+
// Count the number of <pre> tags in the HTML to find the total number of code blocks
102+
const totalNumberOfCodeBlocks = (html.match(/<pre>/g) || []).length
103+
104+
return totalNumberOfCodeBlocks
99105
}
100106

101107
public async sendAIResponse(
@@ -224,7 +230,7 @@ export class Messenger {
224230
relatedSuggestions = []
225231
this.telemetryHelper.recordMessageResponseError(triggerPayload, tabID, statusCode ?? 0)
226232
})
227-
.finally(() => {
233+
.finally(async () => {
228234
if (relatedSuggestions.length !== 0) {
229235
this.dispatcher.sendChatMessage(
230236
new ChatMessage(
@@ -274,7 +280,7 @@ export class Messenger {
274280
messageID,
275281
responseCode,
276282
codeReferenceCount: codeReference.length,
277-
totalNumberOfCodeBlocksInResponse: this.countTotalNumberOfCodeBlocks(message),
283+
totalNumberOfCodeBlocksInResponse: await this.countTotalNumberOfCodeBlocks(message),
278284
})
279285
})
280286
}

0 commit comments

Comments
 (0)