pixellint 0.30.2

Pixellint CLI: validates pixels, postbacks, conversion API payloads, and tracking URLs against spec-backed and vendor-documented rulepacks
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Pixellint command line interface.
//!
//! Exit codes are part of the contract:
//! `0` clean or warnings only, `1` at least one error-severity finding,
//! `2` usage, input, or configuration problem.

use std::env;
use std::fs;
use std::io::{self, Read};
use std::process::ExitCode;

use pixellint_core::{
    ArtifactKind, DocumentReport, Engine, ExpansionState, RuleSourceLevel, Severity,
    ValidationOptions, ValidationRequest, ValidationSummary, VendorDirectory,
    document_request_from_json,
};

const USAGE_EXIT: u8 = 2;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OutputFormat {
    Text,
    Json,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct CliOptions {
    validation: ValidationOptions,
    output_format: OutputFormat,
    expansion_state: ExpansionState,
    claimed_vendor: Option<String>,
    rulepack_files: Vec<String>,
    directory_files: Vec<String>,
}

fn main() -> ExitCode {
    let args: Vec<String> = env::args().skip(1).collect();

    match args.as_slice() {
        [] => {
            print_usage();
            ExitCode::from(USAGE_EXIT)
        }
        [command] if is_help(command) => {
            print_usage();
            ExitCode::SUCCESS
        }
        [command] if is_version(command) => {
            println!("pixellint {}", env!("CARGO_PKG_VERSION"));
            ExitCode::SUCCESS
        }
        [command, rest @ ..] if command == "list-rulepacks" => run_list_rulepacks(rest),
        [command, rest @ ..] if command == "list-vendors" => run_list_vendors(rest),
        [command, rest @ ..] if command == "validate" => run_validate(rest),
        [command, rest @ ..] if command == "validate-many" => run_validate_many(rest),
        [command, ..] => {
            eprintln!("unknown command: {command}");
            print_usage();
            ExitCode::from(USAGE_EXIT)
        }
    }
}

fn run_list_rulepacks(args: &[String]) -> ExitCode {
    let options = match parse_cli_options(args) {
        Ok(options) => options,
        Err(message) => return usage_error(&message),
    };

    let engine = match build_engine(&options) {
        Ok(engine) => engine,
        Err(message) => return usage_error(&message),
    };

    if options.output_format == OutputFormat::Json {
        match serde_json::to_string_pretty(&engine.list_rulepacks()) {
            Ok(payload) => println!("{payload}"),
            Err(error) => return usage_error(&error.to_string()),
        }

        return ExitCode::SUCCESS;
    }

    for rulepack in engine.list_rulepacks() {
        println!(
            "{}\t{}\t{}\t{}",
            rulepack.id,
            rulepack.display_name,
            source_level_label(rulepack.source_level),
            rulepack.description
        );
    }

    ExitCode::SUCCESS
}

fn run_list_vendors(args: &[String]) -> ExitCode {
    let options = match parse_cli_options(args) {
        Ok(options) => options,
        Err(message) => return usage_error(&message),
    };

    let engine = match build_engine(&options) {
        Ok(engine) => engine,
        Err(message) => return usage_error(&message),
    };

    let directory = engine.directory();

    if options.output_format == OutputFormat::Json {
        match serde_json::to_string_pretty(directory.entries()) {
            Ok(payload) => println!("{payload}"),
            Err(error) => return usage_error(&error.to_string()),
        }

        return ExitCode::SUCCESS;
    }

    for entry in directory.entries() {
        println!(
            "{}\t{}\t{}\t{}\t{}",
            entry.vendor,
            entry.display_name,
            entry.category,
            entry.rulepack.as_deref().unwrap_or("-"),
            entry.hosts.join(",")
        );
    }

    eprintln!(
        "\n{} vendors, {} hosts, {} with a rulepack.",
        directory.len(),
        directory.host_count(),
        directory
            .entries()
            .iter()
            .filter(|entry| entry.rulepack.is_some())
            .count()
    );

    ExitCode::SUCCESS
}

fn run_validate(args: &[String]) -> ExitCode {
    let [kind, input, rest @ ..] = args else {
        print_usage();
        return ExitCode::from(USAGE_EXIT);
    };

    let artifact_kind = match parse_artifact_kind(kind) {
        Ok(artifact_kind) => artifact_kind,
        Err(message) => return usage_error(&message),
    };

    let artifact = match read_artifact(input) {
        Ok(artifact) => artifact,
        Err(message) => return usage_error(&message),
    };

    let options = match parse_cli_options(rest) {
        Ok(options) => options,
        Err(message) => return usage_error(&message),
    };

    let engine = match build_engine(&options) {
        Ok(engine) => engine,
        Err(message) => return usage_error(&message),
    };

    let request = ValidationRequest {
        artifact_kind,
        artifact,
        claimed_vendor: options.claimed_vendor.clone(),
        expansion_state: options.expansion_state,
    };

    match engine.validate(&request, &options.validation) {
        Ok(summary) => {
            if let Err(error) = emit_summary(&summary, options.output_format) {
                return usage_error(&error.to_string());
            }

            if has_errors(&summary) {
                ExitCode::FAILURE
            } else {
                ExitCode::SUCCESS
            }
        }
        Err(error) => usage_error(&error.to_string()),
    }
}

fn run_validate_many(args: &[String]) -> ExitCode {
    let [input, rest @ ..] = args else {
        print_usage();
        return ExitCode::from(USAGE_EXIT);
    };

    let raw = match read_artifact(input) {
        Ok(raw) => raw,
        Err(message) => return usage_error(&message),
    };

    let request = match document_request_from_json(&raw) {
        Ok(request) => request,
        Err(message) => return usage_error(&message),
    };

    let options = match parse_cli_options(rest) {
        Ok(options) => options,
        Err(message) => return usage_error(&message),
    };

    let engine = match build_engine(&options) {
        Ok(engine) => engine,
        Err(message) => return usage_error(&message),
    };

    match engine.validate_many(&request, &options.validation) {
        Ok(report) => {
            if let Err(error) = emit_document(&report, options.output_format) {
                return usage_error(&error.to_string());
            }

            if report.is_ok() {
                ExitCode::SUCCESS
            } else {
                ExitCode::FAILURE
            }
        }
        Err(error) => usage_error(&error.to_string()),
    }
}

/// Builds the engine with the built-in packs plus any user-supplied manifests.
fn build_engine(options: &CliOptions) -> Result<Engine, String> {
    let mut engine = Engine::default();

    for path in &options.rulepack_files {
        engine
            .register_manifest_path(path)
            .map_err(|error| error.to_string())?;
    }

    for path in &options.directory_files {
        let extra = VendorDirectory::from_path(path).map_err(|error| error.to_string())?;
        engine
            .merge_directory(extra)
            .map_err(|error| error.to_string())?;
    }

    Ok(engine)
}

fn usage_error(message: &str) -> ExitCode {
    eprintln!("{message}");
    ExitCode::from(USAGE_EXIT)
}

fn is_help(value: &str) -> bool {
    matches!(value, "help" | "--help" | "-h")
}

fn is_version(value: &str) -> bool {
    matches!(value, "version" | "--version" | "-V")
}

fn snippet_kind_rejected(kind: &str) -> String {
    format!(
        "{kind} is not a validation kind. Extract tracking URLs from the snippet, then pixellint validate url. Pixellint does not parse HTML, JavaScript, or GTM containers."
    )
}

fn parse_artifact_kind(value: &str) -> Result<ArtifactKind, String> {
    match value {
        "url" => Ok(ArtifactKind::Url),
        "html" | "js" | "gtm" => Err(snippet_kind_rejected(value)),
        "request" => Ok(ArtifactKind::NetworkRequest),
        "vast" => Ok(ArtifactKind::VastTracker),
        "postback" => Ok(ArtifactKind::ServerPostback),
        "json" => Ok(ArtifactKind::JsonPayload),
        "unknown" => Ok(ArtifactKind::Unknown),
        other => Err(format!(
            "unknown artifact kind: {other} (expected url, request, vast, postback, json, or unknown)"
        )),
    }
}

/// Reads the artifact inline, from `@path`, or from stdin when the input is `-`.
fn read_artifact(input: &str) -> Result<String, String> {
    if input == "-" {
        let mut artifact = String::new();
        return io::stdin()
            .read_to_string(&mut artifact)
            .map(|_| artifact)
            .map_err(|error| format!("failed to read stdin: {error}"));
    }

    if let Some(path) = input.strip_prefix('@') {
        return fs::read_to_string(path).map_err(|error| format!("failed to read {path}: {error}"));
    }

    Ok(input.to_string())
}

fn parse_cli_options(args: &[String]) -> Result<CliOptions, String> {
    let mut validation = ValidationOptions::default();
    let mut output_format = OutputFormat::Text;
    let mut expansion_state = ExpansionState::Unknown;
    let mut claimed_vendor = None;
    let mut rulepack_files = Vec::new();
    let mut directory_files = Vec::new();
    let mut index = 0;

    while index < args.len() {
        let argument = args[index].as_str();

        match argument {
            "--json" => {
                output_format = OutputFormat::Json;
                index += 1;
            }
            "--state" | "--rulepack" | "--except" | "--vendor" | "--rulepack-file"
            | "--directory-file" => {
                let value = args
                    .get(index + 1)
                    .ok_or_else(|| format!("missing value for {argument}"))?;

                match argument {
                    "--state" => expansion_state = parse_expansion_state(value)?,
                    "--rulepack" => validation.only_rulepacks.push(value.clone()),
                    "--except" => validation.except_rulepacks.push(value.clone()),
                    "--vendor" => claimed_vendor = Some(value.clone()),
                    "--rulepack-file" => rulepack_files.push(value.clone()),
                    "--directory-file" => directory_files.push(value.clone()),
                    _ => unreachable!(),
                }

                index += 2;
            }
            other => {
                return Err(format!("unknown argument: {other}"));
            }
        }
    }

    Ok(CliOptions {
        validation,
        output_format,
        expansion_state,
        claimed_vendor,
        rulepack_files,
        directory_files,
    })
}

fn parse_expansion_state(value: &str) -> Result<ExpansionState, String> {
    match value {
        "unknown" => Ok(ExpansionState::Unknown),
        "template" => Ok(ExpansionState::Template),
        "fired" => Ok(ExpansionState::Fired),
        other => Err(format!(
            "unknown expansion state: {other} (expected unknown, template, or fired)"
        )),
    }
}

fn emit_summary(
    summary: &ValidationSummary,
    output_format: OutputFormat,
) -> Result<(), serde_json::Error> {
    match output_format {
        OutputFormat::Text => {
            print_summary(summary);
            Ok(())
        }
        OutputFormat::Json => {
            let payload = serde_json::to_string_pretty(summary)?;
            println!("{payload}");
            Ok(())
        }
    }
}

fn emit_document(
    report: &DocumentReport,
    output_format: OutputFormat,
) -> Result<(), serde_json::Error> {
    match output_format {
        OutputFormat::Text => {
            print_document(report);
            Ok(())
        }
        OutputFormat::Json => {
            let payload = serde_json::to_string_pretty(report)?;
            println!("{payload}");
            Ok(())
        }
    }
}

fn print_reports(reports: &[pixellint_core::ValidationReport]) -> (usize, usize, usize) {
    let mut errors = 0;
    let mut warnings = 0;
    let mut infos = 0;

    for report in reports {
        match &report.detected_vendor {
            Some(vendor) => println!("rulepack: {} (vendor: {vendor})", report.plugin_id),
            None => println!("rulepack: {}", report.plugin_id),
        }

        if report.violations.is_empty() {
            println!("  ok");
            continue;
        }

        for violation in &report.violations {
            match violation.severity {
                Severity::Error => errors += 1,
                Severity::Warning => warnings += 1,
                Severity::Info => infos += 1,
            }

            println!(
                "  {}\t{}\t{}",
                severity_label(violation.severity),
                violation.code,
                violation.message
            );

            if let Some(fix_hint) = &violation.fix_hint {
                println!("    fix: {fix_hint}");
            }

            if let Some(reference) = &violation.source.reference {
                println!("    docs: {reference}");
            }
        }
    }

    (errors, warnings, infos)
}

fn print_summary(summary: &ValidationSummary) {
    let (errors, warnings, infos) = print_reports(&summary.reports);
    println!(
        "\n{errors} error(s), {warnings} warning(s), {infos} info message(s) across {} rulepack(s).",
        summary.reports.len()
    );
}

fn print_document(report: &DocumentReport) {
    println!(
        "document: {} ({} artifact(s), {} unique)",
        report.document_kind,
        report.summary.artifacts_total.unwrap_or(0),
        report.summary.unique_artifacts.unwrap_or(0)
    );
    if let Some(extractor) = &report.extractor {
        match &extractor.version {
            Some(version) => println!("extractor: {} {version}", extractor.id),
            None => println!("extractor: {}", extractor.id),
        }
    }

    for artifact in &report.artifacts {
        println!();
        println!(
            "{} ({} occurrence(s)) {}",
            artifact.artifact_id,
            artifact.occurrences.len(),
            artifact.normalized_artifact
        );
        print_reports(&artifact.reports);
    }

    println!(
        "\n{} error(s), {} warning(s), {} info message(s) across {} unique artifact(s).",
        report.summary.errors,
        report.summary.warnings,
        report.summary.infos,
        report.artifacts.len()
    );
}

fn severity_label(severity: Severity) -> &'static str {
    match severity {
        Severity::Error => "error",
        Severity::Warning => "warning",
        Severity::Info => "info",
    }
}

fn source_level_label(level: RuleSourceLevel) -> &'static str {
    match level {
        RuleSourceLevel::Normative => "normative",
        RuleSourceLevel::OfficialVendor => "official-vendor",
        RuleSourceLevel::OfficialTemplate => "official-template",
        RuleSourceLevel::EcosystemReference => "ecosystem-reference",
        RuleSourceLevel::Heuristic => "heuristic",
    }
}

fn has_errors(summary: &ValidationSummary) -> bool {
    summary
        .reports
        .iter()
        .flat_map(|report| report.violations.iter())
        .any(|violation| violation.severity == Severity::Error)
}

fn print_usage() {
    eprintln!(
        "\
pixellint {version}
Spec-first validator for pixels, postbacks, and other measurement artifacts.

USAGE
  pixellint validate <kind> <artifact> [options]
  pixellint validate-many <document> [options]
  pixellint list-rulepacks [--json] [--rulepack-file <path>]...
  pixellint list-vendors [--json] [--directory-file <path>]...
  pixellint help
  pixellint version

KINDS
  url, request, vast, postback, json, unknown

ARTIFACT
  inline value, @path to read a file, or - to read stdin

DOCUMENT
  JSON object from MULTI_ARTIFACT_SCHEMA.md, or a JSON array of URL strings.
  Extract tracking URLs first. Pixellint does not parse VAST, HTML, or GTM.

OPTIONS
  --json                  Machine-readable output
  --state <state>         unknown (default), template, or fired
  --vendor <slug>         Vendor the caller believes the artifact belongs to
  --rulepack <id>         Run only these rulepacks (repeatable). `directory`
                          selects endpoint attribution
  --except <id>           Skip these rulepacks (repeatable)
  --rulepack-file <path>  Load a custom rulepack manifest (repeatable)
  --directory-file <path>  Merge extra vendor directory entries (repeatable)

EXIT CODES
  0  clean, or warnings and info only
  1  at least one error-severity finding
  2  usage, input, or configuration problem",
        version = env!("CARGO_PKG_VERSION")
    );
}