vite-plugin-lib 3.0.4 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +36 -42
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +319 -0
- package/dist/index.js.map +1 -0
- package/package.json +7 -8
- package/dist/index.d.mts +0 -55
- package/dist/index.mjs +0 -410
package/dist/index.d.ts
CHANGED
|
@@ -1,55 +1,49 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
export { vitePluginDts as dts };
|
|
1
|
+
import * as dts from "vite-plugin-dts";
|
|
2
|
+
import { LibraryFormats, Plugin } from "vite";
|
|
4
3
|
|
|
5
|
-
|
|
6
|
-
enabled: boolean;
|
|
7
|
-
include: string[];
|
|
8
|
-
exclude: string[];
|
|
9
|
-
provider: "v8";
|
|
10
|
-
};
|
|
4
|
+
//#region src/index.d.ts
|
|
11
5
|
interface CommonOptions {
|
|
12
|
-
|
|
6
|
+
verbose: boolean;
|
|
13
7
|
}
|
|
14
8
|
interface TSConfigPathsOptions extends CommonOptions {
|
|
15
|
-
|
|
16
|
-
|
|
9
|
+
/** Path to the tsconfig file (relative to the project root). Defaults to `./tsconfig.json` */
|
|
10
|
+
tsconfig: string;
|
|
17
11
|
}
|
|
18
12
|
interface BundleOptions {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
13
|
+
/** If `false`, all builtin modules will be externalized. Defaults to `false`. */
|
|
14
|
+
builtin: boolean;
|
|
15
|
+
/** If `false`, all dependencies will be externalized. Defaults to `false`. */
|
|
16
|
+
dependencies: boolean;
|
|
17
|
+
/** If `false`, all devDependencies will be externalized. Defaults to `true`. */
|
|
18
|
+
devDependencies: boolean;
|
|
19
|
+
/** If `false`, all dependencies will be externalized. Defaults to `false`. */
|
|
20
|
+
peerDependencies: boolean;
|
|
21
|
+
/** List of packages or modules to externalize. Defaults to `[]`. */
|
|
22
|
+
exclude: (string | RegExp)[];
|
|
23
|
+
/** List of packages or modules to bundle. Acts as an override and defaults to `[]`. */
|
|
24
|
+
include: (string | RegExp)[];
|
|
25
|
+
/** If `false`, all direct imports from `node_modules` will be externalized. Defaults to `false`. */
|
|
26
|
+
nodeModules: boolean;
|
|
33
27
|
}
|
|
34
28
|
interface LibraryOptions extends TSConfigPathsOptions {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
29
|
+
/** Defaults to `src/index.ts`. */
|
|
30
|
+
entry: string;
|
|
31
|
+
/** Bundle configuration for packages and modules. See {@link BundleOptions} for defaults. */
|
|
32
|
+
bundle: Partial<BundleOptions>;
|
|
33
|
+
/** Defaults to `['es']`. */
|
|
34
|
+
formats: LibraryFormats[];
|
|
35
|
+
/** Defaults to `package.json`. */
|
|
36
|
+
manifest: string;
|
|
37
|
+
name?: string;
|
|
38
|
+
/** Remove any temporary build files. Defaults to `true`. */
|
|
39
|
+
cleanup: boolean;
|
|
46
40
|
}
|
|
47
41
|
declare function tsconfigPaths(options?: Partial<TSConfigPathsOptions>): Plugin;
|
|
48
42
|
declare function library(options?: Partial<LibraryOptions>): Plugin[];
|
|
49
43
|
/**
|
|
50
|
-
|
|
51
|
-
|
|
44
|
+
* Remove any temporary `vite.config.ts.timestamp-*` files.
|
|
45
|
+
*/
|
|
52
46
|
declare function cleanup(options?: Partial<CommonOptions>): Plugin;
|
|
53
|
-
|
|
54
|
-
export { cleanup,
|
|
55
|
-
|
|
47
|
+
//#endregion
|
|
48
|
+
export { BundleOptions, CommonOptions, LibraryOptions, TSConfigPathsOptions, cleanup, dts, library, tsconfigPaths };
|
|
49
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"sourcesContent":[],"mappings":";;;;UAwBiB,aAAA;;AAAjB;AAQiB,UAAA,oBAAA,SAA6B,aAAA,CAAA;EAU9C;EA2BA,QAAiB,EAAA,MAAA;;AAIP,UA/BO,aAAA,CA+BP;EAEC;EAN6B,OAAA,EAAA,OAAA;EAAA;EA8BxC,YAAgB,EAAA,OAAA;EAA+B;EAAR,eAAA,EAAA,OAAA;EAAqC;EAAA,gBAAA,EAAA,OAAA;EA2N5E;EAAyC,OAAA,EAAA,CAAA,MAAA,GA1QpB,MA0QoB,CAAA,EAAA;EAAR;EAA+B,OAAA,EAAA,CAAA,MAAA,GAxQ3C,MAwQ2C,CAAA,EAAA;EAAA;EA4EhE,WAAgB,EAAA,OAAA;;AAAiB,UArUhB,cAAA,SAAuB,oBAqUP,CAAA;EAA8B;EAAA,KAAA,EAAA,MAAA;;UAjUrD,QAAQ;;WAEP;;;;;;;iBAwBK,aAAA,WAAuB,QAAQ,wBAA6B;iBA2N5D,OAAA,WAAiB,QAAQ,kBAAuB;;;;iBA4EhD,OAAA,WAAiB,QAAQ,iBAAsB"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import { builtinModules } from "node:module";
|
|
2
|
+
import { existsSync, readFileSync, readdirSync, rmSync } from "node:fs";
|
|
3
|
+
import { readFile, readdir, unlink, writeFile } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import c from "picocolors";
|
|
6
|
+
import ts from "typescript";
|
|
7
|
+
import * as dts from "vite-plugin-dts";
|
|
8
|
+
import dts$1 from "vite-plugin-dts";
|
|
9
|
+
import { normalizePath } from "vite";
|
|
10
|
+
|
|
11
|
+
//#region src/logger.ts
|
|
12
|
+
function log(text) {
|
|
13
|
+
console.log(`${c.cyan("[vite:lib]")} ${text}`);
|
|
14
|
+
}
|
|
15
|
+
function logWarn(text) {
|
|
16
|
+
console.warn(`${c.yellow("[vite:lib]")} ${text}`);
|
|
17
|
+
}
|
|
18
|
+
function logError(text) {
|
|
19
|
+
console.error(`${c.red("[vite:lib]")} ${text}`);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/es-declarations.ts
|
|
24
|
+
async function generateMTSDeclarations(typesDir$1, deleteSourceFiles, verbose) {
|
|
25
|
+
const files = await collectFiles(typesDir$1);
|
|
26
|
+
for (const file of files) {
|
|
27
|
+
await createMTSImports(file, verbose);
|
|
28
|
+
if (deleteSourceFiles) unlink(file);
|
|
29
|
+
}
|
|
30
|
+
log(`Generated ${files.length} MTS declarations.`);
|
|
31
|
+
}
|
|
32
|
+
async function collectFiles(dir) {
|
|
33
|
+
const entries = await readdir(dir, {
|
|
34
|
+
recursive: false,
|
|
35
|
+
withFileTypes: true
|
|
36
|
+
});
|
|
37
|
+
const files = entries.filter((entry) => entry.isFile());
|
|
38
|
+
const nestedFiles = await Promise.all(entries.filter((entry) => entry.isDirectory()).map((entry) => collectFiles(normalizePath(path.join(dir, entry.name)))));
|
|
39
|
+
return files.map((file) => normalizePath(path.join(dir, file.name))).concat(...nestedFiles);
|
|
40
|
+
}
|
|
41
|
+
async function createMTSImports(file, verbose) {
|
|
42
|
+
const modified = (await readFile(file, "utf-8")).split("\n").map((line) => transformLine(file, line, verbose));
|
|
43
|
+
await writeFile(file.replace(".d.ts", ".d.mts"), modified.join("\n"));
|
|
44
|
+
}
|
|
45
|
+
function transformLine(file, line, verbose) {
|
|
46
|
+
return transformStaticImport(file, line, "'", verbose) ?? transformStaticImport(file, line, "\"", verbose) ?? transformExport(file, line, "'", verbose) ?? transformExport(file, line, "\"", verbose) ?? line;
|
|
47
|
+
}
|
|
48
|
+
function transformStaticImport(file, line, quote, verbose) {
|
|
49
|
+
const importPathMarker = `from ${quote}`;
|
|
50
|
+
if (!(line.includes("import ") && line.includes(`${importPathMarker}.`))) return;
|
|
51
|
+
const importStartIndex = line.lastIndexOf(importPathMarker);
|
|
52
|
+
const importPath = line.substring(importStartIndex + importPathMarker.length, line.length - 2);
|
|
53
|
+
const resolvedImport = path.resolve(path.dirname(file), importPath);
|
|
54
|
+
if (existsSync(resolvedImport)) {
|
|
55
|
+
if (verbose) log(`got index import ${resolvedImport}`);
|
|
56
|
+
return `${line.substring(0, line.length - 2)}/index.mjs${quote};`;
|
|
57
|
+
}
|
|
58
|
+
return `${line.substring(0, line.length - 2)}.mjs${quote};`;
|
|
59
|
+
}
|
|
60
|
+
function transformExport(file, line, quote, verbose) {
|
|
61
|
+
const exportPathMarker = ` from ${quote}`;
|
|
62
|
+
if (!(line.includes("export ") && line.includes(`${exportPathMarker}.`))) return;
|
|
63
|
+
const exportStartIndex = line.lastIndexOf(exportPathMarker);
|
|
64
|
+
const exportPath = line.substring(exportStartIndex + exportPathMarker.length, line.length - 2);
|
|
65
|
+
const resolvedExport = path.resolve(path.dirname(file), exportPath);
|
|
66
|
+
if (existsSync(resolvedExport)) {
|
|
67
|
+
if (verbose) log(`got index export ${resolvedExport}`);
|
|
68
|
+
return `${line.substring(0, line.length - 2)}/index.mjs${quote};`;
|
|
69
|
+
}
|
|
70
|
+
return `${line.substring(0, line.length - 2)}.mjs${quote};`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region src/index.ts
|
|
75
|
+
const typesDir = "dist/types";
|
|
76
|
+
const COMMON_DEFAULTS = { verbose: false };
|
|
77
|
+
const TS_CONFIG_PATHS_OPTIONS = {
|
|
78
|
+
...COMMON_DEFAULTS,
|
|
79
|
+
tsconfig: "./tsconfig.json"
|
|
80
|
+
};
|
|
81
|
+
const BUNDLE_DEFAULTS = {
|
|
82
|
+
builtin: false,
|
|
83
|
+
dependencies: false,
|
|
84
|
+
devDependencies: true,
|
|
85
|
+
peerDependencies: false,
|
|
86
|
+
exclude: [],
|
|
87
|
+
include: [],
|
|
88
|
+
nodeModules: false
|
|
89
|
+
};
|
|
90
|
+
const LIBRARY_DEFAULTS = {
|
|
91
|
+
...TS_CONFIG_PATHS_OPTIONS,
|
|
92
|
+
cleanup: true,
|
|
93
|
+
entry: "src/index.ts",
|
|
94
|
+
bundle: {},
|
|
95
|
+
formats: ["es"],
|
|
96
|
+
manifest: "package.json"
|
|
97
|
+
};
|
|
98
|
+
function mergeWithDefaults(options) {
|
|
99
|
+
return {
|
|
100
|
+
...LIBRARY_DEFAULTS,
|
|
101
|
+
...options
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function tsconfigPaths(options = {}) {
|
|
105
|
+
const tsconfig = options.tsconfig ?? TS_CONFIG_PATHS_OPTIONS.tsconfig;
|
|
106
|
+
const verbose = options.verbose ?? TS_CONFIG_PATHS_OPTIONS.verbose;
|
|
107
|
+
return {
|
|
108
|
+
name: "vite-plugin-lib:alias",
|
|
109
|
+
enforce: "pre",
|
|
110
|
+
config: async (config) => {
|
|
111
|
+
const tsconfigPath = path.resolve(config.root ?? ".", tsconfig);
|
|
112
|
+
const { baseUrl, paths } = await readConfig(tsconfigPath);
|
|
113
|
+
if (!baseUrl || !paths) {
|
|
114
|
+
log(`No paths found in ${tsconfig}.`);
|
|
115
|
+
return config;
|
|
116
|
+
}
|
|
117
|
+
const pathToAlias = pathToAliasFactory(tsconfigPath, baseUrl, verbose);
|
|
118
|
+
const aliasOptions = Object.entries(paths).map(pathToAlias).filter((alias) => alias !== void 0);
|
|
119
|
+
if (aliasOptions.length > 0) logInjectedAliases(aliasOptions, config, verbose);
|
|
120
|
+
const existingAlias = transformExistingAlias(config.resolve?.alias);
|
|
121
|
+
return {
|
|
122
|
+
...config,
|
|
123
|
+
resolve: {
|
|
124
|
+
...config.resolve,
|
|
125
|
+
alias: [...existingAlias, ...aliasOptions]
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function buildConfig({ entry, formats, manifest, name, bundle, verbose }) {
|
|
132
|
+
const bundleWithDefaults = {
|
|
133
|
+
...BUNDLE_DEFAULTS,
|
|
134
|
+
...bundle
|
|
135
|
+
};
|
|
136
|
+
const packagesToExternalize = [
|
|
137
|
+
...getBuiltinModules(bundleWithDefaults),
|
|
138
|
+
...getDependencies(manifest, bundleWithDefaults, verbose),
|
|
139
|
+
...bundleWithDefaults.exclude
|
|
140
|
+
];
|
|
141
|
+
if (!bundleWithDefaults.nodeModules) {
|
|
142
|
+
packagesToExternalize.push(/node_modules/);
|
|
143
|
+
if (verbose) log(`Externalized node_modules.`);
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
name: "vite-plugin-lib:build",
|
|
147
|
+
enforce: "pre",
|
|
148
|
+
apply: "build",
|
|
149
|
+
config: async (config) => {
|
|
150
|
+
return {
|
|
151
|
+
...config,
|
|
152
|
+
build: {
|
|
153
|
+
...config.build,
|
|
154
|
+
lib: {
|
|
155
|
+
...config.build?.lib,
|
|
156
|
+
entry: path.resolve(config.root ?? ".", entry),
|
|
157
|
+
formats,
|
|
158
|
+
name,
|
|
159
|
+
fileName: (format) => formatToFileName(entry, format)
|
|
160
|
+
},
|
|
161
|
+
rollupOptions: { external: (source, _importer, _isResolved) => {
|
|
162
|
+
const shouldBeExternalized = packagesToExternalize.some((rule) => matchesRule(source, rule));
|
|
163
|
+
const shouldBeBundled = bundleWithDefaults.include.some((rule) => matchesRule(source, rule));
|
|
164
|
+
return shouldBeExternalized && !shouldBeBundled;
|
|
165
|
+
} }
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function matchesRule(source, rule) {
|
|
172
|
+
return typeof rule === "string" ? rule === source : rule.test(source);
|
|
173
|
+
}
|
|
174
|
+
function getDependencies(manifest, bundle, verbose) {
|
|
175
|
+
try {
|
|
176
|
+
const content = readFileSync(manifest, { encoding: "utf-8" });
|
|
177
|
+
const { dependencies = {}, devDependencies = {}, peerDependencies = {} } = JSON.parse(content);
|
|
178
|
+
const dependenciesToExternalize = [];
|
|
179
|
+
if (!bundle.dependencies) {
|
|
180
|
+
const names = Object.keys(dependencies);
|
|
181
|
+
dependenciesToExternalize.push(...names);
|
|
182
|
+
if (verbose) log(`Externalized ${names.length} dependencies.`);
|
|
183
|
+
}
|
|
184
|
+
if (!bundle.devDependencies) {
|
|
185
|
+
const names = Object.keys(devDependencies);
|
|
186
|
+
dependenciesToExternalize.push(...names);
|
|
187
|
+
if (verbose) log(`Externalized ${names.length} devDependencies.`);
|
|
188
|
+
}
|
|
189
|
+
if (!bundle.peerDependencies) {
|
|
190
|
+
const names = Object.keys(peerDependencies);
|
|
191
|
+
dependenciesToExternalize.push(...names);
|
|
192
|
+
if (verbose) log(`Externalized ${names.length} peerDependencies.`);
|
|
193
|
+
}
|
|
194
|
+
return dependenciesToExternalize;
|
|
195
|
+
} catch (error) {
|
|
196
|
+
const message = getErrorMessage(error);
|
|
197
|
+
logError(`Could not read ${c.green(manifest)}: ${message}`);
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function getBuiltinModules(bundle) {
|
|
202
|
+
if (bundle.builtin) return [];
|
|
203
|
+
log("Externalized builtin modules.");
|
|
204
|
+
return [
|
|
205
|
+
...builtinModules,
|
|
206
|
+
/node:/,
|
|
207
|
+
/bun:/,
|
|
208
|
+
/deno:/
|
|
209
|
+
];
|
|
210
|
+
}
|
|
211
|
+
function logInjectedAliases(aliasOptions, config, verbose) {
|
|
212
|
+
log(`Injected ${c.green(aliasOptions.length)} aliases.`);
|
|
213
|
+
if (!verbose) return;
|
|
214
|
+
const base = `${path.resolve(config.root ?? ".")}/`;
|
|
215
|
+
aliasOptions.map(({ find, replacement }) => ` ${c.gray(">")} ${c.green(find.toString())} ${c.gray(c.bold("->"))} ${c.green(replacement.replace(base, ""))}`).forEach(log);
|
|
216
|
+
}
|
|
217
|
+
function pathToAliasFactory(tsconfigPath, baseUrl, verbose) {
|
|
218
|
+
return ([alias, replacements]) => {
|
|
219
|
+
if (replacements.length === 0) {
|
|
220
|
+
if (verbose) logWarn(`No replacements for alias ${c.green(alias)}.`);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (verbose && replacements.length > 1) {
|
|
224
|
+
logWarn(`Found more than one replacement for alias ${c.green(alias)}.`);
|
|
225
|
+
logWarn("Using the first existing replacement.");
|
|
226
|
+
}
|
|
227
|
+
const find = alias.replace("/*", "");
|
|
228
|
+
const replacement = getFirstExistingReplacement(tsconfigPath, baseUrl, replacements, find);
|
|
229
|
+
if (!replacement) {
|
|
230
|
+
if (verbose) logWarn(`No replacement found for alias ${c.green(alias)}.`);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
return {
|
|
234
|
+
find,
|
|
235
|
+
replacement
|
|
236
|
+
};
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
function getFirstExistingReplacement(tsconfigPath, baseUrl, replacements, find, verbose) {
|
|
240
|
+
for (const replacement of replacements) {
|
|
241
|
+
const resolvedReplacement = path.resolve(tsconfigPath, baseUrl, replacement.replace("/*", "") ?? find);
|
|
242
|
+
if (existsSync(resolvedReplacement)) return resolvedReplacement;
|
|
243
|
+
else if (verbose) logWarn(`Path ${c.green(replacement)} does not exist.`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
function formatToFileName(entry, format) {
|
|
247
|
+
const entryFileName = entry.substring(entry.lastIndexOf("/") + 1, entry.lastIndexOf("."));
|
|
248
|
+
if (format === "es") return `${entryFileName}.mjs`;
|
|
249
|
+
if (format === "cjs") return `${entryFileName}.cjs`;
|
|
250
|
+
return `${entryFileName}.${format}.js`;
|
|
251
|
+
}
|
|
252
|
+
function library(options = {}) {
|
|
253
|
+
const mergedOptions = mergeWithDefaults(options);
|
|
254
|
+
const plugins = [
|
|
255
|
+
tsconfigPaths(mergedOptions),
|
|
256
|
+
buildConfig(mergedOptions),
|
|
257
|
+
dts$1({
|
|
258
|
+
cleanVueFileName: true,
|
|
259
|
+
copyDtsFiles: true,
|
|
260
|
+
include: `${path.resolve(mergedOptions.entry, "..")}/**`,
|
|
261
|
+
outDir: typesDir,
|
|
262
|
+
staticImport: true,
|
|
263
|
+
tsconfigPath: mergedOptions.tsconfig,
|
|
264
|
+
afterBuild: async () => {
|
|
265
|
+
if (includesESFormat(mergedOptions.formats)) await generateMTSDeclarations(typesDir, mergedOptions.formats?.length === 1, options.verbose);
|
|
266
|
+
}
|
|
267
|
+
})
|
|
268
|
+
];
|
|
269
|
+
if (mergedOptions.cleanup) plugins.push(cleanup(mergedOptions));
|
|
270
|
+
return plugins;
|
|
271
|
+
}
|
|
272
|
+
function transformExistingAlias(alias) {
|
|
273
|
+
if (!alias) return [];
|
|
274
|
+
if (Array.isArray(alias)) return alias;
|
|
275
|
+
return Object.entries(alias).map(([find, replacement]) => ({
|
|
276
|
+
find,
|
|
277
|
+
replacement
|
|
278
|
+
}));
|
|
279
|
+
}
|
|
280
|
+
async function readConfig(configPath) {
|
|
281
|
+
try {
|
|
282
|
+
const configFileText = await readFile(configPath, { encoding: "utf-8" });
|
|
283
|
+
const { config } = ts.parseConfigFileTextToJson(configPath, configFileText);
|
|
284
|
+
const { options } = ts.parseJsonConfigFileContent(config, ts.sys, path.dirname(configPath));
|
|
285
|
+
return options;
|
|
286
|
+
} catch (error) {
|
|
287
|
+
logError(`Could not read ${configPath}: ${getErrorMessage(error)}`);
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
function includesESFormat(formats) {
|
|
292
|
+
return formats?.includes("es") ?? true;
|
|
293
|
+
}
|
|
294
|
+
function getErrorMessage(error) {
|
|
295
|
+
return typeof error === "object" && error !== null && "message" in error ? error.message : String(error);
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Remove any temporary `vite.config.ts.timestamp-*` files.
|
|
299
|
+
*/
|
|
300
|
+
function cleanup(options = {}) {
|
|
301
|
+
const verbose = options.verbose ?? COMMON_DEFAULTS.verbose;
|
|
302
|
+
return {
|
|
303
|
+
name: "vite-plugin-lib:cleanup",
|
|
304
|
+
enforce: "post",
|
|
305
|
+
closeBundle: () => {
|
|
306
|
+
let deletedCount = 0;
|
|
307
|
+
readdirSync(".").forEach((file) => {
|
|
308
|
+
if (!file.startsWith("vite.config.ts.timestamp-")) return;
|
|
309
|
+
rmSync(`./${file}`);
|
|
310
|
+
deletedCount++;
|
|
311
|
+
});
|
|
312
|
+
if (verbose) log(`Removed ${deletedCount} temporary files.`);
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
//#endregion
|
|
318
|
+
export { cleanup, dts, library, tsconfigPaths };
|
|
319
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["typesDir","dependenciesToExternalize: string[]","dts","error: any"],"sources":["../src/logger.ts","../src/es-declarations.ts","../src/index.ts"],"sourcesContent":["import c from 'picocolors'\n\nexport function log(text: string): void {\n // eslint-disable-next-line no-console\n console.log(`${c.cyan('[vite:lib]')} ${text}`)\n}\n\nexport function logWarn(text: string): void {\n console.warn(`${c.yellow('[vite:lib]')} ${text}`)\n}\n\nexport function logError(text: string): void {\n console.error(`${c.red('[vite:lib]')} ${text}`)\n}\n","import { existsSync } from 'node:fs'\nimport { readFile, readdir, unlink, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\n\nimport { normalizePath } from 'vite'\n\nimport { log } from './logger'\n\nexport async function generateMTSDeclarations(\n typesDir: string,\n deleteSourceFiles: boolean,\n verbose: boolean | undefined,\n): Promise<void> {\n const files = await collectFiles(typesDir)\n for (const file of files) {\n await createMTSImports(file, verbose)\n if (deleteSourceFiles) {\n unlink(file)\n }\n }\n log(`Generated ${files.length} MTS declarations.`)\n}\n\nasync function collectFiles(dir: string): Promise<string[]> {\n const entries = await readdir(dir, {\n recursive: false, // does not provide full path to nested files\n withFileTypes: true,\n })\n const files = entries.filter((entry) => entry.isFile())\n const nestedFiles = await Promise.all(\n entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => collectFiles(normalizePath(path.join(dir, entry.name)))),\n )\n return files\n .map((file) => normalizePath(path.join(dir, file.name)))\n .concat(...nestedFiles)\n}\n\nasync function createMTSImports(file: string, verbose: boolean | undefined) {\n const content = await readFile(file, 'utf-8')\n const lines = content.split('\\n')\n const modified = lines.map((line) => transformLine(file, line, verbose))\n const targetFile = file.replace('.d.ts', '.d.mts')\n await writeFile(targetFile, modified.join('\\n'))\n}\n\nfunction transformLine(\n file: string,\n line: string,\n verbose: boolean | undefined,\n) {\n return (\n // eslint-disable-next-line style/quotes\n transformStaticImport(file, line, \"'\", verbose) ??\n transformStaticImport(file, line, '\"', verbose) ??\n // eslint-disable-next-line style/quotes\n transformExport(file, line, \"'\", verbose) ??\n transformExport(file, line, '\"', verbose) ??\n line\n )\n}\n\nfunction transformStaticImport(\n file: string,\n line: string,\n quote: string,\n verbose: boolean | undefined,\n) {\n const importPathMarker = `from ${quote}`\n const isStaticImport =\n line.includes('import ') && line.includes(`${importPathMarker}.`)\n if (!isStaticImport) {\n return undefined\n }\n\n const importStartIndex = line.lastIndexOf(importPathMarker)\n const importPath = line.substring(\n importStartIndex + importPathMarker.length,\n line.length - 2,\n )\n const resolvedImport = path.resolve(path.dirname(file), importPath)\n if (existsSync(resolvedImport)) {\n if (verbose) {\n log(`got index import ${resolvedImport}`)\n }\n return `${line.substring(0, line.length - 2)}/index.mjs${quote};`\n }\n\n return `${line.substring(0, line.length - 2)}.mjs${quote};`\n}\n\nfunction transformExport(\n file: string,\n line: string,\n quote: string,\n verbose: boolean | undefined,\n) {\n const exportPathMarker = ` from ${quote}`\n const isStaticExport =\n line.includes('export ') && line.includes(`${exportPathMarker}.`)\n if (!isStaticExport) {\n return undefined\n }\n\n const exportStartIndex = line.lastIndexOf(exportPathMarker)\n const exportPath = line.substring(\n exportStartIndex + exportPathMarker.length,\n line.length - 2,\n )\n const resolvedExport = path.resolve(path.dirname(file), exportPath)\n if (existsSync(resolvedExport)) {\n if (verbose) {\n log(`got index export ${resolvedExport}`)\n }\n return `${line.substring(0, line.length - 2)}/index.mjs${quote};`\n }\n\n return `${line.substring(0, line.length - 2)}.mjs${quote};`\n}\n","import { existsSync, readFileSync, readdirSync, rmSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { builtinModules } from 'node:module'\nimport path from 'node:path'\n\nimport c from 'picocolors'\nimport type { CompilerOptions } from 'typescript'\nimport ts from 'typescript'\nimport type {\n Alias,\n AliasOptions,\n LibraryFormats,\n Plugin,\n UserConfig,\n} from 'vite'\nimport dts from 'vite-plugin-dts'\n\nimport { generateMTSDeclarations } from './es-declarations'\nimport { log, logError, logWarn } from './logger'\n\nexport * as dts from 'vite-plugin-dts'\n\nconst typesDir = 'dist/types'\n\nexport interface CommonOptions {\n verbose: boolean\n}\n\nconst COMMON_DEFAULTS = {\n verbose: false,\n} satisfies Partial<CommonOptions>\n\nexport interface TSConfigPathsOptions extends CommonOptions {\n /** Path to the tsconfig file (relative to the project root). Defaults to `./tsconfig.json` */\n tsconfig: string\n}\n\nconst TS_CONFIG_PATHS_OPTIONS = {\n ...COMMON_DEFAULTS,\n tsconfig: './tsconfig.json',\n} satisfies Partial<TSConfigPathsOptions>\n\nexport interface BundleOptions {\n /** If `false`, all builtin modules will be externalized. Defaults to `false`. */\n builtin: boolean\n /** If `false`, all dependencies will be externalized. Defaults to `false`. */\n dependencies: boolean\n /** If `false`, all devDependencies will be externalized. Defaults to `true`. */\n devDependencies: boolean\n /** If `false`, all dependencies will be externalized. Defaults to `false`. */\n peerDependencies: boolean\n /** List of packages or modules to externalize. Defaults to `[]`. */\n exclude: (string | RegExp)[]\n /** List of packages or modules to bundle. Acts as an override and defaults to `[]`. */\n include: (string | RegExp)[]\n /** If `false`, all direct imports from `node_modules` will be externalized. Defaults to `false`. */\n nodeModules: boolean\n}\n\nconst BUNDLE_DEFAULTS = {\n builtin: false,\n dependencies: false,\n devDependencies: true,\n peerDependencies: false,\n exclude: [],\n include: [],\n nodeModules: false,\n} satisfies BundleOptions\n\nexport interface LibraryOptions extends TSConfigPathsOptions {\n /** Defaults to `src/index.ts`. */\n entry: string\n /** Bundle configuration for packages and modules. See {@link BundleOptions} for defaults. */\n bundle: Partial<BundleOptions>\n /** Defaults to `['es']`. */\n formats: LibraryFormats[]\n /** Defaults to `package.json`. */\n manifest: string\n name?: string\n /** Remove any temporary build files. Defaults to `true`. */\n cleanup: boolean\n}\n\nconst LIBRARY_DEFAULTS = {\n ...TS_CONFIG_PATHS_OPTIONS,\n cleanup: true,\n entry: 'src/index.ts',\n bundle: {},\n formats: ['es'],\n manifest: 'package.json',\n} satisfies Partial<LibraryOptions>\n\nfunction mergeWithDefaults(options: Partial<LibraryOptions>): LibraryOptions {\n return {\n ...LIBRARY_DEFAULTS,\n ...options,\n }\n}\n\nexport function tsconfigPaths(options: Partial<TSConfigPathsOptions> = {}): Plugin {\n const tsconfig = options.tsconfig ?? TS_CONFIG_PATHS_OPTIONS.tsconfig\n const verbose = options.verbose ?? TS_CONFIG_PATHS_OPTIONS.verbose\n return {\n name: 'vite-plugin-lib:alias',\n enforce: 'pre',\n config: async (config) => {\n const tsconfigPath = path.resolve(config.root ?? '.', tsconfig)\n const { baseUrl, paths } = await readConfig(tsconfigPath)\n if (!baseUrl || !paths) {\n log(`No paths found in ${tsconfig}.`)\n return config\n }\n const pathToAlias = pathToAliasFactory(tsconfigPath, baseUrl, verbose)\n const aliasOptions = Object.entries(paths)\n .map(pathToAlias)\n .filter((alias) => alias !== undefined)\n if (aliasOptions.length > 0) {\n logInjectedAliases(aliasOptions, config, verbose)\n }\n const existingAlias = transformExistingAlias(config.resolve?.alias)\n return {\n ...config,\n resolve: {\n ...config.resolve,\n alias: [...existingAlias, ...aliasOptions],\n },\n }\n },\n }\n}\n\nfunction buildConfig({\n entry,\n formats,\n manifest,\n name,\n bundle,\n verbose,\n}: LibraryOptions): Plugin {\n const bundleWithDefaults = { ...BUNDLE_DEFAULTS, ...bundle }\n const packagesToExternalize = [\n ...getBuiltinModules(bundleWithDefaults),\n ...getDependencies(manifest, bundleWithDefaults, verbose),\n ...bundleWithDefaults.exclude,\n ]\n if (!bundleWithDefaults.nodeModules) {\n packagesToExternalize.push(/node_modules/)\n if (verbose) {\n log(`Externalized node_modules.`)\n }\n }\n return {\n name: 'vite-plugin-lib:build',\n enforce: 'pre',\n apply: 'build',\n config: async (config) => {\n return {\n ...config,\n build: {\n ...config.build,\n lib: {\n ...config.build?.lib,\n entry: path.resolve(config.root ?? '.', entry),\n formats,\n name,\n fileName: (format: string) => formatToFileName(entry, format),\n },\n rollupOptions: {\n external: (source: string, _importer: string | undefined, _isResolved: boolean) => {\n const shouldBeExternalized = packagesToExternalize.some((rule) => matchesRule(source, rule))\n const shouldBeBundled = bundleWithDefaults.include.some((rule) => matchesRule(source, rule))\n return shouldBeExternalized && !shouldBeBundled\n },\n },\n },\n }\n },\n }\n}\n\nfunction matchesRule(source: string, rule: string | RegExp) {\n return typeof rule === 'string' ? rule === source : rule.test(source)\n}\n\nfunction getDependencies(manifest: string, bundle: BundleOptions, verbose: boolean): string[] {\n try {\n const content = readFileSync(manifest, { encoding: 'utf-8' })\n const { dependencies = {}, devDependencies = {}, peerDependencies = {} } = JSON.parse(content)\n const dependenciesToExternalize: string[] = []\n if (!bundle.dependencies) {\n const names = Object.keys(dependencies)\n dependenciesToExternalize.push(...names)\n if (verbose) {\n log(`Externalized ${names.length} dependencies.`)\n }\n }\n if (!bundle.devDependencies) {\n const names = Object.keys(devDependencies)\n dependenciesToExternalize.push(...names)\n if (verbose) {\n log(`Externalized ${names.length} devDependencies.`)\n }\n }\n if (!bundle.peerDependencies) {\n const names = Object.keys(peerDependencies)\n dependenciesToExternalize.push(...names)\n if (verbose) {\n log(`Externalized ${names.length} peerDependencies.`)\n }\n }\n return dependenciesToExternalize\n } catch (error) {\n const message = getErrorMessage(error)\n logError(`Could not read ${c.green(manifest)}: ${message}`)\n throw error\n }\n}\n\nfunction getBuiltinModules(bundle: BundleOptions) {\n if (bundle.builtin) {\n return []\n }\n log('Externalized builtin modules.')\n return [...builtinModules, /node:/, /bun:/, /deno:/]\n}\n\nfunction logInjectedAliases(\n aliasOptions: Alias[],\n config: UserConfig,\n verbose?: boolean,\n) {\n log(`Injected ${c.green(aliasOptions.length)} aliases.`)\n if (!verbose) {\n return\n }\n const base = `${path.resolve(config.root ?? '.')}/`\n aliasOptions\n .map(\n ({ find, replacement }) =>\n ` ${c.gray('>')} ${c.green(find.toString())} ${c.gray(\n c.bold('->'),\n )} ${c.green(replacement.replace(base, ''))}`,\n )\n .forEach(log)\n}\n\nfunction pathToAliasFactory(\n tsconfigPath: string,\n baseUrl: string,\n verbose?: boolean,\n): (path: [string, string[]]) => Alias | undefined {\n return ([alias, replacements]) => {\n if (replacements.length === 0) {\n if (verbose) {\n logWarn(`No replacements for alias ${c.green(alias)}.`)\n }\n return undefined\n }\n if (verbose && replacements.length > 1) {\n logWarn(`Found more than one replacement for alias ${c.green(alias)}.`)\n logWarn('Using the first existing replacement.')\n }\n const find = alias.replace('/*', '')\n const replacement = getFirstExistingReplacement(\n tsconfigPath,\n baseUrl,\n replacements,\n find,\n )\n if (!replacement) {\n if (verbose) {\n logWarn(`No replacement found for alias ${c.green(alias)}.`)\n }\n return undefined\n }\n return {\n find,\n replacement,\n }\n }\n}\n\nfunction getFirstExistingReplacement(\n tsconfigPath: string,\n baseUrl: string,\n replacements: string[],\n find: string,\n verbose?: boolean,\n): string | undefined {\n for (const replacement of replacements) {\n const resolvedReplacement = path.resolve(\n tsconfigPath,\n baseUrl,\n replacement.replace('/*', '') ?? find,\n )\n if (existsSync(resolvedReplacement)) {\n return resolvedReplacement\n } else if (verbose) {\n logWarn(`Path ${c.green(replacement)} does not exist.`)\n }\n }\n return undefined\n}\n\nfunction formatToFileName(entry: string, format: string): string {\n const entryFileName = entry.substring(\n entry.lastIndexOf('/') + 1,\n entry.lastIndexOf('.'),\n )\n if (format === 'es') {\n return `${entryFileName}.mjs`\n }\n if (format === 'cjs') {\n return `${entryFileName}.cjs`\n }\n return `${entryFileName}.${format}.js`\n}\n\nexport function library(options: Partial<LibraryOptions> = {}): Plugin[] {\n const mergedOptions = mergeWithDefaults(options)\n const plugins = [\n tsconfigPaths(mergedOptions),\n buildConfig(mergedOptions),\n dts({\n cleanVueFileName: true,\n copyDtsFiles: true,\n include: `${path.resolve(mergedOptions.entry, '..')}/**`,\n outDir: typesDir,\n staticImport: true,\n tsconfigPath: mergedOptions.tsconfig,\n afterBuild: async () => {\n if (includesESFormat(mergedOptions.formats)) {\n await generateMTSDeclarations(\n typesDir,\n mergedOptions.formats?.length === 1,\n options.verbose,\n )\n }\n },\n }),\n ]\n\n if (mergedOptions.cleanup) {\n plugins.push(cleanup(mergedOptions))\n }\n\n return plugins\n}\n\nfunction transformExistingAlias(alias: AliasOptions | undefined): Alias[] {\n if (!alias) {\n return []\n }\n if (Array.isArray(alias)) {\n return alias\n }\n return Object.entries(alias).map(([find, replacement]) => ({\n find,\n replacement,\n }))\n}\n\nasync function readConfig(configPath: string): Promise<CompilerOptions> {\n try {\n const configFileText = await readFile(configPath, { encoding: 'utf-8' })\n\n const { config } = ts.parseConfigFileTextToJson(configPath, configFileText)\n\n const { options } = ts.parseJsonConfigFileContent(\n config,\n ts.sys,\n path.dirname(configPath),\n )\n return options\n } catch (error: any) {\n const message = getErrorMessage(error)\n logError(`Could not read ${configPath}: ${message}`)\n throw error\n }\n}\n\nfunction includesESFormat(formats?: LibraryFormats[]) {\n return formats?.includes('es') ?? true\n}\n\nfunction getErrorMessage(error: unknown) {\n const isObject =\n typeof error === 'object' && error !== null && 'message' in error\n return isObject ? error.message : String(error)\n}\n\n/**\n * Remove any temporary `vite.config.ts.timestamp-*` files.\n */\nexport function cleanup(options: Partial<CommonOptions> = {}): Plugin {\n const verbose = options.verbose ?? COMMON_DEFAULTS.verbose\n return {\n name: 'vite-plugin-lib:cleanup',\n enforce: 'post',\n closeBundle: () => {\n let deletedCount = 0\n readdirSync('.').forEach((file) => {\n if (!file.startsWith('vite.config.ts.timestamp-')) {\n return\n }\n rmSync(`./${file}`)\n deletedCount++\n })\n if (verbose) {\n log(`Removed ${deletedCount} temporary files.`)\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;AAEA,SAAgB,IAAI,MAAoB;AAEtC,SAAQ,IAAI,GAAG,EAAE,KAAK,aAAa,CAAC,GAAG,OAAO;;AAGhD,SAAgB,QAAQ,MAAoB;AAC1C,SAAQ,KAAK,GAAG,EAAE,OAAO,aAAa,CAAC,GAAG,OAAO;;AAGnD,SAAgB,SAAS,MAAoB;AAC3C,SAAQ,MAAM,GAAG,EAAE,IAAI,aAAa,CAAC,GAAG,OAAO;;;;;ACJjD,eAAsB,wBACpB,YACA,mBACA,SACe;CACf,MAAM,QAAQ,MAAM,aAAaA,WAAS;AAC1C,MAAK,MAAM,QAAQ,OAAO;AACxB,QAAM,iBAAiB,MAAM,QAAQ;AACrC,MAAI,kBACF,QAAO,KAAK;;AAGhB,KAAI,aAAa,MAAM,OAAO,oBAAoB;;AAGpD,eAAe,aAAa,KAAgC;CAC1D,MAAM,UAAU,MAAM,QAAQ,KAAK;EACjC,WAAW;EACX,eAAe;EAChB,CAAC;CACF,MAAM,QAAQ,QAAQ,QAAQ,UAAU,MAAM,QAAQ,CAAC;CACvD,MAAM,cAAc,MAAM,QAAQ,IAChC,QACG,QAAQ,UAAU,MAAM,aAAa,CAAC,CACtC,KAAK,UAAU,aAAa,cAAc,KAAK,KAAK,KAAK,MAAM,KAAK,CAAC,CAAC,CAAC,CAC3E;AACD,QAAO,MACJ,KAAK,SAAS,cAAc,KAAK,KAAK,KAAK,KAAK,KAAK,CAAC,CAAC,CACvD,OAAO,GAAG,YAAY;;AAG3B,eAAe,iBAAiB,MAAc,SAA8B;CAG1E,MAAM,YAFU,MAAM,SAAS,MAAM,QAAQ,EACvB,MAAM,KAAK,CACV,KAAK,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4
|
-
"version": "
|
|
4
|
+
"version": "4.0.0",
|
|
5
5
|
"description": "Vite plugin for build configuration, automatic aliases, and type declarations.",
|
|
6
6
|
"author": "Jan Müller <janmueller3698@gmail.com>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -24,12 +24,12 @@
|
|
|
24
24
|
"exports": {
|
|
25
25
|
".": {
|
|
26
26
|
"import": {
|
|
27
|
-
"types": "./dist/index.d.
|
|
28
|
-
"default": "./dist/index.
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"default": "./dist/index.js"
|
|
29
29
|
}
|
|
30
30
|
}
|
|
31
31
|
},
|
|
32
|
-
"types": "dist/index.d.
|
|
32
|
+
"types": "dist/index.d.ts",
|
|
33
33
|
"files": [
|
|
34
34
|
"LICENSE",
|
|
35
35
|
"dist"
|
|
@@ -43,17 +43,16 @@
|
|
|
43
43
|
"vite-plugin-dts": "4.5.4"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
|
-
"
|
|
46
|
+
"tsdown": "0.15.11",
|
|
47
47
|
"typescript": "5.9.3",
|
|
48
|
-
"unbuild": "3.6.1",
|
|
49
48
|
"vite": "7.1.12",
|
|
50
|
-
"@yeger/tsconfig": "2.1.
|
|
49
|
+
"@yeger/tsconfig": "2.1.2"
|
|
51
50
|
},
|
|
52
51
|
"publishConfig": {
|
|
53
52
|
"access": "public"
|
|
54
53
|
},
|
|
55
54
|
"scripts": {
|
|
56
|
-
"build": "
|
|
55
|
+
"build": "tsdown",
|
|
57
56
|
"check:publish": "publint run --strict",
|
|
58
57
|
"check:tsc": "tsc",
|
|
59
58
|
"lint": "yeger-lint"
|
package/dist/index.d.mts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import { LibraryFormats, Plugin } from 'vite';
|
|
2
|
-
import * as vitePluginDts from 'vite-plugin-dts';
|
|
3
|
-
export { vitePluginDts as dts };
|
|
4
|
-
|
|
5
|
-
declare const coverage: {
|
|
6
|
-
enabled: boolean;
|
|
7
|
-
include: string[];
|
|
8
|
-
exclude: string[];
|
|
9
|
-
provider: "v8";
|
|
10
|
-
};
|
|
11
|
-
interface CommonOptions {
|
|
12
|
-
verbose: boolean;
|
|
13
|
-
}
|
|
14
|
-
interface TSConfigPathsOptions extends CommonOptions {
|
|
15
|
-
/** Path to the tsconfig file (relative to the project root). Defaults to `./tsconfig.json` */
|
|
16
|
-
tsconfig: string;
|
|
17
|
-
}
|
|
18
|
-
interface BundleOptions {
|
|
19
|
-
/** If `false`, all builtin modules will be externalized. Defaults to `false`. */
|
|
20
|
-
builtin: boolean;
|
|
21
|
-
/** If `false`, all dependencies will be externalized. Defaults to `false`. */
|
|
22
|
-
dependencies: boolean;
|
|
23
|
-
/** If `false`, all devDependencies will be externalized. Defaults to `true`. */
|
|
24
|
-
devDependencies: boolean;
|
|
25
|
-
/** If `false`, all dependencies will be externalized. Defaults to `false`. */
|
|
26
|
-
peerDependencies: boolean;
|
|
27
|
-
/** List of packages or modules to externalize. Defaults to `[]`. */
|
|
28
|
-
exclude: (string | RegExp)[];
|
|
29
|
-
/** List of packages or modules to bundle. Acts as an override and defaults to `[]`. */
|
|
30
|
-
include: (string | RegExp)[];
|
|
31
|
-
/** If `false`, all direct imports from `node_modules` will be externalized. Defaults to `false`. */
|
|
32
|
-
nodeModules: boolean;
|
|
33
|
-
}
|
|
34
|
-
interface LibraryOptions extends TSConfigPathsOptions {
|
|
35
|
-
/** Defaults to `src/index.ts`. */
|
|
36
|
-
entry: string;
|
|
37
|
-
/** Bundle configuration for packages and modules. See {@link BundleOptions} for defaults. */
|
|
38
|
-
bundle: Partial<BundleOptions>;
|
|
39
|
-
/** Defaults to `['es']`. */
|
|
40
|
-
formats: LibraryFormats[];
|
|
41
|
-
/** Defaults to `package.json`. */
|
|
42
|
-
manifest: string;
|
|
43
|
-
name?: string;
|
|
44
|
-
/** Remove any temporary build files. Defaults to `true`. */
|
|
45
|
-
cleanup: boolean;
|
|
46
|
-
}
|
|
47
|
-
declare function tsconfigPaths(options?: Partial<TSConfigPathsOptions>): Plugin;
|
|
48
|
-
declare function library(options?: Partial<LibraryOptions>): Plugin[];
|
|
49
|
-
/**
|
|
50
|
-
* Remove any temporary `vite.config.ts.timestamp-*` files.
|
|
51
|
-
*/
|
|
52
|
-
declare function cleanup(options?: Partial<CommonOptions>): Plugin;
|
|
53
|
-
|
|
54
|
-
export { cleanup, coverage, library, tsconfigPaths };
|
|
55
|
-
export type { BundleOptions, CommonOptions, LibraryOptions, TSConfigPathsOptions };
|
package/dist/index.mjs
DELETED
|
@@ -1,410 +0,0 @@
|
|
|
1
|
-
import { existsSync, readdirSync, rmSync, readFileSync } from 'node:fs';
|
|
2
|
-
import { unlink, readdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
-
import { builtinModules } from 'node:module';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
import process from 'node:process';
|
|
6
|
-
import c from 'picocolors';
|
|
7
|
-
import ts from 'typescript';
|
|
8
|
-
import dts__default from 'vite-plugin-dts';
|
|
9
|
-
import * as dts from 'vite-plugin-dts';
|
|
10
|
-
export { dts };
|
|
11
|
-
import { normalizePath } from 'vite';
|
|
12
|
-
|
|
13
|
-
function log(text) {
|
|
14
|
-
console.log(`${c.cyan("[vite:lib]")} ${text}`);
|
|
15
|
-
}
|
|
16
|
-
function logWarn(text) {
|
|
17
|
-
console.warn(`${c.yellow("[vite:lib]")} ${text}`);
|
|
18
|
-
}
|
|
19
|
-
function logError(text) {
|
|
20
|
-
console.error(`${c.red("[vite:lib]")} ${text}`);
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
async function generateMTSDeclarations(typesDir, deleteSourceFiles, verbose) {
|
|
24
|
-
const files = await collectFiles(typesDir);
|
|
25
|
-
for (const file of files) {
|
|
26
|
-
await createMTSImports(file, verbose);
|
|
27
|
-
if (deleteSourceFiles) {
|
|
28
|
-
unlink(file);
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
log(`Generated ${files.length} MTS declarations.`);
|
|
32
|
-
}
|
|
33
|
-
async function collectFiles(dir) {
|
|
34
|
-
const entries = await readdir(dir, {
|
|
35
|
-
recursive: false,
|
|
36
|
-
// does not provide full path to nested files
|
|
37
|
-
withFileTypes: true
|
|
38
|
-
});
|
|
39
|
-
const files = entries.filter((entry) => entry.isFile());
|
|
40
|
-
const nestedFiles = await Promise.all(
|
|
41
|
-
entries.filter((entry) => entry.isDirectory()).map((entry) => collectFiles(normalizePath(path.join(dir, entry.name))))
|
|
42
|
-
);
|
|
43
|
-
return files.map((file) => normalizePath(path.join(dir, file.name))).concat(...nestedFiles);
|
|
44
|
-
}
|
|
45
|
-
async function createMTSImports(file, verbose) {
|
|
46
|
-
const content = await readFile(file, "utf-8");
|
|
47
|
-
const lines = content.split("\n");
|
|
48
|
-
const modified = lines.map((line) => transformLine(file, line, verbose));
|
|
49
|
-
const targetFile = file.replace(".d.ts", ".d.mts");
|
|
50
|
-
await writeFile(targetFile, modified.join("\n"));
|
|
51
|
-
}
|
|
52
|
-
function transformLine(file, line, verbose) {
|
|
53
|
-
return (
|
|
54
|
-
// eslint-disable-next-line style/quotes
|
|
55
|
-
transformStaticImport(file, line, "'", verbose) ?? transformStaticImport(file, line, '"', verbose) ?? // eslint-disable-next-line style/quotes
|
|
56
|
-
transformExport(file, line, "'", verbose) ?? transformExport(file, line, '"', verbose) ?? line
|
|
57
|
-
);
|
|
58
|
-
}
|
|
59
|
-
function transformStaticImport(file, line, quote, verbose) {
|
|
60
|
-
const importPathMarker = `from ${quote}`;
|
|
61
|
-
const isStaticImport = line.includes("import ") && line.includes(`${importPathMarker}.`);
|
|
62
|
-
if (!isStaticImport) {
|
|
63
|
-
return void 0;
|
|
64
|
-
}
|
|
65
|
-
const importStartIndex = line.lastIndexOf(importPathMarker);
|
|
66
|
-
const importPath = line.substring(
|
|
67
|
-
importStartIndex + importPathMarker.length,
|
|
68
|
-
line.length - 2
|
|
69
|
-
);
|
|
70
|
-
const resolvedImport = path.resolve(path.dirname(file), importPath);
|
|
71
|
-
if (existsSync(resolvedImport)) {
|
|
72
|
-
if (verbose) {
|
|
73
|
-
log(`got index import ${resolvedImport}`);
|
|
74
|
-
}
|
|
75
|
-
return `${line.substring(0, line.length - 2)}/index.mjs${quote};`;
|
|
76
|
-
}
|
|
77
|
-
return `${line.substring(0, line.length - 2)}.mjs${quote};`;
|
|
78
|
-
}
|
|
79
|
-
function transformExport(file, line, quote, verbose) {
|
|
80
|
-
const exportPathMarker = ` from ${quote}`;
|
|
81
|
-
const isStaticExport = line.includes("export ") && line.includes(`${exportPathMarker}.`);
|
|
82
|
-
if (!isStaticExport) {
|
|
83
|
-
return void 0;
|
|
84
|
-
}
|
|
85
|
-
const exportStartIndex = line.lastIndexOf(exportPathMarker);
|
|
86
|
-
const exportPath = line.substring(
|
|
87
|
-
exportStartIndex + exportPathMarker.length,
|
|
88
|
-
line.length - 2
|
|
89
|
-
);
|
|
90
|
-
const resolvedExport = path.resolve(path.dirname(file), exportPath);
|
|
91
|
-
if (existsSync(resolvedExport)) {
|
|
92
|
-
if (verbose) {
|
|
93
|
-
log(`got index export ${resolvedExport}`);
|
|
94
|
-
}
|
|
95
|
-
return `${line.substring(0, line.length - 2)}/index.mjs${quote};`;
|
|
96
|
-
}
|
|
97
|
-
return `${line.substring(0, line.length - 2)}.mjs${quote};`;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
const typesDir = "dist/types";
|
|
101
|
-
const coverage = {
|
|
102
|
-
enabled: !!process.env.COVERAGE,
|
|
103
|
-
include: ["src/**/*.*"],
|
|
104
|
-
exclude: ["*.d.ts", "*.ohm", ".gitignore"],
|
|
105
|
-
provider: "v8"
|
|
106
|
-
};
|
|
107
|
-
const COMMON_DEFAULTS = {
|
|
108
|
-
verbose: false
|
|
109
|
-
};
|
|
110
|
-
const TS_CONFIG_PATHS_OPTIONS = {
|
|
111
|
-
...COMMON_DEFAULTS,
|
|
112
|
-
tsconfig: "./tsconfig.json"
|
|
113
|
-
};
|
|
114
|
-
const BUNDLE_DEFAULTS = {
|
|
115
|
-
builtin: false,
|
|
116
|
-
dependencies: false,
|
|
117
|
-
devDependencies: true,
|
|
118
|
-
peerDependencies: false,
|
|
119
|
-
exclude: [],
|
|
120
|
-
include: [],
|
|
121
|
-
nodeModules: false
|
|
122
|
-
};
|
|
123
|
-
const LIBRARY_DEFAULTS = {
|
|
124
|
-
...TS_CONFIG_PATHS_OPTIONS,
|
|
125
|
-
cleanup: true,
|
|
126
|
-
entry: "src/index.ts",
|
|
127
|
-
bundle: {},
|
|
128
|
-
formats: ["es"],
|
|
129
|
-
manifest: "package.json"
|
|
130
|
-
};
|
|
131
|
-
function mergeWithDefaults(options) {
|
|
132
|
-
return {
|
|
133
|
-
...LIBRARY_DEFAULTS,
|
|
134
|
-
...options
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
function tsconfigPaths(options = {}) {
|
|
138
|
-
const tsconfig = options.tsconfig ?? TS_CONFIG_PATHS_OPTIONS.tsconfig;
|
|
139
|
-
const verbose = options.verbose ?? TS_CONFIG_PATHS_OPTIONS.verbose;
|
|
140
|
-
return {
|
|
141
|
-
name: "vite-plugin-lib:alias",
|
|
142
|
-
enforce: "pre",
|
|
143
|
-
config: async (config) => {
|
|
144
|
-
const tsconfigPath = path.resolve(config.root ?? ".", tsconfig);
|
|
145
|
-
const { baseUrl, paths } = await readConfig(tsconfigPath);
|
|
146
|
-
if (!baseUrl || !paths) {
|
|
147
|
-
log(`No paths found in ${tsconfig}.`);
|
|
148
|
-
return config;
|
|
149
|
-
}
|
|
150
|
-
const pathToAlias = pathToAliasFactory(tsconfigPath, baseUrl, verbose);
|
|
151
|
-
const aliasOptions = Object.entries(paths).map(pathToAlias).filter((alias) => alias !== void 0);
|
|
152
|
-
if (aliasOptions.length > 0) {
|
|
153
|
-
logInjectedAliases(aliasOptions, config, verbose);
|
|
154
|
-
}
|
|
155
|
-
const existingAlias = transformExistingAlias(config.resolve?.alias);
|
|
156
|
-
return {
|
|
157
|
-
...config,
|
|
158
|
-
resolve: {
|
|
159
|
-
...config.resolve,
|
|
160
|
-
alias: [...existingAlias, ...aliasOptions]
|
|
161
|
-
}
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
function buildConfig({
|
|
167
|
-
entry,
|
|
168
|
-
formats,
|
|
169
|
-
manifest,
|
|
170
|
-
name,
|
|
171
|
-
bundle,
|
|
172
|
-
verbose
|
|
173
|
-
}) {
|
|
174
|
-
const bundleWithDefaults = { ...BUNDLE_DEFAULTS, ...bundle };
|
|
175
|
-
const packagesToExternalize = [
|
|
176
|
-
...getBuiltinModules(bundleWithDefaults),
|
|
177
|
-
...getDependencies(manifest, bundleWithDefaults, verbose),
|
|
178
|
-
...bundleWithDefaults.exclude
|
|
179
|
-
];
|
|
180
|
-
if (!bundleWithDefaults.nodeModules) {
|
|
181
|
-
packagesToExternalize.push(/node_modules/);
|
|
182
|
-
if (verbose) {
|
|
183
|
-
log(`Externalized node_modules.`);
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
return {
|
|
187
|
-
name: "vite-plugin-lib:build",
|
|
188
|
-
enforce: "pre",
|
|
189
|
-
apply: "build",
|
|
190
|
-
config: async (config) => {
|
|
191
|
-
return {
|
|
192
|
-
...config,
|
|
193
|
-
build: {
|
|
194
|
-
...config.build,
|
|
195
|
-
lib: {
|
|
196
|
-
...config.build?.lib,
|
|
197
|
-
entry: path.resolve(config.root ?? ".", entry),
|
|
198
|
-
formats,
|
|
199
|
-
name,
|
|
200
|
-
fileName: (format) => formatToFileName(entry, format)
|
|
201
|
-
},
|
|
202
|
-
rollupOptions: {
|
|
203
|
-
external: (source, _importer, _isResolved) => {
|
|
204
|
-
const shouldBeExternalized = packagesToExternalize.some((rule) => matchesRule(source, rule));
|
|
205
|
-
const shouldBeBundled = bundleWithDefaults.include.some((rule) => matchesRule(source, rule));
|
|
206
|
-
return shouldBeExternalized && !shouldBeBundled;
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
};
|
|
213
|
-
}
|
|
214
|
-
function matchesRule(source, rule) {
|
|
215
|
-
return typeof rule === "string" ? rule === source : rule.test(source);
|
|
216
|
-
}
|
|
217
|
-
function getDependencies(manifest, bundle, verbose) {
|
|
218
|
-
try {
|
|
219
|
-
const content = readFileSync(manifest, { encoding: "utf-8" });
|
|
220
|
-
const { dependencies = {}, devDependencies = {}, peerDependencies = {} } = JSON.parse(content);
|
|
221
|
-
const dependenciesToExternalize = [];
|
|
222
|
-
if (!bundle.dependencies) {
|
|
223
|
-
const names = Object.keys(dependencies);
|
|
224
|
-
dependenciesToExternalize.push(...names);
|
|
225
|
-
if (verbose) {
|
|
226
|
-
log(`Externalized ${names.length} dependencies.`);
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
if (!bundle.devDependencies) {
|
|
230
|
-
const names = Object.keys(devDependencies);
|
|
231
|
-
dependenciesToExternalize.push(...names);
|
|
232
|
-
if (verbose) {
|
|
233
|
-
log(`Externalized ${names.length} devDependencies.`);
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
if (!bundle.peerDependencies) {
|
|
237
|
-
const names = Object.keys(peerDependencies);
|
|
238
|
-
dependenciesToExternalize.push(...names);
|
|
239
|
-
if (verbose) {
|
|
240
|
-
log(`Externalized ${names.length} peerDependencies.`);
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
return dependenciesToExternalize;
|
|
244
|
-
} catch (error) {
|
|
245
|
-
const message = getErrorMessage(error);
|
|
246
|
-
logError(`Could not read ${c.green(manifest)}: ${message}`);
|
|
247
|
-
throw error;
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
function getBuiltinModules(bundle) {
|
|
251
|
-
if (bundle.builtin) {
|
|
252
|
-
return [];
|
|
253
|
-
}
|
|
254
|
-
log("Externalized builtin modules.");
|
|
255
|
-
return [...builtinModules, /node:/, /bun:/, /deno:/];
|
|
256
|
-
}
|
|
257
|
-
function logInjectedAliases(aliasOptions, config, verbose) {
|
|
258
|
-
log(`Injected ${c.green(aliasOptions.length)} aliases.`);
|
|
259
|
-
if (!verbose) {
|
|
260
|
-
return;
|
|
261
|
-
}
|
|
262
|
-
const base = `${path.resolve(config.root ?? ".")}/`;
|
|
263
|
-
aliasOptions.map(
|
|
264
|
-
({ find, replacement }) => ` ${c.gray(">")} ${c.green(find.toString())} ${c.gray(
|
|
265
|
-
c.bold("->")
|
|
266
|
-
)} ${c.green(replacement.replace(base, ""))}`
|
|
267
|
-
).forEach(log);
|
|
268
|
-
}
|
|
269
|
-
function pathToAliasFactory(tsconfigPath, baseUrl, verbose) {
|
|
270
|
-
return ([alias, replacements]) => {
|
|
271
|
-
if (replacements.length === 0) {
|
|
272
|
-
if (verbose) {
|
|
273
|
-
logWarn(`No replacements for alias ${c.green(alias)}.`);
|
|
274
|
-
}
|
|
275
|
-
return void 0;
|
|
276
|
-
}
|
|
277
|
-
if (verbose && replacements.length > 1) {
|
|
278
|
-
logWarn(`Found more than one replacement for alias ${c.green(alias)}.`);
|
|
279
|
-
logWarn("Using the first existing replacement.");
|
|
280
|
-
}
|
|
281
|
-
const find = alias.replace("/*", "");
|
|
282
|
-
const replacement = getFirstExistingReplacement(
|
|
283
|
-
tsconfigPath,
|
|
284
|
-
baseUrl,
|
|
285
|
-
replacements,
|
|
286
|
-
find
|
|
287
|
-
);
|
|
288
|
-
if (!replacement) {
|
|
289
|
-
if (verbose) {
|
|
290
|
-
logWarn(`No replacement found for alias ${c.green(alias)}.`);
|
|
291
|
-
}
|
|
292
|
-
return void 0;
|
|
293
|
-
}
|
|
294
|
-
return {
|
|
295
|
-
find,
|
|
296
|
-
replacement
|
|
297
|
-
};
|
|
298
|
-
};
|
|
299
|
-
}
|
|
300
|
-
function getFirstExistingReplacement(tsconfigPath, baseUrl, replacements, find, verbose) {
|
|
301
|
-
for (const replacement of replacements) {
|
|
302
|
-
const resolvedReplacement = path.resolve(
|
|
303
|
-
tsconfigPath,
|
|
304
|
-
baseUrl,
|
|
305
|
-
replacement.replace("/*", "") ?? find
|
|
306
|
-
);
|
|
307
|
-
if (existsSync(resolvedReplacement)) {
|
|
308
|
-
return resolvedReplacement;
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
return void 0;
|
|
312
|
-
}
|
|
313
|
-
function formatToFileName(entry, format) {
|
|
314
|
-
const entryFileName = entry.substring(
|
|
315
|
-
entry.lastIndexOf("/") + 1,
|
|
316
|
-
entry.lastIndexOf(".")
|
|
317
|
-
);
|
|
318
|
-
if (format === "es") {
|
|
319
|
-
return `${entryFileName}.mjs`;
|
|
320
|
-
}
|
|
321
|
-
if (format === "cjs") {
|
|
322
|
-
return `${entryFileName}.cjs`;
|
|
323
|
-
}
|
|
324
|
-
return `${entryFileName}.${format}.js`;
|
|
325
|
-
}
|
|
326
|
-
function library(options = {}) {
|
|
327
|
-
const mergedOptions = mergeWithDefaults(options);
|
|
328
|
-
const plugins = [
|
|
329
|
-
tsconfigPaths(mergedOptions),
|
|
330
|
-
buildConfig(mergedOptions),
|
|
331
|
-
dts__default({
|
|
332
|
-
cleanVueFileName: true,
|
|
333
|
-
copyDtsFiles: true,
|
|
334
|
-
include: `${path.resolve(mergedOptions.entry, "..")}/**`,
|
|
335
|
-
outDir: typesDir,
|
|
336
|
-
staticImport: true,
|
|
337
|
-
tsconfigPath: mergedOptions.tsconfig,
|
|
338
|
-
afterBuild: async () => {
|
|
339
|
-
if (includesESFormat(mergedOptions.formats)) {
|
|
340
|
-
await generateMTSDeclarations(
|
|
341
|
-
typesDir,
|
|
342
|
-
mergedOptions.formats?.length === 1,
|
|
343
|
-
options.verbose
|
|
344
|
-
);
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
})
|
|
348
|
-
];
|
|
349
|
-
if (mergedOptions.cleanup) {
|
|
350
|
-
plugins.push(cleanup(mergedOptions));
|
|
351
|
-
}
|
|
352
|
-
return plugins;
|
|
353
|
-
}
|
|
354
|
-
function transformExistingAlias(alias) {
|
|
355
|
-
if (!alias) {
|
|
356
|
-
return [];
|
|
357
|
-
}
|
|
358
|
-
if (Array.isArray(alias)) {
|
|
359
|
-
return alias;
|
|
360
|
-
}
|
|
361
|
-
return Object.entries(alias).map(([find, replacement]) => ({
|
|
362
|
-
find,
|
|
363
|
-
replacement
|
|
364
|
-
}));
|
|
365
|
-
}
|
|
366
|
-
async function readConfig(configPath) {
|
|
367
|
-
try {
|
|
368
|
-
const configFileText = await readFile(configPath, { encoding: "utf-8" });
|
|
369
|
-
const { config } = ts.parseConfigFileTextToJson(configPath, configFileText);
|
|
370
|
-
const { options } = ts.parseJsonConfigFileContent(
|
|
371
|
-
config,
|
|
372
|
-
ts.sys,
|
|
373
|
-
path.dirname(configPath)
|
|
374
|
-
);
|
|
375
|
-
return options;
|
|
376
|
-
} catch (error) {
|
|
377
|
-
const message = getErrorMessage(error);
|
|
378
|
-
logError(`Could not read ${configPath}: ${message}`);
|
|
379
|
-
throw error;
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
function includesESFormat(formats) {
|
|
383
|
-
return formats?.includes("es") ?? true;
|
|
384
|
-
}
|
|
385
|
-
function getErrorMessage(error) {
|
|
386
|
-
const isObject = typeof error === "object" && error !== null && "message" in error;
|
|
387
|
-
return isObject ? error.message : String(error);
|
|
388
|
-
}
|
|
389
|
-
function cleanup(options = {}) {
|
|
390
|
-
const verbose = options.verbose ?? COMMON_DEFAULTS.verbose;
|
|
391
|
-
return {
|
|
392
|
-
name: "vite-plugin-lib:cleanup",
|
|
393
|
-
enforce: "post",
|
|
394
|
-
closeBundle: () => {
|
|
395
|
-
let deletedCount = 0;
|
|
396
|
-
readdirSync(".").forEach((file) => {
|
|
397
|
-
if (!file.startsWith("vite.config.ts.timestamp-")) {
|
|
398
|
-
return;
|
|
399
|
-
}
|
|
400
|
-
rmSync(`./${file}`);
|
|
401
|
-
deletedCount++;
|
|
402
|
-
});
|
|
403
|
-
if (verbose) {
|
|
404
|
-
log(`Removed ${deletedCount} temporary files.`);
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
};
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
export { cleanup, coverage, library, tsconfigPaths };
|