variable 0.1.4

Type-safe feature flag code generation from .var files
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use assert_cmd::Command;
use predicates::prelude::*;
use serde_json::Value as JsonValue;
use std::fs;
use std::path::Path;
use tempfile::TempDir;
use variable_core::ast::Value;
use variable_wire::decode_snapshot;

fn cmd() -> Command {
    assert_cmd::cargo::cargo_bin_cmd!("variable")
}

fn workspace_root() -> &'static Path {
    Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap()
}

fn write_var_file(dir: &TempDir, name: &str, content: &str) -> std::path::PathBuf {
    let path = dir.path().join(name);
    fs::write(&path, content).unwrap();
    path
}

#[test]
fn generate_valid_var_file() {
    let input_dir = TempDir::new().unwrap();
    let out_dir = TempDir::new().unwrap();

    let var_file = write_var_file(
        &input_dir,
        "features.var",
        r#"1: Feature Checkout = {
    1: enabled Boolean = true
    2: max_items Integer = 50
    3: header_text String = "Complete your purchase"
}"#,
    );

    cmd()
        .arg("generate")
        .arg("--out")
        .arg(out_dir.path())
        .arg(&var_file)
        .assert()
        .success()
        .stdout(predicate::str::contains("Generated"));

    let output_file = out_dir.path().join("features.generated.ts");
    assert!(output_file.exists());

    let content = fs::read_to_string(&output_file).unwrap();
    assert!(content.contains("CheckoutVariables"));
    assert!(content.contains("import { VariableClient"));
}

#[test]
fn generate_invalid_var_file() {
    let input_dir = TempDir::new().unwrap();
    let out_dir = TempDir::new().unwrap();

    let var_file = write_var_file(
        &input_dir,
        "bad.var",
        r#"1: Feature Checkout = {
    1: enabled = true
}"#,
    );

    cmd()
        .arg("generate")
        .arg("--out")
        .arg(out_dir.path())
        .arg(&var_file)
        .assert()
        .failure()
        .stderr(predicate::str::contains("error").or(predicate::str::contains("expected")));
}

#[test]
fn generate_missing_file() {
    let out_dir = TempDir::new().unwrap();

    cmd()
        .arg("generate")
        .arg("--out")
        .arg(out_dir.path())
        .arg("nonexistent.var")
        .assert()
        .failure()
        .stderr(predicate::str::contains("error"));
}

#[test]
fn generate_missing_out_flag() {
    cmd()
        .arg("generate")
        .arg("test.var")
        .assert()
        .failure()
        .stderr(predicate::str::contains("--out"));
}

#[test]
fn e2e_generate_fixture_and_verify_output() {
    let out_dir = TempDir::new().unwrap();
    let fixture = workspace_root().join("fixtures/example.var");

    cmd()
        .arg("generate")
        .arg("--out")
        .arg(out_dir.path())
        .arg(&fixture)
        .assert()
        .success();

    let output_file = out_dir.path().join("example.generated.ts");
    assert!(output_file.exists(), "generated file should exist");

    let content = fs::read_to_string(&output_file).unwrap();

    // Verify structure
    assert!(content.contains("// This file is generated by Variable. Do not edit."));
    assert!(content.contains("import { VariableClient"));

    // Verify Checkout feature
    assert!(content.contains("export interface CheckoutVariables"));
    assert!(content.contains("enabled: boolean"));
    assert!(content.contains("max_items: number"));
    assert!(content.contains("header_text: string"));
    assert!(content.contains("discount_rate: number"));
    assert!(content.contains("getCheckoutVariables"));

    // Verify Search feature
    assert!(content.contains("export interface SearchVariables"));
    assert!(content.contains("boost_factor: number"));
    assert!(content.contains("getSearchVariables"));
}

#[test]
fn e2e_generated_typescript_compiles() {
    let out_dir = TempDir::new().unwrap();
    let fixture = workspace_root().join("fixtures/example.var");

    // Generate the TypeScript
    cmd()
        .arg("generate")
        .arg("--out")
        .arg(out_dir.path())
        .arg(&fixture)
        .assert()
        .success();

    let output_file = out_dir.path().join("example.generated.ts");
    assert!(output_file.exists());

    // Create a tsconfig that resolves @variable/runtime
    let runtime_path = workspace_root().join("runtime/ts");
    let tsconfig_content = format!(
        r#"{{
  "compilerOptions": {{
    "target": "ES2020",
    "module": "ES2020",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "baseUrl": ".",
    "paths": {{
      "@variable/runtime": ["{}/src/index.ts"]
    }}
  }},
  "include": ["*.ts"]
}}"#,
        runtime_path.display()
    );
    fs::write(out_dir.path().join("tsconfig.json"), tsconfig_content).unwrap();

    // Run tsc --noEmit to verify the generated code compiles
    // Use the tsc binary from the runtime's node_modules
    let tsc_bin = runtime_path.join("node_modules/.bin/tsc");
    let tsc_result = std::process::Command::new(&tsc_bin)
        .arg("--noEmit")
        .current_dir(out_dir.path())
        .output()
        .expect("failed to run tsc");

    let stdout = String::from_utf8_lossy(&tsc_result.stdout);
    let stderr = String::from_utf8_lossy(&tsc_result.stderr);
    assert!(
        tsc_result.status.success(),
        "tsc --noEmit failed:\nstdout: {}\nstderr: {}",
        stdout,
        stderr
    );
}

#[test]
fn encode_valid_var_file_outputs_binary_snapshot() {
    let input_dir = TempDir::new().unwrap();

    let var_file = write_var_file(
        &input_dir,
        "features.var",
        r#"1: Feature Checkout = {
    1: enabled Boolean = true
    2: max_items Integer = 50
    3: header_text String = "Complete your purchase"
}"#,
    );

    let assert = cmd()
        .arg("encode")
        .arg("--schema-revision")
        .arg("5")
        .arg("--manifest-revision")
        .arg("9")
        .arg("--generated-at-unix-ms")
        .arg("123")
        .arg("--source")
        .arg("cli-test")
        .arg(&var_file)
        .assert()
        .success();

    let output = assert.get_output();
    assert!(
        output.stderr.is_empty(),
        "unexpected stderr: {:?}",
        output.stderr
    );
    assert!(output.stdout.starts_with(b"VARB"));

    let report = decode_snapshot(&output.stdout);
    assert!(
        report.diagnostics.is_empty(),
        "unexpected diagnostics: {:?}",
        report.diagnostics
    );

    let snapshot = report.snapshot.expect("expected decoded snapshot");
    assert_eq!(snapshot.metadata.schema_revision, 5);
    assert_eq!(snapshot.metadata.manifest_revision, 9);
    assert_eq!(snapshot.metadata.generated_at_unix_ms, 123);
    assert_eq!(snapshot.metadata.source.as_deref(), Some("cli-test"));
    assert_eq!(snapshot.features.len(), 1);
    assert_eq!(snapshot.features[0].feature_id, 1);
    assert_eq!(snapshot.features[0].variables.len(), 3);
    assert_eq!(
        snapshot.features[0].variables[0].value,
        Value::Boolean(true)
    );
    assert_eq!(snapshot.features[0].variables[1].value, Value::Integer(50));
}

#[test]
fn encode_invalid_var_file_fails() {
    let input_dir = TempDir::new().unwrap();

    let var_file = write_var_file(
        &input_dir,
        "bad.var",
        r#"Feature Checkout = {
    1: enabled Boolean = true
}"#,
    );

    cmd()
        .arg("encode")
        .arg(&var_file)
        .assert()
        .failure()
        .stderr(predicate::str::contains("expected").or(predicate::str::contains("error")));
}

#[test]
fn decode_binary_snapshot_outputs_json() {
    let temp_dir = TempDir::new().unwrap();
    let var_file = write_var_file(
        &temp_dir,
        "features.var",
        r#"1: Feature Checkout = {
    1: enabled Boolean = true
    2: max_items Integer = 50
}"#,
    );
    let binary_file = temp_dir.path().join("snapshot.bin");

    let encode_output = cmd()
        .arg("encode")
        .arg("--schema-revision")
        .arg("3")
        .arg("--manifest-revision")
        .arg("8")
        .arg("--generated-at-unix-ms")
        .arg("1234")
        .arg("--source")
        .arg("decode-test")
        .arg(&var_file)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    fs::write(&binary_file, encode_output).unwrap();

    let output = cmd()
        .arg("decode")
        .arg(&binary_file)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let decoded: JsonValue = serde_json::from_slice(&output).unwrap();
    assert_eq!(decoded["snapshot"]["metadata"]["schema_revision"], 3);
    assert_eq!(decoded["snapshot"]["metadata"]["manifest_revision"], 8);
    assert_eq!(
        decoded["snapshot"]["metadata"]["generated_at_unix_ms"],
        1234
    );
    assert_eq!(decoded["snapshot"]["metadata"]["source"], "decode-test");
    assert_eq!(decoded["snapshot"]["features"][0]["feature_id"], 1);
    assert_eq!(
        decoded["snapshot"]["features"][0]["variables"][0]["value"]["value"],
        true
    );
    assert!(decoded["diagnostics"].as_array().unwrap().is_empty());
}

#[test]
fn decode_fail_on_error_returns_non_zero() {
    let temp_dir = TempDir::new().unwrap();
    let binary_file = temp_dir.path().join("bad.bin");
    fs::write(&binary_file, b"NOPE").unwrap();

    cmd()
        .arg("decode")
        .arg("--fail-on-error")
        .arg(&binary_file)
        .assert()
        .failure()
        .stdout(predicate::str::contains("\"snapshot\":null"))
        .stderr(predicate::str::contains(
            "decode reported error diagnostics",
        ));
}

#[test]
fn generate_struct_fixture() {
    let out_dir = TempDir::new().unwrap();
    let fixture = workspace_root().join("fixtures/structs.var");

    cmd()
        .arg("generate")
        .arg("--out")
        .arg(out_dir.path())
        .arg(&fixture)
        .assert()
        .success();

    let output_file = out_dir.path().join("structs.generated.ts");
    assert!(output_file.exists(), "generated file should exist");

    let content = fs::read_to_string(&output_file).unwrap();

    // Struct interfaces are generated
    assert!(content.contains("export interface Theme"));
    assert!(content.contains("dark_mode: boolean"));
    assert!(content.contains("font_size: number"));
    assert!(content.contains("primary_color: string"));

    assert!(content.contains("export interface ShippingConfig"));
    assert!(content.contains("express_enabled: boolean"));
    assert!(content.contains("max_weight_kg: number"));
    assert!(content.contains("default_carrier: string"));

    // Feature interfaces reference struct types
    assert!(content.contains("theme: Theme"));
    assert!(content.contains("shipping: ShippingConfig"));
}

#[test]
fn encode_decode_roundtrip_with_structs() {
    let temp_dir = TempDir::new().unwrap();
    let var_file = write_var_file(
        &temp_dir,
        "structs.var",
        r#"1: Struct Config = {
    1: retries Integer = 3
    2: verbose Boolean = false
}

1: Feature App = {
    1: enabled Boolean = true
    2: config Config = Config { retries = 5 }
}"#,
    );

    let encode_output = cmd()
        .arg("encode")
        .arg("--schema-revision")
        .arg("1")
        .arg("--manifest-revision")
        .arg("1")
        .arg("--generated-at-unix-ms")
        .arg("100")
        .arg(&var_file)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    assert!(encode_output.starts_with(b"VARB"));

    // Decode and verify the struct fields are present
    let binary_file = temp_dir.path().join("snapshot.bin");
    fs::write(&binary_file, &encode_output).unwrap();

    let output = cmd()
        .arg("decode")
        .arg("--pretty")
        .arg(&binary_file)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let decoded: JsonValue = serde_json::from_slice(&output).unwrap();
    let features = decoded["snapshot"]["features"].as_array().unwrap();
    assert_eq!(features.len(), 1);

    let variables = features[0]["variables"].as_array().unwrap();
    assert_eq!(variables.len(), 2);

    // Variable 2 should be a struct type
    let config_var = &variables[1];
    assert_eq!(config_var["value"]["type"], "struct");
    let fields = &config_var["value"]["fields"];
    // retries was overridden to 5
    assert_eq!(fields["retries"]["value"], 5);
    // verbose was not overridden, uses struct default false
    assert_eq!(fields["verbose"]["value"], false);
}

#[test]
fn encode_struct_with_empty_literal() {
    let temp_dir = TempDir::new().unwrap();
    let var_file = write_var_file(
        &temp_dir,
        "test.var",
        r#"1: Struct Settings = {
    1: enabled Boolean = true
    2: count Integer = 10
}

1: Feature App = {
    1: settings Settings = Settings {}
}"#,
    );

    let encode_output = cmd()
        .arg("encode")
        .arg("--generated-at-unix-ms")
        .arg("0")
        .arg(&var_file)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let report = decode_snapshot(&encode_output);
    assert!(report.diagnostics.is_empty());

    let snapshot = report.snapshot.unwrap();
    let var = &snapshot.features[0].variables[0];
    match &var.value {
        Value::Struct { fields, .. } => {
            // Empty literal means all defaults from struct
            assert_eq!(fields.get("count"), Some(&Value::Integer(10)));
            assert_eq!(fields.get("enabled"), Some(&Value::Boolean(true)));
        }
        _ => panic!("expected struct value"),
    }
}