polen
Version:
A framework for delightful GraphQL developer portals
58 lines • 2.33 kB
JavaScript
import { isSpecifierFromPackage } from '#lib/kit-temp';
import { packagePaths } from '#package-paths';
import { debugPolen } from '#singletons/debug';
import { fileURLToPath } from 'node:url';
let data_ = undefined;
export function initialize(data) {
data_ = data;
}
export const resolve = async (specifier, context, nextResolve) => {
if (!data_)
throw new Error(`Self-contained mode not initialized`);
const debug = debugPolen.sub(`node-module-hooks`);
const from = {
specifier,
context,
};
if (from.context.parentURL && checkIsSelfImportFromProject({
projectDirPathExp: data_.projectDirPathExp,
specifier,
importerPathExpOrFileUrlExp: from.context.parentURL,
})) {
debug(`resolve check`, { specifier, context });
const to = {
specifier: from.specifier,
context: {
conditions: [...from.context.conditions, `source`],
parentURL: import.meta.url,
importAttributes: from.context.importAttributes,
},
};
debug(`resolve`, { from, to });
await nextResolve(to.specifier, to.context);
}
return nextResolve(specifier, context);
};
export const checkIsSelfImportFromProject = (input) => {
// Not clear it would ever not be the case but we're being careful here.
// ...would be intersted to know if this is ever false.
const isImporterTheProject = input.importerPathExpOrFileUrlExp.includes(input.projectDirPathExp);
const isImportMe = isSpecifierFromPackage(input.specifier, packagePaths.name);
return isImporterTheProject && isImportMe;
};
export const VitePluginSelfContainedMode = ({ projectDirPathExp }) => {
const d = debugPolen.sub(`vite-plugin:self-contained-import`);
return {
name: `polen:self-contained-import`,
resolveId(id, importer) {
const isSelfContainedImport = importer
&& checkIsSelfImportFromProject({ projectDirPathExp, specifier: id, importerPathExpOrFileUrlExp: importer });
if (!isSelfContainedImport)
return;
const to = fileURLToPath(import.meta.resolve(id));
d(`did resolve`, { from: id, to });
return to;
},
};
};
//# sourceMappingURL=self-contained-mode.js.map