@konstit/csv 0.6.0 → 0.7.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/README.md +113 -101
- package/THIRD_PARTY_NOTICES.md +27 -0
- package/dist/api.d.ts +84 -57
- package/dist/api.js +211 -40
- package/dist/batch-pipeline.d.ts +10 -0
- package/dist/batch-pipeline.js +83 -0
- package/dist/batches.d.ts +36 -1
- package/dist/batches.js +241 -5
- package/dist/cli-command.d.ts +7 -7
- package/dist/cli-command.js +325 -164
- package/dist/cli-schema.d.ts +51 -21
- package/dist/cli-schema.js +126 -65
- package/dist/cli.js +1 -1
- package/dist/file-stream.d.ts +66 -18
- package/dist/file-stream.js +534 -199
- package/dist/files.d.ts +17 -37
- package/dist/files.js +50 -21
- package/dist/gzip-reader.d.ts +2 -0
- package/dist/gzip-reader.js +37 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/inspect-file.d.ts +26 -3
- package/dist/inspect-file.js +169 -74
- package/dist/inspect-zip.d.ts +26 -0
- package/dist/inspect-zip.js +59 -0
- package/dist/latin1-rows.d.ts +11 -3
- package/dist/latin1-rows.js +276 -75
- package/dist/materialize-field.d.ts +6 -0
- package/dist/materialize-field.js +9 -0
- package/dist/native.d.ts +118 -20
- package/dist/native.js +53 -23
- package/dist/normalize.d.ts +7 -1
- package/dist/normalize.js +49 -9
- package/dist/options.d.ts +27 -12
- package/dist/parser.d.ts +34 -14
- package/dist/parser.js +296 -102
- package/dist/strict-schema.d.ts +7 -8
- package/dist/strict-schema.js +45 -83
- package/dist/transforms.d.ts +1 -3
- package/dist/transforms.js +17 -16
- package/dist/types.d.ts +192 -75
- package/dist/zip-entry.d.ts +14 -0
- package/dist/zip-entry.js +155 -0
- package/dist/zip-reader.d.ts +14 -3
- package/dist/zip-reader.js +65 -23
- package/package.json +34 -23
- package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
- package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
- package/prebuilds/linux-x64/libcsv_native.so +0 -0
- package/prebuilds/manifest.json +18 -8
- package/prebuilds/provenance/darwin-arm64.json +1 -1
- package/prebuilds/provenance/darwin-x64.json +1 -1
- package/prebuilds/provenance/linux-x64.json +1 -1
package/dist/cli-command.js
CHANGED
|
@@ -1,50 +1,33 @@
|
|
|
1
|
-
import { csv } from "./api.js";
|
|
2
1
|
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
} from "./
|
|
2
|
+
CommandFailure
|
|
3
|
+
} from "@konstit/cli";
|
|
4
|
+
import { csv } from "./api.js";
|
|
6
5
|
import { formatBytes } from "./format-bytes.js";
|
|
7
|
-
import { inspectCsvFile } from "./inspect-file.js";
|
|
8
6
|
import {
|
|
7
|
+
inspectCsvFile,
|
|
8
|
+
ZipProbeError
|
|
9
|
+
} from "./inspect-file.js";
|
|
10
|
+
import {
|
|
11
|
+
MAX_FILTER_NESTING,
|
|
9
12
|
normalizeFilterColumn,
|
|
10
13
|
validateRegex
|
|
11
14
|
} from "./normalize.js";
|
|
12
15
|
import { snapshotTransforms } from "./transforms.js";
|
|
13
|
-
|
|
16
|
+
import { AmbiguousZipGlobError } from "./zip-entry.js";
|
|
14
17
|
const OUTPUT_BUFFER_SIZE = 65536;
|
|
15
|
-
export async function
|
|
16
|
-
const result = csvCommand.tryParse(arguments_);
|
|
17
|
-
if (result.type === "display")
|
|
18
|
-
return csvCommand.runParsed(result, customOutput && { stdout: (text) => customOutput.log(text.trimEnd()) });
|
|
19
|
-
const output = customOutput ?? {
|
|
20
|
-
log: console.log,
|
|
21
|
-
error: console.error,
|
|
22
|
-
write: (chunk) => Bun.write(Bun.stdout, chunk)
|
|
23
|
-
};
|
|
24
|
-
if (result.type === "error")
|
|
25
|
-
return usageError(output, result.error.message, `${result.error.commandPath.join(" ")} --help`);
|
|
26
|
-
const { subcommand } = result.value;
|
|
27
|
-
switch (subcommand.name) {
|
|
28
|
-
case "count":
|
|
29
|
-
return runCount(subcommand.args, output);
|
|
30
|
-
case "lines":
|
|
31
|
-
return runLines(subcommand.args, output);
|
|
32
|
-
case "probe":
|
|
33
|
-
return runProbe(subcommand.args, output);
|
|
34
|
-
case "completion":
|
|
35
|
-
return runCompletion(subcommand.args.shell, output);
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
async function runCompletion(shell, output) {
|
|
39
|
-
const { generateCompletion } = await import("@konstit/cli/completion");
|
|
40
|
-
output.log(generateCompletion(csvCommand, shell).trimEnd());
|
|
41
|
-
return 0;
|
|
42
|
-
}
|
|
43
|
-
async function runProbe(args, output) {
|
|
18
|
+
export async function runProbe(args, { stdout, stderr }) {
|
|
44
19
|
try {
|
|
45
|
-
const result = await inspectCsvFile(args.path, {
|
|
20
|
+
const result = await inspectCsvFile(args.path, {
|
|
21
|
+
zipEntry: args.zipEntry,
|
|
22
|
+
encoding: args.encoding,
|
|
23
|
+
delimiter: args.delimiter,
|
|
24
|
+
compression: args.compression,
|
|
25
|
+
sampleSize: args.sampleSize,
|
|
26
|
+
explain: !0
|
|
27
|
+
});
|
|
46
28
|
if (args.json) {
|
|
47
|
-
|
|
29
|
+
await stdout(`${JSON.stringify(result)}
|
|
30
|
+
`);
|
|
48
31
|
return 0;
|
|
49
32
|
}
|
|
50
33
|
const lines = [
|
|
@@ -52,117 +35,235 @@ async function runProbe(args, output) {
|
|
|
52
35
|
`Encoding: ${result.encoding}${result.encodingSource === "explicit" ? " (explicit)" : ""}`,
|
|
53
36
|
`Delimiter: ${result.delimiter === null ? "undetermined" : JSON.stringify(result.delimiter)}${result.delimiterSource === "explicit" ? " (explicit)" : ""}`,
|
|
54
37
|
`Line endings: ${result.lineEnding}`,
|
|
55
|
-
`Compression: ${result.compression}`,
|
|
56
|
-
`First record columns: ${String(result.firstRecordColumns ?? "unknown")}
|
|
38
|
+
`Compression: ${result.compression}${result.compressionSource === "explicit" ? " (explicit)" : ""}`,
|
|
39
|
+
`First record columns: ${String(result.firstRecordColumns ?? "unknown")}`,
|
|
40
|
+
`Sample: ${formatBytes(result.sampleBytes)} of decompressed data (${result.sampleReachedEof ? "complete" : "partial"})`,
|
|
41
|
+
`Sampled records: ${String(result.sampledRecords ?? "unknown")}`
|
|
57
42
|
];
|
|
43
|
+
if (result.minRecordColumns !== null && result.maxRecordColumns !== null) {
|
|
44
|
+
const min = String(result.minRecordColumns);
|
|
45
|
+
const max = String(result.maxRecordColumns);
|
|
46
|
+
lines.push(`Sampled columns: ${min === max ? min : `${min}\u2013${max}`}`);
|
|
47
|
+
}
|
|
58
48
|
if (result.zipEntry !== null)
|
|
59
49
|
lines.push(`ZIP entry: ${JSON.stringify(result.zipEntry)}`);
|
|
60
|
-
if (result.
|
|
61
|
-
lines.push(`
|
|
62
|
-
|
|
63
|
-
|
|
50
|
+
if (result.explanation !== void 0)
|
|
51
|
+
lines.push(`Encoding detail: ${result.explanation.encoding}`);
|
|
52
|
+
const delimiterDetail = result.delimiterReason ?? result.explanation?.delimiter;
|
|
53
|
+
if (delimiterDetail !== void 0)
|
|
54
|
+
lines.push(`Delimiter detail: ${delimiterDetail}`);
|
|
55
|
+
if (result.zipEntries !== void 0)
|
|
56
|
+
lines.push(formatZipTree({ zipEntries: result.zipEntries, zipArchives: result.zipArchives }));
|
|
57
|
+
await stdout(`${lines.join(`
|
|
58
|
+
`)}
|
|
59
|
+
`);
|
|
64
60
|
return 0;
|
|
65
61
|
} catch (error) {
|
|
66
|
-
|
|
62
|
+
await stderr(`${formatReadError(error, args.json)}
|
|
63
|
+
`);
|
|
64
|
+
if (error instanceof AmbiguousZipGlobError && args.json)
|
|
65
|
+
await stdout(`${JSON.stringify({ compression: "zip", error: error.message, candidates: error.candidates })}
|
|
66
|
+
`);
|
|
67
|
+
if (error instanceof ZipProbeError)
|
|
68
|
+
if (args.json) {
|
|
69
|
+
const report = {
|
|
70
|
+
fileSizeBytes: error.fileSizeBytes,
|
|
71
|
+
compression: "zip",
|
|
72
|
+
...error.archive,
|
|
73
|
+
error: error.message
|
|
74
|
+
};
|
|
75
|
+
await stdout(`${JSON.stringify(report)}
|
|
76
|
+
`);
|
|
77
|
+
} else {
|
|
78
|
+
const listing = [formatZipTree(error.archive)];
|
|
79
|
+
const nestedPaths = new Set(error.archive.zipArchives?.filter((archive) => ("zipEntries" in archive)).map((archive) => archive.path));
|
|
80
|
+
if (error.archive.zipEntries.some((path) => !path.endsWith("/") && !nestedPaths.has(path)))
|
|
81
|
+
listing.push("Select an archive file with --zip-entry <path>.");
|
|
82
|
+
if (nestedPaths.size > 0)
|
|
83
|
+
listing.push("Use --zip-entry <archive.zip>/<path> for a nested file. Use !/ to mark the ZIP boundary explicitly.");
|
|
84
|
+
await stdout(`${listing.join(`
|
|
85
|
+
`)}
|
|
86
|
+
`);
|
|
87
|
+
}
|
|
67
88
|
return 1;
|
|
68
89
|
}
|
|
69
90
|
}
|
|
70
|
-
|
|
91
|
+
function formatZipTree(tree) {
|
|
92
|
+
const lines = ["ZIP archive entries:"];
|
|
93
|
+
appendZipTree(tree, lines, 1);
|
|
94
|
+
return lines.join(`
|
|
95
|
+
`);
|
|
96
|
+
}
|
|
97
|
+
function appendZipTree(tree, lines, depth) {
|
|
98
|
+
const paths = tree.zipEntries.toSorted();
|
|
99
|
+
const treePaths = new Set(paths);
|
|
100
|
+
let previous = "";
|
|
101
|
+
for (const path of paths) {
|
|
102
|
+
const parent = path.lastIndexOf("/", path.length - (path.endsWith("/") ? 2 : 1));
|
|
103
|
+
if (parent !== -1)
|
|
104
|
+
treePaths.add(path.slice(0, parent + 1));
|
|
105
|
+
let sharedDirectoryEnd = 0;
|
|
106
|
+
for (let index = 0;index < path.length && path[index] === previous[index]; ++index)
|
|
107
|
+
if (path[index] === "/")
|
|
108
|
+
sharedDirectoryEnd = index + 1;
|
|
109
|
+
if (sharedDirectoryEnd !== 0)
|
|
110
|
+
treePaths.add(path.slice(0, sharedDirectoryEnd));
|
|
111
|
+
previous = path;
|
|
112
|
+
}
|
|
113
|
+
const archives = new Map(tree.zipArchives?.map((archive) => [archive.path, archive]));
|
|
114
|
+
const directories = [];
|
|
115
|
+
for (const path of [...treePaths].sort()) {
|
|
116
|
+
while (directories.length > 0 && !path.startsWith(directories[directories.length - 1] ?? ""))
|
|
117
|
+
directories.pop();
|
|
118
|
+
const name = path.slice(directories.at(-1)?.length ?? 0);
|
|
119
|
+
const indent = depth + directories.length;
|
|
120
|
+
lines.push(`${" ".repeat(indent)}${formatZipLabel(name)}`);
|
|
121
|
+
if (path.endsWith("/"))
|
|
122
|
+
directories.push(path);
|
|
123
|
+
const archive = archives.get(path);
|
|
124
|
+
if (archive !== void 0)
|
|
125
|
+
if ("error" in archive)
|
|
126
|
+
lines.push(`${" ".repeat(indent + 1)}(${archive.error})`);
|
|
127
|
+
else if (archive.zipEntries.length === 0)
|
|
128
|
+
lines.push(`${" ".repeat(indent + 1)}(empty archive)`);
|
|
129
|
+
else
|
|
130
|
+
appendZipTree(archive, lines, indent + 1);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function formatZipLabel(name) {
|
|
134
|
+
return /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(name) || name.trim() !== name ? JSON.stringify(name).replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (char) => `\\u{${(char.codePointAt(0) ?? 0).toString(16)}}`) : name;
|
|
135
|
+
}
|
|
136
|
+
function formatReadError(error, zipCandidatesAsJson = !1) {
|
|
137
|
+
const message = `csv: ${error instanceof Error ? error.message : String(error)}`;
|
|
138
|
+
if (error instanceof AmbiguousZipGlobError && !zipCandidatesAsJson)
|
|
139
|
+
return [message, "Matching ZIP entries:", ...error.candidates.map((entry) => ` ${formatZipLabel(entry)}`)].join(`
|
|
140
|
+
`);
|
|
141
|
+
return message;
|
|
142
|
+
}
|
|
143
|
+
function processingFailure(error) {
|
|
144
|
+
let message = formatReadError(error);
|
|
145
|
+
if (error instanceof Error && error.message === "native ZIP reader failed: ZIP entry '*' requires exactly one file in the archive")
|
|
146
|
+
message += `
|
|
147
|
+
Run 'csv probe <path>' to list ZIP entries, then choose one with --zip-entry.`;
|
|
148
|
+
return Object.assign(new CommandFailure(message), { cause: error });
|
|
149
|
+
}
|
|
150
|
+
export async function runCount(args, context) {
|
|
71
151
|
let options;
|
|
72
152
|
try {
|
|
73
|
-
|
|
153
|
+
const where = parseWhereOptions(args, "count")?.(indexedColumn);
|
|
154
|
+
options = { ...parseFileOptions(args), strict: args.strict, columns: args.columns, where };
|
|
74
155
|
} catch (error) {
|
|
75
|
-
|
|
156
|
+
throw usageFailure(error, context.commandPath);
|
|
76
157
|
}
|
|
77
158
|
try {
|
|
78
|
-
|
|
79
|
-
|
|
159
|
+
const total = await csv.count(args.path === "-" ? context.stdin : args.path, options);
|
|
160
|
+
await context.stdout(`${total}
|
|
161
|
+
`);
|
|
80
162
|
} catch (error) {
|
|
81
|
-
|
|
82
|
-
output.error(`csv: ${message}`);
|
|
83
|
-
return 1;
|
|
163
|
+
throw processingFailure(error);
|
|
84
164
|
}
|
|
85
165
|
}
|
|
86
|
-
async function runLines(args,
|
|
166
|
+
export async function runLines(args, context) {
|
|
87
167
|
let options;
|
|
88
168
|
try {
|
|
89
|
-
options =
|
|
169
|
+
options = parseLinesOptions(args);
|
|
90
170
|
} catch (error) {
|
|
91
|
-
|
|
171
|
+
throw usageFailure(error, context.commandPath);
|
|
92
172
|
}
|
|
93
173
|
try {
|
|
94
|
-
|
|
95
|
-
|
|
174
|
+
const input = args.path === "-" ? context.stdin : args.path;
|
|
175
|
+
const serialize = args.json ? serializeJsonRecord : (row) => serializeCsvRecord(row, args.outputDelimiter);
|
|
176
|
+
if (options.headers === void 0)
|
|
177
|
+
await streamLines(csv.rows(input, options), serialize, context.stdout);
|
|
178
|
+
else if (options.mapped)
|
|
179
|
+
await streamLines(csv.rows(input, options), serializeJsonRecord, context.stdout);
|
|
180
|
+
else
|
|
181
|
+
await streamLines(csv.rows(input, options), serialize, context.stdout);
|
|
96
182
|
} catch (error) {
|
|
97
|
-
if (isBrokenPipe(error))
|
|
98
|
-
|
|
99
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
100
|
-
output.error(`csv: ${message}`);
|
|
101
|
-
return 1;
|
|
183
|
+
if (!isBrokenPipe(error))
|
|
184
|
+
throw processingFailure(error);
|
|
102
185
|
}
|
|
103
186
|
}
|
|
104
|
-
function
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
187
|
+
function parseLinesOptions(args) {
|
|
188
|
+
const headers = args.headers ? !0 : args.headersJson;
|
|
189
|
+
const where = parseWhereOptions(args, headers === void 0 ? "lines" : "named");
|
|
190
|
+
const dialect = args.strict ? { strict: !0 } : {
|
|
191
|
+
quote: args.noQuote ? !1 : void 0,
|
|
192
|
+
recordDelimiter: args.recordDelimiter === "lf" ? `
|
|
193
|
+
` : void 0
|
|
194
|
+
};
|
|
195
|
+
const options = { ...parseFileOptions(args), ...dialect };
|
|
196
|
+
const { indexed, named } = parseTransformOptions(args, headers !== void 0);
|
|
197
|
+
if (headers === void 0)
|
|
198
|
+
return { ...options, columns: args.columns, where: where?.(indexedColumn), transform: indexed, reuseArrays: !0 };
|
|
199
|
+
const namedOptions = {
|
|
200
|
+
...options,
|
|
201
|
+
headers,
|
|
202
|
+
columns: args.columnName.length === 0 ? void 0 : args.columnName,
|
|
203
|
+
where,
|
|
204
|
+
transform: named.length === 0 ? indexed : (column) => [...indexed ?? [], ...named.flatMap((bind) => bind(column))]
|
|
205
|
+
};
|
|
206
|
+
return args.mapped ? { ...namedOptions, mapped: !0 } : { ...namedOptions, mapped: !1, reuseArrays: !0 };
|
|
207
|
+
}
|
|
208
|
+
function parseFileOptions(values) {
|
|
209
|
+
return {
|
|
210
|
+
maxRecordBytes: values.maxRecordBytes,
|
|
211
|
+
delimiter: values.delimiter ?? "auto",
|
|
212
|
+
encoding: values.encoding ?? "auto",
|
|
213
|
+
skipRows: values.skipRows,
|
|
214
|
+
skipEmptyLines: values.skipEmptyLines,
|
|
215
|
+
limit: values.limit,
|
|
216
|
+
chunkSize: values.chunkSize,
|
|
217
|
+
fixedColumns: values.fixedColumns,
|
|
218
|
+
expectedHeaders: values.expectedHeader.length > 0 ? values.expectedHeader : void 0,
|
|
219
|
+
requireHeader: values.requireHeader || void 0,
|
|
220
|
+
minDataRows: values.minDataRows,
|
|
221
|
+
compression: parseCompression(values)
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
function parseCompression({ compression = "auto", zipEntry, maxCompressionRatio, maxDecompressedBytes }) {
|
|
225
|
+
if (zipEntry === void 0 && compression !== "zip")
|
|
132
226
|
return compression;
|
|
133
|
-
|
|
227
|
+
if (compression !== "auto" && compression !== "zip")
|
|
228
|
+
throw Error("--zip-entry requires --compression auto or zip when a format is specified");
|
|
134
229
|
return {
|
|
135
|
-
entry: zipEntry,
|
|
230
|
+
entry: zipEntry ?? "*",
|
|
136
231
|
format: "zip",
|
|
137
232
|
...maxCompressionRatio === void 0 ? {} : { maxCompressionRatio },
|
|
138
233
|
...maxDecompressedBytes === void 0 ? {} : { maxDecompressedBytes }
|
|
139
234
|
};
|
|
140
235
|
}
|
|
141
|
-
async function streamLines(
|
|
142
|
-
for await (const rows of
|
|
236
|
+
async function streamLines(batches, serialize, stdout) {
|
|
237
|
+
for await (const rows of batches) {
|
|
143
238
|
let chunks = [];
|
|
144
239
|
let chunksLength = 0;
|
|
145
240
|
for (const row of rows) {
|
|
146
|
-
const record =
|
|
147
|
-
` : serializeCsvRecord(row, args["output-delimiter"]);
|
|
241
|
+
const record = serialize(row);
|
|
148
242
|
chunks.push(record);
|
|
149
243
|
chunksLength += record.length;
|
|
150
244
|
if (chunksLength >= OUTPUT_BUFFER_SIZE) {
|
|
151
|
-
await
|
|
245
|
+
await stdout(chunks.join(""));
|
|
152
246
|
chunks = [];
|
|
153
247
|
chunksLength = 0;
|
|
154
248
|
}
|
|
155
249
|
}
|
|
156
250
|
if (chunksLength > 0)
|
|
157
|
-
await
|
|
251
|
+
await stdout(chunks.join(""));
|
|
158
252
|
}
|
|
159
253
|
}
|
|
254
|
+
function serializeJsonRecord(row) {
|
|
255
|
+
return `${JSON.stringify(row)}
|
|
256
|
+
`;
|
|
257
|
+
}
|
|
160
258
|
function serializeCsvRecord(row, delimiter) {
|
|
161
|
-
|
|
259
|
+
if (row.length === 1 && row[0] === "")
|
|
260
|
+
return `""
|
|
261
|
+
`;
|
|
262
|
+
return `${row.map((field, index) => serializeCsvField(field, delimiter, index === 0)).join(delimiter)}
|
|
162
263
|
`;
|
|
163
264
|
}
|
|
164
|
-
function serializeCsvField(field, delimiter) {
|
|
165
|
-
if (!field.includes(delimiter) && !field.includes('"') && !field.includes("\r") && !field.includes(`
|
|
265
|
+
function serializeCsvField(field, delimiter, first) {
|
|
266
|
+
if ((!first || !field.startsWith("\uFEFF")) && !field.includes(delimiter) && !field.includes('"') && !field.includes("\r") && !field.includes(`
|
|
166
267
|
`))
|
|
167
268
|
return field;
|
|
168
269
|
return `"${field.replaceAll('"', '""')}"`;
|
|
@@ -170,8 +271,9 @@ function serializeCsvField(field, delimiter) {
|
|
|
170
271
|
function isBrokenPipe(error) {
|
|
171
272
|
return isObject(error) && error.code === "EPIPE";
|
|
172
273
|
}
|
|
173
|
-
function parseTransformOptions(args) {
|
|
174
|
-
const
|
|
274
|
+
function parseTransformOptions(args, allowNames) {
|
|
275
|
+
const indexed = [];
|
|
276
|
+
const named = [];
|
|
175
277
|
for (const [index, { key, value }] of args.transform.entries()) {
|
|
176
278
|
const label = `--transform[${index}]`;
|
|
177
279
|
const columns = key.split(",").map((column) => {
|
|
@@ -184,56 +286,70 @@ function parseTransformOptions(args) {
|
|
|
184
286
|
throw Error(`${label} expected trim, upper, lower, or unaccent, got ${JSON.stringify(op)}`);
|
|
185
287
|
return { op };
|
|
186
288
|
});
|
|
187
|
-
|
|
289
|
+
parseTransformChain({ columns, steps }, label, indexed, named, !1);
|
|
188
290
|
}
|
|
189
|
-
const json = args
|
|
291
|
+
const json = args.transformJson;
|
|
190
292
|
if (json !== void 0) {
|
|
191
293
|
if (!Array.isArray(json))
|
|
192
294
|
throw Error("--transform-json must be a JSON array of chains");
|
|
193
295
|
for (const [index, chain] of json.entries())
|
|
194
|
-
|
|
296
|
+
parseTransformChain(chain, `--transform-json[${index}]`, indexed, named, allowNames);
|
|
195
297
|
}
|
|
196
|
-
return
|
|
298
|
+
return { indexed: indexed.length === 0 ? void 0 : snapshotTransforms(indexed), named };
|
|
197
299
|
}
|
|
198
|
-
function parseTransformChain(value, label) {
|
|
300
|
+
function parseTransformChain(value, label, indexed, named, allowNames) {
|
|
199
301
|
if (!isObject(value))
|
|
200
302
|
throw Error(`${label} must be an object with columns and steps`);
|
|
201
303
|
requireExactKeys(value, ["columns", "steps"], label);
|
|
202
304
|
const { columns, steps } = value;
|
|
203
|
-
if (!Array.isArray(columns))
|
|
305
|
+
if (!Array.isArray(columns) || columns.length === 0)
|
|
204
306
|
throw Error(`${label}.columns must be a non-empty array of column indexes`);
|
|
205
|
-
const
|
|
206
|
-
|
|
307
|
+
const indexes = [];
|
|
308
|
+
const names = [];
|
|
309
|
+
for (const [index, column] of columns.entries())
|
|
310
|
+
if (typeof column === "number")
|
|
311
|
+
indexes.push(column);
|
|
312
|
+
else if (typeof column === "string" && allowNames)
|
|
313
|
+
names.push(column);
|
|
314
|
+
else
|
|
207
315
|
throw Error(`${label}.columns[${index}] must be a number`);
|
|
208
|
-
return column;
|
|
209
|
-
});
|
|
210
|
-
if (first === void 0)
|
|
211
|
-
throw Error(`${label}.columns must be a non-empty array of column indexes`);
|
|
212
316
|
if (!Array.isArray(steps) || steps.length === 0)
|
|
213
317
|
throw Error(`${label}.steps must be a non-empty array`);
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
318
|
+
const firstStep = parseTransformStep(steps[0], `${label}.steps[0]`);
|
|
319
|
+
const laterSteps = steps.slice(1).map((step, index) => parseTransformStep(step, `${label}.steps[${index + 1}]`));
|
|
320
|
+
function applySteps(start) {
|
|
321
|
+
let chain = firstStep(start);
|
|
322
|
+
for (const step of laterSteps)
|
|
323
|
+
chain = step(chain);
|
|
324
|
+
return chain;
|
|
325
|
+
}
|
|
326
|
+
const chain = applySteps(csv.transform());
|
|
327
|
+
const [first, ...rest] = indexes;
|
|
328
|
+
if (first !== void 0)
|
|
329
|
+
indexed.push(chain.on(first, ...rest));
|
|
330
|
+
if (names.length > 0)
|
|
331
|
+
named.push((column) => names.map((name) => applySteps(column(name))));
|
|
218
332
|
}
|
|
219
333
|
function isCleanupTransform(op) {
|
|
220
334
|
return op === "trim" || op === "upper" || op === "lower" || op === "unaccent";
|
|
221
335
|
}
|
|
222
|
-
function parseTransformStep(
|
|
336
|
+
function parseTransformStep(step, label) {
|
|
223
337
|
if (!isObject(step))
|
|
224
338
|
throw Error(`${label} must be an object with an op property`);
|
|
225
339
|
const op = requireString(step.op, `${label}.op`);
|
|
226
340
|
if (isCleanupTransform(op)) {
|
|
227
341
|
requireExactKeys(step, ["op"], label);
|
|
228
|
-
return chain[op]();
|
|
342
|
+
return (chain) => chain[op]();
|
|
229
343
|
}
|
|
230
344
|
switch (op) {
|
|
231
345
|
case "replace": {
|
|
232
346
|
requireExactKeys(step, ["op", "search", "replacement"], label);
|
|
233
347
|
const search = step.search;
|
|
234
348
|
const replacement = requireString(step.replacement, `${label}.replacement`);
|
|
235
|
-
if (!isObject(search))
|
|
236
|
-
|
|
349
|
+
if (!isObject(search)) {
|
|
350
|
+
const literal = requireString(search, `${label}.search`);
|
|
351
|
+
return (chain) => chain.replace(literal, replacement);
|
|
352
|
+
}
|
|
237
353
|
const searchLabel = `${label}.search`;
|
|
238
354
|
requireExactKeys(search, ["source", "flags"], searchLabel, !0);
|
|
239
355
|
const source = requireString(search.source, `${searchLabel}.source`);
|
|
@@ -245,7 +361,7 @@ function parseTransformStep(chain, step, label) {
|
|
|
245
361
|
} catch (error) {
|
|
246
362
|
throw Error(`${searchLabel}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
247
363
|
}
|
|
248
|
-
return chain.replace(regex, replacement);
|
|
364
|
+
return (chain) => chain.replace(regex, replacement);
|
|
249
365
|
}
|
|
250
366
|
case "map": {
|
|
251
367
|
requireExactKeys(step, ["op", "values", "defaultValue"], label, !0);
|
|
@@ -255,33 +371,33 @@ function parseTransformStep(chain, step, label) {
|
|
|
255
371
|
const mapping = new Map;
|
|
256
372
|
for (const [key, value] of Object.entries(values))
|
|
257
373
|
mapping.set(key, requireString(value, `${label}.values[${JSON.stringify(key)}]`));
|
|
258
|
-
|
|
374
|
+
const defaultValue = optionalString(step.defaultValue, `${label}.defaultValue`);
|
|
375
|
+
return (chain) => chain.map(mapping, defaultValue);
|
|
259
376
|
}
|
|
260
377
|
case "date": {
|
|
261
378
|
requireExactKeys(step, ["op", "format", "defaultValue"], label, !0);
|
|
262
379
|
const format = step.format;
|
|
263
380
|
if (format !== "YYYY-MM-DD" && format !== "DD-MM-YYYY" && format !== "DD/MM/YYYY")
|
|
264
381
|
throw Error(`${label}.format must be YYYY-MM-DD, DD-MM-YYYY, or DD/MM/YYYY`);
|
|
265
|
-
|
|
382
|
+
const defaultValue = optionalString(step.defaultValue, `${label}.defaultValue`);
|
|
383
|
+
return (chain) => chain.date(format, defaultValue);
|
|
266
384
|
}
|
|
267
385
|
default:
|
|
268
386
|
throw Error(`${label}.op is an unknown transform: ${JSON.stringify(op)}`);
|
|
269
387
|
}
|
|
270
388
|
}
|
|
271
|
-
function parseWhereOptions(values) {
|
|
389
|
+
function parseWhereOptions(values, mode) {
|
|
272
390
|
const filters = [];
|
|
273
|
-
|
|
274
|
-
filters.push(parseWhereFilter(values.where, "--where"));
|
|
275
|
-
for (const { key, value } of values["where-eq"]) {
|
|
391
|
+
for (const { key, value } of values.whereEq) {
|
|
276
392
|
const column = parseFilterColumn(key, "--where-eq");
|
|
277
393
|
filters.push(csv.column(column).equals(value));
|
|
278
394
|
}
|
|
279
|
-
for (const { key, value } of values
|
|
395
|
+
for (const { key, value } of values.whereNeq) {
|
|
280
396
|
const column = parseFilterColumn(key, "--where-neq");
|
|
281
397
|
filters.push(csv.column(column).doesNotEqual(value));
|
|
282
398
|
}
|
|
283
399
|
const inValuesByColumn = new Map;
|
|
284
|
-
for (const { key, value } of values
|
|
400
|
+
for (const { key, value } of values.whereIn) {
|
|
285
401
|
const column = parseFilterColumn(key, "--where-in");
|
|
286
402
|
const columnValues = inValuesByColumn.get(column);
|
|
287
403
|
if (columnValues === void 0)
|
|
@@ -292,7 +408,7 @@ function parseWhereOptions(values) {
|
|
|
292
408
|
for (const [column, inValues] of inValuesByColumn)
|
|
293
409
|
filters.push(csv.column(column).isOneOf(inValues));
|
|
294
410
|
const notInValuesByColumn = new Map;
|
|
295
|
-
for (const { key, value } of values
|
|
411
|
+
for (const { key, value } of values.whereNoin) {
|
|
296
412
|
const column = parseFilterColumn(key, "--where-noin");
|
|
297
413
|
const columnValues = notInValuesByColumn.get(column);
|
|
298
414
|
if (columnValues === void 0)
|
|
@@ -302,16 +418,24 @@ function parseWhereOptions(values) {
|
|
|
302
418
|
}
|
|
303
419
|
for (const [column, notInValues] of notInValuesByColumn)
|
|
304
420
|
filters.push(csv.column(column).isNoneOf(notInValues));
|
|
305
|
-
for (const { key, value } of values
|
|
421
|
+
for (const { key, value } of values.wherePrefix) {
|
|
306
422
|
const column = parseFilterColumn(key, "--where-prefix");
|
|
307
423
|
filters.push(csv.column(column).startsWith(value));
|
|
308
424
|
}
|
|
309
|
-
for (const expression of values
|
|
425
|
+
for (const expression of values.whereRegex)
|
|
310
426
|
filters.push(parseRegexExpression(expression));
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
427
|
+
if (values.where !== void 0) {
|
|
428
|
+
const advanced = parseWhereFilter(values.where, "--where", mode, filters.length === 0 ? 0 : 1);
|
|
429
|
+
if (mode === "named")
|
|
430
|
+
return (column) => filters.length === 0 ? advanced(column) : csv.all(advanced(column), ...filters);
|
|
431
|
+
filters.unshift(advanced(indexedColumn));
|
|
432
|
+
}
|
|
433
|
+
const [first, ...rest] = filters;
|
|
434
|
+
if (first !== void 0) {
|
|
435
|
+
const filter = rest.length === 0 ? first : csv.all(first, ...rest);
|
|
436
|
+
return () => filter;
|
|
437
|
+
}
|
|
438
|
+
return;
|
|
315
439
|
}
|
|
316
440
|
function parseFilterColumn(key, option) {
|
|
317
441
|
return normalizeFilterColumn(parseColumnIndex(key, `${option} column`));
|
|
@@ -325,60 +449,75 @@ function parseRegexExpression({ key, value }) {
|
|
|
325
449
|
const flags = value.slice(closingSlash + 1);
|
|
326
450
|
return csv.column(column).hasMatch(new RegExp(source, flags));
|
|
327
451
|
}
|
|
328
|
-
function parseWhereFilter(value, label, depth = 0) {
|
|
452
|
+
function parseWhereFilter(value, label, mode, depth = 0) {
|
|
329
453
|
if (depth > MAX_FILTER_NESTING)
|
|
330
454
|
throw Error(`--where nesting exceeds ${MAX_FILTER_NESTING}`);
|
|
331
455
|
if (!isObject(value))
|
|
332
456
|
throw Error(`${label} must be a JSON object`);
|
|
333
457
|
if ("all" in value) {
|
|
334
458
|
requireExactKeys(value, ["all"], label);
|
|
335
|
-
return parseWhereGroup(value.all, `${label}.all`, csv.all, depth);
|
|
459
|
+
return parseWhereGroup(value.all, `${label}.all`, csv.all, mode, depth);
|
|
336
460
|
}
|
|
337
461
|
if ("any" in value) {
|
|
338
462
|
requireExactKeys(value, ["any"], label);
|
|
339
|
-
return parseWhereGroup(value.any, `${label}.any`, csv.any, depth);
|
|
463
|
+
return parseWhereGroup(value.any, `${label}.any`, csv.any, mode, depth);
|
|
340
464
|
}
|
|
341
465
|
if ("not" in value) {
|
|
342
466
|
requireExactKeys(value, ["not"], label);
|
|
343
|
-
|
|
467
|
+
const filter = parseWhereFilter(value.not, `${label}.not`, mode, depth + 1);
|
|
468
|
+
return (column) => csv.not(filter(column));
|
|
344
469
|
}
|
|
345
|
-
return parseWherePredicate(value, label);
|
|
470
|
+
return parseWherePredicate(value, label, mode);
|
|
346
471
|
}
|
|
347
|
-
function parseWhereGroup(value, label, combine, depth) {
|
|
472
|
+
function parseWhereGroup(value, label, combine, mode, depth) {
|
|
348
473
|
if (!Array.isArray(value) || value.length === 0)
|
|
349
474
|
throw Error(`${label} must be a non-empty array`);
|
|
350
|
-
const first = parseWhereFilter(value[0], `${label}[0]`, depth + 1);
|
|
351
|
-
const rest = value.slice(1).map((filter, index) => parseWhereFilter(filter, `${label}[${
|
|
352
|
-
return combine(first, ...rest);
|
|
353
|
-
}
|
|
354
|
-
function
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
475
|
+
const first = parseWhereFilter(value[0], `${label}[0]`, mode, depth + 1);
|
|
476
|
+
const rest = value.slice(1).map((filter, index) => parseWhereFilter(filter, `${label}[${index + 1}]`, mode, depth + 1));
|
|
477
|
+
return (column) => combine(first(column), ...rest.map((filter) => filter(column)));
|
|
478
|
+
}
|
|
479
|
+
function indexedColumn(selector, label = "--where.column") {
|
|
480
|
+
if (typeof selector !== "number")
|
|
481
|
+
throw Error(`${label} must be a number`);
|
|
482
|
+
return csv.column(selector);
|
|
483
|
+
}
|
|
484
|
+
function parseWherePredicate(value, label, mode) {
|
|
485
|
+
const selector = value.column;
|
|
486
|
+
let select;
|
|
487
|
+
if (mode === "named" && typeof selector === "string")
|
|
488
|
+
select = (column) => column(selector);
|
|
489
|
+
else {
|
|
490
|
+
const column = indexedColumn(selector, `${label}.column`);
|
|
491
|
+
select = () => column;
|
|
492
|
+
}
|
|
359
493
|
if ("equals" in value) {
|
|
360
494
|
requireExactKeys(value, ["column", "equals"], label);
|
|
361
|
-
|
|
495
|
+
const operand = parseWhereOperand(value.equals, `${label}.equals`, mode);
|
|
496
|
+
return (column) => select(column).equals(operand);
|
|
362
497
|
}
|
|
363
498
|
if ("in" in value) {
|
|
364
499
|
requireExactKeys(value, ["column", "in"], label);
|
|
365
500
|
if (!Array.isArray(value.in) || value.in.length === 0)
|
|
366
501
|
throw Error(`${label}.in must be a non-empty string array`);
|
|
367
|
-
|
|
502
|
+
const operands = value.in.map((item, index) => parseWhereOperand(item, `${label}.in[${index}]`, mode));
|
|
503
|
+
return (column) => select(column).isOneOf(operands);
|
|
368
504
|
}
|
|
369
505
|
if ("notEquals" in value) {
|
|
370
506
|
requireExactKeys(value, ["column", "notEquals"], label);
|
|
371
|
-
|
|
507
|
+
const operand = parseWhereOperand(value.notEquals, `${label}.notEquals`, mode);
|
|
508
|
+
return (column) => select(column).doesNotEqual(operand);
|
|
372
509
|
}
|
|
373
510
|
if ("notIn" in value) {
|
|
374
511
|
requireExactKeys(value, ["column", "notIn"], label);
|
|
375
512
|
if (!Array.isArray(value.notIn) || value.notIn.length === 0)
|
|
376
513
|
throw Error(`${label}.notIn must be a non-empty string array`);
|
|
377
|
-
|
|
514
|
+
const operands = value.notIn.map((item, index) => parseWhereOperand(item, `${label}.notIn[${index}]`, mode));
|
|
515
|
+
return (column) => select(column).isNoneOf(operands);
|
|
378
516
|
}
|
|
379
517
|
if ("startsWith" in value) {
|
|
380
518
|
requireExactKeys(value, ["column", "startsWith"], label);
|
|
381
|
-
|
|
519
|
+
const operand = parseWhereOperand(value.startsWith, `${label}.startsWith`, mode);
|
|
520
|
+
return (column) => select(column).startsWith(operand);
|
|
382
521
|
}
|
|
383
522
|
if ("regex" in value) {
|
|
384
523
|
requireExactKeys(value, ["column", "regex"], label);
|
|
@@ -387,10 +526,23 @@ function parseWherePredicate(value, label) {
|
|
|
387
526
|
requireExactKeys(value.regex, ["source", "flags"], `${label}.regex`, !0);
|
|
388
527
|
const source = requireString(value.regex.source, `${label}.regex.source`);
|
|
389
528
|
const flags = value.regex.flags === void 0 ? "" : requireString(value.regex.flags, `${label}.regex.flags`);
|
|
390
|
-
|
|
529
|
+
const regex = new RegExp(source, flags);
|
|
530
|
+
if (mode === "named")
|
|
531
|
+
validateRegex(regex);
|
|
532
|
+
return (column) => select(column).hasMatch(regex);
|
|
391
533
|
}
|
|
392
534
|
throw Error(`${label} must contain equals, in, notEquals, notIn, startsWith, or regex`);
|
|
393
535
|
}
|
|
536
|
+
function parseWhereOperand(value, label, mode) {
|
|
537
|
+
if (mode !== "count" && isObject(value) && Object.hasOwn(value, "hex")) {
|
|
538
|
+
requireExactKeys(value, ["hex"], label);
|
|
539
|
+
const hex = requireString(value.hex, `${label}.hex`);
|
|
540
|
+
if (hex.length % 2 !== 0 || /[^0-9a-f]/i.test(hex))
|
|
541
|
+
throw Error(`${label}.hex must contain complete hexadecimal byte pairs`);
|
|
542
|
+
return Buffer.from(hex, "hex");
|
|
543
|
+
}
|
|
544
|
+
return requireString(value, label);
|
|
545
|
+
}
|
|
394
546
|
function isObject(value) {
|
|
395
547
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
396
548
|
}
|
|
@@ -413,8 +565,17 @@ function requireExactKeys(value, allowedKeys, label, allowMissing = !1) {
|
|
|
413
565
|
throw Error(`${label} is missing property: ${missingKey}`);
|
|
414
566
|
}
|
|
415
567
|
}
|
|
416
|
-
function
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
568
|
+
export function parseColumnIndex(value, label) {
|
|
569
|
+
const number = Number(value);
|
|
570
|
+
if (!Number.isSafeInteger(number) || number < 0)
|
|
571
|
+
throw Error(`${label} must be an integer greater than or equal to 0: ${value}`);
|
|
572
|
+
return number;
|
|
573
|
+
}
|
|
574
|
+
export function formatUsageError(error, commandPath) {
|
|
575
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
576
|
+
return `csv: ${message}
|
|
577
|
+
Run '${commandPath.join(" ")} --help' for usage.`;
|
|
578
|
+
}
|
|
579
|
+
function usageFailure(error, commandPath) {
|
|
580
|
+
return Object.assign(new CommandFailure(formatUsageError(error, commandPath), 2), { cause: error });
|
|
420
581
|
}
|