migration-validator 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +105 -2
- package/dist/cli.js +63 -0
- package/dist/reader.js +34 -0
- package/dist/report.js +9 -0
- package/dist/validator.js +16 -0
- package/package.json +36 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Zenkie
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,106 @@
|
|
|
1
|
-
#
|
|
1
|
+
# migration-validator
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Validate every row of a CSV or JSON file against a [Zod](https://zod.dev) schema before you migrate it, and get a report of what is wrong and where.
|
|
4
|
+
|
|
5
|
+
It is read-only: it never writes to, fixes or moves your data. It exits with a non-zero code when any row is invalid, so it can block a CI pipeline.
|
|
6
|
+
|
|
7
|
+
## Requirements
|
|
8
|
+
|
|
9
|
+
- Node.js 24 or newer (schema files written in TypeScript are loaded through Node's built-in type stripping)
|
|
10
|
+
- `zod` 4 installed in the project that holds your schema
|
|
11
|
+
|
|
12
|
+
## Usage
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npx migration-validator customers.csv --schema ./customer-schema.ts
|
|
16
|
+
npx migration-validator orders.json --schema ./order-schema.ts --format json
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The schema file must export a Zod object schema as its default export:
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { z } from 'zod';
|
|
23
|
+
|
|
24
|
+
export default z.object({
|
|
25
|
+
id: z.coerce.number().int().positive(),
|
|
26
|
+
email: z.email(),
|
|
27
|
+
signupDate: z.iso.date(),
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### Text report (default)
|
|
32
|
+
|
|
33
|
+
```text
|
|
34
|
+
Line 2, field "status": Invalid option: expected one of "pending"|"paid"|"shipped"|"cancelled"
|
|
35
|
+
Line 2, field "total": Too small: expected number to be >=0
|
|
36
|
+
Line 3, field "items": Too small: expected array to have >=1 items
|
|
37
|
+
|
|
38
|
+
Rows: 4 total, 1 valid, 3 invalid
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### JSON report
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
{
|
|
45
|
+
"summary": { "total": 4, "valid": 1, "invalid": 3 },
|
|
46
|
+
"errors": [
|
|
47
|
+
{ "line": 2, "field": "status", "message": "Invalid option: expected one of \"pending\"|\"paid\"|\"shipped\"|\"cancelled\"" }
|
|
48
|
+
]
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Nested fields are joined with dots (`items.0.sku`). Errors about the record as a whole use the field `(root)`.
|
|
53
|
+
|
|
54
|
+
## Options
|
|
55
|
+
|
|
56
|
+
| Option | Required | Default | Description |
|
|
57
|
+
| --- | --- | --- | --- |
|
|
58
|
+
| `<file>` | yes | | Input file. The extension decides the parser: `.csv` or `.json`. |
|
|
59
|
+
| `--schema <path>` | yes | | File whose default export is the Zod schema for one row. |
|
|
60
|
+
| `--format <text\|json>` | no | `text` | Report format, written to stdout. |
|
|
61
|
+
|
|
62
|
+
## Exit codes
|
|
63
|
+
|
|
64
|
+
| Code | Meaning |
|
|
65
|
+
| --- | --- |
|
|
66
|
+
| `0` | Every row is valid. |
|
|
67
|
+
| `1` | At least one row is invalid. |
|
|
68
|
+
| `2` | The command could not run: bad arguments, unreadable input, unsupported extension or an invalid schema file. The reason is printed to stderr. |
|
|
69
|
+
|
|
70
|
+
## Input formats
|
|
71
|
+
|
|
72
|
+
- **CSV**: the first row is the header and its names become the field names. `line` is the line in the file where the record starts, so the first data row is line 2. Empty lines are skipped, and a quoted field may span several lines.
|
|
73
|
+
- **JSON**: the file must be an array of records. `line` is the record's 1-based position in the array.
|
|
74
|
+
|
|
75
|
+
## Examples
|
|
76
|
+
|
|
77
|
+
The `examples` folder has made-up data for trying the tool:
|
|
78
|
+
|
|
79
|
+
```sh
|
|
80
|
+
node src/cli.ts examples/customers.csv --schema examples/customer-schema.ts
|
|
81
|
+
node src/cli.ts examples/orders.json --schema examples/order-schema.ts
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`customers.csv` is fully valid. `orders.json` has three broken orders.
|
|
85
|
+
|
|
86
|
+
## Limitations
|
|
87
|
+
|
|
88
|
+
- The schema file is executed as code. Only point `--schema` at files you trust.
|
|
89
|
+
- The whole input file is read into memory. There is no streaming, so very large files need enough RAM.
|
|
90
|
+
- Every CSV value is a string. Use `z.coerce` (for example `z.coerce.number()`) for numbers, booleans and dates.
|
|
91
|
+
- For JSON, `line` is the position in the array, not the line in the text file.
|
|
92
|
+
- TypeScript schema files only support erasable syntax (no `enum` or `namespace`), and Node does not strip types from files inside `node_modules`. A `.js` or `.mjs` schema file works too.
|
|
93
|
+
- Only `.csv` and `.json` extensions are recognized, and the CSV delimiter is always a comma.
|
|
94
|
+
|
|
95
|
+
## Development
|
|
96
|
+
|
|
97
|
+
```sh
|
|
98
|
+
pnpm install
|
|
99
|
+
pnpm typecheck
|
|
100
|
+
pnpm test
|
|
101
|
+
pnpm build
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## License
|
|
105
|
+
|
|
106
|
+
[MIT](LICENSE)
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
3
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
4
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
5
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
return path;
|
|
9
|
+
};
|
|
10
|
+
import { resolve } from 'node:path';
|
|
11
|
+
import { pathToFileURL } from 'node:url';
|
|
12
|
+
import { parseArgs } from 'node:util';
|
|
13
|
+
import { readRows } from "./reader.js";
|
|
14
|
+
import { formatJsonReport, formatTextReport } from "./report.js";
|
|
15
|
+
import { validateRows } from "./validator.js";
|
|
16
|
+
const USAGE = 'Usage: migration-validator <file.csv|file.json> --schema <schema-file> [--format text|json]';
|
|
17
|
+
const REPORT_FORMATTERS = { text: formatTextReport, json: formatJsonReport };
|
|
18
|
+
const EXIT_ALL_VALID = 0;
|
|
19
|
+
const EXIT_INVALID_ROWS = 1;
|
|
20
|
+
const EXIT_USAGE_OR_RUNTIME_ERROR = 2;
|
|
21
|
+
function isReportFormat(format) {
|
|
22
|
+
return Object.hasOwn(REPORT_FORMATTERS, format);
|
|
23
|
+
}
|
|
24
|
+
function isZodSchema(candidate) {
|
|
25
|
+
return typeof candidate?.safeParse === 'function';
|
|
26
|
+
}
|
|
27
|
+
async function loadSchema(schemaPath) {
|
|
28
|
+
const schemaModule = await import(__rewriteRelativeImportExtension(pathToFileURL(resolve(schemaPath)).href));
|
|
29
|
+
if (!isZodSchema(schemaModule.default)) {
|
|
30
|
+
throw new Error(`${schemaPath} must export a Zod schema as its default export`);
|
|
31
|
+
}
|
|
32
|
+
return schemaModule.default;
|
|
33
|
+
}
|
|
34
|
+
async function main() {
|
|
35
|
+
const { values, positionals } = parseArgs({
|
|
36
|
+
allowPositionals: true,
|
|
37
|
+
options: {
|
|
38
|
+
schema: { type: 'string' },
|
|
39
|
+
format: { type: 'string', default: 'text' },
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
const [inputPath, ...unexpectedPositionals] = positionals;
|
|
43
|
+
const schemaPath = values.schema;
|
|
44
|
+
const hasRequiredArguments = inputPath !== undefined && schemaPath !== undefined;
|
|
45
|
+
if (!hasRequiredArguments || unexpectedPositionals.length > 0) {
|
|
46
|
+
throw new Error(USAGE);
|
|
47
|
+
}
|
|
48
|
+
if (!isReportFormat(values.format)) {
|
|
49
|
+
throw new Error(`Unknown format "${values.format}". Use text or json`);
|
|
50
|
+
}
|
|
51
|
+
const formatReport = REPORT_FORMATTERS[values.format];
|
|
52
|
+
const schema = await loadSchema(schemaPath);
|
|
53
|
+
const result = validateRows(await readRows(inputPath), schema);
|
|
54
|
+
process.stdout.write(formatReport(result));
|
|
55
|
+
return result.invalid === 0 ? EXIT_ALL_VALID : EXIT_INVALID_ROWS;
|
|
56
|
+
}
|
|
57
|
+
main().then((exitCode) => {
|
|
58
|
+
process.exitCode = exitCode;
|
|
59
|
+
}, (failure) => {
|
|
60
|
+
const reason = failure instanceof Error ? failure.message : String(failure);
|
|
61
|
+
process.stderr.write(`Error: ${reason}\n`);
|
|
62
|
+
process.exitCode = EXIT_USAGE_OR_RUNTIME_ERROR;
|
|
63
|
+
});
|
package/dist/reader.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { extname } from 'node:path';
|
|
3
|
+
import { parse } from 'csv-parse/sync';
|
|
4
|
+
const BYTE_ORDER_MARK = /^/;
|
|
5
|
+
const ANY_LINE_BREAK = /\r\n?/g;
|
|
6
|
+
function countLineBreaks(values) {
|
|
7
|
+
return values.join('').split('\n').length - 1;
|
|
8
|
+
}
|
|
9
|
+
export function parseCsv(content) {
|
|
10
|
+
const entries = parse(content.replace(ANY_LINE_BREAK, '\n'), {
|
|
11
|
+
columns: true,
|
|
12
|
+
skip_empty_lines: true,
|
|
13
|
+
bom: true,
|
|
14
|
+
info: true,
|
|
15
|
+
});
|
|
16
|
+
return entries.map(({ record, info }) => ({
|
|
17
|
+
line: info.lines - countLineBreaks(Object.values(record)),
|
|
18
|
+
record,
|
|
19
|
+
}));
|
|
20
|
+
}
|
|
21
|
+
export function parseJson(content) {
|
|
22
|
+
const document = JSON.parse(content.replace(BYTE_ORDER_MARK, ''));
|
|
23
|
+
if (!Array.isArray(document))
|
|
24
|
+
throw new Error('JSON input must be an array of records');
|
|
25
|
+
return document.map((record, index) => ({ line: index + 1, record }));
|
|
26
|
+
}
|
|
27
|
+
export async function readRows(filePath) {
|
|
28
|
+
const extension = extname(filePath).toLowerCase();
|
|
29
|
+
if (extension === '.csv')
|
|
30
|
+
return parseCsv(await readFile(filePath, 'utf8'));
|
|
31
|
+
if (extension === '.json')
|
|
32
|
+
return parseJson(await readFile(filePath, 'utf8'));
|
|
33
|
+
throw new Error(`Unsupported file extension "${extension}". Use .csv or .json`);
|
|
34
|
+
}
|
package/dist/report.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export function formatTextReport({ total, valid, invalid, errors }) {
|
|
2
|
+
const errorLines = errors.map(({ line, field, message }) => `Line ${line}, field "${field}": ${message}`);
|
|
3
|
+
const summaryLine = `Rows: ${total} total, ${valid} valid, ${invalid} invalid`;
|
|
4
|
+
const separator = errorLines.length > 0 ? [''] : [];
|
|
5
|
+
return [...errorLines, ...separator, summaryLine, ''].join('\n');
|
|
6
|
+
}
|
|
7
|
+
export function formatJsonReport({ total, valid, invalid, errors }) {
|
|
8
|
+
return `${JSON.stringify({ summary: { total, valid, invalid }, errors }, null, 2)}\n`;
|
|
9
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const ROOT_FIELD = '(root)';
|
|
2
|
+
export function validateRows(rows, schema) {
|
|
3
|
+
const errors = [];
|
|
4
|
+
let invalid = 0;
|
|
5
|
+
for (const { line, record } of rows) {
|
|
6
|
+
const outcome = schema.safeParse(record);
|
|
7
|
+
if (outcome.success)
|
|
8
|
+
continue;
|
|
9
|
+
invalid += 1;
|
|
10
|
+
for (const issue of outcome.error.issues) {
|
|
11
|
+
const field = issue.path.map(String).join('.') || ROOT_FIELD;
|
|
12
|
+
errors.push({ line, field, message: issue.message });
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
return { total: rows.length, valid: rows.length - invalid, invalid, errors };
|
|
16
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "migration-validator",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Read-only CLI that validates CSV or JSON rows against a Zod schema and reports errors per line.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Zenkie",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"bin": {
|
|
9
|
+
"migration-validator": "dist/cli.js"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=24"
|
|
16
|
+
},
|
|
17
|
+
"packageManager": "pnpm@11.29.0",
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc -p tsconfig.build.json",
|
|
20
|
+
"typecheck": "tsc --noEmit",
|
|
21
|
+
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
|
|
22
|
+
"prepublishOnly": "pnpm build"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"csv-parse": "7.0.3"
|
|
26
|
+
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"zod": "^4.0.0"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/jest": "30.0.0",
|
|
32
|
+
"@types/node": "24.19.4",
|
|
33
|
+
"jest": "30.5.2",
|
|
34
|
+
"ts-jest": "29.4.15",
|
|
35
|
+
"typescript": "6.0.3",
|
|
36
|
+
"zod": "4.6.7"
|
|
37
|
+
}
|
|
38
|
+
}
|