forked from GeeDotDee/ai-text-watermark-scanner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.mjs
More file actions
57 lines (52 loc) · 2.07 KB
/
Copy pathcli.mjs
File metadata and controls
57 lines (52 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env node
import { readFile } from "node:fs/promises";
import { scanText, toSarif } from "./index.mjs";
const args = process.argv.slice(2);
const sarif = args.includes("--sarif");
const jsonl = args.includes("--jsonl");
const filePath = args.find((arg) => !arg.startsWith("--"));
const input = filePath ? await readFile(filePath, "utf8") : await new Promise((resolve) => {
let value = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => { value += chunk; });
process.stdin.on("end", () => resolve(value));
});
if (jsonl) {
const lines = input.split(/\r?\n/);
// If the input ends with a trailing newline, don't process an extra empty phantom entry if file is empty or ends with newline
const lineCount = lines.length;
for (let i = 0; i < lineCount; i++) {
const line = lines[i];
if (i === lineCount - 1 && line === "") {
continue;
}
const lineNum = i + 1;
let parsed;
try {
parsed = JSON.parse(line);
} catch (err) {
process.stderr.write(`Error on line ${lineNum}: Invalid JSON record (${err.message})\n`);
process.exitCode = 1;
continue;
}
let textToScan;
if (typeof parsed === "string") {
textToScan = parsed;
} else if (parsed && typeof parsed === "object" && typeof parsed.text === "string") {
textToScan = parsed.text;
} else if (parsed && typeof parsed === "object" && typeof parsed.content === "string") {
textToScan = parsed.content;
} else {
process.stderr.write(`Error on line ${lineNum}: Expected string or object with "text" or "content" string field\n`);
process.exitCode = 1;
continue;
}
const result = scanText(textToScan);
const output = sarif ? toSarif(result, { uri: `${filePath || "stdin.jsonl"}#L${lineNum}`, sourceText: textToScan }) : result;
process.stdout.write(`${JSON.stringify(output)}\n`);
}
} else {
const result = scanText(input);
const output = sarif ? toSarif(result, { uri: filePath || "stdin.txt", sourceText: input }) : result;
process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
}