MCPcopy Create free account
hub / github.com/arktypeio/arktype / getTextWithoutCommentDirectives

Function getTextWithoutCommentDirectives

ark/attest/ts7/server.ts:215–268  ·  view source on GitHub ↗
(
	file: SourceFile
)

Source from the content-addressed store, hash-verified

213 * changed from @ts- to @ts_, or undefined if it has none
214 */
215const getTextWithoutCommentDirectives = (
216 file: SourceFile
217): string | undefined => {
218 const text = file.getFullText()
219 if (!text.includes("@ts-")) return
220
221 const kinds = literalKinds()
222 const literalEnds = new Map<number, number>()
223 // like a literal, a shebang line can't contain a comment
224 if (text.startsWith("#!")) {
225 const shebangEnd = text.search(lineBreak)
226 literalEnds.set(0, shebangEnd === -1 ? text.length : shebangEnd)
227 }
228 for (const node of getDescendants(file)) {
229 if (kinds.has(node.kind)) {
230 // JsxText has no trivia, so its leading whitespace is part of it
231 literalEnds.set(
232 ast.isJsxText(node) ? node.pos : node.getStart(),
233 node.end
234 )
235 }
236 }
237
238 const chars = text.split("")
239 let changed = false
240 const disable = (start: number, end: number, directive: RegExp) => {
241 const comment = text.slice(start, end)
242 if (!directive.test(comment)) return
243 chars[start + comment.indexOf("@ts-") + 3] = "_"
244 changed = true
245 }
246
247 for (let i = 0; i < text.length; i++) {
248 const literalEnd = literalEnds.get(i)
249 if (literalEnd !== undefined && literalEnd > i) i = literalEnd - 1
250 else if (text.startsWith("//", i)) {
251 lineBreak.lastIndex = i
252 const commentEnd = lineBreak.exec(text)?.index ?? text.length
253 disable(i, commentEnd, singleLineDirective)
254 i = commentEnd
255 } else if (text.startsWith("/*", i)) {
256 const closeStart = text.indexOf("*/", i + 2)
257 const commentEnd = closeStart === -1 ? text.length : closeStart + 2
258 // only the last line of a block comment can be a directive
259 let lastLineStart = i
260 lineBreak.lastIndex = i
261 while (lineBreak.test(text) && lineBreak.lastIndex <= commentEnd)
262 lastLineStart = lineBreak.lastIndex
263 disable(lastLineStart, commentEnd, multiLineDirective)
264 i = commentEnd - 1
265 }
266 }
267 return changed ? chars.join("") : undefined
268}
269
270export const getDescendants = (node: Node): Node[] => {
271 const descendants: Node[] = []

Callers 1

Calls 9

literalKindsFunction · 0.85
disableFunction · 0.85
execMethod · 0.80
testMethod · 0.80
getDescendantsFunction · 0.70
getMethod · 0.65
searchMethod · 0.45
setMethod · 0.45
hasMethod · 0.45

Tested by

no test coverage detected