@vixt/core 0.5.17 → 0.6.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.
@@ -1,457 +0,0 @@
1
- import { loadConfig } from 'c12';
2
- import fs from 'fs-extra';
3
- import path, { resolve, normalize } from 'pathe';
4
- import { env, cwd } from 'node:process';
5
- import { cac } from 'cac';
6
- import { findUpSync } from 'find-up';
7
- import { loadEnv as loadEnv$1 } from 'vite';
8
- import defu from 'defu';
9
- import { pathToFileURL } from 'mlly';
10
- import 'tsx/esm';
11
- import Checker from 'vite-plugin-checker';
12
-
13
- function defineVixtConfig(input) {
14
- return input;
15
- }
16
- async function loadVixtConfig(opts) {
17
- const result = await loadConfig({
18
- name: "vixt",
19
- rcFile: false,
20
- ...opts
21
- });
22
- const { config, cwd } = result;
23
- config.rootDir ??= cwd;
24
- config.buildDir ??= resolve(config.rootDir, ".vixt");
25
- config.buildTypesDir ??= resolve(config.buildDir, "types");
26
- config.buildLayersDir ??= resolve(config.buildDir, "layers");
27
- config.buildImportsDir ??= resolve(config.buildDir, "imports");
28
- config.srcDir ??= resolve(config.rootDir, "src");
29
- return result;
30
- }
31
- function applyLayers(layers, config) {
32
- const { rootDir, buildLayersDir } = config;
33
- return layers.filter((e) => e.cwd).map((layer) => {
34
- const meta = layer.config?.meta ?? {};
35
- const layerName = meta.name || layer.cwd.split("/").pop();
36
- if (!isSamePath(layer.cwd, resolve(rootDir))) {
37
- meta.alias = `#/layers/${layerName}`;
38
- }
39
- if (layer.cwd?.includes("node_modules")) {
40
- const newCwd = resolve(buildLayersDir, layerName);
41
- fs.removeSync(newCwd);
42
- fs.copySync(layer.cwd, newCwd, {
43
- filter: (src) => {
44
- const nodeModulesPath = resolve(layer.cwd, "node_modules");
45
- const tsConfigPath = resolve(layer.cwd, "tsconfig.json");
46
- return !isSamePath(src, nodeModulesPath) && !isSamePath(src, tsConfigPath);
47
- }
48
- });
49
- layer.cwd = newCwd;
50
- }
51
- layer.config ??= {};
52
- layer.config.rootDir ??= layer.cwd;
53
- layer.config.srcDir ??= resolve(layer.config.rootDir, "src");
54
- return { ...layer, meta };
55
- });
56
- }
57
- function isSamePath(a, b) {
58
- return normalize(a) === normalize(b);
59
- }
60
- function resolveLayersDirs(layers = []) {
61
- const dirs = {};
62
- for (const layer of layers) {
63
- const srcPath = layer.config.srcDir;
64
- const isExist = fs.existsSync(srcPath);
65
- const contents = isExist ? fs.readdirSync(srcPath) : [];
66
- for (const content of contents) {
67
- const fileOrDirPath = resolve(srcPath, content);
68
- if (fs.statSync(fileOrDirPath).isDirectory()) {
69
- dirs[content] ??= [];
70
- dirs[content].push(fileOrDirPath);
71
- }
72
- }
73
- }
74
- return dirs;
75
- }
76
-
77
- function loadEnv(mode, envDir, prefixes) {
78
- const parsedArgv = cac().parse();
79
- mode = mode || parsedArgv.options.mode || parsedArgv.options.m || env.NODE_ENV;
80
- return {
81
- MODE: mode,
82
- DEV: env.NODE_ENV !== "production",
83
- PROD: env.NODE_ENV === "production",
84
- ...loadWorkspaceEnv(mode, prefixes),
85
- ...loadEnv$1(mode, envDir || cwd(), prefixes)
86
- };
87
- }
88
- function findUpWorkspaceDir() {
89
- const workspaceManifestLocation = findUpSync(["pnpm-workspace.yaml", "pnpm-workspace.yml"]);
90
- return workspaceManifestLocation && path.dirname(workspaceManifestLocation);
91
- }
92
- function loadWorkspaceEnv(mode, prefixes) {
93
- const workspaceDir = findUpWorkspaceDir();
94
- return workspaceDir ? loadEnv$1(mode, workspaceDir, prefixes) : {};
95
- }
96
-
97
- function defineVitePlugin(pluginFn) {
98
- return pluginFn;
99
- }
100
- function defineVixtModule(definition) {
101
- if (typeof definition == "function")
102
- return defineVixtModule({ setup: definition });
103
- const module = definition;
104
- function getOptions(inlineOptions, vixt) {
105
- const configKey = module.meta?.configKey || module.meta?.name;
106
- const configOptions = configKey ? vixt.options[configKey] : {};
107
- const defaultOptions = typeof module.defaults === "function" ? module.defaults(vixt) : module.defaults;
108
- const resolvedOptions = defu(inlineOptions, configOptions, defaultOptions);
109
- if (configKey) {
110
- vixt.options[configKey] = resolvedOptions;
111
- }
112
- return resolvedOptions;
113
- }
114
- function normalizedModule(inlineOptions, vixt) {
115
- const options = getOptions(inlineOptions, vixt);
116
- return module.setup?.(options, vixt);
117
- }
118
- normalizedModule.getMeta = () => module.meta;
119
- normalizedModule.getOptions = getOptions;
120
- return normalizedModule;
121
- }
122
- function installModule(module, inlineOptions, vixt) {
123
- return module(inlineOptions, vixt);
124
- }
125
- async function applyLayerModules(layers) {
126
- const { modules: modulesDirs = [] } = resolveLayersDirs(layers);
127
- const modules = [];
128
- for (const m of modulesDirs.reverse()) {
129
- if (fs.existsSync(m)) {
130
- const files = fs.readdirSync(m);
131
- for (const f of files.filter((f2) => !f2.includes(".") || /\.[jt]s$/.test(f2))) {
132
- try {
133
- const fileURL = pathToFileURL(path.resolve(m, f));
134
- const module = await import(
135
- /* @vite-ignore */
136
- fileURL
137
- ).then((m2) => m2.default);
138
- modules.push(module);
139
- } catch (error) {
140
- console.error("[VixtModule Error]:", error);
141
- }
142
- }
143
- }
144
- }
145
- return modules;
146
- }
147
-
148
- const name$1 = "vixt:config";
149
- const config = defineVixtModule({
150
- meta: { name: name$1 },
151
- setup(_, vixt) {
152
- let env;
153
- return {
154
- name: name$1,
155
- enforce: "pre",
156
- config(config2) {
157
- const { rootDir, buildDir, srcDir, app } = vixt.options;
158
- const defaultAlias = {
159
- "@": srcDir,
160
- "~": srcDir,
161
- "@@": rootDir,
162
- "~~": rootDir
163
- };
164
- for (const layer of vixt._layers) {
165
- if (layer.meta?.alias) {
166
- defaultAlias[layer.meta.alias] = layer.cwd;
167
- }
168
- }
169
- defaultAlias["#"] = buildDir;
170
- env = loadEnv(config2.mode, config2.envDir, config2.envPrefix);
171
- const defineEnv = Object.fromEntries(
172
- Object.entries(env).filter(([k]) => !["MODE", "DEV", "PROD"].includes(k)).map(([k, v]) => [`import.meta.env.${k}`, JSON.stringify(v)])
173
- );
174
- return {
175
- root: rootDir,
176
- base: app?.baseURL,
177
- resolve: {
178
- alias: defaultAlias
179
- },
180
- define: defineEnv
181
- };
182
- },
183
- configResolved(config2) {
184
- Object.assign(config2.env, { ...env, ...config2.env });
185
- vixt.options.vite = config2;
186
- },
187
- configureServer(server) {
188
- const mode = server.config.mode;
189
- const watchFiles = [];
190
- const configFiles = vixt._layers.map((layer) => layer.configFile).filter((e) => !e.includes("node_modules"));
191
- const modulesDirs = vixt._layers.map((layer) => path.resolve(layer.config.srcDir, "modules")).filter((e) => !e.includes("node_modules"));
192
- watchFiles.push(...configFiles, ...modulesDirs);
193
- const workspaceManifestLocation = findUpSync(["pnpm-workspace.yaml", "pnpm-workspace.yml"]);
194
- if (workspaceManifestLocation) {
195
- const workspaceDir = path.dirname(workspaceManifestLocation);
196
- const envFiles = [`${workspaceDir}/.env`, `${workspaceDir}/.env.local`, `${workspaceDir}/.env.${mode}`, `${workspaceDir}/.env.${mode}.local`];
197
- watchFiles.push(...envFiles);
198
- }
199
- server.watcher.add(watchFiles);
200
- server.watcher.on("all", (_2, file) => {
201
- const match = watchFiles.some((e) => path.normalize(file).match(e));
202
- if (match)
203
- server.restart();
204
- });
205
- }
206
- };
207
- }
208
- });
209
-
210
- function generateTsConfig(options, vixt) {
211
- const { buildDir } = vixt.options;
212
- const codePath = path.resolve(buildDir, "tsconfig.json");
213
- const code = JSON.stringify(options.tsConfig, null, 2);
214
- fs.outputFileSync(codePath, code);
215
- }
216
- function generateVixtDts(options, vixt) {
217
- const { buildDir } = vixt.options;
218
- const codePath = path.resolve(buildDir, "vixt.d.ts");
219
- const code = options.references?.map((reference) => {
220
- if (typeof reference === "string") {
221
- return `/// <reference path="${reference}" />`;
222
- } else if (typeof reference === "object" && reference.path && reference.content) {
223
- fs.outputFileSync(path.resolve(buildDir, reference.path), reference.content);
224
- return `/// <reference path="${reference.path}" />`;
225
- } else {
226
- return "";
227
- }
228
- }).concat("export {}").join("\n");
229
- if (code)
230
- fs.outputFileSync(codePath, code);
231
- }
232
- function genarateShim(options, vixt) {
233
- if (!options.shim)
234
- return;
235
- const { buildTypesDir } = vixt.options;
236
- const code = `
237
- declare module '*.vue' {
238
- import type { DefineComponent } from 'vue'
239
-
240
- const component: DefineComponent
241
- export default component
242
- }
243
- `;
244
- const codePath = path.resolve(buildTypesDir, "vue-shim.d.ts");
245
- fs.outputFileSync(codePath, code);
246
- }
247
- function generateEnvDts(env, vixt) {
248
- const { buildTypesDir } = vixt.options;
249
- const codePath = path.resolve(buildTypesDir, "vite-env.d.ts");
250
- const values = Object.entries(env).map(([key, value]) => `/** ${key}=${value} */
251
- ${key}: ${typeof value}`).join("\n ");
252
- const code = `interface ImportMeta {
253
- readonly env: ImportMetaEnv
254
- }
255
- interface ImportMetaEnv {
256
- ${values}
257
- }
258
- `;
259
- fs.outputFileSync(codePath, code);
260
- }
261
- const name = "vixt:typescript";
262
- const typescript = defineVixtModule({
263
- meta: { name, configKey: "typescript" },
264
- defaults(vixt) {
265
- const { rootDir, srcDir } = vixt.options;
266
- const rootAlias = {};
267
- if (rootDir)
268
- rootAlias["@@/*"] = rootAlias["~~/*"] = [`${rootDir}/*`];
269
- const srcAlias = {};
270
- if (srcDir)
271
- srcAlias["@/*"] = srcAlias["~/*"] = [`${srcDir}/*`];
272
- const layersDirs = [];
273
- const layersAlias = {};
274
- for (const layer of vixt._layers) {
275
- layersDirs.push(layer.cwd);
276
- if (layer.meta?.alias)
277
- layersAlias[`${layer.meta.alias}/*`] = [`${layer.cwd}/*`];
278
- }
279
- return {
280
- tsConfig: {
281
- extends: "@vue/tsconfig/tsconfig.dom.json",
282
- compilerOptions: {
283
- baseUrl: rootDir,
284
- paths: { "#/*": ["./*"], ...layersAlias, ...rootAlias, ...srcAlias },
285
- types: ["vite/client"]
286
- },
287
- include: ["./**/*", ...layersDirs]
288
- },
289
- typeCheck: {
290
- enableBuild: false,
291
- overlay: { initialIsOpen: false }
292
- }
293
- };
294
- },
295
- setup(options, vixt) {
296
- return [
297
- {
298
- name,
299
- configResolved(config) {
300
- generateTsConfig(options, vixt);
301
- generateVixtDts(options, vixt);
302
- genarateShim(options, vixt);
303
- generateEnvDts(config.env, vixt);
304
- }
305
- },
306
- Checker(options.typeCheck ?? {})
307
- ];
308
- }
309
- });
310
-
311
- function generateAppConfig(vixt) {
312
- const { buildImportsDir } = vixt.options;
313
- let appConfigsImportTemplate = "";
314
- let appConfigsMergeTemplate = "";
315
- let i = 0;
316
- for (const layer of vixt._layers) {
317
- const appConfigPath = path.resolve(layer.config.srcDir, "app.config.ts");
318
- if (fs.existsSync(appConfigPath)) {
319
- const appConfigName = `__app_config_${i}`;
320
- appConfigsImportTemplate += `import ${appConfigName} from '${appConfigPath}'
321
- `;
322
- appConfigsMergeTemplate += `${appConfigName}, `;
323
- i++;
324
- }
325
- }
326
- const globalAppConfigKey = "__VIXT_APP_CONFIG";
327
- const appConfigTemplate = `
328
- import { defu } from 'defu'
329
- ${appConfigsImportTemplate}
330
- const appConfig = defu(${appConfigsMergeTemplate}{})
331
- globalThis.${globalAppConfigKey} = appConfig
332
- `;
333
- fs.outputFileSync(path.resolve(buildImportsDir, `app.config.ts`), `// Generated by Vixt
334
- // @ts-nocheck
335
- import type { VixtAppConfig } from '@vixt/core/client'
336
-
337
- export const useAppConfig = () => globalThis.${globalAppConfigKey} as VixtAppConfig
338
- `);
339
- return appConfigTemplate;
340
- }
341
-
342
- function generateClient(vixt) {
343
- const { buildImportsDir } = vixt.options;
344
- fs.outputFileSync(
345
- path.resolve(buildImportsDir, `client.ts`),
346
- `// Generated by Vixt
347
- export { defineAppConfig, defineVixtPlugin } from '@vixt/core/client'
348
- `
349
- );
350
- }
351
-
352
- function generateCss(options) {
353
- const cssTemplate = options?.css?.map((css) => `import '${css}'`).join("\n") ?? "";
354
- return cssTemplate;
355
- }
356
-
357
- function resolveHeadTag(tag, attrs) {
358
- const attrsStr = Object.entries(attrs).filter(([k]) => k !== "children").map(([k, v]) => `${k}="${v}"`).join(" ");
359
- return attrs?.children ? `<${tag} ${attrsStr}>${attrs.children}</${tag}>` : `<${tag} ${attrsStr} />`;
360
- }
361
- function generateIndexHtml(options, vixt) {
362
- const { buildDir, rootDir, srcDir } = vixt.options;
363
- const indexHtmlPath = path.resolve(rootDir, "index.html");
364
- if (!fs.existsSync(indexHtmlPath))
365
- fs.outputFileSync(indexHtmlPath, `<!-- Generated by Vixt -->
366
- <!-- This file transform from '${path.basename(buildDir)}/index.html' -->
367
- `);
368
- const { head = {}, rootTag, rootId, entryFile } = options;
369
- const heads = Object.entries(head);
370
- const headTemplate = heads.filter(([k]) => k !== "noscript").map(([tag, attrs]) => attrs.map((e) => resolveHeadTag(tag, e)).reverse()).flat().join("\n");
371
- const noscriptTemplate = heads.filter(([k]) => k === "noscript").map(([tag, attrs]) => attrs.map((e) => resolveHeadTag(tag, e)).reverse()).flat().join("\n");
372
- let { loadingTemplate = "" } = options;
373
- if (!loadingTemplate) {
374
- for (const layer of vixt._layers) {
375
- const loadingTemplatePath = path.resolve(layer.cwd, "loading.html");
376
- if (fs.existsSync(loadingTemplatePath)) {
377
- loadingTemplate = fs.readFileSync(loadingTemplatePath, "utf-8");
378
- break;
379
- }
380
- }
381
- }
382
- const entryFilePath = /&\.|\//.test(entryFile ?? "") ? entryFile : `${srcDir.replace(rootDir, "")}/${entryFile}`;
383
- const code = `<!DOCTYPE html>
384
- <html>
385
- <head>
386
- ${headTemplate}
387
- </head>
388
- <body>
389
- <${rootTag} id="${rootId}">
390
- ${loadingTemplate}
391
- </${rootTag}>
392
- <script type="module" src="${entryFilePath}"><\/script>
393
- ${noscriptTemplate}
394
- </body>
395
- </html>
396
- `;
397
- fs.outputFileSync(path.resolve(buildDir, "index.html"), code);
398
- return code;
399
- }
400
-
401
- function generatePlugins(vixt) {
402
- const { plugins: pluginsDirs = [] } = resolveLayersDirs(vixt._layers);
403
- let pluginsImportTemplate = "";
404
- let pluginsMergeTemplate = "";
405
- let i = 0;
406
- for (const pluginsDir of pluginsDirs.reverse()) {
407
- const files = fs.existsSync(pluginsDir) ? fs.readdirSync(pluginsDir) : [];
408
- for (const f of files.filter((f2) => /[jt]sx?$/.test(f2))) {
409
- const p = path.resolve(pluginsDir, f);
410
- const pluginName = `__plugin_${i}`;
411
- pluginsImportTemplate += `import ${pluginName} from '${p}'
412
- `;
413
- pluginsMergeTemplate += `${pluginName}, `;
414
- i++;
415
- }
416
- }
417
- const pluginsTemplate = `
418
- ${pluginsImportTemplate}
419
- const plugins = [${pluginsMergeTemplate}]
420
- function usePlugins(options) {
421
- for (const plugin of plugins) {
422
- typeof plugin === 'function' && plugin(options)
423
- }
424
- }
425
- `;
426
- return pluginsTemplate;
427
- }
428
-
429
- async function loadVixt(opts) {
430
- const result = await loadVixtConfig(defu(opts, {
431
- defaults: {
432
- modules: [config, typescript]
433
- }
434
- }));
435
- const parsedArgv = cac().parse();
436
- const isForce = !!parsedArgv.options.force;
437
- if (isForce) {
438
- fs.removeSync(result.config.buildDir);
439
- }
440
- result.layers = applyLayers(result.layers ?? [], result.config);
441
- const layerModules = await applyLayerModules(result.layers ?? []);
442
- const vixt = {
443
- options: result.config,
444
- _layers: result.layers ?? [],
445
- _modules: [...result.config.modules ?? [], ...layerModules]
446
- };
447
- return vixt;
448
- }
449
- function createVixtPlugin(loadOptions) {
450
- return defineVitePlugin(async (vixtOptions) => {
451
- const vixt = await loadVixt(defu({ defaults: vixtOptions }, loadOptions));
452
- const plugins = vixt._modules.map((module) => module({}, vixt));
453
- return plugins;
454
- });
455
- }
456
-
457
- export { applyLayerModules, applyLayers, config, createVixtPlugin, defineVitePlugin, defineVixtConfig, defineVixtModule, findUpWorkspaceDir, generateAppConfig, generateClient, generateCss, generateIndexHtml, generatePlugins, installModule, isSamePath, loadEnv, loadVixt, loadVixtConfig, loadWorkspaceEnv, resolveLayersDirs, typescript };