@octohash/vite-config 0.2.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.js ADDED
@@ -0,0 +1,494 @@
1
+ import { __dirname, init_esm_shims } from "./esm-shims-BFgucRO_.js";
2
+ import { isPackageExists } from "local-pkg";
3
+ import { defineConfig as defineConfig$1, mergeConfig } from "vite";
4
+ import { existsSync } from "node:fs";
5
+ import path, { isAbsolute, join, resolve } from "node:path";
6
+ import process from "node:process";
7
+ import deepmerge from "deepmerge";
8
+ import { findUp } from "find-up";
9
+ import { readPackageJSON } from "pkg-types";
10
+ import { fileURLToPath } from "node:url";
11
+ import fsp from "node:fs/promises";
12
+ import { visualizer } from "rollup-plugin-visualizer";
13
+ import { EOL } from "node:os";
14
+ import dayjs from "dayjs";
15
+ import Vue from "@vitejs/plugin-vue";
16
+ import VueJsx from "@vitejs/plugin-vue-jsx";
17
+ import Dts from "vite-plugin-dts";
18
+
19
+ //#region src/utils.ts
20
+ function getProjectType() {
21
+ const htmlPath = join(process.cwd(), "index.html");
22
+ return existsSync(htmlPath) ? "app" : "lib";
23
+ }
24
+ async function loadMergedPackageJson() {
25
+ const root = process.cwd();
26
+ const rootPkgJsonPath = await findUp("pnpm-lock.yaml", {
27
+ cwd: root,
28
+ type: "file"
29
+ });
30
+ const rootPkgJson = rootPkgJsonPath ? await readPackageJSON(rootPkgJsonPath) : {};
31
+ const pkgJson = await readPackageJSON(root);
32
+ return deepmerge(rootPkgJson, pkgJson);
33
+ }
34
+ function extractAuthorInfo(pkgJson) {
35
+ const { author } = pkgJson;
36
+ const isObject = typeof author === "object";
37
+ const name = isObject ? author.name : author;
38
+ const email = isObject ? author.email : void 0;
39
+ const url = isObject ? author.url : void 0;
40
+ return {
41
+ name,
42
+ email,
43
+ url
44
+ };
45
+ }
46
+ async function loadConditionPlugins(conditionPlugins) {
47
+ const plugins = [];
48
+ for (const conditionPlugin of conditionPlugins) if (conditionPlugin.condition) {
49
+ const realPlugins = await conditionPlugin.plugins();
50
+ plugins.push(...realPlugins);
51
+ }
52
+ return plugins.flat();
53
+ }
54
+ function resolveSubOptions(options, key) {
55
+ return typeof options[key] === "boolean" ? {} : options[key] || {};
56
+ }
57
+
58
+ //#endregion
59
+ //#region src/plugins/app-loading/index.ts
60
+ init_esm_shims();
61
+ const INJECT_SCRIPT = `
62
+ <script data-app-loading="inject-js">
63
+ ;(function () {
64
+ const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
65
+ const setting = localStorage.getItem('vueuse-color-scheme') || 'auto'
66
+ if (setting === 'dark' || (prefersDark && setting !== 'light'))
67
+ document.documentElement.classList.toggle('dark', true)
68
+ })()
69
+ </script>
70
+ `;
71
+ async function AppLoadingPlugin(options) {
72
+ const { rootContainer = "app", title = "", filePath = path.join(__dirname, "./default-loading.html") } = options || {};
73
+ const loadingHtml = await getLoadingRawByHtmlTemplate(filePath);
74
+ return {
75
+ name: "vite-plugin-app-loading",
76
+ enforce: "pre",
77
+ transformIndexHtml: {
78
+ order: "pre",
79
+ handler: (html) => {
80
+ const rootContainerPattern = new RegExp(`<div id="${rootContainer}"\\s*></div>`, "i");
81
+ if (!rootContainerPattern.test(html)) return html;
82
+ const processedLoadingHtml = loadingHtml.replace("[app-loading-title]", title);
83
+ const injectedContent = `${INJECT_SCRIPT}${processedLoadingHtml}`;
84
+ return html.replace(rootContainerPattern, `<div id="${rootContainer}">${injectedContent}</div>`);
85
+ }
86
+ }
87
+ };
88
+ }
89
+ async function getLoadingRawByHtmlTemplate(filePath) {
90
+ return await fsp.readFile(filePath, "utf8");
91
+ }
92
+
93
+ //#endregion
94
+ //#region src/ensure.ts
95
+ const scopeUrl = fileURLToPath(new URL(".", import.meta.url));
96
+ const isCwdInScope = isPackageExists("@octohash/vite-config");
97
+ function isPackageInScope(name) {
98
+ return isPackageExists(name, { paths: [scopeUrl] });
99
+ }
100
+ async function ensurePackages(packages) {
101
+ if (process.env.CI || process.stdout.isTTY === false || isCwdInScope === false) return;
102
+ const nonExistingPackages = packages.filter((i) => i && !isPackageInScope(i));
103
+ if (nonExistingPackages.length === 0) return;
104
+ const p = await import("@clack/prompts");
105
+ const result = await p.confirm({ message: `${nonExistingPackages.length === 1 ? "Package is" : "Packages are"} required for this config: ${nonExistingPackages.join(", ")}. Do you want to install them?` });
106
+ if (result) await import("@antfu/install-pkg").then((i) => i.installPackage(nonExistingPackages, { dev: true }));
107
+ }
108
+
109
+ //#endregion
110
+ //#region src/plugins/license.ts
111
+ async function LicensePlugin(options) {
112
+ const licenseText = await generateLicenseText(options || {});
113
+ return {
114
+ name: "vite-plugin-license",
115
+ enforce: "post",
116
+ apply: "build",
117
+ generateBundle: { handler: (_options, bundle) => {
118
+ for (const [, fileContent] of Object.entries(bundle)) if (fileContent.type === "chunk" && fileContent.isEntry) {
119
+ const chunkContent = fileContent;
120
+ const content = chunkContent.code;
121
+ const updatedContent = `${licenseText}${EOL}${content}`;
122
+ fileContent.code = updatedContent;
123
+ }
124
+ } }
125
+ };
126
+ }
127
+ async function generateLicenseText(options) {
128
+ const pkgJson = await loadMergedPackageJson();
129
+ const { name: authorName, email: authorEmail, url: authorUrl } = extractAuthorInfo(pkgJson);
130
+ const { name = pkgJson.name, author = authorName, version = pkgJson.version, description = pkgJson.description, homepage = pkgJson.homepage ?? authorUrl, license, contact = authorEmail, copyright = {
131
+ holder: authorName,
132
+ year: new Date().getFullYear()
133
+ } } = options ?? {};
134
+ const date = dayjs().format("YYYY-MM-DD");
135
+ const lines = [];
136
+ lines.push("/*!");
137
+ if (name) lines.push(` * ${name}`);
138
+ if (version) lines.push(` * Version: ${version}`);
139
+ if (author) lines.push(` * Author: ${author}`);
140
+ if (license) lines.push(` * License: ${license}`);
141
+ if (description) lines.push(` * Description: ${description}`);
142
+ if (homepage) lines.push(` * Homepage: ${homepage}`);
143
+ if (contact) lines.push(` * Contact: ${contact}`);
144
+ if (copyright?.holder) lines.push(` * Copyright (C) ${copyright.year} ${copyright.holder}`);
145
+ if (date) lines.push(` * Date: ${date}`);
146
+ lines.push(" */");
147
+ return lines.join("\n");
148
+ }
149
+
150
+ //#endregion
151
+ //#region src/plugins/common.ts
152
+ async function loadCommonPlugins(options) {
153
+ const { isBuild, visualizer: visualizer$1 = false, license = true, federation } = options;
154
+ ensurePackages([federation ? "@originjs/vite-plugin-federation" : void 0]);
155
+ return await loadConditionPlugins([
156
+ {
157
+ condition: isBuild && !!visualizer$1,
158
+ plugins: () => [visualizer(typeof visualizer$1 === "boolean" ? {
159
+ filename: "./node_modules/.cache/visualizer/stats.html",
160
+ gzipSize: true,
161
+ open: true
162
+ } : visualizer$1)]
163
+ },
164
+ {
165
+ condition: isBuild && !!license,
166
+ plugins: async () => [await LicensePlugin(typeof license === "boolean" ? void 0 : license)]
167
+ },
168
+ {
169
+ condition: !!federation,
170
+ plugins: async () => {
171
+ const module = await import("@originjs/vite-plugin-federation");
172
+ return [module.default(federation)];
173
+ }
174
+ }
175
+ ]);
176
+ }
177
+
178
+ //#endregion
179
+ //#region src/plugins/import-map.ts
180
+ const shimsSubpath = `dist/es-module-shims.js`;
181
+ const providerShimsMap = {
182
+ "jspm.io": `https://ga.jspm.io/npm:es-module-shims@{version}/${shimsSubpath}`,
183
+ "jsdelivr": `https://cdn.jsdelivr.net/npm/es-module-shims@{version}/${shimsSubpath}`,
184
+ "unpkg": `https://unpkg.com/es-module-shims@{version}/${shimsSubpath}`,
185
+ "esm.sh": `https://esm.sh/es-module-shims@{version}/${shimsSubpath}`
186
+ };
187
+ async function ImportMapPlugin(options = {}) {
188
+ await ensurePackages(["vite-plugin-jspm"]);
189
+ const module = await import("vite-plugin-jspm");
190
+ const { defaultProvider = "jspm.io", include = [], exclude = [] } = options;
191
+ const [scan, mapping, post] = await module.default({
192
+ ...options,
193
+ pollyfillProvider: (version) => providerShimsMap[defaultProvider]?.replace("{version}", version)
194
+ });
195
+ const _resolveId = scan.resolveId;
196
+ scan.resolveId = function(id, importer, ctx) {
197
+ if (include.length && !include.includes(id) || exclude.length && exclude.includes(id)) return null;
198
+ return typeof _resolveId === "function" ? _resolveId.call(this, id, importer, ctx) : null;
199
+ };
200
+ const _load = mapping.load;
201
+ mapping.load = function(id) {
202
+ if (include.length && !include.includes(id)) return null;
203
+ return typeof _load === "function" ? _load.call(this, id) : null;
204
+ };
205
+ return [
206
+ scan,
207
+ mapping,
208
+ post
209
+ ];
210
+ }
211
+
212
+ //#endregion
213
+ //#region src/plugins/metadata.ts
214
+ async function MetadataPlugin(options) {
215
+ const { extendMetadata = {} } = options ?? {};
216
+ const pkgJson = await loadMergedPackageJson();
217
+ const { name, description, homepage, license, version } = pkgJson;
218
+ const { name: authorName, email: authorEmail, url: authorUrl } = extractAuthorInfo(pkgJson);
219
+ const buildTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
220
+ return {
221
+ name: "vite-plugin-metadata",
222
+ enforce: "post",
223
+ config: () => {
224
+ return { define: { __VITE_APP_METADATA__: JSON.stringify({
225
+ authorName,
226
+ authorEmail,
227
+ authorUrl,
228
+ buildTime,
229
+ name,
230
+ description,
231
+ homepage,
232
+ license,
233
+ version,
234
+ ...extendMetadata
235
+ }) } };
236
+ }
237
+ };
238
+ }
239
+
240
+ //#endregion
241
+ //#region src/plugins/vue.ts
242
+ async function loadVuePlugins(projectType, options) {
243
+ const { isBuild } = options;
244
+ const isApp = projectType === "app";
245
+ const { devtools = false, i18n = false, imports = isApp, components = isApp, pages = isApp } = resolveSubOptions(options, "vue");
246
+ await ensurePackages([devtools ? "vite-plugin-vue-devtools" : void 0, i18n ? "@intlify/unplugin-vue-i18n" : void 0]);
247
+ return loadConditionPlugins([
248
+ {
249
+ condition: true,
250
+ plugins: () => [Vue(), VueJsx()]
251
+ },
252
+ {
253
+ condition: !isBuild && !!devtools,
254
+ plugins: async () => {
255
+ const module = await import("vite-plugin-vue-devtools");
256
+ return [module.default(typeof devtools === "boolean" ? void 0 : devtools)];
257
+ }
258
+ },
259
+ {
260
+ condition: !!i18n,
261
+ plugins: async () => {
262
+ const module = await import("./vite-CWm9aJTf.js");
263
+ return [module.default(typeof i18n === "boolean" ? {
264
+ compositionOnly: true,
265
+ fullInstall: true,
266
+ runtimeOnly: true
267
+ } : i18n)];
268
+ }
269
+ },
270
+ {
271
+ condition: isApp && !!imports,
272
+ plugins: async () => {
273
+ const module = await import("unplugin-auto-import/vite");
274
+ return [module.default(typeof imports === "boolean" ? {
275
+ dts: "src/typings/auto-imports.d.ts",
276
+ imports: await resolveAutoImports(),
277
+ resolvers: await resolveUIComponentResolvers(),
278
+ dirs: ["src/composables", "src/utils"],
279
+ vueTemplate: true
280
+ } : imports)];
281
+ }
282
+ },
283
+ {
284
+ condition: isApp && !!components,
285
+ plugins: async () => {
286
+ const module = await import("unplugin-vue-components/vite");
287
+ return [module.default(typeof components === "boolean" ? {
288
+ dts: "src/typings/components.d.ts",
289
+ directoryAsNamespace: true
290
+ } : components)];
291
+ }
292
+ },
293
+ {
294
+ condition: isApp && !!pages,
295
+ plugins: async () => {
296
+ const module = await import("unplugin-vue-router/vite");
297
+ return [module.default(typeof pages === "boolean" ? { dts: "src/typings/typed-router.d.ts" } : pages)];
298
+ }
299
+ }
300
+ ]);
301
+ }
302
+ async function resolveAutoImports() {
303
+ const imports = ["vue"];
304
+ if (isPackageExists("vue-router")) imports.push("vue-router");
305
+ if (isPackageExists("pinia")) imports.push("pinia");
306
+ if (isPackageExists("@vueuse/core")) imports.push("@vueuse/core");
307
+ if (isPackageExists("vue-i18n")) imports.push("vue-i18n");
308
+ return imports;
309
+ }
310
+ async function resolveUIComponentResolvers() {
311
+ const resolvers = [];
312
+ if (isPackageExists("ant-design-vue")) {
313
+ const { AntDesignVueResolver } = await import("unplugin-vue-components/resolvers");
314
+ resolvers.push(AntDesignVueResolver({
315
+ importStyle: "css-in-js",
316
+ prefix: ""
317
+ }));
318
+ }
319
+ if (isPackageExists("element-plus")) {
320
+ const { ElementPlusResolver } = await import("unplugin-vue-components/resolvers");
321
+ resolvers.push(...ElementPlusResolver());
322
+ }
323
+ if (isPackageExists("naive-ui")) {
324
+ const { NaiveUiResolver } = await import("unplugin-vue-components/resolvers");
325
+ resolvers.push(NaiveUiResolver());
326
+ }
327
+ if (isPackageExists("vant")) {
328
+ const { VantResolver } = await import("unplugin-vue-components/resolvers");
329
+ resolvers.push(VantResolver());
330
+ }
331
+ return resolvers;
332
+ }
333
+
334
+ //#endregion
335
+ //#region src/plugins/app.ts
336
+ async function loadAppPlugins(options) {
337
+ const { isBuild, dynamicBase, appLoading = true, metadata = true, importMap = false, vue } = options;
338
+ const plugins = await loadCommonPlugins(options);
339
+ plugins.push(await loadConditionPlugins([
340
+ {
341
+ condition: !!dynamicBase,
342
+ plugins: async () => {
343
+ const module = await import("vite-plugin-dynamic-base");
344
+ return [module.dynamicBase({
345
+ publicPath: dynamicBase,
346
+ transformIndexHtml: true
347
+ })];
348
+ }
349
+ },
350
+ {
351
+ condition: !!appLoading,
352
+ plugins: async () => [await AppLoadingPlugin(typeof appLoading === "boolean" ? void 0 : appLoading)]
353
+ },
354
+ {
355
+ condition: !!metadata,
356
+ plugins: async () => {
357
+ return [await MetadataPlugin(typeof metadata === "boolean" ? void 0 : metadata)];
358
+ }
359
+ },
360
+ {
361
+ condition: isBuild && !!importMap,
362
+ plugins: () => {
363
+ return [ImportMapPlugin(typeof importMap === "boolean" ? void 0 : importMap)];
364
+ }
365
+ }
366
+ ]));
367
+ if (vue) plugins.push(await loadVuePlugins("app", options));
368
+ return plugins;
369
+ }
370
+
371
+ //#endregion
372
+ //#region src/config/common.ts
373
+ async function getCommonConfig(options) {
374
+ const { alias = {} } = options;
375
+ const resolvedAlias = Object.entries(alias).reduce((acc, [key, value]) => {
376
+ acc[key] = isAbsolute(value) ? value : resolve(process.cwd(), value);
377
+ return acc;
378
+ }, {});
379
+ return {
380
+ resolve: { alias: {
381
+ "@": resolve(process.cwd(), "./src"),
382
+ ...resolvedAlias
383
+ } },
384
+ build: {
385
+ chunkSizeWarningLimit: 2e3,
386
+ reportCompressedSize: false,
387
+ sourcemap: false
388
+ }
389
+ };
390
+ }
391
+
392
+ //#endregion
393
+ //#region src/config/app.ts
394
+ function defineAppConfig(options) {
395
+ return defineConfig$1(async (config) => {
396
+ const { dynamicBase, vite = {} } = options;
397
+ const { command } = config;
398
+ const isBuild = command === "build";
399
+ const plugins = await loadAppPlugins({
400
+ ...options,
401
+ isBuild
402
+ });
403
+ const appConfig = {
404
+ base: dynamicBase ? "/__dynamic_base__/" : "/",
405
+ plugins,
406
+ build: {
407
+ target: "es2015",
408
+ rollupOptions: { output: {
409
+ assetFileNames: "[ext]/[name]-[hash].[ext]",
410
+ chunkFileNames: "js/[name]-[hash].js",
411
+ entryFileNames: "jse/index-[name]-[hash].js"
412
+ } }
413
+ },
414
+ esbuild: {
415
+ drop: isBuild ? ["debugger"] : [],
416
+ legalComments: "none"
417
+ },
418
+ server: { host: true }
419
+ };
420
+ const mergedCommonConfig = mergeConfig(await getCommonConfig(options), appConfig);
421
+ return mergeConfig(mergedCommonConfig, vite);
422
+ });
423
+ }
424
+
425
+ //#endregion
426
+ //#region src/plugins/lib.ts
427
+ async function loadLibPlugins(options) {
428
+ const { isBuild, dts = true, vue } = options;
429
+ const plugins = await loadCommonPlugins(options);
430
+ plugins.push(await loadConditionPlugins([{
431
+ condition: isBuild && !!dts,
432
+ plugins: () => [Dts(typeof dts === "boolean" ? { logLevel: "error" } : dts)]
433
+ }]));
434
+ if (vue) plugins.push(await loadVuePlugins("lib", options));
435
+ return plugins;
436
+ }
437
+
438
+ //#endregion
439
+ //#region src/config/lib.ts
440
+ function defineLibConfig(options) {
441
+ return defineConfig$1(async (config) => {
442
+ const root = process.cwd();
443
+ const { vite = {} } = options;
444
+ const { command } = config;
445
+ const isBuild = command === "build";
446
+ const plugins = await loadLibPlugins({
447
+ ...options,
448
+ isBuild
449
+ });
450
+ const { dependencies = {}, peerDependencies = {} } = await readPackageJSON(root);
451
+ const externalPackages = [...Object.keys(dependencies), ...Object.keys(peerDependencies)];
452
+ const libConfig = {
453
+ plugins,
454
+ build: {
455
+ lib: {
456
+ entry: "src/index.ts",
457
+ fileName: () => "index.mjs",
458
+ formats: ["es"]
459
+ },
460
+ rollupOptions: { external: (id) => {
461
+ return externalPackages.some((pkg) => id === pkg || id.startsWith(`${pkg}/`));
462
+ } }
463
+ }
464
+ };
465
+ const mergedCommonConfig = mergeConfig(await getCommonConfig(options), libConfig);
466
+ return mergeConfig(mergedCommonConfig, vite);
467
+ });
468
+ }
469
+
470
+ //#endregion
471
+ //#region src/constants.ts
472
+ const VUE_PACKAGES = [
473
+ "vue",
474
+ "nuxt",
475
+ "vitepress"
476
+ ];
477
+
478
+ //#endregion
479
+ //#region src/index.ts
480
+ function defineConfig(options) {
481
+ const resolved = {
482
+ type: getProjectType(),
483
+ vue: VUE_PACKAGES.some((pkg) => isPackageExists(pkg)),
484
+ ...options
485
+ };
486
+ switch (resolved.type) {
487
+ case "app": return defineAppConfig(resolved);
488
+ case "lib": return defineLibConfig(resolved);
489
+ default: throw new Error(`Unsupported project type: ${resolved.type}`);
490
+ }
491
+ }
492
+
493
+ //#endregion
494
+ export { defineConfig };