mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 12:24:44 +00:00
56 lines
2.1 KiB
JavaScript
56 lines
2.1 KiB
JavaScript
// Node module hooks for running TypeScript tests with `node --test`: resolves the
|
|
// "@/..." path alias (tsconfig "paths") to src/, adding the ".ts" extension that the
|
|
// bundler normally infers. Registered by scripts/register-alias.mjs.
|
|
|
|
import ts from "typescript";
|
|
|
|
import { readFile } from "node:fs/promises";
|
|
|
|
const SRC = new URL("../src/", import.meta.url);
|
|
|
|
export async function resolve(specifier, context, nextResolve) {
|
|
if (specifier.startsWith("@/")) {
|
|
const base = new URL(specifier.slice(2), SRC).href;
|
|
for (const candidate of [base, `${base}.ts`, `${base}.tsx`, `${base}/index.ts`]) {
|
|
try {
|
|
return await nextResolve(candidate, context);
|
|
} catch {
|
|
// try the next candidate
|
|
}
|
|
}
|
|
}
|
|
if (context.parentURL && (specifier.startsWith("./") || specifier.startsWith("../"))) {
|
|
try {
|
|
return await nextResolve(specifier, context);
|
|
} catch (error) {
|
|
const base = new URL(specifier, context.parentURL).href;
|
|
for (const candidate of [`${base}.ts`, `${base}.tsx`, `${base}/index.ts`]) {
|
|
try {
|
|
return await nextResolve(candidate, context);
|
|
} catch {
|
|
// try the next TypeScript path
|
|
}
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
return nextResolve(specifier, context);
|
|
}
|
|
|
|
// The bundler imports locale JSON (src/i18n) without `with { type: "json" }`; Node requires the
|
|
// attribute, so add it here. This lets tests import modules that depend on @/i18n (e.g. @/lib/utils).
|
|
export async function load(url, context, nextLoad) {
|
|
if (url.endsWith(".ts") || url.endsWith(".tsx")) {
|
|
const source = await readFile(new URL(url), "utf8");
|
|
const output = ts.transpileModule(source, {
|
|
compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.ReactJSX },
|
|
fileName: url,
|
|
}).outputText;
|
|
return { format: "module", shortCircuit: true, source: output };
|
|
}
|
|
if (url.endsWith(".json") && context.importAttributes?.type !== "json") {
|
|
return nextLoad(url, { ...context, importAttributes: { ...context.importAttributes, type: "json" } });
|
|
}
|
|
return nextLoad(url, context);
|
|
}
|