Skip to content

Commit

Permalink
Safer alias
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy committed Jan 13, 2023
1 parent 5651c38 commit b672f77
Showing 1 changed file with 29 additions and 11 deletions.
40 changes: 29 additions & 11 deletions packages/astro/src/core/build/vite-plugin-alias-resolve.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,50 @@
import type { Plugin as VitePlugin } from 'vite';
import type { Alias, Plugin as VitePlugin } from 'vite';
import type { BuildInternals } from '../../core/build/internal.js';

/**
* `@rollup/plugin-alias` doesn't resolve aliases in Rollup input by default. This plugin fixes it.
* `@rollup/plugin-alias` doesn't resolve aliases in Rollup input by default. This plugin fixes it
* with a partial fork of it's resolve function. https://github.com/rollup/plugins/blob/master/packages/alias/src/index.ts
* When https://github.com/rollup/plugins/pull/1402 is merged, we can remove this plugin.
*/
export function vitePluginAliasResolve(internals: BuildInternals): VitePlugin {
let inputResolve: (id: string) => Promise<string>;
let aliases: Alias[];

return {
name: '@astro/plugin-alias-resolve',
enforce: 'pre',
configResolved(config) {
const viteResolve = config.createResolver();
inputResolve = async (id) => {
const resolved = await viteResolve(id, ' ', true);
return resolved || id;
};
aliases = config.resolve.alias;
},
async resolveId(id, importer) {
async resolveId(id, importer, opts) {
if (
!importer &&
(internals.discoveredHydratedComponents.has(id) ||
internals.discoveredClientOnlyComponents.has(id))
) {
const resolved = await inputResolve(id);
return await this.resolve(resolved, importer, { skipSelf: true });
const matchedEntry = aliases.find((entry) => matches(entry.find, id));
if (!matchedEntry) {
return null;
}

const updatedId = id.replace(matchedEntry.find, matchedEntry.replacement);

return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, opts)).then(
(resolved) => resolved || { id: updatedId }
);
}
},
};
}

function matches(pattern: string | RegExp, importee: string) {
if (pattern instanceof RegExp) {
return pattern.test(importee);
}
if (importee.length < pattern.length) {
return false;
}
if (importee === pattern) {
return true;
}
return importee.startsWith(pattern + '/');
}

0 comments on commit b672f77

Please sign in to comment.