feat: add inline-schema/csv-loader/rollup for tsup/vite

This commit is contained in:
2026-04-04 16:44:03 +08:00
parent d9a91ae8be
commit 08cac3965e
4 changed files with 148 additions and 1 deletions
+89
View File
@@ -0,0 +1,89 @@
import type { Plugin } from 'rollup';
import type { CsvLoaderOptions } from './loader.js';
import { csvToModule } from './loader.js';
import * as path from 'path';
import * as fs from 'fs';
export interface CsvRollupOptions extends CsvLoaderOptions {
/** Include pattern for CSV files (default: /\.csv$/) */
include?: RegExp | string | Array<RegExp | string>;
/** Exclude pattern for CSV files */
exclude?: RegExp | string | Array<RegExp | string>;
}
function matchesPattern(
id: string,
pattern: RegExp | string | Array<RegExp | string> | undefined
): boolean {
if (!pattern) return true;
const patterns = Array.isArray(pattern) ? pattern : [pattern];
return patterns.some((p) => {
if (p instanceof RegExp) {
return p.test(id);
}
return id.includes(p);
});
}
/**
* Rollup plugin for loading CSV files with inline-schema validation.
* Works with both Vite and Tsup (esbuild).
*/
export function csvLoader(options: CsvRollupOptions = {}): Plugin {
const {
include = /\.csv$/,
exclude,
emitTypes = true,
typesOutputDir = '',
writeToDisk = false,
...parseOptions
} = options;
return {
name: 'inline-schema-csv',
transform(code: string, id: string) {
// Check if file matches the include/exclude patterns
if (!matchesPattern(id, include)) return null;
if (exclude && matchesPattern(id, exclude)) return null;
// Only process .csv files
if (!id.endsWith('.csv')) return null;
const result = csvToModule(code, {
...parseOptions,
emitTypes,
});
// Emit type definition file if enabled
if (emitTypes && result.dts) {
const dtsPath = typesOutputDir
? path.join(typesOutputDir, path.basename(id) + '.d.ts')
: id + '.d.ts';
if (writeToDisk) {
// Write directly to disk
const absolutePath = path.isAbsolute(dtsPath)
? dtsPath
: path.join(process.cwd(), dtsPath);
fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
fs.writeFileSync(absolutePath, result.dts);
} else {
// Emit to Rollup's virtual module system
this.emitFile({
type: 'asset',
fileName: dtsPath,
source: result.dts,
});
}
}
return {
code: result.js,
map: null,
};
},
};
}
export default csvLoader;