diff --git a/src/loader/babel.ts b/src/loader/babel.ts index 4a4be2a..1c27b87 100644 --- a/src/loader/babel.ts +++ b/src/loader/babel.ts @@ -10,7 +10,19 @@ import { import { version } from "../../package.json"; -type GetCodeFn = (loc: t.SourceLocation) => string; +interface SourceLocation { + start: { + line: number; + column: number; + index?: number; + }; + end: { + line: number; + column: number; + index?: number; + }; +} +type GetCodeFn = (loc: SourceLocation) => string; const babelPluginUntyped: PluginItem = function ( api: ConfigAPI, @@ -84,11 +96,18 @@ const babelPluginUntyped: PluginItem = function ( } }, FunctionDeclaration(p) { - const schema = parseJSDocs( - (p.parent.leadingComments || []) - .filter((c) => c.type === "CommentBlock") - .map((c) => c.value) - ); + const getCode: GetCodeFn = (loc) => { + return this.file.code.substring(loc.start.index, loc.end.index); + }; + + const comments = (p.parent.leadingComments || []) + .filter((c) => c.type === "CommentBlock") + .map((c) => c.value); + + console.log(this.file); + + const schema = parseJSDocs(comments); + schema.type = "function"; schema.args = []; @@ -108,16 +127,6 @@ const babelPluginUntyped: PluginItem = function ( return; } - const _getLines = cachedFn(() => this.file.code.split("\n")); - const getCode: GetCodeFn = (loc) => { - const _lines = _getLines(); - return ( - _lines[loc.start.line - 1] - .slice(loc.start.column, loc.end.column) - .trim() || "" - ); - }; - // Extract arguments for (const [index, param] of p.node.params.entries()) { if (param.loc?.end.line !== param.loc?.start.line) { diff --git a/test/transform.test.ts b/test/transform.test.ts index 1795917..f3660e6 100644 --- a/test/transform.test.ts +++ b/test/transform.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect } from "vitest"; +import { evalModule } from "mlly"; import { transform } from "../src/loader/transform"; describe("transform (functions)", () => { @@ -127,6 +128,32 @@ describe("transform (functions)", () => { }); } }); + + it("Handles comments above overloads", async () => { + const exports = await evalModule( + transform( + ` + /** an unrelated comment */ + + /** Multiply a by b */ + export function mul (a: number, b:number) + export function mul (a: number, b:number, c: number): number { + return a * b + }; + + /** Adds numbers */ + export function add (a: number, b: number): number; + export function add (a: number, b: number, c: number = 0): number { + return a + b + c + }; + `, + { experimentalFunctions: true } + ) + ); + + expect(exports.mul.$schema.title).toMatch("Multiply a by b"); + expect(exports.add.$schema.title).toMatch("Adds numbers"); + }); }); describe("transform (jsdoc)", () => {