Skip to content

Commit

Permalink
feat: support arbitrary delimiters
Browse files Browse the repository at this point in the history
  • Loading branch information
SegaraRai committed Jul 11, 2024
1 parent f5320ce commit 489fa1f
Showing 1 changed file with 20 additions and 11 deletions.
31 changes: 20 additions & 11 deletions src/frameworks/vite/id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,39 +31,48 @@ export function toImportPath(stringifiedId: string, idInfo: IdInfo): string {

export function parseId(
{ root }: ResolvedConfig,
delimiter: string,
id: string
): readonly [sourceId: string | null, name: string] | null {
if (!id.startsWith(PREFIX)) {
return null;
}

const sliced = id.slice(PREFIX.length);
const name = sliced.match(/[^/]+$/)?.[0] ?? "";
if (!name) {
return null;
}

const sourceId = restoreSourceId(sliced.slice(0, -name.length - 1), root);
return [sourceId || null, name.replace(/\?.*$/, "")];
const name = sliced.split(delimiter).pop()!;
const sourceId =
sliced !== name
? restoreSourceId(sliced.slice(0, -name.length - delimiter.length), root)
: null;
return [sourceId, name.replace(/\?.*$/, "")];
}

export function stringifyId(
{ root }: ResolvedConfig,
delimiter: string,
sourceId: string | null,
name: string
): string {
if (!sourceId) {
return `${PREFIX}${name}`;
}

return `${PREFIX}${stringifySourceId(sourceId, root)}/${name}`;
return `${PREFIX}${stringifySourceId(sourceId, root)}${delimiter}${name}`;
}

export function createIdFunctions(
config: ResolvedConfig
config: ResolvedConfig,
delimiter = "/"
): CodegenFunctionsForId {
if (/^[a-z.]*$/i.test(delimiter) || /[\\?&#]/.test(delimiter)) {
throw new Error(
`Invalid delimiter: "${delimiter}". Parsing would be ambiguous.`
);
}

return {
parseId: (id) => parseId(config, id),
stringifyId: (sourceId, name) => stringifyId(config, sourceId, name),
parseId: (id) => parseId(config, delimiter, id),
stringifyId: (sourceId, name) =>
stringifyId(config, delimiter, sourceId, name),
};
}

0 comments on commit 489fa1f

Please sign in to comment.