@creationix/rex 0.1.4 → 0.3.1

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/rex-cli.ts ADDED
@@ -0,0 +1,200 @@
1
+ import { compile, parse, parseToIR, stringify } from "./rex.ts";
2
+ import { evaluateSource } from "./rexc-interpreter.ts";
3
+ import { dirname, resolve } from "node:path";
4
+ import { readFile, writeFile } from "node:fs/promises";
5
+
6
+ type CliOptions = {
7
+ expr?: string;
8
+ file?: string;
9
+ out?: string;
10
+ compile: boolean;
11
+ ir: boolean;
12
+ minifyNames: boolean;
13
+ dedupeValues: boolean;
14
+ dedupeMinBytes?: number;
15
+ help: boolean;
16
+ };
17
+
18
+ function parseArgs(argv: string[]): CliOptions {
19
+ const options: CliOptions = {
20
+ compile: false,
21
+ ir: false,
22
+ minifyNames: false,
23
+ dedupeValues: false,
24
+ help: false,
25
+ };
26
+ for (let index = 0; index < argv.length; index += 1) {
27
+ const arg = argv[index];
28
+ if (!arg) continue;
29
+ if (arg === "--help" || arg === "-h") {
30
+ options.help = true;
31
+ continue;
32
+ }
33
+ if (arg === "--compile" || arg === "-c") {
34
+ options.compile = true;
35
+ continue;
36
+ }
37
+ if (arg === "--ir") {
38
+ options.ir = true;
39
+ continue;
40
+ }
41
+ if (arg === "--minify-names" || arg === "-m") {
42
+ options.minifyNames = true;
43
+ continue;
44
+ }
45
+ if (arg === "--dedupe-values") {
46
+ options.dedupeValues = true;
47
+ continue;
48
+ }
49
+ if (arg === "--dedupe-min-bytes") {
50
+ const value = argv[index + 1];
51
+ if (!value) throw new Error("Missing value for --dedupe-min-bytes");
52
+ const parsed = Number(value);
53
+ if (!Number.isInteger(parsed) || parsed < 1) throw new Error("--dedupe-min-bytes must be a positive integer");
54
+ options.dedupeMinBytes = parsed;
55
+ index += 1;
56
+ continue;
57
+ }
58
+ if (arg === "--expr" || arg === "-e") {
59
+ const value = argv[index + 1];
60
+ if (!value) throw new Error("Missing value for --expr");
61
+ options.expr = value;
62
+ index += 1;
63
+ continue;
64
+ }
65
+ if (arg === "--file" || arg === "-f") {
66
+ const value = argv[index + 1];
67
+ if (!value) throw new Error("Missing value for --file");
68
+ options.file = value;
69
+ index += 1;
70
+ continue;
71
+ }
72
+ if (arg === "--out" || arg === "-o") {
73
+ const value = argv[index + 1];
74
+ if (!value) throw new Error("Missing value for --out");
75
+ options.out = value;
76
+ index += 1;
77
+ continue;
78
+ }
79
+ // Positional argument = file path
80
+ if (!arg.startsWith("-")) {
81
+ if (options.file) throw new Error("Multiple file arguments provided");
82
+ options.file = arg;
83
+ continue;
84
+ }
85
+ throw new Error(`Unknown option: ${arg}`);
86
+ }
87
+ return options;
88
+ }
89
+
90
+ function usage() {
91
+ return [
92
+ "Rex expression language CLI.",
93
+ "",
94
+ "Usage:",
95
+ " rex Start interactive REPL",
96
+ " rex input.rex Evaluate a Rex script (JSON output)",
97
+ " rex --expr '1 + 2' Evaluate an inline expression",
98
+ " cat input.rex | rex Evaluate from stdin",
99
+ " rex -c input.rex Compile to rexc bytecode",
100
+ "",
101
+ "Input:",
102
+ " <file> Evaluate/compile a Rex source file",
103
+ " -e, --expr <source> Evaluate/compile an inline expression",
104
+ " -f, --file <path> Evaluate/compile source from a file",
105
+ "",
106
+ "Output mode:",
107
+ " (default) Evaluate and output result as JSON",
108
+ " -c, --compile Compile to rexc bytecode",
109
+ " --ir Output lowered IR as JSON",
110
+ "",
111
+ "Compile options:",
112
+ " -m, --minify-names Minify local variable names",
113
+ " --dedupe-values Deduplicate large repeated values",
114
+ " --dedupe-min-bytes <n> Minimum bytes for dedupe (default: 4)",
115
+ "",
116
+ "General:",
117
+ " -o, --out <path> Write output to file instead of stdout",
118
+ " -h, --help Show this message",
119
+ ].join("\n");
120
+ }
121
+
122
+ async function readStdin(): Promise<string> {
123
+ const chunks: Buffer[] = [];
124
+ for await (const chunk of process.stdin) {
125
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
126
+ }
127
+ return Buffer.concat(chunks).toString("utf8");
128
+ }
129
+
130
+ async function resolveSource(options: CliOptions): Promise<string> {
131
+ if (options.expr && options.file) throw new Error("Use only one of --expr, --file, or a positional file path");
132
+ if (options.expr) return options.expr;
133
+ if (options.file) return readFile(options.file, "utf8");
134
+ if (!process.stdin.isTTY) {
135
+ const piped = await readStdin();
136
+ if (piped.trim().length > 0) return piped;
137
+ }
138
+ throw new Error("No input provided. Use a file path, --expr, or pipe source via stdin.");
139
+ }
140
+
141
+ async function loadDomainConfigFromFolder(folderPath: string): Promise<unknown | undefined> {
142
+ const configPath = resolve(folderPath, ".config.rex");
143
+ try {
144
+ return parse(await readFile(configPath, "utf8"));
145
+ } catch (error) {
146
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
147
+ throw error;
148
+ }
149
+ }
150
+
151
+ async function resolveDomainConfig(options: CliOptions): Promise<unknown | undefined> {
152
+ const baseFolder = options.file ? dirname(resolve(options.file)) : process.cwd();
153
+ return loadDomainConfigFromFolder(baseFolder);
154
+ }
155
+
156
+ async function main() {
157
+ const options = parseArgs(process.argv.slice(2));
158
+ if (options.help) {
159
+ console.log(usage());
160
+ return;
161
+ }
162
+
163
+ // No source provided on a TTY → launch interactive REPL
164
+ const hasSource = options.expr || options.file || !process.stdin.isTTY;
165
+ if (!hasSource && !options.compile && !options.ir) {
166
+ const { startRepl } = await import("./rex-repl.ts");
167
+ await startRepl();
168
+ return;
169
+ }
170
+
171
+ const source = await resolveSource(options);
172
+
173
+ let output: string;
174
+ if (options.ir) {
175
+ output = JSON.stringify(parseToIR(source), null, 2);
176
+ } else if (options.compile) {
177
+ const domainConfig = await resolveDomainConfig(options);
178
+ output = compile(source, {
179
+ minifyNames: options.minifyNames,
180
+ dedupeValues: options.dedupeValues,
181
+ dedupeMinBytes: options.dedupeMinBytes,
182
+ domainConfig,
183
+ });
184
+ } else {
185
+ const { value } = evaluateSource(source);
186
+ output = stringify(value);
187
+ }
188
+
189
+ if (options.out) {
190
+ await writeFile(options.out, `${output}\n`, "utf8");
191
+ return;
192
+ }
193
+ console.log(output);
194
+ }
195
+
196
+ await main().catch((error) => {
197
+ const message = error instanceof Error ? error.message : String(error);
198
+ console.error(`rex: ${message}`);
199
+ process.exit(1);
200
+ });