initial commit

This commit is contained in:
Zoe
2023-01-03 09:29:04 -06:00
commit 7851137d88
12889 changed files with 2557443 additions and 0 deletions

32
node_modules/vite-plugin-checker/dist/esm/Checker.d.ts generated vendored Normal file
View File

@@ -0,0 +1,32 @@
import * as vite from 'vite';
import { Script } from './worker.js';
import { BuildInCheckerNames, CreateDiagnostic, ServeAndBuildChecker, BuildInCheckers } from './types.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import './checkers/vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
interface CheckerMeta<T extends BuildInCheckerNames> {
name: T;
absFilePath: string;
createDiagnostic: CreateDiagnostic<T>;
build: ServeAndBuildChecker['build'];
script?: Script<any>;
}
declare abstract class Checker<T extends BuildInCheckerNames> implements CheckerMeta<T> {
static logger: ((...args: any[]) => void)[];
static log(...args: any[]): void;
name: T;
absFilePath: string;
createDiagnostic: CreateDiagnostic<T>;
build: ServeAndBuildChecker['build'];
script?: Script<any>;
constructor({ name, absFilePath, createDiagnostic, build }: CheckerMeta<T>);
prepare(): Script<Pick<BuildInCheckers, T>>;
initMainThread(): ((config: any, env: vite.ConfigEnv) => ServeAndBuildChecker) | undefined;
initWorkerThread(): void;
}
export { Checker, CheckerMeta };

50
node_modules/vite-plugin-checker/dist/esm/Checker.js generated vendored Normal file
View File

@@ -0,0 +1,50 @@
import invariant from "tiny-invariant";
import { isInVitestEntryThread, isMainThread } from "./utils.js";
import { createScript } from "./worker.js";
if (!(isMainThread || isInVitestEntryThread)) {
process.stdout.isTTY = true;
}
class Checker {
static log(...args) {
this.logger.forEach((fn) => fn(...args));
}
constructor({ name, absFilePath, createDiagnostic, build }) {
this.name = name;
this.absFilePath = absFilePath;
this.build = build;
this.createDiagnostic = createDiagnostic;
this.build = build;
}
prepare() {
const script = createScript({
absFilename: this.absFilePath,
buildBin: this.build.buildBin,
serverChecker: { createDiagnostic: this.createDiagnostic }
});
this.script = script;
return script;
}
initMainThread() {
invariant(this.script, `script should be created in 'prepare', but got ${this.script}`);
if (isMainThread || isInVitestEntryThread) {
const createServeAndBuild = this.script.mainScript();
return createServeAndBuild;
}
return;
}
initWorkerThread() {
invariant(this.script, `script should be created in 'prepare', but got ${this.script}`);
if (!(isMainThread || isInVitestEntryThread)) {
this.script.workerScript();
}
}
}
Checker.logger = [
(...args) => {
console.log(args[0].payload);
}
];
export {
Checker
};
//# sourceMappingURL=Checker.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/Checker.ts"],"sourcesContent":["import invariant from 'tiny-invariant'\nimport { isInVitestEntryThread, isMainThread } from './utils.js'\n\nimport { createScript, Script } from './worker.js'\n\n// still an only issue https://github.com/microsoft/TypeScript/issues/29808#issuecomment-829750974\nimport type {} from 'vite'\nimport type {\n CreateDiagnostic,\n BuildInCheckers,\n ServeAndBuildChecker,\n BuildInCheckerNames,\n} from './types.js'\n\nif (!(isMainThread || isInVitestEntryThread)) {\n process.stdout.isTTY = true\n}\n\nexport interface CheckerMeta<T extends BuildInCheckerNames> {\n name: T\n absFilePath: string\n createDiagnostic: CreateDiagnostic<T>\n build: ServeAndBuildChecker['build']\n script?: Script<any>\n}\n\nexport abstract class Checker<T extends BuildInCheckerNames> implements CheckerMeta<T> {\n public static logger: ((...args: any[]) => void)[] = [\n (...args: any[]) => {\n console.log(args[0].payload)\n },\n ]\n\n public static log(...args: any[]) {\n this.logger.forEach((fn) => fn(...args))\n }\n\n public name: T\n public absFilePath: string\n public createDiagnostic: CreateDiagnostic<T>\n public build: ServeAndBuildChecker['build']\n public script?: Script<any>\n\n public constructor({ name, absFilePath, createDiagnostic, build }: CheckerMeta<T>) {\n this.name = name\n this.absFilePath = absFilePath\n this.build = build\n this.createDiagnostic = createDiagnostic\n this.build = build\n }\n\n public prepare() {\n const script = createScript<Pick<BuildInCheckers, T>>({\n absFilename: this.absFilePath,\n buildBin: this.build.buildBin,\n serverChecker: { createDiagnostic: this.createDiagnostic },\n })!\n\n this.script = script\n return script\n }\n\n public initMainThread() {\n invariant(this.script, `script should be created in 'prepare', but got ${this.script}`)\n\n if (isMainThread || isInVitestEntryThread) {\n const createServeAndBuild = this.script.mainScript()\n return createServeAndBuild\n }\n\n return\n }\n\n public initWorkerThread() {\n invariant(this.script, `script should be created in 'prepare', but got ${this.script}`)\n\n if (!(isMainThread || isInVitestEntryThread)) {\n this.script.workerScript()\n }\n }\n}\n"],"mappings":"AAAA,OAAO,eAAe;AACtB,SAAS,uBAAuB,oBAAoB;AAEpD,SAAS,oBAA4B;AAWrC,IAAI,EAAE,gBAAgB,wBAAwB;AAC5C,UAAQ,OAAO,QAAQ;AACzB;AAUO,MAAe,QAAiE;AAAA,EAOrF,OAAc,OAAO,MAAa;AAChC,SAAK,OAAO,QAAQ,CAAC,OAAO,GAAG,GAAG,IAAI,CAAC;AAAA,EACzC;AAAA,EAQO,YAAY,EAAE,MAAM,aAAa,kBAAkB,MAAM,GAAmB;AACjF,SAAK,OAAO;AACZ,SAAK,cAAc;AACnB,SAAK,QAAQ;AACb,SAAK,mBAAmB;AACxB,SAAK,QAAQ;AAAA,EACf;AAAA,EAEO,UAAU;AACf,UAAM,SAAS,aAAuC;AAAA,MACpD,aAAa,KAAK;AAAA,MAClB,UAAU,KAAK,MAAM;AAAA,MACrB,eAAe,EAAE,kBAAkB,KAAK,iBAAiB;AAAA,IAC3D,CAAC;AAED,SAAK,SAAS;AACd,WAAO;AAAA,EACT;AAAA,EAEO,iBAAiB;AACtB,cAAU,KAAK,QAAQ,kDAAkD,KAAK,QAAQ;AAEtF,QAAI,gBAAgB,uBAAuB;AACzC,YAAM,sBAAsB,KAAK,OAAO,WAAW;AACnD,aAAO;AAAA,IACT;AAEA;AAAA,EACF;AAAA,EAEO,mBAAmB;AACxB,cAAU,KAAK,QAAQ,kDAAkD,KAAK,QAAQ;AAEtF,QAAI,EAAE,gBAAgB,wBAAwB;AAC5C,WAAK,OAAO,aAAa;AAAA,IAC3B;AAAA,EACF;AACF;AAtDsB,QACN,SAAuC;AAAA,EACnD,IAAI,SAAgB;AAClB,YAAQ,IAAI,KAAK,GAAG,OAAO;AAAA,EAC7B;AACF;","names":[]}

View File

@@ -0,0 +1,26 @@
import { NormalizedDiagnostic } from './logger.js';
import '@babel/code-frame';
import './types.js';
import 'vite';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import './checkers/vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
import 'vscode-languageclient';
import 'vscode-languageclient/node';
import 'typescript';
declare class FileDiagnosticManager {
diagnostics: NormalizedDiagnostic[];
private initialized;
/**
* Only used when initializing the manager
*/
initWith(diagnostics: NormalizedDiagnostic[]): void;
getDiagnostics(fileName?: string): NormalizedDiagnostic[];
updateByFileId(fileId: string, next: NormalizedDiagnostic[] | null): void;
}
export { FileDiagnosticManager };

View File

@@ -0,0 +1,37 @@
class FileDiagnosticManager {
constructor() {
this.diagnostics = [];
this.initialized = false;
}
initWith(diagnostics) {
if (this.initialized) {
throw new Error("FileDiagnosticManager is already initialized");
}
diagnostics.forEach((d) => {
this.diagnostics.push(d);
});
this.initialized = true;
}
getDiagnostics(fileName) {
if (fileName) {
return this.diagnostics.filter((f) => f.id === fileName);
}
return this.diagnostics;
}
updateByFileId(fileId, next) {
var _a;
for (let i = 0; i < this.diagnostics.length; i++) {
if (((_a = this.diagnostics[i]) == null ? void 0 : _a.id) === fileId) {
this.diagnostics.splice(i, 1);
i--;
}
}
if (next == null ? void 0 : next.length) {
this.diagnostics.push(...next);
}
}
}
export {
FileDiagnosticManager
};
//# sourceMappingURL=FileDiagnosticManager.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/FileDiagnosticManager.ts"],"sourcesContent":["import type { NormalizedDiagnostic } from './logger.js'\n\nclass FileDiagnosticManager {\n public diagnostics: NormalizedDiagnostic[] = []\n private initialized = false\n\n /**\n * Only used when initializing the manager\n */\n public initWith(diagnostics: NormalizedDiagnostic[]) {\n if (this.initialized) {\n throw new Error('FileDiagnosticManager is already initialized')\n }\n\n diagnostics.forEach((d) => {\n this.diagnostics.push(d)\n })\n\n this.initialized = true\n }\n\n public getDiagnostics(fileName?: string) {\n if (fileName) {\n return this.diagnostics.filter((f) => f.id === fileName)\n }\n\n return this.diagnostics\n }\n\n public updateByFileId(fileId: string, next: NormalizedDiagnostic[] | null) {\n for (let i = 0; i < this.diagnostics.length; i++) {\n if (this.diagnostics[i]?.id === fileId) {\n this.diagnostics.splice(i, 1)\n i--\n }\n }\n\n if (next?.length) {\n this.diagnostics.push(...next)\n }\n }\n}\n\nexport { FileDiagnosticManager }\n"],"mappings":"AAEA,MAAM,sBAAsB;AAAA,EAA5B;AACE,SAAO,cAAsC,CAAC;AAC9C,SAAQ,cAAc;AAAA;AAAA,EAKf,SAAS,aAAqC;AACnD,QAAI,KAAK,aAAa;AACpB,YAAM,IAAI,MAAM,8CAA8C;AAAA,IAChE;AAEA,gBAAY,QAAQ,CAAC,MAAM;AACzB,WAAK,YAAY,KAAK,CAAC;AAAA,IACzB,CAAC;AAED,SAAK,cAAc;AAAA,EACrB;AAAA,EAEO,eAAe,UAAmB;AACvC,QAAI,UAAU;AACZ,aAAO,KAAK,YAAY,OAAO,CAAC,MAAM,EAAE,OAAO,QAAQ;AAAA,IACzD;AAEA,WAAO,KAAK;AAAA,EACd;AAAA,EAEO,eAAe,QAAgB,MAAqC;AA7B7E;AA8BI,aAAS,IAAI,GAAG,IAAI,KAAK,YAAY,QAAQ,KAAK;AAChD,YAAI,UAAK,YAAY,OAAjB,mBAAqB,QAAO,QAAQ;AACtC,aAAK,YAAY,OAAO,GAAG,CAAC;AAC5B;AAAA,MACF;AAAA,IACF;AAEA,QAAI,6BAAM,QAAQ;AAChB,WAAK,YAAY,KAAK,GAAG,IAAI;AAAA,IAC/B;AAAA,EACF;AACF;","names":[]}

View File

@@ -0,0 +1,28 @@
declare function translateOptions({ cache, cacheFile, cacheLocation, cacheStrategy, config, env, errorOnUnmatchedPattern, eslintrc, ext, fix, fixDryRun, fixType, global, ignore, ignorePath, ignorePattern, inlineConfig, parser, parserOptions, plugin, quiet, reportUnusedDisableDirectives, resolvePluginsRelativeTo, rule, rulesdir, }: any): {
allowInlineConfig: any;
cache: any;
cacheLocation: any;
cacheStrategy: any;
errorOnUnmatchedPattern: any;
extensions: any;
fix: any;
fixTypes: any;
ignore: any;
ignorePath: any;
overrideConfig: {
env: any;
globals: any;
ignorePatterns: any;
parser: any;
parserOptions: any;
plugins: any;
rules: any;
};
overrideConfigFile: any;
reportUnusedDisableDirectives: string | undefined;
resolvePluginsRelativeTo: any;
rulePaths: any;
useEslintrc: any;
};
export { translateOptions };

View File

@@ -0,0 +1,71 @@
function quietFixPredicate(message) {
return message.severity === 2;
}
function translateOptions({
cache,
cacheFile,
cacheLocation,
cacheStrategy,
config,
env,
errorOnUnmatchedPattern,
eslintrc,
ext,
fix,
fixDryRun,
fixType,
global,
ignore,
ignorePath,
ignorePattern,
inlineConfig,
parser,
parserOptions,
plugin,
quiet,
reportUnusedDisableDirectives,
resolvePluginsRelativeTo,
rule,
rulesdir
}) {
return {
allowInlineConfig: inlineConfig,
cache,
cacheLocation: cacheLocation || cacheFile,
cacheStrategy,
errorOnUnmatchedPattern,
extensions: ext,
fix: (fix || fixDryRun) && (quiet ? quietFixPredicate : true),
fixTypes: fixType,
ignore,
ignorePath,
overrideConfig: {
env: env && env.reduce((obj, name) => {
obj[name] = true;
return obj;
}, {}),
globals: global && global.reduce((obj, name) => {
if (name.endsWith(":true")) {
obj[name.slice(0, -5)] = "writable";
} else {
obj[name] = "readonly";
}
return obj;
}, {}),
ignorePatterns: ignorePattern,
parser,
parserOptions,
plugins: plugin,
rules: rule
},
overrideConfigFile: config,
reportUnusedDisableDirectives: reportUnusedDisableDirectives ? "error" : void 0,
resolvePluginsRelativeTo,
rulePaths: rulesdir,
useEslintrc: eslintrc
};
}
export {
translateOptions
};
//# sourceMappingURL=cli.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/checkers/eslint/cli.ts"],"sourcesContent":["/* eslint-disable */\n\n/**\n * This file is directly copied from https://github.com/eslint/eslint/blob/6f940c3ce715327f282c197d0f71b91848e5d83d/lib/cli.js\n *\n * Usually, developer rarely use JS programming API to run ESLint. So we let\n * developers to write their own ESLint commands just like in CI or lint-staged.\n * And the config will be translated and pass to `new ESLint(translatedOptions)`.\n * So in build mode, it's the same as the command you pass in.\n * In dev mode, some flag will be ignored (such as `max-warnings`) because it\n * will be only respected in ESLint CLI.\n */\n\n// @ts-expect-error\nfunction quietFixPredicate(message) {\n return message.severity === 2\n}\n\nexport function translateOptions({\n cache,\n cacheFile,\n cacheLocation,\n cacheStrategy,\n config,\n env,\n errorOnUnmatchedPattern,\n eslintrc,\n ext,\n fix,\n fixDryRun,\n fixType,\n global,\n ignore,\n ignorePath,\n ignorePattern,\n inlineConfig,\n parser,\n parserOptions,\n plugin,\n quiet,\n reportUnusedDisableDirectives,\n resolvePluginsRelativeTo,\n rule,\n rulesdir,\n}: any) {\n return {\n allowInlineConfig: inlineConfig,\n cache,\n cacheLocation: cacheLocation || cacheFile,\n cacheStrategy,\n errorOnUnmatchedPattern,\n extensions: ext,\n fix: (fix || fixDryRun) && (quiet ? quietFixPredicate : true),\n fixTypes: fixType,\n ignore,\n ignorePath,\n overrideConfig: {\n env:\n env &&\n // @ts-expect-error\n env.reduce((obj, name) => {\n obj[name] = true\n return obj\n }, {}),\n globals:\n global &&\n // @ts-expect-error\n global.reduce((obj, name) => {\n if (name.endsWith(':true')) {\n obj[name.slice(0, -5)] = 'writable'\n } else {\n obj[name] = 'readonly'\n }\n return obj\n }, {}),\n ignorePatterns: ignorePattern,\n parser,\n parserOptions,\n plugins: plugin,\n rules: rule,\n },\n overrideConfigFile: config,\n reportUnusedDisableDirectives: reportUnusedDisableDirectives ? 'error' : void 0,\n resolvePluginsRelativeTo,\n rulePaths: rulesdir,\n useEslintrc: eslintrc,\n }\n}\n"],"mappings":"AAcA,SAAS,kBAAkB,SAAS;AAClC,SAAO,QAAQ,aAAa;AAC9B;AAEO,SAAS,iBAAiB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAQ;AACN,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB;AAAA,IACA,eAAe,iBAAiB;AAAA,IAChC;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ,MAAM,OAAO,eAAe,QAAQ,oBAAoB;AAAA,IACxD,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,MACd,KACE,OAEA,IAAI,OAAO,CAAC,KAAK,SAAS;AACxB,YAAI,QAAQ;AACZ,eAAO;AAAA,MACT,GAAG,CAAC,CAAC;AAAA,MACP,SACE,UAEA,OAAO,OAAO,CAAC,KAAK,SAAS;AAC3B,YAAI,KAAK,SAAS,OAAO,GAAG;AAC1B,cAAI,KAAK,MAAM,GAAG,EAAE,KAAK;AAAA,QAC3B,OAAO;AACL,cAAI,QAAQ;AAAA,QACd;AACA,eAAO;AAAA,MACT,GAAG,CAAC,CAAC;AAAA,MACP,gBAAgB;AAAA,MAChB;AAAA,MACA;AAAA,MACA,SAAS;AAAA,MACT,OAAO;AAAA,IACT;AAAA,IACA,oBAAoB;AAAA,IACpB,+BAA+B,gCAAgC,UAAU;AAAA,IACzE;AAAA,IACA,WAAW;AAAA,IACX,aAAa;AAAA,EACf;AACF;","names":[]}

View File

@@ -0,0 +1,18 @@
import { Checker } from '../../Checker.js';
import 'vite';
import '../../worker.js';
import '../../types.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import '../vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
declare let createServeAndBuild: any;
declare class EslintChecker extends Checker<'eslint'> {
constructor();
init(): void;
}
export { EslintChecker, createServeAndBuild };

View File

@@ -0,0 +1,144 @@
import chokidar from "chokidar";
import { ESLint } from "eslint";
import path from "path";
import { fileURLToPath } from "url";
import { parentPort } from "worker_threads";
import { Checker } from "../../Checker.js";
import { FileDiagnosticManager } from "../../FileDiagnosticManager.js";
import {
composeCheckerSummary,
consoleLog,
diagnosticToRuntimeError,
diagnosticToTerminalLog,
filterLogLevel,
normalizeEslintDiagnostic,
toViteCustomPayload
} from "../../logger.js";
import { ACTION_TYPES, DiagnosticLevel } from "../../types.js";
import { translateOptions } from "./cli.js";
import { options as optionator } from "./options.js";
const __filename = fileURLToPath(import.meta.url);
const manager = new FileDiagnosticManager();
let createServeAndBuild;
const createDiagnostic = (pluginConfig) => {
let overlay = true;
let terminal = true;
return {
config: async ({ enableOverlay, enableTerminal }) => {
overlay = enableOverlay;
terminal = enableTerminal;
},
async configureServer({ root }) {
var _a;
if (!pluginConfig.eslint)
return;
const options = optionator.parse(pluginConfig.eslint.lintCommand);
const translatedOptions = translateOptions(options);
const logLevel = (() => {
var _a2;
if (typeof pluginConfig.eslint !== "object")
return void 0;
const userLogLevel = (_a2 = pluginConfig.eslint.dev) == null ? void 0 : _a2.logLevel;
if (!userLogLevel)
return void 0;
const map = {
error: DiagnosticLevel.Error,
warning: DiagnosticLevel.Warning
};
return userLogLevel.map((l) => map[l]);
})();
const eslintOptions = {
cwd: root,
...translatedOptions,
...(_a = pluginConfig.eslint.dev) == null ? void 0 : _a.overrideConfig
};
const eslint = new ESLint(eslintOptions);
const dispatchDiagnostics = () => {
var _a2;
const diagnostics2 = filterLogLevel(manager.getDiagnostics(), logLevel);
if (terminal) {
diagnostics2.forEach((d) => {
consoleLog(diagnosticToTerminalLog(d, "ESLint"));
});
const errorCount = diagnostics2.filter((d) => d.level === DiagnosticLevel.Error).length;
const warningCount = diagnostics2.filter((d) => d.level === DiagnosticLevel.Warning).length;
consoleLog(composeCheckerSummary("ESLint", errorCount, warningCount));
}
if (overlay) {
(_a2 = parentPort) == null ? void 0 : _a2.postMessage({
type: ACTION_TYPES.overlayError,
payload: toViteCustomPayload(
"eslint",
diagnostics2.map((d) => diagnosticToRuntimeError(d))
)
});
}
};
const handleFileChange = async (filePath, type) => {
const extension = path.extname(filePath);
const { extensions } = eslintOptions;
const hasExtensionsConfig = Array.isArray(extensions);
if (hasExtensionsConfig && !extensions.includes(extension))
return;
const isChangedFileIgnored = await eslint.isPathIgnored(filePath);
if (isChangedFileIgnored)
return;
const absPath = path.resolve(root, filePath);
if (type === "unlink") {
manager.updateByFileId(absPath, []);
} else if (type === "change") {
const diagnosticsOfChangedFile = await eslint.lintFiles(filePath);
const newDiagnostics = diagnosticsOfChangedFile.map((d) => normalizeEslintDiagnostic(d)).flat(1);
manager.updateByFileId(absPath, newDiagnostics);
}
dispatchDiagnostics();
};
const files = options._.slice(1);
const diagnostics = await eslint.lintFiles(files);
manager.initWith(diagnostics.map((p) => normalizeEslintDiagnostic(p)).flat(1));
dispatchDiagnostics();
const watcher = chokidar.watch([], {
cwd: root,
ignored: (path2) => path2.includes("node_modules")
});
watcher.add(files);
watcher.on("change", async (filePath) => {
handleFileChange(filePath, "change");
});
watcher.on("unlink", async (filePath) => {
handleFileChange(filePath, "unlink");
});
}
};
};
class EslintChecker extends Checker {
constructor() {
super({
name: "eslint",
absFilePath: __filename,
build: {
buildBin: (pluginConfig) => {
if (pluginConfig.eslint) {
const { lintCommand } = pluginConfig.eslint;
return ["eslint", lintCommand.split(" ").slice(1)];
}
return ["eslint", [""]];
}
},
createDiagnostic
});
}
init() {
const _createServeAndBuild = super.initMainThread();
createServeAndBuild = _createServeAndBuild;
super.initWorkerThread();
}
}
const eslintChecker = new EslintChecker();
eslintChecker.prepare();
eslintChecker.init();
export {
EslintChecker,
createServeAndBuild
};
//# sourceMappingURL=main.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,45 @@
/**
* The options object parsed by Optionator.
* @typedef {Object} ParsedCLIOptions
* @property {boolean} cache Only check changed files
* @property {string} cacheFile Path to the cache file. Deprecated: use --cache-location
* @property {string} [cacheLocation] Path to the cache file or directory
* @property {"metadata" | "content"} cacheStrategy Strategy to use for detecting changed files in the cache
* @property {boolean} [color] Force enabling/disabling of color
* @property {string} [config] Use this configuration, overriding .eslintrc.* config options if present
* @property {boolean} debug Output debugging information
* @property {string[]} [env] Specify environments
* @property {boolean} envInfo Output execution environment information
* @property {boolean} errorOnUnmatchedPattern Prevent errors when pattern is unmatched
* @property {boolean} eslintrc Disable use of configuration from .eslintrc.*
* @property {string[]} [ext] Specify JavaScript file extensions
* @property {boolean} fix Automatically fix problems
* @property {boolean} fixDryRun Automatically fix problems without saving the changes to the file system
* @property {("directive" | "problem" | "suggestion" | "layout")[]} [fixType] Specify the types of fixes to apply (directive, problem, suggestion, layout)
* @property {string} format Use a specific output format
* @property {string[]} [global] Define global variables
* @property {boolean} [help] Show help
* @property {boolean} ignore Disable use of ignore files and patterns
* @property {string} [ignorePath] Specify path of ignore file
* @property {string[]} [ignorePattern] Pattern of files to ignore (in addition to those in .eslintignore)
* @property {boolean} init Run config initialization wizard
* @property {boolean} inlineConfig Prevent comments from changing config or rules
* @property {number} maxWarnings Number of warnings to trigger nonzero exit code
* @property {string} [outputFile] Specify file to write report to
* @property {string} [parser] Specify the parser to be used
* @property {Object} [parserOptions] Specify parser options
* @property {string[]} [plugin] Specify plugins
* @property {string} [printConfig] Print the configuration for the given file
* @property {boolean | undefined} reportUnusedDisableDirectives Adds reported errors for unused eslint-disable directives
* @property {string} [resolvePluginsRelativeTo] A folder where plugins should be resolved from, CWD by default
* @property {Object} [rule] Specify rules
* @property {string[]} [rulesdir] Load additional rules from this directory. Deprecated: Use rules from plugins
* @property {boolean} stdin Lint code provided on <STDIN>
* @property {string} [stdinFilename] Specify filename to process STDIN as
* @property {boolean} quiet Report errors only
* @property {boolean} [version] Output the version number
* @property {string[]} _ Positional filenames or patterns
*/
declare const options: any;
export { options };

View File

@@ -0,0 +1,266 @@
import optionator from "optionator";
const options = optionator({
prepend: "eslint [options] file.js [file.js] [dir]",
defaults: {
concatRepeatedArrays: true,
mergeRepeatedObjects: true
},
options: [
{
heading: "Basic configuration"
},
{
option: "eslintrc",
type: "Boolean",
default: "true",
description: "Disable use of configuration from .eslintrc.*"
},
{
option: "config",
alias: "c",
type: "path::String",
description: "Use this configuration, overriding .eslintrc.* config options if present"
},
{
option: "env",
type: "[String]",
description: "Specify environments"
},
{
option: "ext",
type: "[String]",
description: "Specify JavaScript file extensions"
},
{
option: "global",
type: "[String]",
description: "Define global variables"
},
{
option: "parser",
type: "String",
description: "Specify the parser to be used"
},
{
option: "parser-options",
type: "Object",
description: "Specify parser options"
},
{
option: "resolve-plugins-relative-to",
type: "path::String",
description: "A folder where plugins should be resolved from, CWD by default"
},
{
heading: "Specifying rules and plugins"
},
{
option: "plugin",
type: "[String]",
description: "Specify plugins"
},
{
option: "rule",
type: "Object",
description: "Specify rules"
},
{
option: "rulesdir",
type: "[path::String]",
description: "Load additional rules from this directory. Deprecated: Use rules from plugins"
},
{
heading: "Fixing problems"
},
{
option: "fix",
type: "Boolean",
default: false,
description: "Automatically fix problems"
},
{
option: "fix-dry-run",
type: "Boolean",
default: false,
description: "Automatically fix problems without saving the changes to the file system"
},
{
option: "fix-type",
type: "Array",
description: "Specify the types of fixes to apply (directive, problem, suggestion, layout)"
},
{
heading: "Ignoring files"
},
{
option: "ignore-path",
type: "path::String",
description: "Specify path of ignore file"
},
{
option: "ignore",
type: "Boolean",
default: "true",
description: "Disable use of ignore files and patterns"
},
{
option: "ignore-pattern",
type: "[String]",
description: "Pattern of files to ignore (in addition to those in .eslintignore)",
concatRepeatedArrays: [
true,
{
oneValuePerFlag: true
}
]
},
{
heading: "Using stdin"
},
{
option: "stdin",
type: "Boolean",
default: "false",
description: "Lint code provided on <STDIN>"
},
{
option: "stdin-filename",
type: "String",
description: "Specify filename to process STDIN as"
},
{
heading: "Handling warnings"
},
{
option: "quiet",
type: "Boolean",
default: "false",
description: "Report errors only"
},
{
option: "max-warnings",
type: "Int",
default: "-1",
description: "Number of warnings to trigger nonzero exit code"
},
{
heading: "Output"
},
{
option: "output-file",
alias: "o",
type: "path::String",
description: "Specify file to write report to"
},
{
option: "format",
alias: "f",
type: "String",
default: "stylish",
description: "Use a specific output format"
},
{
option: "color",
type: "Boolean",
alias: "no-color",
description: "Force enabling/disabling of color"
},
{
heading: "Inline configuration comments"
},
{
option: "inline-config",
type: "Boolean",
default: "true",
description: "Prevent comments from changing config or rules"
},
{
option: "report-unused-disable-directives",
type: "Boolean",
default: void 0,
description: "Adds reported errors for unused eslint-disable directives"
},
{
heading: "Caching"
},
{
option: "cache",
type: "Boolean",
default: "false",
description: "Only check changed files"
},
{
option: "cache-file",
type: "path::String",
default: ".eslintcache",
description: "Path to the cache file. Deprecated: use --cache-location"
},
{
option: "cache-location",
type: "path::String",
description: "Path to the cache file or directory"
},
{
option: "cache-strategy",
dependsOn: ["cache"],
type: "String",
default: "metadata",
enum: ["metadata", "content"],
description: "Strategy to use for detecting changed files in the cache"
},
{
heading: "Miscellaneous"
},
{
option: "init",
type: "Boolean",
default: "false",
description: "Run config initialization wizard"
},
{
option: "env-info",
type: "Boolean",
default: "false",
description: "Output execution environment information"
},
{
option: "error-on-unmatched-pattern",
type: "Boolean",
default: "true",
description: "Prevent errors when pattern is unmatched"
},
{
option: "exit-on-fatal-error",
type: "Boolean",
default: "false",
description: "Exit with exit code 2 in case of fatal error"
},
{
option: "debug",
type: "Boolean",
default: false,
description: "Output debugging information"
},
{
option: "help",
alias: "h",
type: "Boolean",
description: "Show help"
},
{
option: "version",
alias: "v",
type: "Boolean",
description: "Output the version number"
},
{
option: "print-config",
type: "path::String",
description: "Print the configuration for the given file"
}
]
});
export {
options
};
//# sourceMappingURL=options.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,18 @@
import { Checker } from '../../Checker.js';
import 'vite';
import '../../worker.js';
import '../../types.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import '../vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
declare let createServeAndBuild: any;
declare class StylelintChecker extends Checker<'stylelint'> {
constructor();
init(): void;
}
export { StylelintChecker, createServeAndBuild };

View File

@@ -0,0 +1,131 @@
import chokidar from "chokidar";
import stylelint from "stylelint";
import { translateOptions } from "./options.js";
import path from "path";
import { fileURLToPath } from "url";
import { parentPort } from "worker_threads";
import { Checker } from "../../Checker.js";
import { FileDiagnosticManager } from "../../FileDiagnosticManager.js";
import {
composeCheckerSummary,
consoleLog,
diagnosticToRuntimeError,
diagnosticToTerminalLog,
filterLogLevel,
normalizeStylelintDiagnostic,
toViteCustomPayload
} from "../../logger.js";
import { ACTION_TYPES, DiagnosticLevel } from "../../types.js";
const manager = new FileDiagnosticManager();
let createServeAndBuild;
const __filename = fileURLToPath(import.meta.url);
const createDiagnostic = (pluginConfig) => {
let overlay = true;
let terminal = true;
return {
config: async ({ enableOverlay, enableTerminal }) => {
overlay = enableOverlay;
terminal = enableTerminal;
},
async configureServer({ root }) {
var _a;
if (!pluginConfig.stylelint)
return;
const translatedOptions = translateOptions(pluginConfig.stylelint.lintCommand);
const logLevel = (() => {
var _a2;
if (typeof pluginConfig.stylelint !== "object")
return void 0;
const userLogLevel = (_a2 = pluginConfig.stylelint.dev) == null ? void 0 : _a2.logLevel;
if (!userLogLevel)
return void 0;
const map = {
error: DiagnosticLevel.Error,
warning: DiagnosticLevel.Warning
};
return userLogLevel.map((l) => map[l]);
})();
const dispatchDiagnostics = () => {
var _a2;
const diagnostics2 = filterLogLevel(manager.getDiagnostics(), logLevel);
if (terminal) {
diagnostics2.forEach((d) => {
consoleLog(diagnosticToTerminalLog(d, "Stylelint"));
});
const errorCount = diagnostics2.filter((d) => d.level === DiagnosticLevel.Error).length;
const warningCount = diagnostics2.filter((d) => d.level === DiagnosticLevel.Warning).length;
consoleLog(composeCheckerSummary("Stylelint", errorCount, warningCount));
}
if (overlay) {
(_a2 = parentPort) == null ? void 0 : _a2.postMessage({
type: ACTION_TYPES.overlayError,
payload: toViteCustomPayload(
"stylelint",
diagnostics2.map((d) => diagnosticToRuntimeError(d))
)
});
}
};
const handleFileChange = async (filePath, type) => {
const absPath = path.resolve(root, filePath);
if (type === "unlink") {
manager.updateByFileId(absPath, []);
} else if (type === "change") {
const { results: diagnosticsOfChangedFile } = await stylelint.lint({ files: filePath });
const newDiagnostics = diagnosticsOfChangedFile.map((d) => normalizeStylelintDiagnostic(d)).flat(1);
manager.updateByFileId(absPath, newDiagnostics);
}
dispatchDiagnostics();
};
const { results: diagnostics } = await stylelint.lint({
cwd: root,
...translatedOptions,
...(_a = pluginConfig.stylelint.dev) == null ? void 0 : _a.overrideConfig
});
manager.initWith(diagnostics.map((p) => normalizeStylelintDiagnostic(p)).flat(1));
dispatchDiagnostics();
const watcher = chokidar.watch([], {
cwd: root,
ignored: (path2) => path2.includes("node_modules")
});
watcher.add(translatedOptions.files);
watcher.on("change", async (filePath) => {
handleFileChange(filePath, "change");
});
watcher.on("unlink", async (filePath) => {
handleFileChange(filePath, "unlink");
});
}
};
};
class StylelintChecker extends Checker {
constructor() {
super({
name: "stylelint",
absFilePath: __filename,
build: {
buildBin: (pluginConfig) => {
if (pluginConfig.stylelint) {
const { lintCommand } = pluginConfig.stylelint;
return ["stylelint", lintCommand.split(" ").slice(1)];
}
return ["stylelint", [""]];
}
},
createDiagnostic
});
}
init() {
const _createServeAndBuild = super.initMainThread();
createServeAndBuild = _createServeAndBuild;
super.initWorkerThread();
}
}
const stylelintChecker = new StylelintChecker();
stylelintChecker.prepare();
stylelintChecker.init();
export {
StylelintChecker,
createServeAndBuild
};
//# sourceMappingURL=main.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
import Stylelint__default from 'stylelint';
declare const translateOptions: (command: string) => Stylelint__default.LinterOptions;
export { translateOptions };

View File

@@ -0,0 +1,226 @@
import meow from "meow";
const EXIT_CODE_ERROR = 2;
const translateOptions = (command) => {
const result = meow({
autoHelp: false,
autoVersion: false,
help: `
Usage: stylelint [input] [options]
Input: Files(s), glob(s), or nothing to use stdin.
If an input argument is wrapped in quotation marks, it will be passed to
globby for cross-platform glob support. node_modules are always ignored.
You can also pass no input and use stdin, instead.
Options:
--config
Path to a specific configuration file (JSON, YAML, or CommonJS), or the
name of a module in node_modules that points to one. If no --config
argument is provided, stylelint will search for configuration files in
the following places, in this order:
- a stylelint property in package.json
- a .stylelintrc file (with or without filename extension:
.json, .yaml, .yml, and .js are available)
- a stylelint.config.js file exporting a JS object
The search will begin in the working directory and move up the directory
tree until a configuration file is found.
--config-basedir
An absolute path to the directory that relative paths defining "extends"
and "plugins" are *relative to*. Only necessary if these values are
relative paths.
--print-config
Print the configuration for the given path.
--ignore-path, -i
Path to a file containing patterns that describe files to ignore. The
path can be absolute or relative to process.cwd(). By default, stylelint
looks for .stylelintignore in process.cwd().
--ignore-pattern, --ip
Pattern of files to ignore (in addition to those in .stylelintignore)
--fix
Automatically fix problems of certain rules.
--custom-syntax
Module name or path to a JS file exporting a PostCSS-compatible syntax.
--stdin
Accept stdin input even if it is empty.
--stdin-filename
A filename to assign stdin input.
--ignore-disables, --id
Ignore stylelint-disable comments.
--disable-default-ignores, --di
Allow linting of node_modules.
--cache [default: false]
Store the info about processed files in order to only operate on the
changed ones the next time you run stylelint. By default, the cache
is stored in "./.stylelintcache". To adjust this, use --cache-location.
--cache-location [default: '.stylelintcache']
Path to a file or directory to be used for the cache location.
Default is "./.stylelintcache". If a directory is specified, a cache
file will be created inside the specified folder, with a name derived
from a hash of the current working directory.
If the directory for the cache does not exist, make sure you add a trailing "/"
on *nix systems or "\\" on Windows. Otherwise the path will be assumed to be a file.
--formatter, -f [default: "string"]
The output formatter: "compact", "json", "tap", "unix" or "verbose"
--custom-formatter
Path to a JS file exporting a custom formatting function.
--quiet, -q
Only register problems for rules with an "error"-level severity (ignore
"warning"-level).
--color
--no-color
Force enabling/disabling of color.
--report-needless-disables, --rd
Also report errors for stylelint-disable comments that are not blocking a lint warning.
The process will exit with code ${EXIT_CODE_ERROR} if needless disables are found.
--report-invalid-scope-disables, --risd
Report stylelint-disable comments that used for rules that don't exist within the configuration object.
The process will exit with code ${EXIT_CODE_ERROR} if invalid scope disables are found.
--report-descriptionless-disables, --rdd
Report stylelint-disable comments without a description.
The process will exit with code ${EXIT_CODE_ERROR} if descriptionless disables are found.
--max-warnings, --mw
Number of warnings above which the process will exit with code ${EXIT_CODE_ERROR}.
Useful when setting "defaultSeverity" to "warning" and expecting the
process to fail on warnings (e.g. CI build).
--output-file, -o
Path of file to write report.
--version, -v
Show the currently installed version of stylelint.
--allow-empty-input, --aei
When glob pattern matches no files, the process will exit without throwing an error.
`,
flags: {
allowEmptyInput: {
alias: "aei",
type: "boolean"
},
cache: {
type: "boolean"
},
cacheLocation: {
type: "string"
},
color: {
type: "boolean"
},
config: {
type: "string"
},
configBasedir: {
type: "string"
},
customFormatter: {
type: "string"
},
customSyntax: {
type: "string"
},
disableDefaultIgnores: {
alias: "di",
type: "boolean"
},
fix: {
type: "boolean"
},
formatter: {
alias: "f",
default: "json",
type: "string"
},
help: {
alias: "h",
type: "boolean"
},
ignoreDisables: {
alias: "id",
type: "boolean"
},
ignorePath: {
alias: "i",
type: "string"
},
ignorePattern: {
alias: "ip",
type: "string",
isMultiple: true
},
maxWarnings: {
alias: "mw",
type: "number"
},
outputFile: {
alias: "o",
type: "string"
},
printConfig: {
type: "boolean"
},
quiet: {
alias: "q",
type: "boolean"
},
reportDescriptionlessDisables: {
alias: "rdd",
type: "boolean"
},
reportInvalidScopeDisables: {
alias: "risd",
type: "boolean"
},
reportNeedlessDisables: {
alias: "rd",
type: "boolean"
},
stdin: {
type: "boolean"
},
stdinFilename: {
type: "string"
},
syntax: {
alias: "s",
type: "string"
},
version: {
alias: "v",
type: "boolean"
}
},
argv: command.split(" ").filter((item) => !!item)
});
return {
...Object.fromEntries(
Object.entries(result.flags).filter(
([key]) => [
"files",
"globbyOptions",
"cache",
"cacheLocation",
"code",
"codeFilename",
"config",
"configFile",
"configBasedir",
"cwd",
"ignoreDisables",
"ignorePath",
"ignorePattern",
"reportDescriptionlessDisables",
"reportNeedlessDisables",
"reportInvalidScopeDisables",
"maxWarnings",
"customSyntax",
"formatter",
"disableDefaultIgnores",
"fix",
"allowEmptyInput",
"quiet"
].includes(key)
)
),
formatter: result.flags.formatter === "string" ? "json" : result.flags.formatter,
files: result.input[1]
};
};
export {
translateOptions
};
//# sourceMappingURL=options.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,18 @@
import { Checker } from '../../Checker.js';
import 'vite';
import '../../worker.js';
import '../../types.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import '../vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
declare let createServeAndBuild: any;
declare class TscChecker extends Checker<'typescript'> {
constructor();
init(): void;
}
export { TscChecker, createServeAndBuild };

View File

@@ -0,0 +1,144 @@
import os from "os";
import path from "path";
import invariant from "tiny-invariant";
import ts from "typescript";
import { fileURLToPath } from "url";
import { parentPort } from "worker_threads";
import { Checker } from "../../Checker.js";
import {
consoleLog,
diagnosticToRuntimeError,
diagnosticToTerminalLog,
ensureCall,
normalizeTsDiagnostic,
toViteCustomPayload,
wrapCheckerSummary
} from "../../logger.js";
import { ACTION_TYPES } from "../../types.js";
const __filename = fileURLToPath(import.meta.url);
let createServeAndBuild;
const createDiagnostic = (pluginConfig) => {
let overlay = true;
let terminal = true;
let currDiagnostics = [];
return {
config: async ({ enableOverlay, enableTerminal }) => {
overlay = enableOverlay;
terminal = enableTerminal;
},
configureServer({ root }) {
invariant(pluginConfig.typescript, "config.typescript should be `false`");
const finalConfig = pluginConfig.typescript === true ? { root, tsconfigPath: "tsconfig.json" } : {
root: pluginConfig.typescript.root ?? root,
tsconfigPath: pluginConfig.typescript.tsconfigPath ?? "tsconfig.json"
};
let configFile;
configFile = ts.findConfigFile(finalConfig.root, ts.sys.fileExists, finalConfig.tsconfigPath);
if (configFile === void 0) {
throw Error(
`Failed to find a valid tsconfig.json: ${finalConfig.tsconfigPath} at ${finalConfig.root} is not a valid tsconfig`
);
}
let logChunk = "";
const reportDiagnostic = (diagnostic) => {
const normalizedDiagnostic = normalizeTsDiagnostic(diagnostic);
if (normalizedDiagnostic === null) {
return;
}
currDiagnostics.push(diagnosticToRuntimeError(normalizedDiagnostic));
logChunk += os.EOL + diagnosticToTerminalLog(normalizedDiagnostic, "TypeScript");
};
const reportWatchStatusChanged = (diagnostic, newLine, options, errorCount) => {
var _a;
if (diagnostic.code === 6031)
return;
switch (diagnostic.code) {
case 6031:
case 6032:
logChunk = "";
currDiagnostics = [];
return;
case 6193:
case 6194:
if (overlay) {
(_a = parentPort) == null ? void 0 : _a.postMessage({
type: ACTION_TYPES.overlayError,
payload: toViteCustomPayload("typescript", currDiagnostics)
});
}
}
ensureCall(() => {
if (errorCount === 0) {
logChunk = "";
}
if (terminal) {
consoleLog(
logChunk + os.EOL + wrapCheckerSummary("TypeScript", diagnostic.messageText.toString())
);
}
});
};
const createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram;
if (typeof pluginConfig.typescript === "object" && pluginConfig.typescript.buildMode) {
const host = ts.createSolutionBuilderWithWatchHost(
ts.sys,
createProgram,
reportDiagnostic,
void 0,
reportWatchStatusChanged
);
ts.createSolutionBuilderWithWatch(host, [configFile], {}).build();
} else {
const host = ts.createWatchCompilerHost(
configFile,
{ noEmit: true },
ts.sys,
createProgram,
reportDiagnostic,
reportWatchStatusChanged
);
ts.createWatchProgram(host);
}
}
};
};
class TscChecker extends Checker {
constructor() {
super({
name: "typescript",
absFilePath: __filename,
build: {
buildBin: (config) => {
if (typeof config.typescript === "object") {
const { root, tsconfigPath, buildMode } = config.typescript;
let args = [buildMode ? "-b" : "--noEmit"];
if (tsconfigPath) {
const fullConfigPath = root ? path.join(root, tsconfigPath) : tsconfigPath;
if (buildMode) {
args = args.concat([fullConfigPath]);
} else {
args = args.concat(["-p", fullConfigPath]);
}
}
return ["tsc", args];
}
return ["tsc", ["--noEmit"]];
}
},
createDiagnostic
});
}
init() {
const _createServeAndBuild = super.initMainThread();
createServeAndBuild = _createServeAndBuild;
super.initWorkerThread();
}
}
const tscChecker = new TscChecker();
tscChecker.prepare();
tscChecker.init();
export {
TscChecker,
createServeAndBuild
};
//# sourceMappingURL=main.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,53 @@
import * as vscode_languageserver_node from 'vscode-languageserver/node';
import { Duplex } from 'stream';
import { VLS } from 'vls';
import { DiagnosticSeverity, Logger } from 'vscode-languageserver/node.js';
import { URI } from 'vscode-uri';
import { NormalizedDiagnostic } from '../../logger.js';
import { DeepPartial } from '../../types.js';
import { VlsOptions } from './initParams.js';
import '@babel/code-frame';
import 'vite';
import 'vscode-languageclient';
import 'eslint';
import 'stylelint';
import 'vscode-languageclient/node';
import 'typescript';
import 'worker_threads';
declare type LogLevel = typeof logLevels[number];
declare const logLevels: readonly ["ERROR", "WARN", "INFO", "HINT"];
declare const logLevel2Severity: {
ERROR: 1;
WARN: 2;
INFO: 3;
HINT: 4;
};
interface DiagnosticOptions {
watch: boolean;
verbose: boolean;
config: DeepPartial<VlsOptions> | null;
onDispatchDiagnostics?: (normalized: NormalizedDiagnostic[]) => void;
onDispatchDiagnosticsSummary?: (errorCount: number, warningCount: number) => void;
}
declare function diagnostics(workspace: string | null, logLevel: LogLevel, options?: DiagnosticOptions): Promise<void>;
declare class NullLogger implements Logger {
error(_message: string): void;
warn(_message: string): void;
info(_message: string): void;
log(_message: string): void;
}
declare class TestStream extends Duplex {
_write(chunk: string, _encoding: string, done: () => void): void;
_read(_size: number): void;
}
declare function prepareClientConnection(workspaceUri: URI, severity: DiagnosticSeverity, options: DiagnosticOptions): Promise<{
clientConnection: vscode_languageserver_node.ProtocolConnection;
serverConnection: vscode_languageserver_node.Connection;
vls: VLS;
up: TestStream;
down: TestStream;
logger: NullLogger;
}>;
export { DiagnosticOptions, LogLevel, TestStream, diagnostics, logLevel2Severity, logLevels, prepareClientConnection };

View File

@@ -0,0 +1,306 @@
import chalk from "chalk";
import chokidar from "chokidar";
import glob from "fast-glob";
import fs from "fs";
import os from "os";
import path from "path";
import { Duplex } from "stream";
import { VLS } from "vls";
import {
createConnection,
createProtocolConnection,
DiagnosticSeverity,
DidChangeTextDocumentNotification,
DidChangeWatchedFilesNotification,
DidOpenTextDocumentNotification,
InitializeRequest,
StreamMessageReader,
StreamMessageWriter
} from "vscode-languageserver/node.js";
import pkg from "vscode-uri";
const { URI } = pkg;
import {
diagnosticToTerminalLog,
normalizeLspDiagnostic,
normalizePublishDiagnosticParams
} from "../../logger.js";
import { getInitParams } from "./initParams.js";
import { FileDiagnosticManager } from "../../FileDiagnosticManager.js";
var DOC_VERSION = /* @__PURE__ */ ((DOC_VERSION2) => {
DOC_VERSION2[DOC_VERSION2["init"] = -1] = "init";
return DOC_VERSION2;
})(DOC_VERSION || {});
const logLevels = ["ERROR", "WARN", "INFO", "HINT"];
let disposeSuppressConsole;
let initialVueFilesCount = 0;
let initialVueFilesTick = 0;
const fileDiagnosticManager = new FileDiagnosticManager();
const logLevel2Severity = {
ERROR: DiagnosticSeverity.Error,
WARN: DiagnosticSeverity.Warning,
INFO: DiagnosticSeverity.Information,
HINT: DiagnosticSeverity.Hint
};
async function diagnostics(workspace, logLevel, options = { watch: false, verbose: false, config: null }) {
var _a;
if (options.verbose) {
console.log("====================================");
console.log("Getting Vetur diagnostics");
}
let workspaceUri;
if (workspace) {
const absPath = path.resolve(process.cwd(), workspace);
console.log(`Loading Vetur in workspace path: ${chalk.green(absPath)}`);
workspaceUri = URI.file(absPath);
} else {
console.log(`Loading Vetur in current directory: ${chalk.green(process.cwd())}`);
workspaceUri = URI.file(process.cwd());
}
const result = await getDiagnostics(workspaceUri, logLevel2Severity[logLevel], options);
if (options.verbose) {
console.log("====================================");
}
if (!options.watch && typeof result === "object" && result !== null) {
const { initialErrorCount, initialWarningCount } = result;
(_a = options == null ? void 0 : options.onDispatchDiagnosticsSummary) == null ? void 0 : _a.call(options, initialErrorCount, initialWarningCount);
process.exit(initialErrorCount > 0 ? 1 : 0);
}
}
class NullLogger {
error(_message) {
}
warn(_message) {
}
info(_message) {
}
log(_message) {
}
}
class TestStream extends Duplex {
_write(chunk, _encoding, done) {
this.emit("data", chunk);
done();
}
_read(_size) {
}
}
function suppressConsole() {
let disposed = false;
const rawConsoleLog = console.log;
console.log = () => {
};
return () => {
if (disposed)
return;
disposed = true;
console.log = rawConsoleLog;
};
}
async function prepareClientConnection(workspaceUri, severity, options) {
const up = new TestStream();
const down = new TestStream();
const logger = new NullLogger();
const clientConnection = createProtocolConnection(
new StreamMessageReader(down),
new StreamMessageWriter(up),
logger
);
const serverConnection = createConnection(
new StreamMessageReader(up),
new StreamMessageWriter(down)
);
serverConnection.sendDiagnostics = async (publishDiagnostics) => {
var _a, _b;
disposeSuppressConsole == null ? void 0 : disposeSuppressConsole();
if (publishDiagnostics.version === -1 /* init */) {
return;
}
const absFilePath = URI.parse(publishDiagnostics.uri).fsPath;
publishDiagnostics.diagnostics = filterDiagnostics(publishDiagnostics.diagnostics, severity);
const nextDiagnosticInFile = await normalizePublishDiagnosticParams(publishDiagnostics);
fileDiagnosticManager.updateByFileId(absFilePath, nextDiagnosticInFile);
const normalized = fileDiagnosticManager.getDiagnostics();
const errorCount = normalized.filter((d) => d.level === DiagnosticSeverity.Error).length;
const warningCount = normalized.filter((d) => d.level === DiagnosticSeverity.Warning).length;
initialVueFilesTick++;
if (initialVueFilesTick >= initialVueFilesCount) {
(_a = options.onDispatchDiagnostics) == null ? void 0 : _a.call(options, normalized);
(_b = options.onDispatchDiagnosticsSummary) == null ? void 0 : _b.call(options, errorCount, warningCount);
}
};
const vls = new VLS(serverConnection);
vls.validateTextDocument = async (textDocument, cancellationToken) => {
const diagnostics2 = await vls.doValidate(textDocument, cancellationToken);
if (diagnostics2) {
vls.lspConnection.sendDiagnostics({
uri: textDocument.uri,
version: textDocument.version,
diagnostics: diagnostics2
});
}
};
serverConnection.onInitialize(async (params) => {
await vls.init(params);
if (options.verbose) {
console.log("Vetur initialized");
console.log("====================================");
}
return {
capabilities: vls.capabilities
};
});
vls.listen();
clientConnection.listen();
const initParams = getInitParams(workspaceUri);
if (options.config) {
mergeDeep(initParams.initializationOptions.config, options.config);
}
await clientConnection.sendRequest(InitializeRequest.type, initParams);
return { clientConnection, serverConnection, vls, up, down, logger };
}
function extToGlobs(exts) {
return exts.map((e) => "**/*" + e);
}
const watchedDidChangeContent = [".vue"];
const watchedDidChangeWatchedFiles = [".js", ".ts", ".json"];
const watchedDidChangeContentGlob = extToGlobs(watchedDidChangeContent);
async function getDiagnostics(workspaceUri, severity, options) {
const { clientConnection } = await prepareClientConnection(workspaceUri, severity, options);
const files = glob.sync([...watchedDidChangeContentGlob], {
cwd: workspaceUri.fsPath,
ignore: ["node_modules/**"]
});
if (files.length === 0) {
console.log("[VLS checker] No input files");
return { initialWarningCount: 0, initialErrorCount: 0 };
}
if (options.verbose) {
console.log("");
console.log("Getting diagnostics from: ", files, "\n");
}
const absFilePaths = files.map((f) => path.resolve(workspaceUri.fsPath, f));
disposeSuppressConsole = suppressConsole();
initialVueFilesCount = absFilePaths.length;
let initialErrorCount = 0;
let initialWarningCount = 0;
await Promise.all(
absFilePaths.map(async (absFilePath) => {
const fileText = await fs.promises.readFile(absFilePath, "utf-8");
clientConnection.sendNotification(DidOpenTextDocumentNotification.type, {
textDocument: {
languageId: "vue",
uri: URI.file(absFilePath).toString(),
version: -1 /* init */,
text: fileText
}
});
if (options.watch)
return;
try {
let diagnostics2 = await clientConnection.sendRequest("$/getDiagnostics", {
uri: URI.file(absFilePath).toString(),
version: -1 /* init */
});
diagnostics2 = filterDiagnostics(diagnostics2, severity);
let logChunk = "";
if (diagnostics2.length > 0) {
logChunk += os.EOL + diagnostics2.map(
(d) => diagnosticToTerminalLog(
normalizeLspDiagnostic({
diagnostic: d,
absFilePath,
fileText
}),
"VLS"
)
).join(os.EOL);
diagnostics2.forEach((d) => {
if (d.severity === DiagnosticSeverity.Error) {
initialErrorCount++;
}
if (d.severity === DiagnosticSeverity.Warning) {
initialWarningCount++;
}
});
}
console.log(logChunk);
return { initialErrorCount, initialWarningCount };
} catch (err) {
console.error(err.stack);
return { initialErrorCount, initialWarningCount };
}
})
);
if (!options.watch) {
return { initialErrorCount, initialWarningCount };
}
await Promise.all(
absFilePaths.map(async (absFilePath) => {
const fileText = await fs.promises.readFile(absFilePath, "utf-8");
clientConnection.sendNotification(DidOpenTextDocumentNotification.type, {
textDocument: {
languageId: "vue",
uri: URI.file(absFilePath).toString(),
version: -1 /* init */,
text: fileText
}
});
})
);
const watcher = chokidar.watch([], {
ignored: (path2) => path2.includes("node_modules")
});
watcher.add(workspaceUri.fsPath);
watcher.on("all", async (event, filePath) => {
const extname = path.extname(filePath);
if (!filePath.endsWith(".vue"))
return;
const fileContent = await fs.promises.readFile(filePath, "utf-8");
clientConnection.sendNotification(DidChangeTextDocumentNotification.type, {
textDocument: {
uri: URI.file(filePath).toString(),
version: Date.now()
},
contentChanges: [{ text: fileContent }]
});
if (watchedDidChangeWatchedFiles.includes(extname)) {
clientConnection.sendNotification(DidChangeWatchedFilesNotification.type, {
changes: [
{
uri: URI.file(filePath).toString(),
type: event === "add" ? 1 : event === "unlink" ? 3 : 2
}
]
});
}
});
return null;
}
function isObject(item) {
return item && typeof item === "object" && !Array.isArray(item);
}
function mergeDeep(target, source) {
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key])
Object.assign(target, { [key]: {} });
mergeDeep(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return target;
}
function filterDiagnostics(diagnostics2, severity) {
return diagnostics2.filter((r) => r.source !== "eslint-plugin-vue").filter((r) => r.severity && r.severity <= severity);
}
export {
TestStream,
diagnostics,
logLevel2Severity,
logLevels,
prepareClientConnection
};
//# sourceMappingURL=diagnostics.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,72 @@
import { URI } from 'vscode-uri';
import { InitializeParams } from 'vscode-languageserver/node';
declare type VlsOptions = ReturnType<typeof getDefaultVLSConfig>;
declare function getInitParams(workspaceUri: URI): InitializeParams;
declare function getDefaultVLSConfig(): {
vetur: {
ignoreProjectWarning: boolean;
useWorkspaceDependencies: boolean;
validation: {
template: boolean;
templateProps: boolean;
interpolation: boolean;
style: boolean;
script: boolean;
};
completion: {
autoImport: boolean;
tagCasing: string;
scaffoldSnippetSources: {
workspace: string;
user: string;
vetur: string;
};
};
grammar: {
customBlocks: {};
};
format: {
enable: boolean;
options: {
tabSize: number;
useTabs: boolean;
};
defaultFormatter: {};
defaultFormatterOptions: {};
scriptInitialIndent: boolean;
styleInitialIndent: boolean;
};
languageFeatures: {
codeActions: boolean;
updateImportOnFileMove: boolean;
semanticTokens: boolean;
};
trace: {
server: string;
};
dev: {
vlsPath: string;
vlsPort: number;
logLevel: string;
};
experimental: {
templateInterpolationService: boolean;
};
};
css: {};
html: {
suggest: {};
};
javascript: {
format: {};
};
typescript: {
tsdk: null;
format: {};
};
emmet: {};
stylusSupremacy: {};
};
export { VlsOptions, getDefaultVLSConfig, getInitParams };

View File

@@ -0,0 +1,95 @@
function getInitParams(workspaceUri) {
const defaultVLSConfig = getDefaultVLSConfig();
defaultVLSConfig.vetur.validation = {
template: true,
style: true,
script: true,
interpolation: true,
templateProps: true
};
defaultVLSConfig.vetur.experimental = {
templateInterpolationService: true
};
const init = {
rootPath: workspaceUri.fsPath,
rootUri: workspaceUri.toString(),
processId: process.pid,
capabilities: {},
initializationOptions: {
config: defaultVLSConfig
}
};
return init;
}
function getDefaultVLSConfig() {
return {
vetur: {
ignoreProjectWarning: false,
useWorkspaceDependencies: false,
validation: {
template: true,
templateProps: true,
interpolation: true,
style: true,
script: true
},
completion: {
autoImport: false,
tagCasing: "initial",
scaffoldSnippetSources: {
workspace: "\u{1F4BC}",
user: "\u{1F5D2}\uFE0F",
vetur: "\u270C"
}
},
grammar: {
customBlocks: {}
},
format: {
enable: true,
options: {
tabSize: 2,
useTabs: false
},
defaultFormatter: {},
defaultFormatterOptions: {},
scriptInitialIndent: false,
styleInitialIndent: false
},
languageFeatures: {
codeActions: true,
updateImportOnFileMove: true,
semanticTokens: true
},
trace: {
server: "off"
},
dev: {
vlsPath: "",
vlsPort: -1,
logLevel: "INFO"
},
experimental: {
templateInterpolationService: false
}
},
css: {},
html: {
suggest: {}
},
javascript: {
format: {}
},
typescript: {
tsdk: null,
format: {}
},
emmet: {},
stylusSupremacy: {}
};
}
export {
getDefaultVLSConfig,
getInitParams
};
//# sourceMappingURL=initParams.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/checkers/vls/initParams.ts"],"sourcesContent":["import type { URI } from 'vscode-uri'\n\nimport type { InitializeParams } from 'vscode-languageserver/node'\n\nexport type VlsOptions = ReturnType<typeof getDefaultVLSConfig>\n\nexport function getInitParams(workspaceUri: URI): InitializeParams {\n const defaultVLSConfig = getDefaultVLSConfig()\n\n defaultVLSConfig.vetur.validation = {\n template: true,\n style: true,\n script: true,\n interpolation: true,\n templateProps: true,\n }\n defaultVLSConfig.vetur.experimental = {\n templateInterpolationService: true,\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const init: InitializeParams = {\n rootPath: workspaceUri.fsPath,\n rootUri: workspaceUri.toString(),\n processId: process.pid,\n capabilities: {},\n initializationOptions: {\n config: defaultVLSConfig,\n },\n } as InitializeParams\n\n return init\n}\n\nexport function getDefaultVLSConfig() {\n return {\n vetur: {\n ignoreProjectWarning: false,\n useWorkspaceDependencies: false,\n validation: {\n template: true,\n templateProps: true,\n interpolation: true,\n style: true,\n script: true,\n },\n completion: {\n autoImport: false,\n tagCasing: 'initial',\n scaffoldSnippetSources: {\n workspace: '💼',\n user: '🗒️',\n vetur: '✌',\n },\n },\n grammar: {\n customBlocks: {},\n },\n format: {\n enable: true,\n options: {\n tabSize: 2,\n useTabs: false,\n },\n defaultFormatter: {},\n defaultFormatterOptions: {},\n scriptInitialIndent: false,\n styleInitialIndent: false,\n },\n languageFeatures: {\n codeActions: true,\n updateImportOnFileMove: true,\n semanticTokens: true,\n },\n trace: {\n server: 'off',\n },\n dev: {\n vlsPath: '',\n vlsPort: -1,\n logLevel: 'INFO',\n },\n experimental: {\n templateInterpolationService: false,\n },\n },\n css: {},\n html: {\n suggest: {},\n },\n javascript: {\n format: {},\n },\n typescript: {\n tsdk: null,\n format: {},\n },\n emmet: {},\n stylusSupremacy: {},\n }\n}\n"],"mappings":"AAMO,SAAS,cAAc,cAAqC;AACjE,QAAM,mBAAmB,oBAAoB;AAE7C,mBAAiB,MAAM,aAAa;AAAA,IAClC,UAAU;AAAA,IACV,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,eAAe;AAAA,IACf,eAAe;AAAA,EACjB;AACA,mBAAiB,MAAM,eAAe;AAAA,IACpC,8BAA8B;AAAA,EAChC;AAGA,QAAM,OAAyB;AAAA,IAC7B,UAAU,aAAa;AAAA,IACvB,SAAS,aAAa,SAAS;AAAA,IAC/B,WAAW,QAAQ;AAAA,IACnB,cAAc,CAAC;AAAA,IACf,uBAAuB;AAAA,MACrB,QAAQ;AAAA,IACV;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,sBAAsB;AACpC,SAAO;AAAA,IACL,OAAO;AAAA,MACL,sBAAsB;AAAA,MACtB,0BAA0B;AAAA,MAC1B,YAAY;AAAA,QACV,UAAU;AAAA,QACV,eAAe;AAAA,QACf,eAAe;AAAA,QACf,OAAO;AAAA,QACP,QAAQ;AAAA,MACV;AAAA,MACA,YAAY;AAAA,QACV,YAAY;AAAA,QACZ,WAAW;AAAA,QACX,wBAAwB;AAAA,UACtB,WAAW;AAAA,UACX,MAAM;AAAA,UACN,OAAO;AAAA,QACT;AAAA,MACF;AAAA,MACA,SAAS;AAAA,QACP,cAAc,CAAC;AAAA,MACjB;AAAA,MACA,QAAQ;AAAA,QACN,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,SAAS;AAAA,UACT,SAAS;AAAA,QACX;AAAA,QACA,kBAAkB,CAAC;AAAA,QACnB,yBAAyB,CAAC;AAAA,QAC1B,qBAAqB;AAAA,QACrB,oBAAoB;AAAA,MACtB;AAAA,MACA,kBAAkB;AAAA,QAChB,aAAa;AAAA,QACb,wBAAwB;AAAA,QACxB,gBAAgB;AAAA,MAClB;AAAA,MACA,OAAO;AAAA,QACL,QAAQ;AAAA,MACV;AAAA,MACA,KAAK;AAAA,QACH,SAAS;AAAA,QACT,SAAS;AAAA,QACT,UAAU;AAAA,MACZ;AAAA,MACA,cAAc;AAAA,QACZ,8BAA8B;AAAA,MAChC;AAAA,IACF;AAAA,IACA,KAAK,CAAC;AAAA,IACN,MAAM;AAAA,MACJ,SAAS,CAAC;AAAA,IACZ;AAAA,IACA,YAAY;AAAA,MACV,QAAQ,CAAC;AAAA,IACX;AAAA,IACA,YAAY;AAAA,MACV,MAAM;AAAA,MACN,QAAQ,CAAC;AAAA,IACX;AAAA,IACA,OAAO,CAAC;AAAA,IACR,iBAAiB,CAAC;AAAA,EACpB;AACF;","names":[]}

View File

@@ -0,0 +1,19 @@
import { Checker } from '../../Checker.js';
import { CreateDiagnostic } from '../../types.js';
import 'vite';
import '../../worker.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import './initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
declare let createServeAndBuild: any;
declare const createDiagnostic: CreateDiagnostic<'vls'>;
declare class VlsChecker extends Checker<'vls'> {
constructor();
init(): void;
}
export { VlsChecker, createDiagnostic, createServeAndBuild };

View File

@@ -0,0 +1,92 @@
import os from "os";
import { fileURLToPath } from "url";
import { parentPort } from "worker_threads";
import { Checker } from "../../Checker.js";
import {
composeCheckerSummary,
consoleLog,
diagnosticToRuntimeError,
diagnosticToTerminalLog,
toViteCustomPayload
} from "../../logger.js";
import { ACTION_TYPES } from "../../types.js";
import { diagnostics } from "./diagnostics.js";
const __filename = fileURLToPath(import.meta.url);
let createServeAndBuild;
const createDiagnostic = (pluginConfig) => {
let overlay = true;
let terminal = true;
let command;
return {
config: ({ enableOverlay, enableTerminal, env }) => {
overlay = enableOverlay;
terminal = enableTerminal;
command = env.command;
},
async configureServer({ root }) {
const workDir = root;
const onDispatchDiagnosticsSummary = (errorCount, warningCount) => {
if (!terminal)
return;
consoleLog(composeCheckerSummary("VLS", errorCount, warningCount));
};
const onDispatchDiagnostics = (normalized) => {
var _a;
if (overlay && command === "serve") {
(_a = parentPort) == null ? void 0 : _a.postMessage({
type: ACTION_TYPES.overlayError,
payload: toViteCustomPayload("vls", diagnosticToRuntimeError(normalized))
});
}
if (terminal) {
consoleLog(normalized.map((d) => diagnosticToTerminalLog(d, "VLS")).join(os.EOL));
}
};
const vlsConfig = pluginConfig == null ? void 0 : pluginConfig.vls;
await diagnostics(workDir, "WARN", {
onDispatchDiagnostics,
onDispatchDiagnosticsSummary,
watch: true,
verbose: false,
config: typeof vlsConfig === "object" ? vlsConfig : null
});
}
};
};
class VlsChecker extends Checker {
constructor() {
super({
name: "vls",
absFilePath: __filename,
build: {
buildBin: (config) => {
if (typeof config.vls === "object") {
return [
"vti",
[
"diagnostics",
'"' + JSON.stringify(config.vls).replace(/[\\"]/g, "\\$&") + '"'
]
];
}
return ["vti", ["diagnostics"]];
}
},
createDiagnostic
});
}
init() {
const _createServeAndBuild = super.initMainThread();
createServeAndBuild = _createServeAndBuild;
super.initWorkerThread();
}
}
const vlsChecker = new VlsChecker();
vlsChecker.prepare();
vlsChecker.init();
export {
VlsChecker,
createDiagnostic,
createServeAndBuild
};
//# sourceMappingURL=main.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/checkers/vls/main.ts"],"sourcesContent":["import os from 'os'\nimport { fileURLToPath } from 'url'\nimport { parentPort } from 'worker_threads'\n\nimport { Checker } from '../../Checker.js'\nimport {\n composeCheckerSummary,\n consoleLog,\n diagnosticToRuntimeError,\n diagnosticToTerminalLog,\n toViteCustomPayload,\n} from '../../logger.js'\nimport { ACTION_TYPES } from '../../types.js'\nimport { DiagnosticOptions, diagnostics } from './diagnostics.js'\n\nimport type { ConfigEnv } from 'vite'\nimport type { CreateDiagnostic } from '../../types.js'\n\nconst __filename = fileURLToPath(import.meta.url)\n\nlet createServeAndBuild\n\nexport const createDiagnostic: CreateDiagnostic<'vls'> = (pluginConfig) => {\n let overlay = true\n let terminal = true\n let command: ConfigEnv['command']\n\n return {\n config: ({ enableOverlay, enableTerminal, env }) => {\n overlay = enableOverlay\n terminal = enableTerminal\n command = env.command\n },\n async configureServer({ root }) {\n const workDir: string = root\n\n const onDispatchDiagnosticsSummary: DiagnosticOptions['onDispatchDiagnosticsSummary'] = (\n errorCount,\n warningCount\n ) => {\n if (!terminal) return\n\n consoleLog(composeCheckerSummary('VLS', errorCount, warningCount))\n }\n\n const onDispatchDiagnostics: DiagnosticOptions['onDispatchDiagnostics'] = (normalized) => {\n if (overlay && command === 'serve') {\n parentPort?.postMessage({\n type: ACTION_TYPES.overlayError,\n payload: toViteCustomPayload('vls', diagnosticToRuntimeError(normalized)),\n })\n }\n\n if (terminal) {\n consoleLog(normalized.map((d) => diagnosticToTerminalLog(d, 'VLS')).join(os.EOL))\n }\n }\n\n const vlsConfig = pluginConfig?.vls\n await diagnostics(workDir, 'WARN', {\n onDispatchDiagnostics,\n onDispatchDiagnosticsSummary,\n watch: true,\n verbose: false,\n config: typeof vlsConfig === 'object' ? vlsConfig : null,\n })\n },\n }\n}\n\nexport class VlsChecker extends Checker<'vls'> {\n public constructor() {\n super({\n name: 'vls',\n absFilePath: __filename,\n build: {\n buildBin: (config) => {\n if (typeof config.vls === 'object') {\n return [\n 'vti',\n [\n 'diagnostics',\n // Escape quotes so that the system shell doesn't strip them out:\n '\"' + JSON.stringify(config.vls).replace(/[\\\\\"]/g, '\\\\$&') + '\"',\n ],\n ]\n }\n\n return ['vti', ['diagnostics']]\n },\n },\n createDiagnostic,\n })\n }\n\n public init() {\n const _createServeAndBuild = super.initMainThread()\n createServeAndBuild = _createServeAndBuild\n super.initWorkerThread()\n }\n}\n\nexport { createServeAndBuild }\nconst vlsChecker = new VlsChecker()\nvlsChecker.prepare()\nvlsChecker.init()\n"],"mappings":"AAAA,OAAO,QAAQ;AACf,SAAS,qBAAqB;AAC9B,SAAS,kBAAkB;AAE3B,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAA4B,mBAAmB;AAK/C,MAAM,aAAa,cAAc,YAAY,GAAG;AAEhD,IAAI;AAEG,MAAM,mBAA4C,CAAC,iBAAiB;AACzE,MAAI,UAAU;AACd,MAAI,WAAW;AACf,MAAI;AAEJ,SAAO;AAAA,IACL,QAAQ,CAAC,EAAE,eAAe,gBAAgB,IAAI,MAAM;AAClD,gBAAU;AACV,iBAAW;AACX,gBAAU,IAAI;AAAA,IAChB;AAAA,IACA,MAAM,gBAAgB,EAAE,KAAK,GAAG;AAC9B,YAAM,UAAkB;AAExB,YAAM,+BAAkF,CACtF,YACA,iBACG;AACH,YAAI,CAAC;AAAU;AAEf,mBAAW,sBAAsB,OAAO,YAAY,YAAY,CAAC;AAAA,MACnE;AAEA,YAAM,wBAAoE,CAAC,eAAe;AA7ChG;AA8CQ,YAAI,WAAW,YAAY,SAAS;AAClC,kDAAY,YAAY;AAAA,YACtB,MAAM,aAAa;AAAA,YACnB,SAAS,oBAAoB,OAAO,yBAAyB,UAAU,CAAC;AAAA,UAC1E;AAAA,QACF;AAEA,YAAI,UAAU;AACZ,qBAAW,WAAW,IAAI,CAAC,MAAM,wBAAwB,GAAG,KAAK,CAAC,EAAE,KAAK,GAAG,GAAG,CAAC;AAAA,QAClF;AAAA,MACF;AAEA,YAAM,YAAY,6CAAc;AAChC,YAAM,YAAY,SAAS,QAAQ;AAAA,QACjC;AAAA,QACA;AAAA,QACA,OAAO;AAAA,QACP,SAAS;AAAA,QACT,QAAQ,OAAO,cAAc,WAAW,YAAY;AAAA,MACtD,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEO,MAAM,mBAAmB,QAAe;AAAA,EACtC,cAAc;AACnB,UAAM;AAAA,MACJ,MAAM;AAAA,MACN,aAAa;AAAA,MACb,OAAO;AAAA,QACL,UAAU,CAAC,WAAW;AACpB,cAAI,OAAO,OAAO,QAAQ,UAAU;AAClC,mBAAO;AAAA,cACL;AAAA,cACA;AAAA,gBACE;AAAA,gBAEA,MAAM,KAAK,UAAU,OAAO,GAAG,EAAE,QAAQ,UAAU,MAAM,IAAI;AAAA,cAC/D;AAAA,YACF;AAAA,UACF;AAEA,iBAAO,CAAC,OAAO,CAAC,aAAa,CAAC;AAAA,QAChC;AAAA,MACF;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEO,OAAO;AACZ,UAAM,uBAAuB,MAAM,eAAe;AAClD,0BAAsB;AACtB,UAAM,iBAAiB;AAAA,EACzB;AACF;AAGA,MAAM,aAAa,IAAI,WAAW;AAClC,WAAW,QAAQ;AACnB,WAAW,KAAK;","names":[]}

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1 @@
//# sourceMappingURL=typings.d.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}

View File

@@ -0,0 +1,18 @@
import { Checker } from '../../Checker.js';
import 'vite';
import '../../worker.js';
import '../../types.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import '../vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
declare let createServeAndBuild: any;
declare class VueTscChecker extends Checker<'vueTsc'> {
constructor();
init(): void;
}
export { VueTscChecker, createServeAndBuild };

View File

@@ -0,0 +1,137 @@
import { createRequire } from "module";
import os from "os";
import path from "path";
import invariant from "tiny-invariant";
import { fileURLToPath } from "url";
import { parentPort } from "worker_threads";
import { Checker } from "../../Checker.js";
import {
consoleLog,
diagnosticToRuntimeError,
diagnosticToTerminalLog,
ensureCall,
normalizeVueTscDiagnostic,
toViteCustomPayload,
wrapCheckerSummary
} from "../../logger.js";
import { ACTION_TYPES } from "../../types.js";
import { prepareVueTsc } from "./prepareVueTsc.js";
const _require = createRequire(import.meta.url);
const __filename = fileURLToPath(import.meta.url);
let createServeAndBuild;
const createDiagnostic = (pluginConfig) => {
let overlay = true;
let terminal = true;
let currDiagnostics = [];
return {
config: ({ enableOverlay, enableTerminal }) => {
overlay = enableOverlay;
terminal = enableTerminal;
},
async configureServer({ root }) {
invariant(pluginConfig.vueTsc, "config.vueTsc should be `false`");
const { targetTsDir } = await prepareVueTsc();
const vueTs = _require(path.resolve(targetTsDir, "lib/tsc.js"));
const finalConfig = pluginConfig.vueTsc === true ? { root, tsconfigPath: "tsconfig.json" } : {
root: pluginConfig.vueTsc.root ?? root,
tsconfigPath: pluginConfig.vueTsc.tsconfigPath ?? "tsconfig.json"
};
let configFile;
configFile = vueTs.findConfigFile(
finalConfig.root,
vueTs.sys.fileExists,
finalConfig.tsconfigPath
);
if (configFile === void 0) {
throw Error(
`Failed to find a valid tsconfig.json: ${finalConfig.tsconfigPath} at ${finalConfig.root} is not a valid tsconfig`
);
}
let logChunk = "";
const reportDiagnostic = (diagnostic) => {
const normalizedDiagnostic = normalizeVueTscDiagnostic(diagnostic);
if (normalizedDiagnostic === null) {
return;
}
currDiagnostics.push(diagnosticToRuntimeError(normalizedDiagnostic));
logChunk += os.EOL + diagnosticToTerminalLog(normalizedDiagnostic, "vue-tsc");
};
const reportWatchStatusChanged = (diagnostic, newLine, options, errorCount) => {
var _a;
if (diagnostic.code === 6031)
return;
switch (diagnostic.code) {
case 6031:
case 6032:
logChunk = "";
currDiagnostics = [];
return;
case 6193:
case 6194:
if (overlay) {
(_a = parentPort) == null ? void 0 : _a.postMessage({
type: ACTION_TYPES.overlayError,
payload: toViteCustomPayload("vue-tsc", currDiagnostics)
});
}
}
ensureCall(() => {
if (errorCount === 0) {
logChunk = "";
}
if (terminal) {
consoleLog(
logChunk + os.EOL + wrapCheckerSummary("vue-tsc", diagnostic.messageText.toString())
);
}
});
};
const createProgram = vueTs.createSemanticDiagnosticsBuilderProgram;
const host = vueTs.createWatchCompilerHost(
configFile,
{ noEmit: true },
vueTs.sys,
createProgram,
reportDiagnostic,
reportWatchStatusChanged
);
vueTs.createWatchProgram(host);
}
};
};
class VueTscChecker extends Checker {
constructor() {
super({
name: "vueTsc",
absFilePath: __filename,
build: {
buildBin: (config) => {
if (typeof config.vueTsc === "object") {
const { root, tsconfigPath } = config.vueTsc;
let args = ["--noEmit"];
if (tsconfigPath) {
const fullConfigPath = root ? path.join(root, tsconfigPath) : tsconfigPath;
args = args.concat(["-p", fullConfigPath]);
}
return ["vue-tsc", args];
}
return ["vue-tsc", ["--noEmit"]];
}
},
createDiagnostic
});
}
init() {
const _createServeAndBuild = super.initMainThread();
createServeAndBuild = _createServeAndBuild;
super.initWorkerThread();
}
}
const tscChecker = new VueTscChecker();
tscChecker.prepare();
tscChecker.init();
export {
VueTscChecker,
createServeAndBuild
};
//# sourceMappingURL=main.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
declare function prepareVueTsc(): {
targetTsDir: string;
};
export { prepareVueTsc };

View File

@@ -0,0 +1,109 @@
import fs from "fs";
import { createRequire } from "module";
import path, { dirname } from "path";
import { fileURLToPath } from "url";
const _require = createRequire(import.meta.url);
const _filename = fileURLToPath(import.meta.url);
const _dirname = dirname(_filename);
let proxyPath;
let createProgramFunction;
try {
proxyPath = _require.resolve("vue-tsc/out/index");
createProgramFunction = "createProgram";
} catch (e) {
proxyPath = _require.resolve("vue-tsc/out/proxy");
createProgramFunction = "createProgramProxy";
}
const textToReplace = [
{
target: `ts.supportedTSExtensions = [[".ts", ".tsx", ".d.ts"], [".cts", ".d.cts"], [".mts", ".d.mts"]];`,
replacement: `ts.supportedTSExtensions = [[".ts", ".tsx", ".d.ts"], [".cts", ".d.cts"], [".mts", ".d.mts"], [".vue"]];`
},
{
target: `ts.supportedJSExtensions = [[".js", ".jsx"], [".mjs"], [".cjs"]];`,
replacement: `ts.supportedJSExtensions = [[".js", ".jsx"], [".mjs"], [".cjs"], [".vue"]];`
},
{
target: `var allSupportedExtensions = [[".ts", ".tsx", ".d.ts", ".js", ".jsx"], [".cts", ".d.cts", ".cjs"], [".mts", ".d.mts", ".mjs"]];`,
replacement: `var allSupportedExtensions = [[".ts", ".tsx", ".d.ts", ".js", ".jsx"], [".cts", ".d.cts", ".cjs"], [".mts", ".d.mts", ".mjs"], [".vue"]];`
},
{
target: `function createIncrementalProgram(_a) {`,
replacement: `function createIncrementalProgram(_a) { console.error('incremental mode is not yet supported'); throw 'incremental mode is not yet supported';`
},
{
target: `function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {`,
replacement: `function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { return require(${JSON.stringify(
proxyPath
)}).${createProgramFunction}(...arguments);`
},
{
target: `ts.executeCommandLine(ts.sys, ts.noop, ts.sys.args);`,
replacement: `module.exports = ts`
}
];
function prepareVueTsc() {
const targetTsDir = path.resolve(_dirname, "typescript-vue-tsc");
const vueTscFlagFile = path.resolve(targetTsDir, "vue-tsc-resolve-path");
let shouldPrepare = true;
const targetDirExist = fs.existsSync(targetTsDir);
if (targetDirExist) {
try {
const targetTsVersion = _require(path.resolve(targetTsDir, "package.json")).version;
const currTsVersion = _require("typescript/package.json").version;
if (targetTsVersion === currTsVersion && fs.existsSync(vueTscFlagFile) && fs.readFileSync(vueTscFlagFile, "utf8") === proxyPath) {
shouldPrepare = true;
}
} catch {
shouldPrepare = true;
}
}
if (shouldPrepare) {
rimraf(targetTsDir);
fs.mkdirSync(targetTsDir);
const sourceTsDir = path.resolve(_require.resolve("typescript"), "../..");
copyDirRecursively(sourceTsDir, targetTsDir);
fs.writeFileSync(vueTscFlagFile, proxyPath);
const tscJs = _require.resolve(path.resolve(targetTsDir, "lib/tsc.js"));
modifyFileText(tscJs, textToReplace);
}
return { targetTsDir };
}
function modifyFileText(filePath, textToReplace2) {
const text = fs.readFileSync(filePath, "utf8");
let newText = text;
for (const { target, replacement } of textToReplace2) {
newText = newText.replace(target, replacement);
}
fs.writeFileSync(filePath, newText);
}
function copyDirRecursively(src, dest) {
const files = fs.readdirSync(src, { withFileTypes: true });
for (const file of files) {
const srcPath = path.join(src, file.name);
const destPath = path.join(dest, file.name);
if (file.isDirectory()) {
fs.mkdirSync(destPath, { recursive: true });
copyDirRecursively(srcPath, destPath);
} else {
fs.copyFileSync(srcPath, destPath);
}
}
}
function rimraf(dir_path) {
if (fs.existsSync(dir_path)) {
fs.readdirSync(dir_path).forEach((entry) => {
const entry_path = path.join(dir_path, entry);
if (fs.lstatSync(entry_path).isDirectory()) {
rimraf(entry_path);
} else {
fs.unlinkSync(entry_path);
}
});
fs.rmdirSync(dir_path);
}
}
export {
prepareVueTsc
};
//# sourceMappingURL=prepareVueTsc.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,7 @@
declare const RUNTIME_PUBLIC_PATH = "/@vite-plugin-checker-runtime";
declare const RUNTIME_FILE_PATH: string;
declare const WS_CHECKER_ERROR_EVENT = "vite-plugin-checker:error";
declare const WS_CHECKER_RECONNECT_EVENT = "vite-plugin-checker:reconnect";
declare const runtimeCode: string;
export { RUNTIME_FILE_PATH, RUNTIME_PUBLIC_PATH, WS_CHECKER_ERROR_EVENT, WS_CHECKER_RECONNECT_EVENT, runtimeCode };

View File

@@ -0,0 +1,16 @@
import fs from "fs";
import { createRequire } from "module";
const _require = createRequire(import.meta.url);
const RUNTIME_PUBLIC_PATH = "/@vite-plugin-checker-runtime";
const RUNTIME_FILE_PATH = import.meta.url.endsWith(".ts") ? _require.resolve("../@runtime/main.js") : _require.resolve("../../@runtime/main.js");
const WS_CHECKER_ERROR_EVENT = "vite-plugin-checker:error";
const WS_CHECKER_RECONNECT_EVENT = "vite-plugin-checker:reconnect";
const runtimeCode = `${fs.readFileSync(RUNTIME_FILE_PATH, "utf-8")};`;
export {
RUNTIME_FILE_PATH,
RUNTIME_PUBLIC_PATH,
WS_CHECKER_ERROR_EVENT,
WS_CHECKER_RECONNECT_EVENT,
runtimeCode
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/client/index.ts"],"sourcesContent":["import fs from 'fs'\nimport { createRequire } from 'module'\nconst _require = createRequire(import.meta.url)\n\n// #region\n// NOTE: sync modification with packages/runtime/src/ws.js\nexport const RUNTIME_PUBLIC_PATH = '/@vite-plugin-checker-runtime'\nexport const RUNTIME_FILE_PATH = import.meta.url.endsWith('.ts')\n ? _require.resolve('../@runtime/main.js')\n : _require.resolve('../../@runtime/main.js')\nexport const WS_CHECKER_ERROR_EVENT = 'vite-plugin-checker:error'\nexport const WS_CHECKER_RECONNECT_EVENT = 'vite-plugin-checker:reconnect'\n// #endregion\n\nexport const runtimeCode = `${fs.readFileSync(RUNTIME_FILE_PATH, 'utf-8')};`\n"],"mappings":"AAAA,OAAO,QAAQ;AACf,SAAS,qBAAqB;AAC9B,MAAM,WAAW,cAAc,YAAY,GAAG;AAIvC,MAAM,sBAAsB;AAC5B,MAAM,oBAAoB,YAAY,IAAI,SAAS,KAAK,IAC3D,SAAS,QAAQ,qBAAqB,IACtC,SAAS,QAAQ,wBAAwB;AACtC,MAAM,yBAAyB;AAC/B,MAAM,6BAA6B;AAGnC,MAAM,cAAc,GAAG,GAAG,aAAa,mBAAmB,OAAO;","names":[]}

View File

@@ -0,0 +1,10 @@
import ts from 'typescript';
import { SourceLocation } from '@babel/code-frame';
declare function createFrame({ source, location, }: {
source: string;
location: SourceLocation;
}): string;
declare function tsLocationToBabelLocation(tsLoc: Record<'start' | 'end', ts.LineAndCharacter /** 0-based */>): SourceLocation;
export { createFrame, tsLocationToBabelLocation };

22
node_modules/vite-plugin-checker/dist/esm/codeFrame.js generated vendored Normal file
View File

@@ -0,0 +1,22 @@
import os from "os";
import { codeFrameColumns } from "@babel/code-frame";
function createFrame({
source,
location
}) {
const frame = codeFrameColumns(source, location, {
highlightCode: true
}).split("\n").map((line) => " " + line).join(os.EOL);
return frame;
}
function tsLocationToBabelLocation(tsLoc) {
return {
start: { line: tsLoc.start.line + 1, column: tsLoc.start.character + 1 },
end: { line: tsLoc.end.line + 1, column: tsLoc.end.character + 1 }
};
}
export {
createFrame,
tsLocationToBabelLocation
};
//# sourceMappingURL=codeFrame.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/codeFrame.ts"],"sourcesContent":["import os from 'os'\nimport type ts from 'typescript'\n\nimport { codeFrameColumns, SourceLocation } from '@babel/code-frame'\n\nexport function createFrame({\n source,\n location,\n}: {\n source: string // file source code\n location: SourceLocation\n}) {\n const frame = codeFrameColumns(source, location, {\n highlightCode: true,\n })\n .split('\\n')\n .map((line) => ' ' + line)\n .join(os.EOL)\n\n return frame\n}\n\nexport function tsLocationToBabelLocation(\n tsLoc: Record<'start' | 'end', ts.LineAndCharacter /** 0-based */>\n): SourceLocation {\n return {\n start: { line: tsLoc.start.line + 1, column: tsLoc.start.character + 1 },\n end: { line: tsLoc.end.line + 1, column: tsLoc.end.character + 1 },\n }\n}\n"],"mappings":"AAAA,OAAO,QAAQ;AAGf,SAAS,wBAAwC;AAE1C,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA;AACF,GAGG;AACD,QAAM,QAAQ,iBAAiB,QAAQ,UAAU;AAAA,IAC/C,eAAe;AAAA,EACjB,CAAC,EACE,MAAM,IAAI,EACV,IAAI,CAAC,SAAS,OAAO,IAAI,EACzB,KAAK,GAAG,GAAG;AAEd,SAAO;AACT;AAEO,SAAS,0BACd,OACgB;AAChB,SAAO;AAAA,IACL,OAAO,EAAE,MAAM,MAAM,MAAM,OAAO,GAAG,QAAQ,MAAM,MAAM,YAAY,EAAE;AAAA,IACvE,KAAK,EAAE,MAAM,MAAM,IAAI,OAAO,GAAG,QAAQ,MAAM,IAAI,YAAY,EAAE;AAAA,EACnE;AACF;","names":[]}

63
node_modules/vite-plugin-checker/dist/esm/logger.d.ts generated vendored Normal file
View File

@@ -0,0 +1,63 @@
import { SourceLocation } from '@babel/code-frame';
import { DiagnosticLevel, DiagnosticToRuntime } from './types.js';
import { CustomPayload } from 'vite';
import { Range } from 'vscode-languageclient';
import { ESLint } from 'eslint';
import Stylelint__default from 'stylelint';
import { Diagnostic as Diagnostic$1, PublishDiagnosticsParams } from 'vscode-languageclient/node';
import { LineAndCharacter, Diagnostic } from 'typescript';
import 'worker_threads';
import './checkers/vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
interface NormalizedDiagnostic {
/** error message */
message?: string;
/** error conclusion */
conclusion?: string;
/** error stack */
stack?: string | string[];
/** file name */
id?: string;
/** checker diagnostic source */
checker: string;
/** raw code frame generated by @babel/code-frame */
codeFrame?: string;
/** code frame, but striped */
stripedCodeFrame?: string;
/** error code location */
loc?: SourceLocation;
/** error level */
level?: DiagnosticLevel;
}
declare function filterLogLevel(diagnostics: NormalizedDiagnostic, level?: DiagnosticLevel[]): NormalizedDiagnostic | null;
declare function filterLogLevel(diagnostics: NormalizedDiagnostic[], level?: DiagnosticLevel[]): NormalizedDiagnostic[];
declare function diagnosticToTerminalLog(d: NormalizedDiagnostic, name?: 'TypeScript' | 'vue-tsc' | 'VLS' | 'ESLint' | 'Stylelint'): string;
declare function diagnosticToRuntimeError(d: NormalizedDiagnostic): DiagnosticToRuntime;
declare function diagnosticToRuntimeError(d: NormalizedDiagnostic[]): DiagnosticToRuntime[];
declare function toViteCustomPayload(id: string, diagnostics: DiagnosticToRuntime[]): CustomPayload;
declare function createFrame({ source, location, }: {
/** file source code */
source: string;
location: SourceLocation;
}): string;
declare function tsLocationToBabelLocation(tsLoc: Record<'start' | 'end', LineAndCharacter /** 0-based */>): SourceLocation;
declare function wrapCheckerSummary(checkerName: string, rawSummary: string): string;
declare function composeCheckerSummary(checkerName: string, errorCount: number, warningCount: number): string;
declare function normalizeTsDiagnostic(d: Diagnostic): NormalizedDiagnostic;
declare function normalizeLspDiagnostic({ diagnostic, absFilePath, fileText, }: {
diagnostic: Diagnostic$1;
absFilePath: string;
fileText: string;
}): NormalizedDiagnostic;
declare function normalizePublishDiagnosticParams(publishDiagnostics: PublishDiagnosticsParams): Promise<NormalizedDiagnostic[]>;
declare function uriToAbsPath(documentUri: string): string;
declare function lspRange2Location(range: Range): SourceLocation;
declare function normalizeVueTscDiagnostic(d: Diagnostic): NormalizedDiagnostic;
declare function normalizeEslintDiagnostic(diagnostic: ESLint.LintResult): NormalizedDiagnostic[];
declare function normalizeStylelintDiagnostic(diagnostic: Stylelint__default.LintResult): NormalizedDiagnostic[];
declare function ensureCall(callback: CallableFunction): void;
declare function consoleLog(value: string): void;
export { NormalizedDiagnostic, composeCheckerSummary, consoleLog, createFrame, diagnosticToRuntimeError, diagnosticToTerminalLog, ensureCall, filterLogLevel, lspRange2Location, normalizeEslintDiagnostic, normalizeLspDiagnostic, normalizePublishDiagnosticParams, normalizeStylelintDiagnostic, normalizeTsDiagnostic, normalizeVueTscDiagnostic, toViteCustomPayload, tsLocationToBabelLocation, uriToAbsPath, wrapCheckerSummary };

329
node_modules/vite-plugin-checker/dist/esm/logger.js generated vendored Normal file
View File

@@ -0,0 +1,329 @@
import chalk from "chalk";
import fs from "fs";
import { createRequire } from "module";
import os from "os";
import strip from "strip-ansi";
import vscodeUri from "vscode-uri";
import { parentPort } from "worker_threads";
import { codeFrameColumns } from "@babel/code-frame";
import { WS_CHECKER_ERROR_EVENT } from "./client/index.js";
import { ACTION_TYPES, DiagnosticLevel } from "./types.js";
import { isMainThread } from "./utils.js";
const _require = createRequire(import.meta.url);
const { URI } = vscodeUri;
const defaultLogLevel = [
DiagnosticLevel.Warning,
DiagnosticLevel.Error,
DiagnosticLevel.Suggestion,
DiagnosticLevel.Message
];
function filterLogLevel(diagnostics, level = defaultLogLevel) {
if (Array.isArray(diagnostics)) {
return diagnostics.filter((d) => {
if (typeof d.level !== "number")
return false;
return level.includes(d.level);
});
} else {
if (!diagnostics.level)
return null;
return level.includes(diagnostics.level) ? diagnostics : null;
}
}
function diagnosticToTerminalLog(d, name) {
const nameInLabel = name ? `(${name})` : "";
const boldBlack = chalk.bold.rgb(0, 0, 0);
const labelMap = {
[DiagnosticLevel.Error]: boldBlack.bgRedBright(` ERROR${nameInLabel} `),
[DiagnosticLevel.Warning]: boldBlack.bgYellowBright(` WARNING${nameInLabel} `),
[DiagnosticLevel.Suggestion]: boldBlack.bgBlueBright(` SUGGESTION${nameInLabel} `),
[DiagnosticLevel.Message]: boldBlack.bgCyanBright(` MESSAGE${nameInLabel} `)
};
const levelLabel = labelMap[d.level ?? DiagnosticLevel.Error];
const fileLabel = boldBlack.bgCyanBright(" FILE ") + " ";
const position = d.loc ? chalk.yellow(d.loc.start.line) + ":" + chalk.yellow(d.loc.start.column) : "";
return [
levelLabel + " " + d.message,
fileLabel + d.id + ":" + position + os.EOL,
d.codeFrame + os.EOL,
d.conclusion
].filter(Boolean).join(os.EOL);
}
function diagnosticToRuntimeError(diagnostics) {
const diagnosticsArray = Array.isArray(diagnostics) ? diagnostics : [diagnostics];
const results = diagnosticsArray.map((d) => {
let loc;
if (d.loc) {
loc = {
file: d.id ?? "",
line: d.loc.start.line,
column: typeof d.loc.start.column === "number" ? d.loc.start.column : 0
};
}
return {
message: d.message ?? "",
stack: typeof d.stack === "string" ? d.stack : Array.isArray(d.stack) ? d.stack.join(os.EOL) : "",
id: d.id,
frame: d.stripedCodeFrame,
checkerId: d.checker,
level: d.level,
loc
};
});
return Array.isArray(diagnostics) ? results : results[0];
}
function toViteCustomPayload(id, diagnostics) {
return {
type: "custom",
event: WS_CHECKER_ERROR_EVENT,
data: {
checkerId: id,
diagnostics
}
};
}
function createFrame({
source,
location
}) {
const frame = codeFrameColumns(source, location, {
forceColor: true
}).split("\n").map((line) => " " + line).join(os.EOL);
return frame;
}
function tsLocationToBabelLocation(tsLoc) {
return {
start: { line: tsLoc.start.line + 1, column: tsLoc.start.character + 1 },
end: { line: tsLoc.end.line + 1, column: tsLoc.end.character + 1 }
};
}
function wrapCheckerSummary(checkerName, rawSummary) {
return `[${checkerName}] ${rawSummary}`;
}
function composeCheckerSummary(checkerName, errorCount, warningCount) {
const message = `Found ${errorCount} error${errorCount > 1 ? "s" : ""} and ${warningCount} warning${warningCount > 1 ? "s" : ""}`;
const hasError = errorCount > 0;
const hasWarning = warningCount > 0;
const color = hasError ? "red" : hasWarning ? "yellow" : "green";
return chalk[color](wrapCheckerSummary(checkerName, message));
}
function normalizeTsDiagnostic(d) {
var _a, _b, _c, _d, _e;
const fileName = (_a = d.file) == null ? void 0 : _a.fileName;
const {
flattenDiagnosticMessageText
} = _require("typescript");
const message = flattenDiagnosticMessageText(d.messageText, os.EOL);
let loc;
const pos = d.start === void 0 ? null : (_c = (_b = d.file) == null ? void 0 : _b.getLineAndCharacterOfPosition) == null ? void 0 : _c.call(_b, d.start);
if (pos && d.file && typeof d.start === "number" && typeof d.length === "number") {
loc = tsLocationToBabelLocation({
start: (_d = d.file) == null ? void 0 : _d.getLineAndCharacterOfPosition(d.start),
end: (_e = d.file) == null ? void 0 : _e.getLineAndCharacterOfPosition(d.start + d.length)
});
}
let codeFrame;
if (loc) {
codeFrame = createFrame({
source: d.file.text,
location: loc
});
}
return {
message,
conclusion: "",
codeFrame,
stripedCodeFrame: codeFrame && strip(codeFrame),
id: fileName,
checker: "TypeScript",
loc,
level: d.category
};
}
function normalizeLspDiagnostic({
diagnostic,
absFilePath,
fileText
}) {
let level = DiagnosticLevel.Error;
const loc = lspRange2Location(diagnostic.range);
const codeFrame = codeFrameColumns(fileText, loc);
switch (diagnostic.severity) {
case 1:
level = DiagnosticLevel.Error;
break;
case 2:
level = DiagnosticLevel.Warning;
break;
case 3:
level = DiagnosticLevel.Message;
break;
case 4:
level = DiagnosticLevel.Suggestion;
break;
}
return {
message: diagnostic.message.trim(),
conclusion: "",
codeFrame,
stripedCodeFrame: codeFrame && strip(codeFrame),
id: absFilePath,
checker: "VLS",
loc,
level
};
}
async function normalizePublishDiagnosticParams(publishDiagnostics) {
const diagnostics = publishDiagnostics.diagnostics;
const absFilePath = uriToAbsPath(publishDiagnostics.uri);
const { readFile } = fs.promises;
const fileText = await readFile(absFilePath, "utf-8");
const res = diagnostics.map((d) => {
return normalizeLspDiagnostic({
diagnostic: d,
absFilePath,
fileText
});
});
return res;
}
function uriToAbsPath(documentUri) {
return URI.parse(documentUri).fsPath;
}
function lspRange2Location(range) {
return {
start: {
line: range.start.line + 1,
column: range.start.character + 1
},
end: {
line: range.end.line + 1,
column: range.end.character + 1
}
};
}
function normalizeVueTscDiagnostic(d) {
const diagnostic = normalizeTsDiagnostic(d);
diagnostic.checker = "vue-tsc";
return diagnostic;
}
const isNormalizedDiagnostic = (d) => {
return Boolean(d);
};
function normalizeEslintDiagnostic(diagnostic) {
return diagnostic.messages.map((d) => {
let level = DiagnosticLevel.Error;
switch (d.severity) {
case 0:
level = DiagnosticLevel.Error;
return null;
case 1:
level = DiagnosticLevel.Warning;
break;
case 2:
level = DiagnosticLevel.Error;
break;
}
const loc = {
start: {
line: d.line,
column: d.column
},
end: {
line: d.endLine || 0,
column: d.endColumn
}
};
const codeFrame = createFrame({
source: diagnostic.source ?? "",
location: loc
});
return {
message: `${d.message} (${d.ruleId})`,
conclusion: "",
codeFrame,
stripedCodeFrame: codeFrame && strip(codeFrame),
id: diagnostic.filePath,
checker: "ESLint",
loc,
level
};
}).filter(isNormalizedDiagnostic);
}
function normalizeStylelintDiagnostic(diagnostic) {
return diagnostic.warnings.map((d) => {
let level = DiagnosticLevel.Error;
switch (d.severity) {
case "warning":
level = DiagnosticLevel.Warning;
break;
case "error":
level = DiagnosticLevel.Error;
break;
default:
level = DiagnosticLevel.Error;
return null;
}
const loc = {
start: {
line: d.line,
column: d.column
},
end: {
line: d.endLine || 0,
column: d.endColumn
}
};
const codeFrame = createFrame({
source: diagnostic._postcssResult.css ?? "",
location: loc
});
return {
message: `${d.text} (${d.rule})`,
conclusion: "",
codeFrame,
stripedCodeFrame: codeFrame && strip(codeFrame),
id: diagnostic.source,
checker: "Stylelint",
loc,
level
};
}).filter(isNormalizedDiagnostic);
}
function ensureCall(callback) {
setTimeout(() => {
callback();
});
}
function consoleLog(value) {
var _a;
if (isMainThread) {
console.log(value);
} else {
(_a = parentPort) == null ? void 0 : _a.postMessage({
type: ACTION_TYPES.console,
payload: value
});
}
}
export {
composeCheckerSummary,
consoleLog,
createFrame,
diagnosticToRuntimeError,
diagnosticToTerminalLog,
ensureCall,
filterLogLevel,
lspRange2Location,
normalizeEslintDiagnostic,
normalizeLspDiagnostic,
normalizePublishDiagnosticParams,
normalizeStylelintDiagnostic,
normalizeTsDiagnostic,
normalizeVueTscDiagnostic,
toViteCustomPayload,
tsLocationToBabelLocation,
uriToAbsPath,
wrapCheckerSummary
};
//# sourceMappingURL=logger.js.map

File diff suppressed because one or more lines are too long

12
node_modules/vite-plugin-checker/dist/esm/main.d.ts generated vendored Normal file
View File

@@ -0,0 +1,12 @@
import { Plugin } from 'vite';
import { UserPluginConfig } from './types.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import './checkers/vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
declare function checker(userConfig: UserPluginConfig): Plugin;
export { checker, checker as default };

212
node_modules/vite-plugin-checker/dist/esm/main.js generated vendored Normal file
View File

@@ -0,0 +1,212 @@
import chalk from "chalk";
import { spawn } from "child_process";
import pick from "lodash.pick";
import npmRunPath from "npm-run-path";
import path from "path";
import { Checker } from "./Checker.js";
import { RUNTIME_PUBLIC_PATH, runtimeCode, WS_CHECKER_RECONNECT_EVENT } from "./client/index.js";
import {
ACTION_TYPES
} from "./types.js";
const sharedConfigKeys = ["enableBuild", "overlay"];
const buildInCheckerKeys = [
"typescript",
"vueTsc",
"vls",
"eslint",
"stylelint"
];
async function createCheckers(userConfig, env) {
const serveAndBuildCheckers = [];
const sharedConfig = pick(userConfig, sharedConfigKeys);
for (const name of buildInCheckerKeys) {
if (!userConfig[name])
continue;
const { createServeAndBuild } = await import(`./checkers/${name}/main.js`);
serveAndBuildCheckers.push(
createServeAndBuild({ [name]: userConfig[name], ...sharedConfig }, env)
);
}
return serveAndBuildCheckers;
}
function checker(userConfig) {
const enableBuild = (userConfig == null ? void 0 : userConfig.enableBuild) ?? true;
const enableOverlay = (userConfig == null ? void 0 : userConfig.overlay) !== false;
const enableTerminal = (userConfig == null ? void 0 : userConfig.terminal) !== false;
const overlayConfig = typeof (userConfig == null ? void 0 : userConfig.overlay) === "object" ? userConfig == null ? void 0 : userConfig.overlay : {};
let resolvedRuntimePath = RUNTIME_PUBLIC_PATH;
let checkers = [];
let viteMode;
let resolvedConfig;
return {
name: "vite-plugin-checker",
__internal__checker: Checker,
config: async (config, env) => {
viteMode = env.command;
checkers = await createCheckers(userConfig || {}, env);
if (viteMode !== "serve")
return;
checkers.forEach((checker2) => {
const workerConfig = checker2.serve.config;
workerConfig({
enableOverlay,
enableTerminal,
env
});
});
},
configResolved(config) {
resolvedConfig = config;
resolvedRuntimePath = config.base + RUNTIME_PUBLIC_PATH.slice(1);
},
buildEnd() {
if (viteMode === "serve") {
checkers.forEach((checker2) => {
const { worker } = checker2.serve;
worker.terminate();
});
}
},
resolveId(id) {
if (viteMode === "serve") {
if (id === RUNTIME_PUBLIC_PATH) {
return id;
}
}
return;
},
load(id) {
if (viteMode === "serve") {
if (id === RUNTIME_PUBLIC_PATH) {
return runtimeCode;
}
}
return;
},
transform(code, id, options) {
if (id === RUNTIME_PUBLIC_PATH) {
if (!resolvedConfig)
return;
const devBase = resolvedConfig.base;
const hmrConfig = isObject(resolvedConfig.server.hmr) ? resolvedConfig.server.hmr : {};
const host = hmrConfig.host || null;
const protocol = hmrConfig.protocol || null;
let port = (hmrConfig == null ? void 0 : hmrConfig.clientPort) || (hmrConfig == null ? void 0 : hmrConfig.port) || null;
if (resolvedConfig.server.middlewareMode) {
port || (port = 24678);
}
let hmrBase = devBase;
if (hmrConfig == null ? void 0 : hmrConfig.path) {
hmrBase = path.posix.join(hmrBase, hmrConfig.path);
}
return code.replace(/__HMR_PROTOCOL__/g, JSON.stringify(protocol)).replace(/__HMR_HOSTNAME__/g, JSON.stringify(host)).replace(/__HMR_PORT__/g, JSON.stringify(port)).replace(/__HMR_BASE__/g, JSON.stringify(hmrBase));
}
return null;
},
transformIndexHtml() {
if (viteMode === "serve") {
return [
{
tag: "script",
attrs: { type: "module" },
children: `import { inject } from "${resolvedRuntimePath}";
inject({
overlayConfig: ${JSON.stringify(overlayConfig)},
base: "${resolvedConfig == null ? void 0 : resolvedConfig.base}",
});`
}
];
}
return;
},
buildStart: () => {
if (viteMode !== "build" || !enableBuild)
return;
const localEnv = npmRunPath.env({
env: process.env,
cwd: process.cwd(),
execPath: process.execPath
});
(async () => {
const exitCodes = await Promise.all(
checkers.map((checker2) => spawnChecker(checker2, userConfig, localEnv))
);
const exitCode = exitCodes.find((code) => code !== 0) ?? 0;
if (exitCode !== 0 && !(resolvedConfig == null ? void 0 : resolvedConfig.build.watch)) {
process.exit(exitCode);
}
})();
},
configureServer(server) {
let connectedTimes = 0;
let latestOverlayErrors = new Array(checkers.length);
checkers.forEach((checker2, index) => {
const { worker, configureServer: workerConfigureServer } = checker2.serve;
workerConfigureServer({ root: server.config.root });
worker.on("message", (action) => {
if (action.type === ACTION_TYPES.overlayError) {
latestOverlayErrors[index] = action.payload;
if (action.payload) {
server.ws.send(action.payload);
}
} else if (action.type === ACTION_TYPES.console) {
Checker.log(action);
}
});
});
return () => {
if (server.ws.on) {
server.ws.on("connection", () => {
connectedTimes++;
if (connectedTimes > 1) {
server.ws.send({
type: "custom",
event: WS_CHECKER_RECONNECT_EVENT,
data: latestOverlayErrors.filter(Boolean)
});
}
});
} else {
setTimeout(() => {
console.warn(
chalk.yellow(
"[vite-plugin-checker]: `server.ws.on` is introduced to Vite in 2.6.8, see [PR](https://github.com/vitejs/vite/pull/5273) and [changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md#268-2021-10-18). \nvite-plugin-checker relies on `server.ws.on` to bring diagnostics back after a full reload and it' not available for you now due to the old version of Vite. You can upgrade Vite to latest version to eliminate this warning."
)
);
}, 5e3);
}
server.middlewares.use((req, res, next) => {
next();
});
};
}
};
}
function spawnChecker(checker2, userConfig, localEnv) {
return new Promise((resolve) => {
const buildBin = checker2.build.buildBin;
const finalBin = typeof buildBin === "function" ? buildBin(userConfig) : buildBin;
const proc = spawn(...finalBin, {
cwd: process.cwd(),
stdio: "inherit",
env: localEnv,
shell: true
});
proc.on("exit", (code) => {
if (code !== null && code !== 0) {
resolve(code);
} else {
resolve(0);
}
});
});
}
function isObject(value) {
return Object.prototype.toString.call(value) === "[object Object]";
}
var main_default = checker;
export {
checker,
main_default as default
};
//# sourceMappingURL=main.js.map

File diff suppressed because one or more lines are too long

216
node_modules/vite-plugin-checker/dist/esm/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,216 @@
import { CustomPayload, ErrorPayload, ConfigEnv } from 'vite';
import { Worker } from 'worker_threads';
import { ESLint } from 'eslint';
import * as Stylelint from 'stylelint';
import { VlsOptions } from './checkers/vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
interface TsConfigOptions {
/**
* path to tsconfig.json file
*/
tsconfigPath: string;
/**
* root path of cwd
*/
root: string;
/**
* root path of cwd
*/
buildMode: boolean;
}
/**
* TypeScript checker configuration
* @default true
*/
declare type TscConfig =
/**
* - set to `true` to enable type checking with default configuration
* - set to `false` to disable type checking, you can also remove `config.typescript` directly
*/
boolean | Partial<TsConfigOptions>;
/** vue-tsc checker configuration */
declare type VueTscConfig =
/**
* - set to `true` to enable type checking with default configuration
* - set to `false` to disable type checking, you can also remove `config.vueTsc` directly
*/
boolean | Partial<Omit<TsConfigOptions, 'buildMode'>>;
/** vls checker configuration */
declare type VlsConfig = boolean | DeepPartial<VlsOptions>;
/** ESLint checker configuration */
declare type EslintConfig = false | {
/**
* lintCommand will be executed at build mode, and will also be used as
* default config for dev mode when options.eslint.dev.eslint is nullable.
*/
lintCommand: string;
dev?: Partial<{
/** You can override the options of translated from lintCommand. */
overrideConfig: ESLint.Options;
/** which level of the diagnostic will be emitted from plugin */
logLevel: ('error' | 'warning')[];
}>;
};
/** Stylelint checker configuration */
declare type StylelintConfig = false | {
/**
* lintCommand will be executed at build mode, and will also be used as
* default config for dev mode when options.stylelint.dev.stylelint is nullable.
*/
lintCommand: string;
dev?: Partial<{
/** You can override the options of translated from lintCommand. */
overrideConfig: Stylelint.LinterOptions;
/** which level of the diagnostic will be emitted from plugin */
logLevel: ('error' | 'warning')[];
}>;
};
declare enum DiagnosticLevel {
Warning = 0,
Error = 1,
Suggestion = 2,
Message = 3
}
declare type ErrorPayloadErr = ErrorPayload['err'];
interface DiagnosticToRuntime extends ErrorPayloadErr {
checkerId: string;
level?: DiagnosticLevel;
}
/** checkers shared configuration */
interface SharedConfig {
/**
* Show overlay on UI view when there are errors or warnings in dev mode.
* - Set `true` to show overlay
* - Set `false` to disable overlay
* - Set with a object to customize overlay
*
* @defaultValue `true`
*/
overlay: boolean | {
/**
* Set this true if you want the overlay to default to being open if
* errors/warnings are found
* @defaultValue `true`
*/
initialIsOpen?: boolean;
/**
* The position of the vite-plugin-checker badge to open and close
* the diagnostics panel
* @default `bl`
*/
position?: 'tl' | 'tr' | 'bl' | 'br';
/**
* Use this to add extra style string to the badge button, the string format is
* [Svelte style](https://svelte.dev/docs#template-syntax-element-directives-style-property)
* For example, if you want to hide the badge,
* you can pass `display: none;` to the badgeStyle property
* @default no default value
*/
badgeStyle?: string;
/**
* Use this to add extra style string to the diagnostic panel, the string format is
* [Svelte style](https://svelte.dev/docs#template-syntax-element-directives-style-property)
* For example, if you want to change the opacity of the panel,
* you can pass `opacity: 0.8;` to the panelStyle property
* @default no default value
*/
panelStyle?: string;
};
/**
* stdout in terminal which starts the Vite server in dev mode.
* - Set `true` to enable
* - Set `false` to disable
*
* @defaultValue `true`
*/
terminal: boolean;
/**
* Enable checking in build mode
* @defaultValue `true`
*/
enableBuild: boolean;
}
interface BuildInCheckers {
typescript: TscConfig;
vueTsc: VueTscConfig;
vls: VlsConfig;
eslint: EslintConfig;
stylelint: StylelintConfig;
}
declare type BuildInCheckerNames = keyof BuildInCheckers;
declare type PluginConfig = SharedConfig & BuildInCheckers;
/** Userland plugin configuration */
declare type UserPluginConfig = Partial<PluginConfig>;
declare enum ACTION_TYPES {
config = "config",
configureServer = "configureServer",
overlayError = "overlayError",
console = "console",
unref = "unref"
}
interface Action {
type: string;
payload: unknown;
}
interface OverlayErrorAction extends Action {
type: ACTION_TYPES.overlayError;
/**
* send `CustomPayload` to raise error overlay provided by Vite
* send `null` to clear overlay for current checker
*/
payload: CustomPayload | null;
}
interface ConfigActionPayload {
enableOverlay: boolean;
enableTerminal: boolean;
env: ConfigEnv;
}
interface ConfigAction extends Action {
type: ACTION_TYPES.config;
payload: ConfigActionPayload;
}
interface ConfigureServerAction extends Action {
type: ACTION_TYPES.configureServer;
payload: {
root: string;
};
}
interface UnrefAction extends Action {
type: ACTION_TYPES.unref;
}
declare type Actions = OverlayErrorAction | ConfigAction | ConfigureServerAction | UnrefAction;
declare type BuildCheckBin = BuildCheckBinStr | BuildCheckBinFn;
declare type BuildCheckBinStr = [string, ReadonlyArray<string>];
declare type BuildCheckBinFn = (config: UserPluginConfig) => [string, ReadonlyArray<string>];
interface ConfigureServeChecker {
worker: Worker;
config: (config: ConfigAction['payload']) => void;
configureServer: (serverConfig: ConfigureServerAction['payload']) => void;
}
interface ServeAndBuildChecker {
serve: ConfigureServeChecker;
build: {
buildBin: BuildCheckBin;
buildFile?: string;
};
}
/**
* create serve & build checker
*/
interface ServeChecker<T extends BuildInCheckerNames = any> {
createDiagnostic: CreateDiagnostic<T>;
}
interface CheckerDiagnostic {
config: (options: ConfigActionPayload) => unknown;
configureServer: (options: {
root: string;
}) => unknown;
}
declare type CreateDiagnostic<T extends BuildInCheckerNames = any> = (config: Pick<BuildInCheckers, T> & SharedConfig) => CheckerDiagnostic;
declare type DeepPartial<T> = {
[P in keyof T]?: DeepPartial<T[P]>;
};
export { ACTION_TYPES, Actions, BuildCheckBin, BuildCheckBinFn, BuildCheckBinStr, BuildInCheckerNames, BuildInCheckers, CheckerDiagnostic, ConfigAction, ConfigureServeChecker, ConfigureServerAction, CreateDiagnostic, DeepPartial, DiagnosticLevel, DiagnosticToRuntime, EslintConfig, OverlayErrorAction, PluginConfig, ServeAndBuildChecker, ServeChecker, SharedConfig, StylelintConfig, TscConfig, UnrefAction, UserPluginConfig, VlsConfig, VueTscConfig };

20
node_modules/vite-plugin-checker/dist/esm/types.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
var DiagnosticLevel = /* @__PURE__ */ ((DiagnosticLevel2) => {
DiagnosticLevel2[DiagnosticLevel2["Warning"] = 0] = "Warning";
DiagnosticLevel2[DiagnosticLevel2["Error"] = 1] = "Error";
DiagnosticLevel2[DiagnosticLevel2["Suggestion"] = 2] = "Suggestion";
DiagnosticLevel2[DiagnosticLevel2["Message"] = 3] = "Message";
return DiagnosticLevel2;
})(DiagnosticLevel || {});
var ACTION_TYPES = /* @__PURE__ */ ((ACTION_TYPES2) => {
ACTION_TYPES2["config"] = "config";
ACTION_TYPES2["configureServer"] = "configureServer";
ACTION_TYPES2["overlayError"] = "overlayError";
ACTION_TYPES2["console"] = "console";
ACTION_TYPES2["unref"] = "unref";
return ACTION_TYPES2;
})(ACTION_TYPES || {});
export {
ACTION_TYPES,
DiagnosticLevel
};
//# sourceMappingURL=types.js.map

File diff suppressed because one or more lines are too long

4
node_modules/vite-plugin-checker/dist/esm/utils.d.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
declare const isInVitestEntryThread: string | false | undefined;
declare const isMainThread: string | boolean | undefined;
export { isInVitestEntryThread, isMainThread };

8
node_modules/vite-plugin-checker/dist/esm/utils.js generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import { isMainThread as _isMainThread, threadId } from "worker_threads";
const isInVitestEntryThread = threadId === 1 && process.env["VITEST"];
const isMainThread = _isMainThread || isInVitestEntryThread;
export {
isInVitestEntryThread,
isMainThread
};
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import { isMainThread as _isMainThread, threadId } from 'worker_threads'\n\n// since vitest run all cases in worker thread, we should compatible with it to pass E2E tests\nexport const isInVitestEntryThread = threadId === 1 && process.env['VITEST']\nexport const isMainThread = _isMainThread || isInVitestEntryThread\n"],"mappings":"AAAA,SAAS,gBAAgB,eAAe,gBAAgB;AAGjD,MAAM,wBAAwB,aAAa,KAAK,QAAQ,IAAI;AAC5D,MAAM,eAAe,iBAAiB;","names":[]}

21
node_modules/vite-plugin-checker/dist/esm/worker.d.ts generated vendored Normal file
View File

@@ -0,0 +1,21 @@
import { ConfigEnv } from 'vite';
import { SharedConfig, ServeAndBuildChecker, BuildInCheckers, BuildCheckBin, ServeChecker } from './types.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import './checkers/vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
interface WorkerScriptOptions {
absFilename: string;
buildBin: BuildCheckBin;
serverChecker: ServeChecker;
}
interface Script<T> {
mainScript: () => (config: T & SharedConfig, env: ConfigEnv) => ServeAndBuildChecker;
workerScript: () => void;
}
declare function createScript<T extends Partial<BuildInCheckers>>({ absFilename, buildBin, serverChecker, }: WorkerScriptOptions): Script<T>;
export { Script, createScript };

74
node_modules/vite-plugin-checker/dist/esm/worker.js generated vendored Normal file
View File

@@ -0,0 +1,74 @@
import { parentPort, Worker, workerData } from "worker_threads";
import { ACTION_TYPES } from "./types.js";
function createScript({
absFilename,
buildBin,
serverChecker
}) {
return {
mainScript: () => {
const createWorker = (checkerConfig, env) => {
const isBuild = env.command === "build";
const worker = new Worker(absFilename, {
workerData: { env, checkerConfig }
});
return {
worker,
config: (config) => {
if (isBuild)
return;
const configAction = { type: ACTION_TYPES.config, payload: config };
worker.postMessage(configAction);
},
configureServer: (serverConfig) => {
const configureServerAction = {
type: ACTION_TYPES.configureServer,
payload: serverConfig
};
worker.postMessage(configureServerAction);
}
};
};
return (config, env) => {
return {
serve: createWorker(config, env),
build: { buildBin }
};
};
},
workerScript: () => {
let diagnostic = null;
if (!parentPort)
throw Error("should have parentPort as file runs in worker thread");
const isBuild = workerData.env.command === "build";
const port = parentPort.on(
"message",
(action) => {
switch (action.type) {
case ACTION_TYPES.config: {
const checkerConfig = workerData.checkerConfig;
diagnostic = serverChecker.createDiagnostic(checkerConfig);
diagnostic.config(action.payload);
break;
}
case ACTION_TYPES.configureServer:
if (!diagnostic)
throw Error("diagnostic should be initialized in `config` hook of Vite");
diagnostic.configureServer(action.payload);
break;
case ACTION_TYPES.unref:
port.unref();
break;
}
}
);
if (isBuild) {
port.unref();
}
}
};
}
export {
createScript
};
//# sourceMappingURL=worker.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/worker.ts"],"sourcesContent":["import type { ConfigEnv } from 'vite'\nimport { parentPort, Worker, workerData } from 'worker_threads'\n\nimport { ACTION_TYPES } from './types.js'\n\nimport type {\n ServeChecker,\n ConfigureServeChecker,\n ConfigAction,\n ConfigureServerAction,\n CheckerDiagnostic,\n BuildCheckBin,\n ServeAndBuildChecker,\n SharedConfig,\n UnrefAction,\n BuildInCheckers,\n} from './types.js'\n\ninterface WorkerScriptOptions {\n absFilename: string\n buildBin: BuildCheckBin\n serverChecker: ServeChecker\n}\n\nexport interface Script<T> {\n mainScript: () => (config: T & SharedConfig, env: ConfigEnv) => ServeAndBuildChecker\n workerScript: () => void\n}\n\nexport function createScript<T extends Partial<BuildInCheckers>>({\n absFilename,\n buildBin,\n serverChecker,\n}: WorkerScriptOptions): Script<T> {\n type CheckerConfig = T & SharedConfig\n\n return {\n mainScript: () => {\n // initialized in main thread\n const createWorker = (\n checkerConfig: CheckerConfig,\n env: ConfigEnv\n ): ConfigureServeChecker => {\n const isBuild = env.command === 'build'\n const worker = new Worker(absFilename, {\n workerData: { env, checkerConfig },\n })\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return {\n worker,\n config: (config) => {\n if (isBuild) return // just run the command\n\n const configAction: ConfigAction = { type: ACTION_TYPES.config, payload: config }\n worker.postMessage(configAction)\n },\n configureServer: (serverConfig) => {\n const configureServerAction: ConfigureServerAction = {\n type: ACTION_TYPES.configureServer,\n payload: serverConfig,\n }\n\n worker.postMessage(configureServerAction)\n },\n }\n }\n\n return (config, env) => {\n return {\n serve: createWorker(config, env),\n build: { buildBin },\n }\n }\n },\n workerScript: () => {\n // runs in worker thread\n let diagnostic: CheckerDiagnostic | null = null\n if (!parentPort) throw Error('should have parentPort as file runs in worker thread')\n const isBuild = workerData.env.command === 'build'\n // only run bin command and do not listen message in build mode\n\n const port = parentPort.on(\n 'message',\n (action: ConfigAction | ConfigureServerAction | UnrefAction) => {\n switch (action.type) {\n case ACTION_TYPES.config: {\n const checkerConfig: T & SharedConfig = workerData.checkerConfig\n diagnostic = serverChecker.createDiagnostic(checkerConfig)\n diagnostic.config(action.payload)\n break\n }\n case ACTION_TYPES.configureServer:\n if (!diagnostic)\n throw Error('diagnostic should be initialized in `config` hook of Vite')\n diagnostic.configureServer(action.payload)\n break\n case ACTION_TYPES.unref:\n port.unref()\n break\n }\n }\n )\n\n if (isBuild) {\n port.unref()\n }\n },\n }\n}\n"],"mappings":"AACA,SAAS,YAAY,QAAQ,kBAAkB;AAE/C,SAAS,oBAAoB;AA0BtB,SAAS,aAAiD;AAAA,EAC/D;AAAA,EACA;AAAA,EACA;AACF,GAAmC;AAGjC,SAAO;AAAA,IACL,YAAY,MAAM;AAEhB,YAAM,eAAe,CACnB,eACA,QAC0B;AAC1B,cAAM,UAAU,IAAI,YAAY;AAChC,cAAM,SAAS,IAAI,OAAO,aAAa;AAAA,UACrC,YAAY,EAAE,KAAK,cAAc;AAAA,QACnC,CAAC;AAGD,eAAO;AAAA,UACL;AAAA,UACA,QAAQ,CAAC,WAAW;AAClB,gBAAI;AAAS;AAEb,kBAAM,eAA6B,EAAE,MAAM,aAAa,QAAQ,SAAS,OAAO;AAChF,mBAAO,YAAY,YAAY;AAAA,UACjC;AAAA,UACA,iBAAiB,CAAC,iBAAiB;AACjC,kBAAM,wBAA+C;AAAA,cACnD,MAAM,aAAa;AAAA,cACnB,SAAS;AAAA,YACX;AAEA,mBAAO,YAAY,qBAAqB;AAAA,UAC1C;AAAA,QACF;AAAA,MACF;AAEA,aAAO,CAAC,QAAQ,QAAQ;AACtB,eAAO;AAAA,UACL,OAAO,aAAa,QAAQ,GAAG;AAAA,UAC/B,OAAO,EAAE,SAAS;AAAA,QACpB;AAAA,MACF;AAAA,IACF;AAAA,IACA,cAAc,MAAM;AAElB,UAAI,aAAuC;AAC3C,UAAI,CAAC;AAAY,cAAM,MAAM,sDAAsD;AACnF,YAAM,UAAU,WAAW,IAAI,YAAY;AAG3C,YAAM,OAAO,WAAW;AAAA,QACtB;AAAA,QACA,CAAC,WAA+D;AAC9D,kBAAQ,OAAO;AAAA,iBACR,aAAa,QAAQ;AACxB,oBAAM,gBAAkC,WAAW;AACnD,2BAAa,cAAc,iBAAiB,aAAa;AACzD,yBAAW,OAAO,OAAO,OAAO;AAChC;AAAA,YACF;AAAA,iBACK,aAAa;AAChB,kBAAI,CAAC;AACH,sBAAM,MAAM,2DAA2D;AACzE,yBAAW,gBAAgB,OAAO,OAAO;AACzC;AAAA,iBACG,aAAa;AAChB,mBAAK,MAAM;AACX;AAAA;AAAA,QAEN;AAAA,MACF;AAEA,UAAI,SAAS;AACX,aAAK,MAAM;AAAA,MACb;AAAA,IACF;AAAA,EACF;AACF;","names":[]}