Skip to content
Open
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
3 changes: 3 additions & 0 deletions knip.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
"docs"
],
"workspaces": {
".": {
"entry": ["tools/validate-package-imports.ts"]
},
"packages/appkit": {
"ignoreDependencies": [
"vitest",
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
},
"devDependencies": {
"@arethetypeswrong/core": "0.18.4",
"@ast-grep/napi": "0.37.0",
"@commitlint/cli": "19.8.1",
"@commitlint/config-conventional": "19.8.1",
"@cyclonedx/cdxgen": "12.1.2",
Expand Down
47 changes: 47 additions & 0 deletions packages/appkit/src/tsdown/tests/package-imports.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

import { assertPackageImportsResolve } from "@tools/validate-package-imports";
import { afterEach, describe, expect, test } from "vitest";

const dirs: string[] = [];

afterEach(() => {
for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true });
});

function fixture(files: Record<string, string>): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-package-imports-"));
dirs.push(dir);
for (const [name, contents] of Object.entries(files)) {
const file = path.join(dir, name);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, contents);
}
return dir;
}

describe("published package imports", () => {
test("accepts relative imports included in the package", () => {
const dir = fixture({
"cli/command.js": [
'import { helper } from "../helper.js";',
'const example = `import missing from "../not-an-import.js"`;',
].join("\n"),
"helper.js": "export const helper = true;",
});

expect(() => assertPackageImportsResolve(dir)).not.toThrow();
});

test("rejects a CLI command whose relative helper was not packaged", () => {
const dir = fixture({
"cli/commands/example.js": 'import { helper } from "../../helper.js";',
});

expect(() => assertPackageImportsResolve(dir)).toThrow(
"cli/commands/example.js -> ../../helper.js",
);
});
});
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions tools/dist-appkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import fs from "node:fs";
import path from "node:path";
import { parseArgs } from "node:util";

import { assertPackageImportsResolve } from "./validate-package-imports";

const __dirname = path.dirname(new URL(import.meta.url).pathname);
const { values } = parseArgs({
options: {
Expand Down Expand Up @@ -140,6 +142,8 @@ if (fs.existsSync(sharedPostinstall)) {
fs.copyFileSync(sharedPostinstall, "tmp/scripts/postinstall.js");
}

assertPackageImportsResolve("tmp/dist/cli");

// Copy documentation from docs/build into tmp/docs/
const docsBuildPath = path.join(__dirname, "../docs/build");

Expand Down
58 changes: 58 additions & 0 deletions tools/validate-package-imports.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import fs from "node:fs";
import path from "node:path";

import { Lang, parse } from "@ast-grep/napi";

function findJavaScriptFiles(dir: string): string[] {
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const file = path.join(dir, entry.name);
if (entry.isDirectory()) return findJavaScriptFiles(file);
return /\.[cm]?js$/.test(entry.name) ? [file] : [];
});
}

function relativeImports(source: string): string[] {
const root = parse(Lang.JavaScript, source).root();
const imports = root
.findAll({
rule: {
any: [{ kind: "import_statement" }, { kind: "export_statement" }],
},
})
.map((node) => node.field("source")?.text())
.filter((value): value is string => Boolean(value));

for (const call of root.findAll({ rule: { kind: "call_expression" } })) {
if (call.field("function")?.text() !== "import") continue;
const argument = call
.field("arguments")
?.children()
.find((node) => node.kind() === "string");
if (argument) imports.push(argument.text());
}

return imports
.map((value) => value.slice(1, -1))
.filter((value) => value.startsWith("."));
}

/** Fail packaging when a built JavaScript module has a missing relative import. */
export function assertPackageImportsResolve(dir: string): void {
const missing = findJavaScriptFiles(dir).flatMap((file) =>
relativeImports(fs.readFileSync(file, "utf8"))
.map((specifier) => ({
file,
specifier,
target: path.resolve(path.dirname(file), specifier),
}))
.filter(({ target }) => !fs.existsSync(target)),
);

if (missing.length) {
throw new Error(
`Package contains missing relative imports:\n${missing
.map(({ file, specifier }) => `- ${file} -> ${specifier}`)
.join("\n")}`,
);
}
}
Loading