vite-plugin-i18n-validator
Version:
A Vite plugin validates Json files with internationalization support in worker thread.
84 lines (81 loc) • 2.28 kB
JavaScript
// src/worker.ts
import { parentPort } from "worker_threads";
// src/checker.ts
var compareWithBaseFile = (json, cachedBaseFile, prohibitedKeys, prohibitedValues, ignoreKeysFilter, ignoreKeys) => {
const errors = [];
for (let i = 0; i < cachedBaseFile.length; i++) {
const result = checkNestedProperty(
json,
cachedBaseFile[i],
prohibitedKeys,
prohibitedValues,
ignoreKeysFilter,
ignoreKeys
);
if (result === true) {
continue;
}
if (result.notFound) {
errors.push(`Not found: '${cachedBaseFile[i]}'`);
} else if (result.noValue) {
errors.push(`No value: '${cachedBaseFile[i]}'`);
} else if (result.prohibitedKey) {
errors.push(`Prohibited key: '${cachedBaseFile[i]}'`);
} else if (result.prohibitedValue) {
errors.push(`Prohibited value: '${cachedBaseFile[i]}'`);
}
}
return errors;
};
var checkNestedProperty = (obj, propertyPath, prohibitedKeys, prohibitedValues, ignoreKeysFilter, ignoreKeys) => {
if (ignoreKeys && ignoreKeysFilter && ignoreKeysFilter(propertyPath)) {
return true;
}
const properties = propertyPath.split(".");
for (let i = 0; i < properties.length; i++) {
const prop = properties[i];
if (prohibitedKeys && prohibitedKeys.includes(prop)) {
return { prohibitedKey: true };
}
if (!obj.hasOwnProperty(prop)) {
return { notFound: true };
} else {
obj = obj[prop];
if (!obj) {
return { noValue: true };
} else if (typeof obj === "string" && prohibitedValues) {
for (let j = 0; j < prohibitedValues.length; j++) {
if (obj.includes(prohibitedValues[j])) {
return { prohibitedValue: true };
}
}
}
}
}
return true;
};
// src/worker.ts
import { createFilter } from "vite";
parentPort?.on(
"message",
(msg) => {
const {
json,
cachedBaseFile,
prohibitedValues,
prohibitedKeys,
file,
ignoreKeys
} = msg;
const ignoreKeysFilter = createFilter(ignoreKeys);
const errors = compareWithBaseFile(
json,
cachedBaseFile,
prohibitedKeys,
prohibitedValues,
ignoreKeysFilter,
ignoreKeys
);
parentPort?.postMessage({ errors, file });
}
);