vize 0.100.0 → 0.103.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/cli.mjs CHANGED
@@ -1,1020 +1,7 @@
1
- import { loadConfig } from "./config.mjs";
2
1
  import { createRequire } from "node:module";
3
- import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
4
- import * as path from "node:path";
5
- import { spawnSync } from "node:child_process";
6
- import { pathToFileURL } from "node:url";
7
2
  //#region src/cli.ts
8
- const require = createRequire(import.meta.url);
9
- const WORKSPACE_BINDING_PATH = "../../vize-native";
10
- const BUILD_BATCH_SIZE = 128;
11
- const BUILD_BATCH_MAX_BYTES = 32 * 1024 * 1024;
12
- const SKIPPED_VUE_FILE_DIRECTORIES = new Set([
13
- "node_modules",
14
- "dist",
15
- ".git",
16
- ".nuxt",
17
- ".output",
18
- ".nitro",
19
- "coverage"
20
- ]);
21
- function isMusl() {
22
- const report = process.report?.getReport();
23
- if (typeof report === "object" && report !== null && "header" in report) return !report.header.glibcVersionRuntime;
24
- try {
25
- return readFileSync(require("child_process").execSync("which ldd").toString().trim(), "utf8").includes("musl");
26
- } catch {
27
- return true;
28
- }
29
- }
30
- function getBindingPackageName() {
31
- const { platform, arch } = process;
32
- switch (platform) {
33
- case "darwin": switch (arch) {
34
- case "x64": return "@vizejs/native-darwin-x64";
35
- case "arm64": return "@vizejs/native-darwin-arm64";
36
- default: throw new Error(`Unsupported architecture on macOS: ${arch}`);
37
- }
38
- case "win32": switch (arch) {
39
- case "x64": return "@vizejs/native-win32-x64-msvc";
40
- case "arm64": return "@vizejs/native-win32-arm64-msvc";
41
- default: throw new Error(`Unsupported architecture on Windows: ${arch}`);
42
- }
43
- case "linux": switch (arch) {
44
- case "x64": return isMusl() ? "@vizejs/native-linux-x64-musl" : "@vizejs/native-linux-x64-gnu";
45
- case "arm64": return isMusl() ? "@vizejs/native-linux-arm64-musl" : "@vizejs/native-linux-arm64-gnu";
46
- default: throw new Error(`Unsupported architecture on Linux: ${arch}`);
47
- }
48
- default: throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`);
49
- }
50
- }
51
- const REQUIRED_BINDINGS = {
52
- build: "compileSfcBatchWithResults",
53
- check: "typeCheck",
54
- fmt: "formatSfc",
55
- lint: "lint"
56
- };
57
- function loadNative(command) {
58
- const attemptedPackages = getAttemptedPackages();
59
- let lastError = null;
60
- const requiredBinding = REQUIRED_BINDINGS[command];
61
- for (const packageName of attemptedPackages) try {
62
- const binding = require(packageName);
63
- if (typeof binding[requiredBinding] !== "function") throw new Error(`${packageName} does not expose the ${command} binding.`);
64
- return binding;
65
- } catch (error) {
66
- lastError = error;
67
- }
68
- console.error(`Failed to load native binding. Tried: ${attemptedPackages.join(", ")}`);
69
- console.error("Try reinstalling: npm install vize");
70
- throw lastError instanceof Error ? lastError : /* @__PURE__ */ new Error("Failed to load native binding");
71
- }
72
- function getAttemptedPackages() {
73
- const platformBindingPackage = getBindingPackageName();
74
- return shouldPreferWorkspaceBinding(resolveWorkspaceBindingPath()) ? [WORKSPACE_BINDING_PATH, platformBindingPackage] : [platformBindingPackage, WORKSPACE_BINDING_PATH];
75
- }
76
- function resolveWorkspaceBindingPath() {
77
- try {
78
- return require.resolve(WORKSPACE_BINDING_PATH);
79
- } catch {
80
- return null;
81
- }
82
- }
83
- function shouldPreferWorkspaceBinding(resolvedPath) {
84
- const override = process.env.VIZE_PREFER_WORKSPACE_BINDING;
85
- if (override === "1" || override === "true") return true;
86
- if (override === "0" || override === "false") return false;
87
- if (resolvedPath == null) return false;
88
- return resolvedPath.includes(`${path.sep}npm${path.sep}vize-native${path.sep}`);
89
- }
90
- function printUsage() {
91
- console.error("Usage: vize <command> [options]");
92
- console.error("Commands: build, fmt, check, lint, upgrade, ready, musea");
93
- }
94
- function printBuildUsage() {
95
- console.error("Usage: vize build [options] [files-or-directories]");
96
- console.error("Options:");
97
- console.error(" -o, --output <dir> Output directory");
98
- console.error(" -f, --format <js|json|stats> Output format");
99
- console.error(" --ssr Enable SSR compilation");
100
- console.error(" --script-ext <mode> preserve or downcompile");
101
- console.error(" -j, --threads <number> Worker thread count");
102
- }
103
- function printFmtUsage() {
104
- console.error("Usage: vize fmt [options] [files-or-directories]");
105
- console.error("Options:");
106
- console.error(" --check Exit with an error if files need formatting");
107
- console.error(" -w, --write Write formatted output");
108
- console.error(" --single-quote Use single quotes");
109
- console.error(" --print-width <number> Maximum line width");
110
- console.error(" --tab-width <number> Indentation width");
111
- console.error(" --use-tabs Indent with tabs");
112
- console.error(" --no-semi Omit semicolons");
113
- }
114
- function printCheckUsage() {
115
- console.error("Usage: vize check [options] [files-or-directories]");
116
- console.error("Options:");
117
- console.error(" -f, --format <text|json> Output format");
118
- console.error(" -q, --quiet Show summary only");
119
- console.error(" --strict Enable strict checks");
120
- console.error(" --show-virtual-ts Print generated Virtual TS");
121
- console.error(" --declaration Emit Vue component .d.ts files");
122
- console.error(" --declaration-dir <dir> Output directory for declarations");
123
- console.error(" --max-warnings <number> Fail when warnings exceed the limit");
124
- console.error(" -c, --config <path> Use a specific vize config file");
125
- console.error(" --no-config Disable config discovery");
126
- console.error("");
127
- console.error("Note: npm `vize check` uses the packaged NAPI checker. Install the Rust CLI for project-backed Corsa diagnostics.");
128
- }
129
- function printUpgradeUsage() {
130
- console.error("Usage: vize upgrade [options]");
131
- console.error("Options:");
132
- console.error(" --package-manager <name> npm, pnpm, yarn, bun, or vp");
133
- console.error(" -g, --global Upgrade the global installation");
134
- console.error(" --dry-run Print the command without running it");
135
- }
136
- function printReadyUsage() {
137
- console.error("Usage: vize ready [options] [files-or-directories]");
138
- console.error("Runs: fmt --write -> lint -> check -> build");
139
- console.error("Options:");
140
- console.error(" -o, --output <dir> Output directory for build");
141
- console.error(" --ssr Enable SSR compilation for build");
142
- console.error(" --script-ext <mode> preserve or downcompile");
143
- }
144
- function resolvePackageBinaryFromCwd(packageName, binName = packageName) {
145
- const packageJsonPath = createRequire(pathToFileURL(path.join(process.cwd(), "package.json")).href).resolve(`${packageName}/package.json`);
146
- const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
147
- const bin = typeof packageJson.bin === "string" ? packageJson.bin : packageJson.bin?.[binName];
148
- if (!bin) throw new Error(`Could not resolve binary '${binName}' from package '${packageName}'`);
149
- return path.resolve(path.dirname(packageJsonPath), bin);
150
- }
151
- function runMusea(args) {
152
- if (args.includes("--help") || args.includes("-h")) {
153
- console.error("Usage: vize musea [--build] [...vite options]");
154
- console.error(" --build Run `vite build` instead of `vite dev`");
155
- return;
156
- }
157
- const isBuild = args.includes("--build");
158
- const viteArgs = args.filter((arg) => arg !== "--build");
159
- const viteCommand = isBuild ? "build" : "dev";
160
- const viteBin = resolvePackageBinaryFromCwd("vite");
161
- const result = spawnSync(process.execPath, [
162
- viteBin,
163
- viteCommand,
164
- ...viteArgs
165
- ], {
166
- stdio: "inherit",
167
- cwd: process.cwd(),
168
- env: process.env
169
- });
170
- if (result.error) throw result.error;
171
- process.exit(result.status ?? 1);
172
- }
173
- function parseLintCommand(args) {
174
- const patterns = [];
175
- const options = {};
176
- const sharedConfig = { configMode: "root" };
177
- for (let i = 0; i < args.length; i++) {
178
- const arg = args[i];
179
- if (arg === "--format" || arg === "-f") options.format = args[++i];
180
- else if (arg === "--max-warnings") options.maxWarnings = Number.parseInt(args[++i], 10);
181
- else if (arg === "--quiet" || arg === "-q") options.quiet = true;
182
- else if (arg === "--fix") options.fix = true;
183
- else if (arg === "--help-level") options.helpLevel = args[++i];
184
- else if (arg === "--preset") options.preset = args[++i];
185
- else if (arg === "--config" || arg === "-c") {
186
- const configFile = args[++i];
187
- if (!configFile) throw new Error("Missing path after --config");
188
- sharedConfig.configFile = configFile;
189
- } else if (arg === "--no-config") sharedConfig.configMode = "none";
190
- else if (!arg.startsWith("-")) patterns.push(arg);
191
- }
192
- return {
193
- patterns,
194
- options,
195
- sharedConfig
196
- };
197
- }
198
- function parseBuildCommand(args) {
199
- const patterns = [];
200
- const options = {
201
- output: "./dist",
202
- format: "js",
203
- scriptExt: "downcompile"
204
- };
205
- const sharedConfig = { configMode: "root" };
206
- for (let i = 0; i < args.length; i++) {
207
- const arg = args[i];
208
- if (arg === "--output" || arg === "-o") options.output = args[++i] ?? options.output;
209
- else if (arg === "--format" || arg === "-f") {
210
- const format = args[++i];
211
- if (format === "js" || format === "json" || format === "stats") options.format = format;
212
- } else if (arg === "--ssr") options.ssr = true;
213
- else if (arg === "--vapor") options.vapor = true;
214
- else if (arg === "--custom-renderer") options.customRenderer = true;
215
- else if (arg === "--script-ext") {
216
- const scriptExt = args[++i];
217
- if (scriptExt === "preserve" || scriptExt === "downcompile") options.scriptExt = scriptExt;
218
- } else if (arg === "--threads" || arg === "-j") options.threads = Number.parseInt(args[++i], 10);
219
- else if (arg === "--config" || arg === "-c") {
220
- const configFile = args[++i];
221
- if (!configFile) throw new Error("Missing path after --config");
222
- sharedConfig.configFile = configFile;
223
- } else if (arg === "--no-config") sharedConfig.configMode = "none";
224
- else if (arg === "--profile" || arg === "--continue-on-error") {} else if (arg === "--help" || arg === "-h") options.help = true;
225
- else if (!arg.startsWith("-")) patterns.push(arg);
226
- }
227
- return {
228
- patterns,
229
- options,
230
- sharedConfig
231
- };
232
- }
233
- function getScriptLang(source) {
234
- return source.match(/<script\b[^>]*\blang=["']([^"']+)["']/i)?.[1] ?? "js";
235
- }
236
- function getOutputExtension(source, scriptExt) {
237
- if (scriptExt === "downcompile") return "js";
238
- const lang = getScriptLang(source);
239
- return lang === "ts" || lang === "tsx" || lang === "jsx" ? lang : "js";
240
- }
241
- function outputFileName(file, extension) {
242
- return path.basename(file).replace(/\.vue$/i, `.${extension}`);
243
- }
244
- function toNativeBuildOptions(options) {
245
- const isTs = options.scriptExt === "preserve";
246
- return {
247
- ssr: options.ssr,
248
- vapor: options.vapor,
249
- customRenderer: options.customRenderer,
250
- custom_renderer: options.customRenderer,
251
- isTs,
252
- is_ts: isTs,
253
- threads: options.threads
254
- };
255
- }
256
- async function runBuild(args) {
257
- const { patterns, options, sharedConfig } = parseBuildCommand(args);
258
- if (options.help) {
259
- printBuildUsage();
260
- return;
261
- }
262
- const config = await loadConfig(process.cwd(), {
263
- mode: sharedConfig.configMode,
264
- configFile: sharedConfig.configFile,
265
- env: {
266
- mode: process.env.NODE_ENV ?? "development",
267
- command: "build"
268
- }
269
- });
270
- if (sharedConfig.configFile && !config) throw new Error(`Could not find config file: ${sharedConfig.configFile}`);
271
- options.ssr ??= config?.compiler?.ssr;
272
- options.vapor ??= config?.compiler?.vapor;
273
- options.customRenderer ??= config?.compiler?.customRenderer;
274
- if (config?.compiler?.scriptExt === "ts") options.scriptExt = "preserve";
275
- else if (config?.compiler?.scriptExt === "js") options.scriptExt = "downcompile";
276
- const files = collectVueFiles(patterns);
277
- if (files.length === 0) {
278
- process.stderr.write(`No Vue files found matching inputs: ${sanitizeTerminalText(JSON.stringify(patterns))}\n`);
279
- process.exit(1);
280
- }
281
- const native = loadNative("build");
282
- const startedAt = performance.now();
283
- const batches = createBoundedFileBatches(files, {
284
- maxFiles: BUILD_BATCH_SIZE,
285
- maxBytes: BUILD_BATCH_MAX_BYTES
286
- });
287
- if (options.format !== "stats") mkdirSync(options.output, { recursive: true });
288
- let nativeTimeMs = 0;
289
- let failed = 0;
290
- let success = 0;
291
- for (const batch of batches) {
292
- const inputs = [];
293
- const extensionByPath = /* @__PURE__ */ new Map();
294
- for (const file of batch) {
295
- const source = readFileSync(file, "utf8");
296
- extensionByPath.set(file, getOutputExtension(source, options.scriptExt));
297
- inputs.push({
298
- path: file,
299
- source
300
- });
301
- }
302
- const chunkStartedAt = performance.now();
303
- const result = native.compileSfcBatchWithResults(inputs, toNativeBuildOptions(options));
304
- inputs.length = 0;
305
- nativeTimeMs += result.timeMs ?? result.time_ms ?? performance.now() - chunkStartedAt;
306
- const results = result.results.sort((left, right) => left.path.localeCompare(right.path));
307
- for (const fileResult of results) {
308
- for (const warning of fileResult.warnings) process.stderr.write(`warning: ${displayPath(fileResult.path)} ${sanitizeTerminalText(warning)}\n`);
309
- for (const error of fileResult.errors) process.stderr.write(`error: ${displayPath(fileResult.path)} ${sanitizeTerminalText(error)}\n`);
310
- if (fileResult.errors.length > 0 || options.format === "stats") continue;
311
- const extension = options.format === "json" ? "json" : extensionByPath.get(fileResult.path) ?? "js";
312
- writeFileSync(path.join(options.output, outputFileName(fileResult.path, extension)), options.format === "json" ? JSON.stringify(fileResult, null, 2) : fileResult.code);
313
- }
314
- const chunkFailed = result.failedCount ?? result.failed_count ?? results.filter((r) => r.errors.length).length;
315
- failed += chunkFailed;
316
- success += result.successCount ?? result.success_count ?? results.length - chunkFailed;
317
- }
318
- const timeMs = nativeTimeMs || performance.now() - startedAt;
319
- process.stderr.write(`\x1b[32mOK\x1b[0m Built ${success} Vue file(s) in ${timeMs.toFixed(2)}ms\n`);
320
- if (failed > 0) {
321
- process.stderr.write(`\x1b[31mERR\x1b[0m ${failed} file(s) failed\n`);
322
- process.exit(1);
323
- }
324
- }
325
- function parseFmtCommand(args) {
326
- const patterns = [];
327
- const options = {};
328
- const sharedConfig = { configMode: "root" };
329
- for (let i = 0; i < args.length; i++) {
330
- const arg = args[i];
331
- if (arg === "--check") options.check = true;
332
- else if (arg === "--write" || arg === "-w") options.write = true;
333
- else if (arg === "--single-quote") options.singleQuote = true;
334
- else if (arg === "--print-width") options.printWidth = Number.parseInt(args[++i], 10);
335
- else if (arg === "--tab-width") options.tabWidth = Number.parseInt(args[++i], 10);
336
- else if (arg === "--use-tabs") options.useTabs = true;
337
- else if (arg === "--no-semi") options.semi = false;
338
- else if (arg === "--sort-attributes") options.sortAttributes = true;
339
- else if (arg === "--single-attribute-per-line") options.singleAttributePerLine = true;
340
- else if (arg === "--max-attributes-per-line") options.maxAttributesPerLine = Number.parseInt(args[++i], 10);
341
- else if (arg === "--normalize-directive-shorthands") options.normalizeDirectiveShorthands = true;
342
- else if (arg === "--config" || arg === "-c") {
343
- const configFile = args[++i];
344
- if (!configFile) throw new Error("Missing path after --config");
345
- sharedConfig.configFile = configFile;
346
- } else if (arg === "--no-config") sharedConfig.configMode = "none";
347
- else if (arg === "--profile") {} else if (arg === "--help" || arg === "-h") options.help = true;
348
- else if (!arg.startsWith("-")) patterns.push(arg);
349
- }
350
- return {
351
- patterns,
352
- options,
353
- sharedConfig
354
- };
355
- }
356
- function toNativeFormatOptions(options) {
357
- return {
358
- printWidth: options.printWidth,
359
- print_width: options.printWidth,
360
- tabWidth: options.tabWidth,
361
- tab_width: options.tabWidth,
362
- useTabs: options.useTabs,
363
- use_tabs: options.useTabs,
364
- semi: options.semi,
365
- singleQuote: options.singleQuote,
366
- single_quote: options.singleQuote,
367
- sortAttributes: options.sortAttributes,
368
- sort_attributes: options.sortAttributes,
369
- singleAttributePerLine: options.singleAttributePerLine,
370
- single_attribute_per_line: options.singleAttributePerLine,
371
- maxAttributesPerLine: options.maxAttributesPerLine,
372
- max_attributes_per_line: options.maxAttributesPerLine,
373
- normalizeDirectiveShorthands: options.normalizeDirectiveShorthands,
374
- normalize_directive_shorthands: options.normalizeDirectiveShorthands
375
- };
376
- }
377
- async function runFmt(args) {
378
- const { patterns, options, sharedConfig } = parseFmtCommand(args);
379
- if (options.help) {
380
- printFmtUsage();
381
- return;
382
- }
383
- const config = await loadConfig(process.cwd(), {
384
- mode: sharedConfig.configMode,
385
- configFile: sharedConfig.configFile,
386
- env: {
387
- mode: process.env.NODE_ENV ?? "development",
388
- command: "fmt"
389
- }
390
- });
391
- if (sharedConfig.configFile && !config) throw new Error(`Could not find config file: ${sharedConfig.configFile}`);
392
- options.printWidth ??= config?.formatter?.printWidth;
393
- options.tabWidth ??= config?.formatter?.tabWidth;
394
- options.useTabs ??= config?.formatter?.useTabs;
395
- options.semi ??= config?.formatter?.semi;
396
- options.singleQuote ??= config?.formatter?.singleQuote;
397
- const files = collectVueFiles(patterns);
398
- if (files.length === 0) {
399
- process.stderr.write(`No Vue files found matching inputs: ${sanitizeTerminalText(JSON.stringify(patterns))}\n`);
400
- return;
401
- }
402
- const native = loadNative("fmt");
403
- let changed = 0;
404
- let errored = 0;
405
- for (const file of files) {
406
- const source = readFileSync(file, "utf8");
407
- try {
408
- const result = native.formatSfc(source, toNativeFormatOptions(options));
409
- if (!result.changed) continue;
410
- changed++;
411
- if (options.check) process.stderr.write(`Would reformat: ${displayPath(file)}\n`);
412
- else if (options.write) {
413
- writeFileSync(file, result.code);
414
- process.stderr.write(`Reformatted: ${displayPath(file)}\n`);
415
- } else process.stderr.write(`Would reformat: ${displayPath(file)}\n`);
416
- } catch (error) {
417
- errored++;
418
- process.stderr.write(`Error formatting ${displayPath(file)}: ${sanitizeTerminalText(error instanceof Error ? error.message : String(error))}\n`);
419
- }
420
- }
421
- process.stderr.write(`\x1b[32mOK\x1b[0m Formatted ${files.length} Vue file(s), ${changed} changed\n`);
422
- if (errored > 0 || options.check && changed > 0) process.exit(1);
423
- }
424
- function parseCheckCommand(args) {
425
- const patterns = [];
426
- const options = {};
427
- const sharedConfig = { configMode: "root" };
428
- for (let i = 0; i < args.length; i++) {
429
- const arg = args[i];
430
- if (arg === "--format" || arg === "-f") options.format = args[++i];
431
- else if (arg === "--quiet" || arg === "-q") options.quiet = true;
432
- else if (arg === "--strict") options.strict = true;
433
- else if (arg === "--no-strict") options.strict = false;
434
- else if (arg === "--show-virtual-ts" || arg === "--include-virtual-ts") options.includeVirtualTs = true;
435
- else if (arg === "--max-warnings") options.maxWarnings = Number.parseInt(args[++i], 10);
436
- else if (arg === "--no-check-props") options.checkProps = false;
437
- else if (arg === "--no-check-emits") options.checkEmits = false;
438
- else if (arg === "--no-check-template-bindings") options.checkTemplateBindings = false;
439
- else if (arg === "--no-check-reactivity") options.checkReactivity = false;
440
- else if (arg === "--no-check-setup-context") options.checkSetupContext = false;
441
- else if (arg === "--no-check-invalid-exports") options.checkInvalidExports = false;
442
- else if (arg === "--no-check-fallthrough-attrs") options.checkFallthroughAttrs = false;
443
- else if (arg === "--declaration") options.declaration = true;
444
- else if (arg === "--declaration-dir") {
445
- const declarationDir = args[++i];
446
- if (!declarationDir) throw new Error("Missing path after --declaration-dir");
447
- options.declarationDir = declarationDir;
448
- } else if (arg === "--config" || arg === "-c") {
449
- const configFile = args[++i];
450
- if (!configFile) throw new Error("Missing path after --config");
451
- sharedConfig.configFile = configFile;
452
- } else if (arg === "--no-config") sharedConfig.configMode = "none";
453
- else if (arg === "--help" || arg === "-h") options.help = true;
454
- else if (arg === "--tsconfig" || arg === "--corsa-path" || arg === "--servers") i++;
455
- else if (arg === "--socket" || arg === "-s") i++;
456
- else if (arg === "--profile") {} else if (!arg.startsWith("-")) patterns.push(arg);
457
- }
458
- return {
459
- patterns,
460
- options,
461
- sharedConfig
462
- };
463
- }
464
- function shouldRetainCheckSource(options) {
465
- return Boolean(options.declaration || options.format !== "json" && !options.quiet);
466
- }
467
- function hasGlobSyntax(pattern) {
468
- return pattern.includes("*") || pattern.includes("?") || pattern.includes("[");
469
- }
470
- function normalizePath(filePath) {
471
- return filePath.split(path.sep).join("/");
472
- }
473
- function sanitizeTerminalText(value) {
474
- const text = String(value);
475
- let sanitized = "";
476
- for (let i = 0; i < text.length; i++) {
477
- const code = text.charCodeAt(i);
478
- if (code === 27) {
479
- i = skipTerminalEscapeSequence(text, i);
480
- continue;
481
- }
482
- if (isUnsafeTerminalControl(code)) continue;
483
- sanitized += text[i];
484
- }
485
- return sanitized;
486
- }
487
- function skipTerminalEscapeSequence(text, escapeIndex) {
488
- const introducer = text.charCodeAt(escapeIndex + 1);
489
- if (introducer === 91) return skipUntilAnsiFinalByte(text, escapeIndex + 2);
490
- if (introducer === 93 || introducer === 80 || introducer === 94 || introducer === 95) return skipUntilStringTerminator(text, escapeIndex + 2);
491
- if (Number.isNaN(introducer)) return escapeIndex;
492
- return escapeIndex + 1;
493
- }
494
- function skipUntilAnsiFinalByte(text, index) {
495
- for (let i = index; i < text.length; i++) {
496
- const code = text.charCodeAt(i);
497
- if (code >= 64 && code <= 126) return i;
498
- }
499
- return text.length - 1;
500
- }
501
- function skipUntilStringTerminator(text, index) {
502
- for (let i = index; i < text.length; i++) {
503
- const code = text.charCodeAt(i);
504
- if (code === 7) return i;
505
- if (code === 27 && text.charCodeAt(i + 1) === 92) return i + 1;
506
- }
507
- return text.length - 1;
508
- }
509
- function isUnsafeTerminalControl(code) {
510
- if (code === 9 || code === 10 || code === 13) return false;
511
- return code >= 0 && code <= 31 || code >= 127 && code <= 159;
512
- }
513
- function displayPath(filePath) {
514
- const relative = path.relative(process.cwd(), filePath);
515
- if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) return sanitizeTerminalText(normalizePath(relative));
516
- return sanitizeTerminalText(normalizePath(filePath));
517
- }
518
- function isVueFile(filePath) {
519
- return path.extname(filePath) === ".vue";
520
- }
521
- function collectVueFilesFromDirectory(directory, recursive, files = []) {
522
- const entries = readdirSync(directory, { withFileTypes: true });
523
- for (const entry of entries) {
524
- const entryPath = path.join(directory, entry.name);
525
- if (entry.isDirectory()) {
526
- if (SKIPPED_VUE_FILE_DIRECTORIES.has(entry.name)) continue;
527
- if (recursive) collectVueFilesFromDirectory(entryPath, true, files);
528
- } else if (entry.isFile() && isVueFile(entryPath)) files.push(entryPath);
529
- }
530
- return files;
531
- }
532
- function globBase(pattern) {
533
- const normalized = normalizePath(pattern);
534
- const globIndex = normalized.search(/[*?[]/);
535
- if (globIndex === -1) return normalized;
536
- const beforeGlob = normalized.slice(0, globIndex);
537
- const slashIndex = beforeGlob.lastIndexOf("/");
538
- if (slashIndex === -1) return ".";
539
- return beforeGlob.slice(0, slashIndex) || "/";
540
- }
541
- function globToRegExp(pattern) {
542
- const normalized = normalizePath(pattern);
543
- let source = "";
544
- for (let i = 0; i < normalized.length; i++) {
545
- const char = normalized[i];
546
- const next = normalized[i + 1];
547
- const afterNext = normalized[i + 2];
548
- if (char === "*" && next === "*" && afterNext === "/") {
549
- source += "(?:.*/)?";
550
- i += 2;
551
- } else if (char === "*" && next === "*") {
552
- source += ".*";
553
- i++;
554
- } else if (char === "*") source += "[^/]*";
555
- else if (char === "?") source += "[^/]";
556
- else if ("\\^$+?.()|{}[]".includes(char)) source += `\\${char}`;
557
- else source += char;
558
- }
559
- return new RegExp(`^${source}$`);
560
- }
561
- function shouldRecurseGlob(pattern, base) {
562
- const normalizedPattern = normalizePath(pattern);
563
- const normalizedBase = normalizePath(base);
564
- return (normalizedBase === "." ? normalizedPattern : normalizedPattern.slice(normalizedBase.length).replace(/^\/+/, "")).includes("/");
565
- }
566
- function collectVueFilesFromGlob(pattern) {
567
- const basePattern = globBase(pattern);
568
- const base = path.resolve(process.cwd(), basePattern);
569
- if (!existsSync(base)) return [];
570
- const isAbsolutePattern = path.isAbsolute(pattern);
571
- const regex = globToRegExp(normalizePath(isAbsolutePattern ? path.resolve(pattern) : pattern));
572
- return collectVueFilesFromDirectory(base, shouldRecurseGlob(pattern, basePattern)).filter((file) => {
573
- const comparable = isAbsolutePattern ? normalizePath(file) : normalizePath(path.relative(process.cwd(), file));
574
- return regex.test(comparable);
575
- });
576
- }
577
- function collectVueFiles(patterns) {
578
- const files = /* @__PURE__ */ new Set();
579
- const inputs = patterns.length === 0 ? ["."] : patterns;
580
- for (const input of inputs) {
581
- if (hasGlobSyntax(input)) {
582
- for (const file of collectVueFilesFromGlob(input)) files.add(path.resolve(file));
583
- continue;
584
- }
585
- const resolved = path.resolve(process.cwd(), input);
586
- if (!existsSync(resolved)) continue;
587
- const stats = statSync(resolved);
588
- if (stats.isDirectory()) for (const file of collectVueFilesFromDirectory(resolved, true)) files.add(path.resolve(file));
589
- else if (stats.isFile() && isVueFile(resolved)) files.add(resolved);
590
- }
591
- return Array.from(files).sort();
592
- }
593
- function statFileSize(file) {
594
- try {
595
- return statSync(file).size;
596
- } catch {
597
- return 0;
598
- }
599
- }
600
- function createBoundedFileBatches(files, options) {
601
- const maxFiles = Math.max(1, Math.floor(options.maxFiles));
602
- const maxBytes = Math.max(1, Math.floor(options.maxBytes));
603
- const sizeOf = options.sizeOf ?? statFileSize;
604
- const batches = [];
605
- let current = [];
606
- let currentBytes = 0;
607
- for (const file of files) {
608
- const fileBytes = Math.max(0, sizeOf(file));
609
- if (current.length > 0 && (current.length >= maxFiles || currentBytes + fileBytes > maxBytes)) {
610
- batches.push(current);
611
- current = [];
612
- currentBytes = 0;
613
- }
614
- current.push(file);
615
- currentBytes += fileBytes;
616
- }
617
- if (current.length > 0) batches.push(current);
618
- return batches;
619
- }
620
- function commonSourceDirectory(files) {
621
- let common = path.dirname(files[0] ?? process.cwd());
622
- for (let i = 1; i < files.length; i++) {
623
- const directory = path.dirname(files[i]);
624
- while (common !== path.dirname(common)) {
625
- const relative = path.relative(common, directory);
626
- if (relative !== ".." && !relative.startsWith(`..${path.sep}`)) break;
627
- common = path.dirname(common);
628
- }
629
- }
630
- return common;
631
- }
632
- function emitCheckDeclaration(file, source, sourceRoot, native, options) {
633
- const outDir = path.resolve(process.cwd(), options.declarationDir ?? "dist/types");
634
- const relative = normalizePath(path.relative(sourceRoot, file));
635
- const outputPath = path.join(outDir, `${relative}.d.ts`);
636
- mkdirSync(path.dirname(outputPath), { recursive: true });
637
- writeFileSync(outputPath, native.generateDeclaration(source, { filename: file }).code);
638
- return {
639
- file: displayPath(outputPath),
640
- path: outputPath
641
- };
642
- }
643
- function lineStarts(source) {
644
- const starts = [0];
645
- for (let i = 0; i < source.length; i++) if (source.charCodeAt(i) === 10) starts.push(i + 1);
646
- return starts;
647
- }
648
- function offsetToLineColumn(starts, offset) {
649
- let low = 0;
650
- let high = starts.length - 1;
651
- while (low <= high) {
652
- const mid = Math.floor((low + high) / 2);
653
- if (starts[mid] <= offset) low = mid + 1;
654
- else high = mid - 1;
655
- }
656
- const lineIndex = Math.max(0, high);
657
- return {
658
- line: lineIndex + 1,
659
- column: offset - starts[lineIndex] + 1
660
- };
661
- }
662
- function toNativeTypeCheckOptions(file, options) {
663
- return {
664
- filename: file,
665
- strict: options.strict,
666
- includeVirtualTs: options.includeVirtualTs,
667
- include_virtual_ts: options.includeVirtualTs,
668
- checkProps: options.checkProps,
669
- check_props: options.checkProps,
670
- checkEmits: options.checkEmits,
671
- check_emits: options.checkEmits,
672
- checkTemplateBindings: options.checkTemplateBindings,
673
- check_template_bindings: options.checkTemplateBindings,
674
- checkReactivity: options.checkReactivity,
675
- check_reactivity: options.checkReactivity,
676
- checkSetupContext: options.checkSetupContext,
677
- check_setup_context: options.checkSetupContext,
678
- checkInvalidExports: options.checkInvalidExports,
679
- check_invalid_exports: options.checkInvalidExports,
680
- checkFallthroughAttrs: options.checkFallthroughAttrs,
681
- check_fallthrough_attrs: options.checkFallthroughAttrs
682
- };
683
- }
684
- function renderCheckFileText(file, source, result, options) {
685
- if (options.includeVirtualTs && result.virtualTs) process.stderr.write(`\n=== ${displayPath(file)} ===\n${sanitizeTerminalText(result.virtualTs)}\n`);
686
- if (options.quiet || result.diagnostics.length === 0) return;
687
- const starts = lineStarts(source);
688
- process.stdout.write(`\n\x1b[4m${displayPath(file)}\x1b[0m\n`);
689
- for (const diagnostic of result.diagnostics) {
690
- const color = diagnostic.severity === "error" ? "\x1B[31m" : "\x1B[33m";
691
- const location = offsetToLineColumn(starts, diagnostic.start);
692
- const code = diagnostic.code ? ` [${sanitizeTerminalText(diagnostic.code)}]` : "";
693
- process.stdout.write(` ${color}${diagnostic.severity}:${location.line}:${location.column}\x1b[0m${code} ${sanitizeTerminalText(diagnostic.message)}\n`);
694
- if (diagnostic.help) process.stdout.write(` help: ${sanitizeTerminalText(diagnostic.help)}\n`);
695
- }
696
- }
697
- function renderCheckSummary(totalErrors, totalWarnings, fileCount, timeMs, declarations) {
698
- const status = totalErrors > 0 ? "\x1B[31mERR\x1B[0m" : "\x1B[32mOK\x1B[0m";
699
- process.stdout.write(`\n${status} Type checked ${fileCount} Vue files in ${timeMs.toFixed(2)}ms\n`);
700
- if (totalErrors > 0) process.stdout.write(` \x1b[31m${totalErrors} error(s)\x1b[0m\n`);
701
- else process.stdout.write(" \x1B[32mNo type errors found!\x1B[0m\n");
702
- if (totalWarnings > 0) process.stdout.write(` \x1b[33m${totalWarnings} warning(s)\x1b[0m\n`);
703
- if (declarations.length > 0) process.stdout.write(` \x1b[32mEmitted ${declarations.length} declaration file(s)\x1b[0m\n`);
704
- }
705
- function indentJson(value, spaces) {
706
- const padding = " ".repeat(spaces);
707
- return JSON.stringify(value, null, 2).split("\n").map((line) => `${padding}${line}`).join("\n");
708
- }
709
- function writeCheckJsonFile(index, file, result) {
710
- if (index > 0) process.stdout.write(",\n");
711
- process.stdout.write(indentJson({
712
- file: displayPath(file),
713
- diagnostics: result.diagnostics,
714
- virtualTs: result.virtualTs
715
- }, 4));
716
- }
717
- function writeCheckJsonEnd(totalErrors, totalWarnings, fileCount, declarations) {
718
- process.stdout.write("\n ],\n");
719
- process.stdout.write(` "errorCount": ${totalErrors},\n`);
720
- process.stdout.write(` "warningCount": ${totalWarnings},\n`);
721
- process.stdout.write(` "fileCount": ${fileCount},\n`);
722
- process.stdout.write(` "declarations": ${indentJson(declarations.map(({ file }) => file), 2).trimStart()}\n`);
723
- process.stdout.write("}\n");
724
- }
725
- async function runCheck(args) {
726
- const { patterns, options, sharedConfig } = parseCheckCommand(args);
727
- if (options.help) {
728
- printCheckUsage();
729
- return;
730
- }
731
- const config = await loadConfig(process.cwd(), {
732
- mode: sharedConfig.configMode,
733
- configFile: sharedConfig.configFile,
734
- env: {
735
- mode: process.env.NODE_ENV ?? "development",
736
- command: "check"
737
- }
738
- });
739
- if (sharedConfig.configFile && !config) throw new Error(`Could not find config file: ${sharedConfig.configFile}`);
740
- if (config?.typeChecker?.enabled === false) {
741
- process.stderr.write("[vize] Skipping check because typeChecker.enabled is false in vize.config.\n");
742
- return;
743
- }
744
- options.strict ??= config?.typeChecker?.strict;
745
- options.checkProps ??= config?.typeChecker?.checkProps;
746
- options.checkEmits ??= config?.typeChecker?.checkEmits;
747
- options.checkTemplateBindings ??= config?.typeChecker?.checkTemplateBindings;
748
- const files = collectVueFiles(patterns);
749
- if (files.length === 0) {
750
- process.stderr.write(`No Vue files found matching inputs: ${sanitizeTerminalText(JSON.stringify(patterns))}\n`);
751
- return;
752
- }
753
- const native = loadNative("check");
754
- if (options.declaration && typeof native.generateDeclaration !== "function") throw new Error("The loaded native binding does not support declaration generation.");
755
- const sourceRoot = options.declaration ? commonSourceDirectory(files) : "";
756
- const checkStartedAt = performance.now();
757
- const retainSource = shouldRetainCheckSource(options);
758
- const declarations = [];
759
- let totalErrors = 0;
760
- let totalWarnings = 0;
761
- let checkedCount = 0;
762
- if (options.format === "json") process.stdout.write("{\n \"files\": [\n");
763
- for (const file of files) {
764
- const source = readFileSync(file, "utf8");
765
- const result = native.typeCheck(source, toNativeTypeCheckOptions(file, options));
766
- totalErrors += result.errorCount;
767
- totalWarnings += result.warningCount;
768
- checkedCount++;
769
- if (options.declaration) declarations.push(emitCheckDeclaration(file, source, sourceRoot, native, options));
770
- if (options.format === "json") writeCheckJsonFile(checkedCount - 1, file, result);
771
- else renderCheckFileText(file, retainSource ? source : "", result, options);
772
- }
773
- const timeMs = performance.now() - checkStartedAt;
774
- if (options.format === "json") writeCheckJsonEnd(totalErrors, totalWarnings, checkedCount, declarations);
775
- else renderCheckSummary(totalErrors, totalWarnings, checkedCount, timeMs, declarations);
776
- if (totalErrors > 0) process.exit(1);
777
- if (options.maxWarnings !== void 0 && totalWarnings > options.maxWarnings) {
778
- process.stderr.write(`\nToo many warnings (${totalWarnings} > max ${options.maxWarnings})\n`);
779
- process.exit(1);
780
- }
781
- }
782
- async function runLint(args) {
783
- const { patterns, options, sharedConfig } = parseLintCommand(args);
784
- const config = await loadConfig(process.cwd(), {
785
- mode: sharedConfig.configMode,
786
- configFile: sharedConfig.configFile,
787
- env: {
788
- mode: process.env.NODE_ENV ?? "development",
789
- command: "lint"
790
- }
791
- });
792
- if (sharedConfig.configFile && !config) throw new Error(`Could not find config file: ${sharedConfig.configFile}`);
793
- if (config?.linter?.enabled === false) {
794
- process.stderr.write("[vize] Skipping lint because linter.enabled is false in vize.config.\n");
795
- return;
796
- }
797
- options.preset ??= config?.linter?.preset;
798
- if (patterns.length === 0) patterns.push(".");
799
- const result = loadNative("lint").lint(patterns, {
800
- format: options.format,
801
- max_warnings: options.maxWarnings,
802
- quiet: options.quiet,
803
- fix: options.fix,
804
- help_level: options.helpLevel,
805
- preset: options.preset
806
- });
807
- if (result.output) {
808
- process.stdout.write(sanitizeTerminalText(result.output));
809
- if (!result.output.endsWith("\n")) process.stdout.write("\n");
810
- }
811
- if (options.fix) process.stderr.write("\nNote: --fix is not yet implemented\n");
812
- if (result.errorCount > 0) process.exit(1);
813
- if (options.maxWarnings !== void 0 && result.warningCount > options.maxWarnings) {
814
- process.stderr.write(`\nToo many warnings (${result.warningCount} > max ${options.maxWarnings})\n`);
815
- process.exit(1);
816
- }
817
- }
818
- function parseUpgradeCommand(args) {
819
- const options = {};
820
- for (let i = 0; i < args.length; i++) {
821
- const arg = args[i];
822
- if (arg === "--package-manager") {
823
- const packageManager = args[++i];
824
- if (packageManager === "bun" || packageManager === "npm" || packageManager === "pnpm" || packageManager === "vp" || packageManager === "yarn") options.packageManager = packageManager;
825
- } else if (arg === "--global" || arg === "-g") options.global = true;
826
- else if (arg === "--dry-run") options.dryRun = true;
827
- else if (arg === "--help" || arg === "-h") options.help = true;
828
- }
829
- return options;
830
- }
831
- function readCwdPackageJson() {
832
- const packageJsonPath = path.join(process.cwd(), "package.json");
833
- if (!existsSync(packageJsonPath)) return null;
834
- return JSON.parse(readFileSync(packageJsonPath, "utf8"));
835
- }
836
- function detectPackageManager(explicit) {
837
- if (explicit) return explicit;
838
- const userAgent = process.env.npm_config_user_agent ?? "";
839
- if (userAgent.startsWith("pnpm")) return "pnpm";
840
- if (userAgent.startsWith("yarn")) return "yarn";
841
- if (userAgent.startsWith("bun")) return "bun";
842
- if (userAgent.startsWith("npm")) return "npm";
843
- const packageManager = readCwdPackageJson()?.packageManager;
844
- if (packageManager?.startsWith("pnpm")) return "pnpm";
845
- if (packageManager?.startsWith("yarn")) return "yarn";
846
- if (packageManager?.startsWith("bun")) return "bun";
847
- return "npm";
848
- }
849
- function buildUpgradeCommand(packageManager, options) {
850
- const saveDev = !readCwdPackageJson()?.dependencies?.vize;
851
- const packageSpec = "vize@latest";
852
- if (packageManager === "vp") return {
853
- command: "vp",
854
- args: [
855
- "install",
856
- ...options.global ? ["-g"] : saveDev ? ["-D"] : [],
857
- packageSpec
858
- ]
859
- };
860
- if (packageManager === "pnpm") return {
861
- command: "pnpm",
862
- args: [
863
- "add",
864
- ...options.global ? ["-g"] : saveDev ? ["-D"] : [],
865
- packageSpec
866
- ]
867
- };
868
- if (packageManager === "yarn") return {
869
- command: "yarn",
870
- args: options.global ? [
871
- "global",
872
- "add",
873
- packageSpec
874
- ] : [
875
- "add",
876
- ...saveDev ? ["-D"] : [],
877
- packageSpec
878
- ]
879
- };
880
- if (packageManager === "bun") return {
881
- command: "bun",
882
- args: [
883
- "add",
884
- ...options.global ? ["-g"] : saveDev ? ["-d"] : [],
885
- packageSpec
886
- ]
887
- };
888
- return {
889
- command: "npm",
890
- args: [
891
- "install",
892
- ...options.global ? ["-g"] : saveDev ? ["-D"] : [],
893
- packageSpec
894
- ]
895
- };
896
- }
897
- function runUpgrade(args) {
898
- const options = parseUpgradeCommand(args);
899
- if (options.help) {
900
- printUpgradeUsage();
901
- return;
902
- }
903
- const command = buildUpgradeCommand(detectPackageManager(options.packageManager), options);
904
- if (options.dryRun) {
905
- process.stdout.write(`${command.command} ${command.args.join(" ")}\n`);
906
- return;
907
- }
908
- const result = spawnSync(command.command, command.args, {
909
- stdio: "inherit",
910
- cwd: process.cwd(),
911
- env: process.env
912
- });
913
- if (result.error) throw result.error;
914
- process.exit(result.status ?? 1);
915
- }
916
- function parseReadyCommand(args) {
917
- const patterns = [];
918
- const options = {
919
- output: "./dist",
920
- scriptExt: "downcompile"
921
- };
922
- for (let i = 0; i < args.length; i++) {
923
- const arg = args[i];
924
- if (arg === "--output" || arg === "-o") options.output = args[++i] ?? options.output;
925
- else if (arg === "--ssr") options.ssr = true;
926
- else if (arg === "--script-ext") {
927
- const scriptExt = args[++i];
928
- if (scriptExt === "preserve" || scriptExt === "downcompile") options.scriptExt = scriptExt;
929
- } else if (arg === "--help" || arg === "-h") options.help = true;
930
- else if (!arg.startsWith("-")) patterns.push(arg);
931
- }
932
- return {
933
- patterns,
934
- options
935
- };
936
- }
937
- async function runReady(args) {
938
- const { patterns, options } = parseReadyCommand(args);
939
- if (options.help) {
940
- printReadyUsage();
941
- return;
942
- }
943
- process.stderr.write("vize ready: fmt\n");
944
- await runFmt(["--write", ...patterns]);
945
- process.stderr.write("vize ready: lint\n");
946
- await runLint(patterns);
947
- process.stderr.write("vize ready: check\n");
948
- await runCheck(patterns);
949
- process.stderr.write("vize ready: build\n");
950
- await runBuild([
951
- "--output",
952
- options.output,
953
- "--script-ext",
954
- options.scriptExt,
955
- ...options.ssr ? ["--ssr"] : [],
956
- ...patterns
957
- ]);
958
- }
959
- const NAPI_COMMANDS = new Set([
960
- "build",
961
- "check",
962
- "fmt",
963
- "lint"
964
- ]);
965
- const JS_COMMANDS = new Set([
966
- "musea",
967
- "ready",
968
- "upgrade"
969
- ]);
970
- async function main() {
971
- const args = process.argv.slice(2);
972
- const command = args[0];
973
- if (!command || command === "--help" || command === "-h") {
974
- printUsage();
975
- process.exit(1);
976
- }
977
- if (NAPI_COMMANDS.has(command)) {
978
- const commandArgs = args.slice(1);
979
- switch (command) {
980
- case "build":
981
- await runBuild(commandArgs);
982
- break;
983
- case "check":
984
- await runCheck(commandArgs);
985
- break;
986
- case "fmt":
987
- await runFmt(commandArgs);
988
- break;
989
- case "lint":
990
- await runLint(commandArgs);
991
- break;
992
- }
993
- } else if (JS_COMMANDS.has(command)) {
994
- const commandArgs = args.slice(1);
995
- switch (command) {
996
- case "musea":
997
- runMusea(commandArgs);
998
- break;
999
- case "ready":
1000
- await runReady(commandArgs);
1001
- break;
1002
- case "upgrade":
1003
- runUpgrade(commandArgs);
1004
- break;
1005
- }
1006
- } else {
1007
- printUsage();
1008
- console.error(`Unknown command: ${sanitizeTerminalText(command)}`);
1009
- console.error("For commands not yet available via NAPI, install from source: cargo install vize");
1010
- process.exit(1);
1011
- }
1012
- }
1013
- if (!(Boolean(import.meta.vitest) || process.env.VITEST === "true" || process.env.NODE_ENV === "test")) main().catch((error) => {
1014
- console.error(sanitizeTerminalText(error instanceof Error ? error.message : String(error)));
1015
- process.exit(1);
1016
- });
3
+ createRequire(import.meta.url)("@vizejs/native").runCli(process.argv.slice(2));
1017
4
  //#endregion
1018
- export { createBoundedFileBatches, displayPath, sanitizeTerminalText, shouldPreferWorkspaceBinding, shouldRetainCheckSource };
5
+ export {};
1019
6
 
1020
7
  //# sourceMappingURL=cli.mjs.map