Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 25 additions & 16 deletions src/loader/babel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 = [];

Expand All @@ -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) {
Expand Down
27 changes: 27 additions & 0 deletions test/transform.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { describe, it, expect } from "vitest";
import { evalModule } from "mlly";
import { transform } from "../src/loader/transform";

describe("transform (functions)", () => {
Expand Down Expand Up @@ -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)", () => {
Expand Down