orderPricePageLoader.mjs 1.86 KB
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";

const supportDir = path.dirname(fileURLToPath(import.meta.url));
const projectRoot = path.resolve(supportDir, "../../..");
const mockApiUrl = pathToFileURL(path.join(supportDir, "orderPricePageApi.mock.mjs")).href;
const mockStoreUrl = pathToFileURL(path.join(supportDir, "orderPricePageStore.mock.mjs")).href;

function resolveExistingModule(candidate) {
	return [candidate, `${candidate}.js`, path.join(candidate, "index.js")].find((item) => existsSync(item));
}

export async function resolve(specifier, context, nextResolve) {
	if (specifier === "~/store/index" || specifier === "~/store/ModalToQueueControl") {
		return { shortCircuit: true, url: mockStoreUrl };
	}

	if (specifier === "~/api/api" || specifier === "~/api/api.js") {
		return { shortCircuit: true, url: mockApiUrl };
	}

	if (specifier.startsWith("./") || specifier.startsWith("../")) {
		const parentPath = fileURLToPath(context.parentURL);
		const candidate = path.resolve(path.dirname(parentPath), specifier);
		const tabWorkOrderApi = path.join(projectRoot, "tabWorkOrder", "api");
		if (candidate === tabWorkOrderApi || candidate === `${tabWorkOrderApi}.js`) {
			return { shortCircuit: true, url: mockApiUrl };
		}
	}

	if (specifier.startsWith("~/")) {
		const mapped = resolveExistingModule(path.join(projectRoot, specifier.slice(2)));
		if (mapped) return { shortCircuit: true, url: pathToFileURL(mapped).href };
	}

	if ((specifier.startsWith("./") || specifier.startsWith("../")) && !/\.(?:m?js|json|node)$/.test(specifier)) {
		const parentPath = fileURLToPath(context.parentURL);
		const mapped = resolveExistingModule(path.resolve(path.dirname(parentPath), specifier));
		if (mapped) return { shortCircuit: true, url: pathToFileURL(mapped).href };
	}

	return nextResolve(specifier, context);
}