diff --git a/CHANGELOG.md b/CHANGELOG.md index 99b81be..9b8299c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,31 @@ All notable changes to LibreDevOpsHelpers are recorded here. +## Unreleased + +### Added +- A Json module, the twin of the ldo CLI's `ldo json` commands: `ConvertFrom-LdoJson`, + `Repair-LdoJson`, `Test-LdoJson`, `Get-LdoJsonValue` and `Merge-LdoJson`. It reads JSON as it + was written (keys in order and case-sensitive, big numbers whole, strings never turned into + dates), repairs what is nearly JSON when asked and logs each fix, and merges documents deeply or + as an RFC 7396 merge patch. The two agree through one set of test cases, `tests/shared`, that + both suites run. +- `ConvertTo-LdoYaml -Indent`, for the spaces per level. + +### Fixed +- `ConvertTo-LdoYaml` wrote a multi-line string as `|` whatever its ending, so a string with no + final line break read back with one. It now writes `|-`, `|` or `|+` as the string ends, and + quotes a string it cannot write as a block (one starting with a space, or with a line ending in + a space). +- `ConvertTo-LdoYaml` left plain some strings that YAML 1.1 readers (PyYAML, yamllint, Ansible) + read as something else: `12:30` (a number), `2026-09-24` (a date), `0x1F`, `.inf`, `y` and `N`. + They are quoted now, and control characters inside quotes are escaped (a tab was written raw). + +### Changed +- `ConvertTo-LdoYaml` writes a float as Python does, `1.0`, `1.0e-07`, `.nan` or `.inf`, where it + wrote `1`, `1E-07` or `NaN`, so a whole float reads back as a float. A date is written in ISO + 8601, `"2026-12-04T10:00:00.0000000Z"`, where it was `12/04/2026 10:00:00`. + ## 3.0.1 ### Fixed diff --git a/LibreDevOpsHelpers/LibreDevOpsHelpers.Json/LibreDevOpsHelpers.Json.psm1 b/LibreDevOpsHelpers/LibreDevOpsHelpers.Json/LibreDevOpsHelpers.Json.psm1 new file mode 100644 index 0000000..aba7706 --- /dev/null +++ b/LibreDevOpsHelpers/LibreDevOpsHelpers.Json/LibreDevOpsHelpers.Json.psm1 @@ -0,0 +1,1836 @@ +Set-StrictMode -Version Latest + +# JSON as people and tools really write it: read strictly, repaired, checked, values got out of +# it by path, and merged. The twin of the ldo CLI's core.json_text, core.field_paths and +# core.json_merge (libre-devops/ldo-cli). The cases in tests/shared are the contract both meet: +# change a case in ldo-cli first, copy it here, and make both meet it. +# +# JSON objects are read as ordered dictionaries that are case-sensitive, as JSON's keys are +# (ConvertFrom-Json refuses keys that differ only in case), strings stay strings (no dates), and +# numbers are [long], [System.Numerics.BigInteger] or [double]. The work is done in classes, +# whose methods return lists whole where a function would unroll them. + +class LdoJsonNote { + # Something found in, or done to, JSON text: where (line and column in the text as given, + # from 1, the column in characters), how much it matters (error, warning or fixed), which + # rule, and what it means. + [int]$Line + [int]$Column + [string]$Severity + [string]$Rule + [string]$Message + + LdoJsonNote([int]$line, [int]$column, [string]$severity, [string]$rule, [string]$message) { + $this.Line = $line + $this.Column = $column + $this.Severity = $severity + $this.Rule = $rule + $this.Message = $message + } +} + +class LdoJsonError : System.FormatException { + # Text that is not JSON. Repairable names the rules it breaks that repairing fixes, and + # Complete says whether that is all that is wrong. Empty is set when there is no text. + [string[]]$Repairable = @() + [bool]$Complete + [bool]$Empty + + LdoJsonError([string]$message) : base($message) {} +} + +class LdoJsonReadError : System.Exception { + # Where a strict read stopped, as an offset in the text it read. + [int]$Offset + [string]$Reason + + LdoJsonReadError([string]$reason, [int]$offset) : base($reason) { + $this.Reason = $reason + $this.Offset = $offset + } +} + +class LdoJsonNonFinite : System.Exception { + # NaN or Infinity, which JSON cannot hold, met while reading strictly. + [string]$Word + + LdoJsonNonFinite([string]$word) : base($word) { + $this.Word = $word + } +} + +class LdoJsonRunTogether : System.Exception { + # A second document on the line the one before it ended, met while reading strictly. + [int]$Offset + + LdoJsonRunTogether([int]$offset) : base('run together') { + $this.Offset = $offset + } +} + +class LdoJsonTokens { + # The text as tokens, in three arrays side by side: kind, text and offset. + static [regex]$Pattern = [regex]::new(@' +(?\s+) +|(?//[^\n]*|/\*.*?\*/) +|(?"(?:[^"\\\n]|\\.)*") +|(?'(?:[^'\\\n]|\\.)*') +|(?-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?) +|(?-?[A-Za-z_$][A-Za-z0-9_$]*) +|(?[{}\[\]:,]) +|(?.) +'@, 'IgnorePatternWhitespace, Singleline') + static [string[]]$Kinds = @('space', 'comment', 'string', 'quoted', 'number', 'word', 'punct', 'other') + + [string[]]$Kind + [string[]]$Text + [int[]]$Offset + [int]$Count + + LdoJsonTokens([string]$text) { + $found = [LdoJsonTokens]::Pattern.Matches($text) + $this.Count = $found.Count + $this.Kind = [string[]]::new($this.Count) + $this.Text = [string[]]::new($this.Count) + $this.Offset = [int[]]::new($this.Count) + $groups = [int[]]::new(8) + for ($k = 0; $k -lt 8; $k++) { + $groups[$k] = [LdoJsonTokens]::Pattern.GroupNumberFromName([LdoJsonTokens]::Kinds[$k]) + } + for ($i = 0; $i -lt $this.Count; $i++) { + $match = $found[$i] + $this.Text[$i] = $match.Value + $this.Offset[$i] = $match.Index + for ($k = 0; $k -lt 8; $k++) { + if ($match.Groups[$groups[$k]].Success) { + $this.Kind[$i] = [LdoJsonTokens]::Kinds[$k] + break + } + } + } + } +} + +class LdoJsonLines { + # Offsets in a text as lines and columns, counted from 1, a column in characters (a pair + # of surrogates is one), as Python counts them. + [int[]]$Starts + [string]$Text + [bool]$Astral + + LdoJsonLines([string]$text) { + $found = [System.Collections.Generic.List[int]]::new() + $found.Add(0) + $at = $text.IndexOf([char]10) + while ($at -ge 0) { + $found.Add($at + 1) + $at = $text.IndexOf([char]10, $at + 1) + } + $this.Starts = $found.ToArray() + $this.Text = $text + $this.Astral = $text -cmatch '[\ud800-\udfff]' + } + + [int[]] At([int]$offset) { + $index = [Array]::BinarySearch($this.Starts, $offset) + $line = if ($index -ge 0) { $index + 1 } else { -bnot $index } + $start = $this.Starts[$line - 1] + $column = $offset - $start + 1 + if ($this.Astral) { + for ($i = $start + 1; $i -lt $offset; $i++) { + if ([char]::IsLowSurrogate($this.Text[$i]) -and [char]::IsHighSurrogate($this.Text[$i - 1])) { + $column-- + } + } + } + return @($line, $column) + } +} + +class LdoJsonReader { + # Reads documents one after another, strictly, from tokens, and notices a key given twice. + [LdoJsonTokens]$Tokens + [string]$Text + [int]$At + [int]$End + [bool]$Duplicates + + LdoJsonReader([string]$text) { + $this.Text = $text + $this.Tokens = [LdoJsonTokens]::new($text) + } + + # Each document as @(value, start, end). With runTogether set, a document starting on the + # line the one before it ended is refused, as reading strictly does. + [System.Collections.Generic.List[object]] Documents([bool]$runTogether) { + $found = [System.Collections.Generic.List[object]]::new() + $this.SkipSpace() + $previous = -1 + while ($this.At -lt $this.Tokens.Count) { + $start = $this.Tokens.Offset[$this.At] + if ($runTogether -and $previous -ge 0 -and $this.Text.IndexOf([char]10, $previous, $start - $previous) -lt 0) { + throw [LdoJsonRunTogether]::new($start) + } + $entry = [object[]]::new(3) + $entry[0] = $this.Value() + $entry[1] = $start + $entry[2] = $this.End + $found.Add($entry) + $previous = $this.End + $this.SkipSpace() + } + return $found + } + + [void] SkipSpace() { + while ($this.At -lt $this.Tokens.Count -and $this.Tokens.Kind[$this.At] -ceq 'space') { + $space = $this.Tokens.Text[$this.At] + $other = [regex]::Match($space, '[^ \t\r\n]') + if ($other.Success) { + throw [LdoJsonReadError]::new('Expecting value', $this.Tokens.Offset[$this.At] + $other.Index) + } + $this.At++ + } + } + + [int] Here() { + if ($this.At -lt $this.Tokens.Count) { return $this.Tokens.Offset[$this.At] } + return $this.Text.Length + } + + [bool] Is([string]$punct) { + return $this.At -lt $this.Tokens.Count -and $this.Tokens.Kind[$this.At] -ceq 'punct' -and + $this.Tokens.Text[$this.At] -ceq $punct + } + + [void] Take() { + $this.End = $this.Tokens.Offset[$this.At] + $this.Tokens.Text[$this.At].Length + $this.At++ + } + + [object] Value() { + if ($this.At -ge $this.Tokens.Count) { throw [LdoJsonReadError]::new('Expecting value', $this.Text.Length) } + $kind = $this.Tokens.Kind[$this.At] + $token = $this.Tokens.Text[$this.At] + $offset = $this.Tokens.Offset[$this.At] + if ($kind -ceq 'punct' -and $token -ceq '{') { return $this.Object() } + if ($kind -ceq 'punct' -and $token -ceq '[') { return $this.Array() } + if ($kind -ceq 'string') { + $this.Take() + return [LdoJsonReader]::DecodeString($token, $offset) + } + if ($kind -ceq 'number') { + $this.Take() + return [LdoJsonReader]::Number($token) + } + if ($kind -ceq 'word') { + if ($token -ceq 'true') { $this.Take(); return $true } + if ($token -ceq 'false') { $this.Take(); return $false } + if ($token -ceq 'null') { $this.Take(); return $null } + if ([LdoJsonWalk]::NonFinite -ccontains $token) { throw [LdoJsonNonFinite]::new($token) } + } + if ($kind -ceq 'other' -and $token -ceq '"') { + throw [LdoJsonReadError]::new('Unterminated string starting at', $offset) + } + throw [LdoJsonReadError]::new('Expecting value', $offset) + } + + [object] Object() { + $this.Take() + $result = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + $this.SkipSpace() + if ($this.Is('}')) { + $this.Take() + return $result + } + while ($true) { + if ($this.At -ge $this.Tokens.Count -or $this.Tokens.Kind[$this.At] -cne 'string') { + throw [LdoJsonReadError]::new('Expecting property name enclosed in double quotes', $this.Here()) + } + $key = [LdoJsonReader]::DecodeString($this.Tokens.Text[$this.At], $this.Tokens.Offset[$this.At]) + $this.Take() + $this.SkipSpace() + if (-not $this.Is(':')) { throw [LdoJsonReadError]::new("Expecting ':' delimiter", $this.Here()) } + $this.Take() + $this.SkipSpace() + $item = $this.Value() + if ($result.Contains($key)) { $this.Duplicates = $true } + $result[$key] = $item + $this.SkipSpace() + if ($this.Is(',')) { + $this.Take() + $this.SkipSpace() + continue + } + if ($this.Is('}')) { + $this.Take() + return $result + } + throw [LdoJsonReadError]::new("Expecting ',' delimiter", $this.Here()) + } + throw [LdoJsonReadError]::new('Expecting value', $this.Here()) + } + + [object] Array() { + $this.Take() + $items = [System.Collections.Generic.List[object]]::new() + $this.SkipSpace() + if ($this.Is(']')) { + $this.Take() + return $items.ToArray() + } + while ($true) { + $items.Add($this.Value()) + $this.SkipSpace() + if ($this.Is(',')) { + $this.Take() + $this.SkipSpace() + continue + } + if ($this.Is(']')) { + $this.Take() + return $items.ToArray() + } + throw [LdoJsonReadError]::new("Expecting ',' delimiter", $this.Here()) + } + throw [LdoJsonReadError]::new('Expecting value', $this.Here()) + } + + static [object] Number([string]$token) { + $invariant = [System.Globalization.CultureInfo]::InvariantCulture + if ($token.IndexOfAny([char[]]'.eE') -lt 0) { + [long]$small = 0 + if ([long]::TryParse($token, [System.Globalization.NumberStyles]::AllowLeadingSign, $invariant, [ref]$small)) { + return $small + } + return [System.Numerics.BigInteger]::Parse($token, $invariant) + } + return [double]::Parse($token, [System.Globalization.NumberStyles]::Float, $invariant) + } + + # A string token (quotes and all) as the text it holds. The offset places an error. + static [string] DecodeString([string]$token, [int]$offset) { + $inner = $token.Substring(1, $token.Length - 2) + $control = [regex]::Match($inner, '[\x00-\x1f]') + if ($control.Success) { + throw [LdoJsonReadError]::new('Invalid control character at', $offset + 1 + $control.Index) + } + if ($inner.IndexOf([char]92) -lt 0) { return $inner } + foreach ($escape in [regex]::Matches($inner, '\\(u[0-9a-fA-F]{4}|.)', 'Singleline')) { + $code = $escape.Groups[1].Value + if ($code.Length -ne 5 -and '"\/bfnrt'.IndexOf($code[0]) -lt 0) { + throw [LdoJsonReadError]::new('Invalid \escape', $offset + 1 + $escape.Index) + } + } + return [regex]::Replace($inner, '\\(u[0-9a-fA-F]{4}|.)', [System.Text.RegularExpressions.MatchEvaluator] { + param($found) + $code = $found.Groups[1].Value + if ($code.Length -eq 5) { return [string][char][System.Convert]::ToInt32($code.Substring(1), 16) } + switch -CaseSensitive ($code) { + 'b' { return [string][char]8 } + 'f' { return [string][char]12 } + 'n' { return [string][char]10 } + 'r' { return [string][char]13 } + 't' { return [string][char]9 } + } + return $code + }, 'Singleline') + } +} + +class LdoJsonRepair { + # One thing repairing changes: where, by which rule, said as done and as a problem. + [int]$Line + [int]$Column + [string]$Rule + [string]$Done + [string]$Wrong + + LdoJsonRepair([int[]]$at, [string]$rule, [string]$done, [string]$wrong) { + $this.Line = $at[0] + $this.Column = $at[1] + $this.Rule = $rule + $this.Done = $done + $this.Wrong = $wrong + } + + [LdoJsonNote] Fixed() { return [LdoJsonNote]::new($this.Line, $this.Column, 'fixed', $this.Rule, $this.Done) } + + [LdoJsonNote] Problem() { return [LdoJsonNote]::new($this.Line, $this.Column, 'error', $this.Rule, $this.Wrong) } +} + +class LdoJsonWalk { + # One pass over the text's tokens: the repaired text, piece by piece with the token each + # came from, and each repair made. + static [string[]]$NonFinite = @('NaN', 'Infinity', '-Infinity') + static [string[]]$ValueWords = @('true', 'false', 'null', 'True', 'False', 'None', 'undefined', 'NaN', 'Infinity', '-Infinity') + static [string[]]$ValueKinds = @('string', 'quoted', 'number', 'word') + + [LdoJsonTokens]$Tokens + [LdoJsonLines]$Lines + [System.Collections.Generic.List[LdoJsonRepair]]$Repairs + [System.Collections.Generic.List[string]]$Written + [System.Collections.Generic.List[int]]$From + [System.Collections.Generic.List[string]]$Depth + [int]$EndedLine + + LdoJsonWalk([string]$text) { + $this.Tokens = [LdoJsonTokens]::new($text) + $this.Lines = [LdoJsonLines]::new($text) + $this.Repairs = [System.Collections.Generic.List[LdoJsonRepair]]::new() + $this.Written = [System.Collections.Generic.List[string]]::new() + $this.From = [System.Collections.Generic.List[int]]::new() + $this.Depth = [System.Collections.Generic.List[string]]::new() + for ($i = 0; $i -lt $this.Tokens.Count; $i++) { + $this.Token($i) + } + } + + # The text with every repair made. + [string] Text() { return [string]::Concat($this.Written) } + + # The rules the repairs follow, each once, in the order first met. + [string[]] Rules() { + $seen = [System.Collections.Generic.List[string]]::new() + foreach ($repair in $this.Repairs) { + if (-not $seen.Contains($repair.Rule)) { $seen.Add($repair.Rule) } + } + return $seen.ToArray() + } + + # Where an offset in the repaired text was in the text as given. + [int[]] Original([int]$position) { + if ($this.Written.Count -eq 0) { return @(1, 1) } + $starts = [int[]]::new($this.Written.Count) + $total = 0 + for ($i = 0; $i -lt $this.Written.Count; $i++) { + $starts[$i] = $total + $total += $this.Written[$i].Length + } + $index = [Array]::BinarySearch($starts, $position) + if ($index -lt 0) { $index = (-bnot $index) - 1 } + $index = [Math]::Max($index, 0) + $token = $this.From[$index] + $inside = [Math]::Min($position - $starts[$index], [Math]::Max($this.Tokens.Text[$token].Length - 1, 0)) + return $this.Lines.At($this.Tokens.Offset[$token] + $inside) + } + + # Keys given twice in one object, and unless duplicatesOnly, keys that differ only in case. + [System.Collections.Generic.List[LdoJsonNote]] KeyNotes([bool]$duplicatesOnly) { + $notes = [System.Collections.Generic.List[LdoJsonNote]]::new() + $objects = [System.Collections.Generic.List[object]]::new() + for ($i = 0; $i -lt $this.Tokens.Count; $i++) { + $kind = $this.Tokens.Kind[$i] + $text = $this.Tokens.Text[$i] + if ($kind -ceq 'punct' -and ($text -ceq '{' -or $text -ceq '[')) { + $keys = $null + if ($text -ceq '{') { $keys = [System.Collections.Generic.Dictionary[string, string[]]]::new([System.StringComparer]::Ordinal) } + $objects.Add($keys) + } + elseif ($kind -ceq 'punct' -and ($text -ceq '}' -or $text -ceq ']')) { + if ($objects.Count -gt 0) { $objects.RemoveAt($objects.Count - 1) } + } + elseif ($objects.Count -gt 0 -and $null -ne $objects[$objects.Count - 1] -and $this.IsKey($i)) { + $note = $this.Seen($objects[$objects.Count - 1], $i) + if ($null -ne $note) { $notes.Add($note) } + } + } + if (-not $duplicatesOnly) { return $notes } + $only = [System.Collections.Generic.List[LdoJsonNote]]::new() + foreach ($note in $notes) { + if ($note.Rule -ceq 'duplicate-key') { $only.Add($note) } + } + return $only + } + + [LdoJsonNote] Seen([System.Collections.Generic.Dictionary[string, string[]]]$keys, [int]$index) { + $key = [LdoJsonWalk]::KeyText($this.Tokens.Kind[$index], $this.Tokens.Text[$index]) + $folded = $key.ToLowerInvariant() + $at = $this.Lines.At($this.Tokens.Offset[$index]) + if (-not $keys.ContainsKey($folded)) { + $keys[$folded] = @($key, "line $($at[0]), column $($at[1])") + return $null + } + $first = $keys[$folded][0] + $firstAt = $keys[$folded][1] + if ([string]::Equals($first, $key)) { + $message = "the key `"$key`" again (first at $firstAt): a reader keeps one, most often the last, and says nothing" + return [LdoJsonNote]::new($at[0], $at[1], 'warning', 'duplicate-key', $message) + } + $message = "the key `"$key`" differs from `"$first`" (at $firstAt) only in case: PowerShell's ConvertFrom-Json refuses that" + return [LdoJsonNote]::new($at[0], $at[1], 'warning', 'case-only-key', $message) + } + + [void] Token([int]$index) { + $kind = $this.Tokens.Kind[$index] + $text = $this.Tokens.Text[$index] + $scalar = $this.IsScalar($index) + if ($this.Depth.Count -eq 0 -and ($scalar -or ($kind -ceq 'punct' -and ($text -ceq '{' -or $text -ceq '[')))) { + $this.StartsDocument($index) + } + if ($kind -ceq 'comment') { + $this.Fix($index, 'comment', 'removed a comment', 'a comment: JSON has none') + $this.Write(' ', $index) # keeps the tokens either side of it apart + } + elseif ($kind -ceq 'quoted') { + $this.Fix($index, 'single-quote', 'double-quoted a single-quoted string', 'a single-quoted string: JSON strings take double quotes') + $this.Write([LdoJsonWalk]::DoubleQuoted($text), $index) + } + elseif ($kind -ceq 'word') { + $this.Word($index) + } + elseif ($kind -ceq 'punct') { + $this.Punct($index) + } + else { + $this.Write($text, $index) + } + if ($scalar -and $this.Depth.Count -eq 0) { + $this.EndedLine = $this.Lines.At($this.Tokens.Offset[$index])[0] + } + } + + [void] StartsDocument([int]$index) { + if ($this.EndedLine -gt 0 -and $this.Lines.At($this.Tokens.Offset[$index])[0] -eq $this.EndedLine) { + $this.Fix($index, 'run-together', 'split documents run together on one line', 'a second document on the line the one before it ended') + $this.Write("`n", $index) # so the repaired text is one document to a line + } + } + + [void] Word([int]$index) { + $word = $this.Tokens.Text[$index] + $literal = [LdoJsonWalk]::Literal($word) + if ($this.Depth.Count -gt 0 -and $this.Depth[$this.Depth.Count - 1] -ceq '{' -and $this.IsKey($index)) { + $this.Fix($index, 'bare-key', "quoted the key $word", "the key $word is unquoted") + $this.Write('"' + $word + '"', $index) + } + elseif ($literal -cne '') { + $this.Fix($index, 'literal', "$word became $literal", "$word is not JSON, which writes $literal") + $this.Write($literal, $index) + } + elseif ([LdoJsonWalk]::NonFinite -ccontains $word) { + $this.Fix($index, 'non-finite', "$word became null", "$word, which JSON cannot hold") + $this.Write('null', $index) + } + else { + $this.Write($word, $index) + } + } + + [void] Punct([int]$index) { + $text = $this.Tokens.Text[$index] + if ($text -ceq ',') { + $next = $this.Next($index) + if ($next -ceq '}' -or $next -ceq ']') { + $this.Fix($index, 'trailing-comma', 'removed a trailing comma', 'a trailing comma') + return + } + } + $this.Write($text, $index) + if ($text -ceq '{' -or $text -ceq '[') { + $this.Depth.Add($text) + } + elseif (($text -ceq '}' -or $text -ceq ']') -and $this.Depth.Count -gt 0) { + $this.Depth.RemoveAt($this.Depth.Count - 1) + if ($this.Depth.Count -eq 0) { $this.EndedLine = $this.Lines.At($this.Tokens.Offset[$index])[0] } + } + } + + [bool] IsKey([int]$index) { + return [LdoJsonWalk]::ValueKinds -ccontains $this.Tokens.Kind[$index] -and $this.Next($index) -ceq ':' + } + + # Whether a token is a whole value: a string, a number, or a word that is one. + [bool] IsScalar([int]$index) { + $kind = $this.Tokens.Kind[$index] + if ($kind -ceq 'word') { return [LdoJsonWalk]::ValueWords -ccontains $this.Tokens.Text[$index] } + return $kind -ceq 'string' -or $kind -ceq 'quoted' -or $kind -ceq 'number' + } + + # The next token that is not space or a comment, as text; empty at the end. + [string] Next([int]$index) { + for ($i = $index + 1; $i -lt $this.Tokens.Count; $i++) { + $kind = $this.Tokens.Kind[$i] + if ($kind -cne 'space' -and $kind -cne 'comment') { return $this.Tokens.Text[$i] } + } + return '' + } + + [void] Write([string]$text, [int]$index) { + $this.Written.Add($text) + $this.From.Add($index) + } + + [void] Fix([int]$index, [string]$rule, [string]$done, [string]$wrong) { + $this.Repairs.Add([LdoJsonRepair]::new($this.Lines.At($this.Tokens.Offset[$index]), $rule, $done, $wrong)) + } + + # Bare words other languages write for JSON's own: repairing writes JSON's. Empty if not one + # (a method that returns a string cannot return null). + static [string] Literal([string]$word) { + if ($word -ceq 'True') { return 'true' } + if ($word -ceq 'False') { return 'false' } + if ($word -ceq 'None' -or $word -ceq 'undefined') { return 'null' } + return '' + } + + # A single-quoted string as JSON writes it: \' is a quote, a bare " is escaped, and an + # escape JSON has not got loses its backslash, as JavaScript reads it. + static [string] DoubleQuoted([string]$text) { + $inner = $text.Substring(1, $text.Length - 2) + $swapped = [regex]::Replace($inner, '\\.|"', [System.Text.RegularExpressions.MatchEvaluator] { + param($found) + $part = $found.Value + if ($part -ceq '"') { return '\"' } + if ($part[1] -ceq [char]39) { return [string][char]39 } + if ('"\/bfnrtu'.IndexOf($part[1]) -ge 0) { return $part } + return [string]$part[1] + }, 'Singleline') + return '"' + $swapped + '"' + } + + # A key as a reader sees it once its quotes and escapes are gone. + static [string] KeyText([string]$kind, [string]$text) { + $asJson = if ($kind -ceq 'quoted') { [LdoJsonWalk]::DoubleQuoted($text) } else { $text } + if ($kind -cne 'string' -and $kind -cne 'quoted') { return $asJson } + try { + return [LdoJsonReader]::DecodeString($asJson, 0) + } + catch { + return $asJson.Substring(1, $asJson.Length - 2) + } + } +} + +class LdoJsonText { + # Reading (strictly or repaired), checking and expanding: core.json_text's parse, check and + # expand. + + # The exception thrown, under the MethodInvocationException PowerShell wraps around one + # thrown from a method a method called. + static [System.Exception] Cause([System.Exception]$exception) { + while ($exception -is [System.Management.Automation.MethodInvocationException] -and $null -ne $exception.InnerException) { + $exception = $exception.InnerException + } + return $exception + } + # Whether the text starts with a byte order mark. Not String.StartsWith, which compares by + # culture, where the mark is ignorable and so starts every string. + static [bool] HasBom([string]$text) { + return $text.Length -gt 0 -and $text[0] -eq [char]0xFEFF + } + + static [System.Collections.Specialized.OrderedDictionary]$Repairable = [ordered]@{ + 'comment' = 'comments' + 'trailing-comma' = 'trailing commas' + 'single-quote' = 'single-quoted strings' + 'bare-key' = 'unquoted keys' + 'literal' = "Python's True, False and None, and JavaScript's undefined" + 'non-finite' = 'NaN and Infinity' + 'run-together' = 'documents run together on one line' + } + + # Every document in the text, and the notes on them (repairs made, and warnings), as an + # object with Documents, Notes and (repaired) Text. Throws LdoJsonError. + static [object] Parse([string]$text, [bool]$repair) { + if ([LdoJsonText]::HasBom($text)) { $text = $text.Substring(1) } + if ($text.Trim().Length -eq 0) { + $empty = [LdoJsonError]::new('the input is empty') + $empty.Empty = $true + throw $empty + } + if ($repair) { return [LdoJsonText]::ParseRepaired($text) } + return [LdoJsonText]::ParseStrict($text) + } + + static [object] ParseStrict([string]$text) { + $reader = [LdoJsonReader]::new($text) + $found = $null + try { + $found = $reader.Documents($true) + } + catch [LdoJsonReadError] { + $at = [LdoJsonLines]::new($text).At([LdoJsonText]::Cause($_.Exception).Offset) + throw [LdoJsonText]::NotJson("not JSON: $([LdoJsonText]::Cause($_.Exception).Reason) at line $($at[0]), column $($at[1])", [LdoJsonWalk]::new($text)) + } + catch [LdoJsonNonFinite] { + throw [LdoJsonText]::NonFiniteError($text, [LdoJsonText]::Cause($_.Exception).Word) + } + catch [LdoJsonRunTogether] { + $at = [LdoJsonLines]::new($text).At([LdoJsonText]::Cause($_.Exception).Offset) + $message = "not JSON: a second document starts at line $($at[0]), column $($at[1]), on the line the one before it ended" + throw [LdoJsonText]::NotJson($message, [LdoJsonWalk]::new($text)) + } + $notes = [System.Collections.Generic.List[LdoJsonNote]]::new() + if ($reader.Duplicates) { $notes = [LdoJsonWalk]::new($text).KeyNotes($true) } + return [pscustomobject]@{ Documents = [LdoJsonText]::Values($found); Notes = $notes.ToArray(); Text = $text } + } + + static [object] ParseRepaired([string]$text) { + $walk = [LdoJsonWalk]::new($text) + $repaired = $walk.Text() + $reader = [LdoJsonReader]::new($repaired) + $found = $null + try { + $found = $reader.Documents($false) + } + catch [LdoJsonReadError] { + $at = $walk.Original([LdoJsonText]::Cause($_.Exception).Offset) + throw [LdoJsonError]::new("not JSON, even repaired: $([LdoJsonText]::Cause($_.Exception).Reason) at line $($at[0]), column $($at[1])") + } + $notes = [System.Collections.Generic.List[LdoJsonNote]]::new() + foreach ($repair in $walk.Repairs) { $notes.Add($repair.Fixed()) } + if ($reader.Duplicates) { $notes.AddRange($walk.KeyNotes($true)) } + return [pscustomobject]@{ Documents = [LdoJsonText]::Values($found); Notes = $notes.ToArray(); Text = $repaired } + } + + # What is wrong with the text as JSON, in order: errors where it is not JSON (most of which + # repairing fixes), and warnings where it is, but a reader may lose or refuse part of it. + static [LdoJsonNote[]] Check([string]$text) { + $notes = [System.Collections.Generic.List[LdoJsonNote]]::new() + if ([LdoJsonText]::HasBom($text)) { + $notes.Add([LdoJsonNote]::new(1, 1, 'warning', 'byte-order-mark', "a byte order mark: Python's json and Go's encoding/json refuse it")) + $text = $text.Substring(1) + } + if ($text.Trim().Length -eq 0) { + $notes.Add([LdoJsonNote]::new(1, 1, 'error', 'not-json', 'no JSON at all: the text is empty')) + return $notes.ToArray() + } + $walk = [LdoJsonWalk]::new($text) + foreach ($repair in $walk.Repairs) { $notes.Add($repair.Problem()) } + $notes.AddRange([LdoJsonText]::DecodeProblems($walk)) + $notes.AddRange($walk.KeyNotes($false)) + # A stable sort, by line and then column, as Python's sorted is. + $key = [System.Func[LdoJsonNote, long]] { param($note) [long]$note.Line * 4294967296 + $note.Column } + return [System.Linq.Enumerable]::ToArray([System.Linq.Enumerable]::OrderBy($notes, $key)) + } + + # Where the text is still not JSON once repaired: what repairing cannot fix. + static [LdoJsonNote[]] DecodeProblems([LdoJsonWalk]$walk) { + try { + [void][LdoJsonReader]::new($walk.Text()).Documents($false) + } + catch [LdoJsonReadError] { + $at = $walk.Original([LdoJsonText]::Cause($_.Exception).Offset) + return @([LdoJsonNote]::new($at[0], $at[1], 'error', 'not-json', "not JSON: $([LdoJsonText]::Cause($_.Exception).Reason)")) + } + return @() + } + + static [LdoJsonError] NotJson([string]$message, [LdoJsonWalk]$walk) { + $refused = [LdoJsonError]::new($message) + $refused.Repairable = $walk.Rules() + $refused.Complete = $refused.Repairable.Count -gt 0 -and [LdoJsonText]::DecodeProblems($walk).Count -eq 0 + return $refused + } + + static [LdoJsonError] NonFiniteError([string]$text, [string]$word) { + $walk = [LdoJsonWalk]::new($text) + $where = '' + foreach ($repair in $walk.Repairs) { + if ($repair.Rule -ceq 'non-finite') { + $where = " at line $($repair.Line), column $($repair.Column)" + break + } + } + return [LdoJsonText]::NotJson("not JSON: $word$where, which JSON cannot hold", $walk) + } + + static [object[]] Values([System.Collections.Generic.List[object]]$found) { + $documents = [object[]]::new($found.Count) + for ($i = 0; $i -lt $found.Count; $i++) { $documents[$i] = $found[$i][0] } + return $documents + } + + # The value with every string that holds a JSON object or array replaced by what it holds, + # however deep; counter[0] counts them. + static [object] Expand([object]$value, [int[]]$counter) { + if ($value -is [System.Collections.IDictionary]) { + $result = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + foreach ($key in $value.Keys) { $result[[string]$key] = [LdoJsonText]::Expand($value[$key], $counter) } + return $result + } + if ($value -is [System.Collections.IList]) { + $items = [object[]]::new($value.Count) + for ($i = 0; $i -lt $value.Count; $i++) { $items[$i] = [LdoJsonText]::Expand($value[$i], $counter) } + return $items + } + if ($value -is [string]) { return [LdoJsonText]::ExpandString($value, $counter) } + return $value + } + + static [object] ExpandString([string]$text, [int[]]$counter) { + $stripped = $text.Trim() + if ($stripped.Length -lt 2) { return $text } + $ends = [string]$stripped[0] + [string]$stripped[$stripped.Length - 1] + if ($ends -cne '{}' -and $ends -cne '[]') { return $text } + $found = $null + try { + $found = [LdoJsonReader]::new($stripped).Documents($false) + } + catch { + return $text # an ARM expression such as [concat(...)], or any other text + } + if ($found.Count -ne 1) { return $text } + $counter[0]++ + return [LdoJsonText]::Expand($found[0][0], $counter) + } +} + +class LdoFieldPathError : System.ArgumentException { + # A field path that cannot be read: Character is where (from 1), or 0 when it is empty. + [int]$Character + + LdoFieldPathError([string]$message, [int]$character) : base($message) { + $this.Character = $character + } +} + +class LdoFieldPathMissing : System.Exception { + # Nothing at a path, and (Hint) what is there instead. + [string]$Hint + + LdoFieldPathMissing([string]$message, [string]$hint) : base($message) { + $this.Hint = $hint + } +} + +class LdoFieldStep { + # One step of a path: a Key, an item by Index, or (neither) every item. + [string]$Key + [object]$Index + [bool]$IsKey + + LdoFieldStep() {} +} + +class LdoFieldMatch { + # A value a path found, and the path that names it alone: alert.mitre[1].tactic for one + # item of alert.mitre[].tactic. + [string]$Path + [object]$Value + + LdoFieldMatch([string]$path, [object]$value) { + $this.Path = $path + $this.Value = $value + } +} + +class LdoFieldPath { + # Field paths: core.field_paths' parse, resolve and display. + static [string]$Syntax = 'write a path as alert.severity, items[0], items[-1] (the last), items[].name (every ' + + 'item), or ["key.with.dots"] for a key a plain name cannot spell; . is the whole document' + static [regex]$Part = [regex]::new(@' +\G(?: +(?\.)?(?[^.\[\]\s"']+) +|\[(?-?[0-9]+)\] +|\[(?)\] +|\["(?(?:[^"\\]|\\.)*)"\] +|\['(?(?:[^'\\]|\\.)*)'\] +) +'@, 'IgnorePatternWhitespace, Singleline') + static [regex]$PlainKey = [regex]::new('\A[^.\[\]\s"'']+\z') + static [int]$KeysShown = 20 + + static [LdoFieldStep[]] Parse([string]$path) { + if ([string]::Equals($path.Trim(), '.')) { return @() } + $steps = [System.Collections.Generic.List[LdoFieldStep]]::new() + $position = 0 + while ($position -lt $path.Length) { + $found = [LdoFieldPath]::Part.Match($path, $position) + if (-not $found.Success -or ($steps.Count -gt 0 -and $found.Groups['name'].Success -and -not $found.Groups['dot'].Success)) { + throw [LdoFieldPathError]::new("cannot read the field path '$path' at character $($position + 1): $([LdoFieldPath]::Syntax)", $position + 1) + } + $steps.Add([LdoFieldPath]::Step($found)) + $position += $found.Length + } + if ($steps.Count -eq 0) { throw [LdoFieldPathError]::new("the field path is empty: $([LdoFieldPath]::Syntax)", 0) } + return $steps.ToArray() + } + + static [LdoFieldStep] Step([System.Text.RegularExpressions.Match]$found) { + $step = [LdoFieldStep]::new() + if ($found.Groups['name'].Success) { + $step.Key = $found.Groups['name'].Value + $step.IsKey = $true + } + elseif ($found.Groups['index'].Success) { + $step.Index = [System.Numerics.BigInteger]::Parse($found.Groups['index'].Value, [System.Globalization.CultureInfo]::InvariantCulture) + } + elseif (-not $found.Groups['every'].Success) { + $quoted = if ($found.Groups['double'].Success) { $found.Groups['double'].Value } else { $found.Groups['single'].Value } + $step.Key = [regex]::Replace($quoted, '\\(.)', '$1', 'Singleline') + $step.IsKey = $true + } + return $step + } + + # Every value the steps reach, in order. Where [] fans out, an item without the rest of + # the path is passed over; LdoFieldPathMissing says when nothing at all is there, and what is. + static [LdoFieldMatch[]] Resolve([object]$data, [LdoFieldStep[]]$steps) { + $found = [System.Collections.Generic.List[LdoFieldMatch]]::new() + $found.Add([LdoFieldMatch]::new('', $data)) + for ($number = 0; $number -lt $steps.Count; $number++) { + $following = [System.Collections.Generic.List[LdoFieldMatch]]::new() + foreach ($current in $found) { $following.AddRange([LdoFieldPath]::Take($current, $steps[$number])) } + if ($following.Count -eq 0) { + $taken = $steps[0..$number] + throw [LdoFieldPathMissing]::new("nothing at $([LdoFieldPath]::Display($taken))", [LdoFieldPath]::WhatIsThere($found[0])) + } + $found = $following + } + $result = [LdoFieldMatch[]]::new($found.Count) + for ($i = 0; $i -lt $found.Count; $i++) { + $path = if ($found[$i].Path) { $found[$i].Path } else { '.' } + $result[$i] = [LdoFieldMatch]::new($path, $found[$i].Value) + } + return $result + } + + # The steps written as a path, the way Parse reads it. + static [string] Display([LdoFieldStep[]]$steps) { + $path = '' + foreach ($step in $steps) { + if ($step.IsKey) { $path = [LdoFieldPath]::KeyPath($path, $step.Key) } + elseif ($null -ne $step.Index) { $path = "$path[$($step.Index)]" } + else { $path = "$path[]" } + } + if ($path) { return $path } + return '.' + } + + static [LdoFieldMatch[]] Take([LdoFieldMatch]$current, [LdoFieldStep]$step) { + $value = $current.Value + if ($step.IsKey) { + if ($value -is [System.Collections.IDictionary] -and $value.Contains($step.Key)) { + return @([LdoFieldMatch]::new([LdoFieldPath]::KeyPath($current.Path, $step.Key), $value[$step.Key])) + } + return @() + } + if ($null -ne $step.Index) { + if ($value -is [System.Collections.IList]) { + $count = $value.Count + if (-$count -le $step.Index -and $step.Index -lt $count) { + $position = [int]$step.Index + if ($position -lt 0) { $position += $count } + return @([LdoFieldMatch]::new("$($current.Path)[$position]", $value[$position])) + } + } + return @() + } + $each = [System.Collections.Generic.List[LdoFieldMatch]]::new() + if ($value -is [System.Collections.IList]) { + for ($i = 0; $i -lt $value.Count; $i++) { $each.Add([LdoFieldMatch]::new("$($current.Path)[$i]", $value[$i])) } + } + elseif ($value -is [System.Collections.IDictionary]) { + foreach ($key in $value.Keys) { $each.Add([LdoFieldMatch]::new([LdoFieldPath]::KeyPath($current.Path, [string]$key), $value[$key])) } + } + return $each.ToArray() + } + + # The path followed by a key: alert.severity, or alert["odd.key"] for a key a plain name + # cannot spell. An empty path is the top of the document. + static [string] KeyPath([string]$path, [string]$key) { + if ([LdoFieldPath]::PlainKey.IsMatch($key)) { + if ($path) { return "$path.$key" } + return $key + } + $escaped = $key.Replace('\', '\\').Replace('"', '\"') + return $path + '["' + $escaped + '"]' + } + + static [string] WhatIsThere([LdoFieldMatch]$match) { + $where = if ($match.Path) { "$($match.Path) is" } else { 'the document is' } + $value = $match.Value + if ($value -is [System.Collections.IDictionary]) { + if ($value.Count -eq 0) { return "$where an empty object" } + $keys = [string[]]@($value.Keys) + $shown = [System.Collections.Generic.List[string]]::new() + for ($i = 0; $i -lt [Math]::Min($keys.Count, [LdoFieldPath]::KeysShown); $i++) { $shown.Add([LdoFieldPath]::KeyPath('', $keys[$i])) } + $more = '' + if ($keys.Count -gt [LdoFieldPath]::KeysShown) { $more = " and $($keys.Count - [LdoFieldPath]::KeysShown) more" } + return "$where an object with: $($shown -join ', ')$more" + } + if ($value -is [System.Collections.IList]) { + if ($value.Count -eq 0) { return "$where an empty list" } + return "$where a list of $($value.Count): [0] to [$($value.Count - 1)], or [] for each" + } + $kind = 'a string' + if ($null -eq $value) { $kind = 'null' } + elseif ($value -is [bool]) { $kind = 'true or false' } + elseif ([LdoJsonData]::IsNumber($value)) { $kind = 'a number' } + return "$where $kind, with no keys or items" + } +} + +class LdoJsonData { + # JSON values as PowerShell holds them: what kind each is, whether two are the same as JSON + # sees it, and other objects made into JSON's. + static [type[]]$Integers = @([int], [long], [System.Numerics.BigInteger], [short], [byte], [sbyte], [uint16], [uint32], [uint64]) + + static [bool] IsNumber([object]$value) { + if ($null -eq $value -or $value -is [bool]) { return $false } + return $value -is [double] -or $value -is [single] -or $value -is [decimal] -or [LdoJsonData]::IsInteger($value) + } + + static [bool] IsInteger([object]$value) { + foreach ($type in [LdoJsonData]::Integers) { if ($value -is $type) { return $true } } + return $false + } + + static [string] Kind([object]$value) { + if ($null -eq $value) { return 'null' } + if ($value -is [bool]) { return 'boolean' } + if ([LdoJsonData]::IsNumber($value)) { return 'number' } + if ($value -is [string]) { return 'string' } + if ($value -is [System.Collections.IDictionary]) { return 'object' } + if ($value -is [System.Collections.IList]) { return 'array' } + return 'other' + } + + # Whether two values are equal as JSON sees it: numbers by value, true never 1, objects + # whatever their key order, strings exactly. + static [bool] Same([object]$left, [object]$right) { + $kind = [LdoJsonData]::Kind($left) + if ($kind -cne [LdoJsonData]::Kind($right)) { return $false } + switch -CaseSensitive ($kind) { + 'null' { return $true } + 'boolean' { return $left -eq $right } + 'number' { return [LdoJsonData]::SameNumber($left, $right) } + 'string' { return [string]::Equals([string]$left, [string]$right) } # ordinal: -ceq ignores control characters + 'object' { + if ($left.Count -ne $right.Count) { return $false } + foreach ($key in $left.Keys) { + if (-not $right.Contains($key) -or -not [LdoJsonData]::Same($left[$key], $right[$key])) { return $false } + } + return $true + } + 'array' { + if ($left.Count -ne $right.Count) { return $false } + for ($i = 0; $i -lt $left.Count; $i++) { + if (-not [LdoJsonData]::Same($left[$i], $right[$i])) { return $false } + } + return $true + } + } + return [object]::Equals($left, $right) + } + + # Numbers compared exactly, as Python compares an int and a float: 1 and 1.0 are the same, + # and a big integer is not the same as the float nearest it. + static [bool] SameNumber([object]$left, [object]$right) { + $leftWhole = [LdoJsonData]::Whole($left) + $rightWhole = [LdoJsonData]::Whole($right) + if ($null -ne $leftWhole -and $null -ne $rightWhole) { return $leftWhole -eq $rightWhole } + if ($null -ne $leftWhole -or $null -ne $rightWhole) { return $false } + return [double]$left -eq [double]$right + } + + # A number as a BigInteger when it is a whole one (1.0 is), or null. + static [object] Whole([object]$value) { + if ([LdoJsonData]::IsInteger($value)) { return [System.Numerics.BigInteger]$value } + $real = [double]$value + if ([double]::IsNaN($real) -or [double]::IsInfinity($real) -or [Math]::Floor($real) -ne $real) { return $null } + return [System.Numerics.BigInteger]::new($real) + } + + # Any object as JSON's: dictionaries and PSCustomObjects as ordered, case-sensitive + # dictionaries, lists as arrays, all the way down. + static [object] Convert([object]$value) { + if ($null -eq $value) { return $null } + if ($value -is [string] -or $value -is [bool] -or [LdoJsonData]::IsNumber($value)) { return $value } + if ($value -is [System.Collections.IDictionary]) { + $result = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + foreach ($key in $value.Keys) { $result[[string]$key] = [LdoJsonData]::Convert($value[$key]) } + return $result + } + if ($value -is [System.Management.Automation.PSCustomObject]) { + $result = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + foreach ($property in $value.PSObject.Properties) { $result[$property.Name] = [LdoJsonData]::Convert($property.Value) } + return $result + } + if ($value -is [System.Collections.IEnumerable]) { + $items = [System.Collections.Generic.List[object]]::new() + foreach ($item in $value) { $items.Add([LdoJsonData]::Convert($item)) } + return $items.ToArray() + } + return $value + } +} + +class LdoJsonChange { + # One thing a document changed: Kind is added (Before is null), changed, or removed (After + # is null). Document counts from 1, the base. + [string]$Path + [string]$Kind + [object]$Before + [object]$After + [int]$Document + + LdoJsonChange([string]$path, [string]$kind, [object]$before, [object]$after, [int]$document) { + $this.Path = $path + $this.Kind = $kind + $this.Before = $before + $this.After = $after + $this.Document = $document + } +} + +class LdoJsonMergeError : System.ArgumentException { + # Merging that cannot be done. Reason names which: nothing-to-merge, lists-with-patch, + # bad-lists or strict, when Unknown lists the keys a later document added (or deleted) + # that the document so far had not got. + [string]$Reason + [LdoJsonChange[]]$Unknown = @() + + LdoJsonMergeError([string]$reason, [string]$message) : base($message) { + $this.Reason = $reason + } +} + +class LdoJsonMerger { + # Merging documents left to right, deeply or as a merge patch (RFC 7396): core.json_merge. + static [string[]]$ListModes = @('replace', 'append', 'unique', 'by-key') + + [string]$ListMode = 'replace' + [string]$ListKey + [int]$Document = 1 + [System.Collections.Generic.List[LdoJsonChange]]$Changes = [System.Collections.Generic.List[LdoJsonChange]]::new() + [System.Collections.Generic.List[LdoJsonChange]]$Unknown = [System.Collections.Generic.List[LdoJsonChange]]::new() + + # replace, append, unique or by-key=FIELD, as typed, into the mode and its key. + static [string[]] ParseLists([string]$text) { + $equals = $text.IndexOf([char]'=') + $mode = if ($equals -ge 0) { $text.Substring(0, $equals) } else { $text } + $key = if ($equals -ge 0) { $text.Substring($equals + 1) } else { '' } + # Compared ordinally: PowerShell's -ceq and -ccontains ignore control characters. + if ([string]::Equals($mode, 'by-key') -and $key -cmatch '\A[^\s.\[\]"''=]+\z') { return @('by-key', $key) } + if ([Array]::IndexOf([LdoJsonMerger]::ListModes, $mode) -ge 0 -and -not [string]::Equals($mode, 'by-key') -and $equals -lt 0) { return @($mode, '') } + throw [LdoJsonMergeError]::new('bad-lists', "cannot merge lists by '$text': use replace, append, unique, or by-key=FIELD (such as by-key=name)") + } + + # The documents merged; Changes holds what each document after the base changed. + [object] Merge([object[]]$documents, [bool]$patch, [bool]$strict) { + if ($documents.Count -eq 0) { throw [LdoJsonMergeError]::new('nothing-to-merge', 'there is nothing to merge') } + if ($patch -and $this.ListMode -cne 'replace') { + throw [LdoJsonMergeError]::new('lists-with-patch', "a merge patch always replaces lists, so lists cannot be merged by $($this.ListMode)") + } + $result = $documents[0] + for ($number = 1; $number -lt $documents.Count; $number++) { + $this.Document = $number + 1 + if ($patch) { $result = $this.Patch($result, $documents[$number], '') } + else { $result = $this.Deep($result, $documents[$number], '') } + } + if ($strict -and $this.Unknown.Count -gt 0) { + $paths = foreach ($change in $this.Unknown) { "$($change.Path) (document $($change.Document))" } + $refused = [LdoJsonMergeError]::new('strict', "$($this.Unknown.Count) key(s) the documents before had not got: $($paths -join ', ')") + $refused.Unknown = $this.Unknown.ToArray() + throw $refused + } + return $result + } + + [object] Deep([object]$target, [object]$value, [string]$path) { + if ($target -is [System.Collections.IDictionary] -and $value -is [System.Collections.IDictionary]) { + $result = [LdoJsonMerger]::Copy($target) + foreach ($key in $value.Keys) { + $where = [LdoFieldPath]::KeyPath($path, [string]$key) + if ($result.Contains($key)) { + $result[$key] = $this.Deep($result[$key], $value[$key], $where) + } + else { + $this.Added($where, $value[$key]) + $result[$key] = $value[$key] + } + } + return $result + } + if ($target -is [System.Collections.IList] -and $value -is [System.Collections.IList] -and $this.ListMode -cne 'replace') { + return $this.Lists($target, $value, $path) + } + return $this.Replaced($target, $value, $path) + } + + [object] Patch([object]$target, [object]$value, [string]$path) { + if ($value -isnot [System.Collections.IDictionary]) { return $this.Replaced($target, $value, $path) } + if ($target -isnot [System.Collections.IDictionary]) { return $this.Replaced($target, [LdoJsonMerger]::WithoutNulls($value), $path) } + $result = [LdoJsonMerger]::Copy($target) + foreach ($key in $value.Keys) { + $where = [LdoFieldPath]::KeyPath($path, [string]$key) + $item = $value[$key] + if ($null -eq $item) { + if ($result.Contains($key)) { + $this.Record($where, 'removed', $result[$key], $null) + $result.Remove($key) + } + else { + $this.Unknown.Add([LdoJsonChange]::new($where, 'removed', $null, $null, $this.Document)) + } + } + elseif ($result.Contains($key)) { + $result[$key] = $this.Patch($result[$key], $item, $where) + } + else { + $result[$key] = [LdoJsonMerger]::WithoutNulls($item) + $this.Added($where, $result[$key]) + } + } + return $result + } + + [object] Lists([System.Collections.IList]$target, [System.Collections.IList]$value, [string]$path) { + if ($this.ListMode -ceq 'by-key') { return $this.ByKey($target, $value, $path) } + $result = [System.Collections.Generic.List[object]]::new() + foreach ($item in $target) { $result.Add($item) } + foreach ($item in $value) { + if ($this.ListMode -ceq 'append' -or -not [LdoJsonMerger]::Holds($result, $item)) { $result.Add($item) } + } + $merged = $result.ToArray() + if ($merged.Count -ne $target.Count) { $this.Record($path, 'changed', $target, $merged) } + return $merged + } + + [object] ByKey([System.Collections.IList]$target, [System.Collections.IList]$value, [string]$path) { + $result = [System.Collections.Generic.List[object]]::new() + foreach ($item in $target) { $result.Add($item) } + foreach ($item in $value) { + $position = $this.Match($result, $item) + if ($position -lt 0) { + $this.Record("$path[$($result.Count)]", 'added', $null, $item) + $result.Add($item) + } + else { + $result[$position] = $this.Deep($result[$position], $item, "$path[$position]") + } + } + return $result.ToArray() + } + + # Where an object with the same key field as the item is, or -1. + [int] Match([System.Collections.Generic.List[object]]$items, [object]$item) { + $key = $this.ListKey + if ($item -isnot [System.Collections.IDictionary] -or -not $item.Contains($key)) { return -1 } + for ($i = 0; $i -lt $items.Count; $i++) { + $existing = $items[$i] + if ($existing -is [System.Collections.IDictionary] -and $existing.Contains($key) -and [LdoJsonData]::Same($existing[$key], $item[$key])) { + return $i + } + } + return -1 + } + + [object] Replaced([object]$target, [object]$value, [string]$path) { + # An equal value (1.0 for 1) changes nothing, so the document keeps its own spelling. + if ([LdoJsonData]::Same($target, $value)) { return $target } + $this.Record($path, 'changed', $target, $value) + return $value + } + + [void] Added([string]$path, [object]$value) { + $this.Unknown.Add($this.Record($path, 'added', $null, $value)) + } + + [LdoJsonChange] Record([string]$path, [string]$kind, [object]$before, [object]$after) { + if (-not $path) { $path = '.' } + $change = [LdoJsonChange]::new($path, $kind, $before, $after, $this.Document) + $this.Changes.Add($change) + return $change + } + + static [bool] Holds([System.Collections.Generic.List[object]]$items, [object]$item) { + foreach ($kept in $items) { if ([LdoJsonData]::Same($item, $kept)) { return $true } } + return $false + } + + static [System.Collections.Specialized.OrderedDictionary] Copy([System.Collections.IDictionary]$value) { + $result = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + foreach ($key in $value.Keys) { $result[[string]$key] = $value[$key] } + return $result + } + + # What a merge patch makes of a value where there was nothing: an object loses its null + # members, however deep (RFC 7396 applies it to an empty object). + static [object] WithoutNulls([object]$value) { + if ($value -isnot [System.Collections.IDictionary]) { return $value } + $result = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + foreach ($key in $value.Keys) { + if ($null -ne $value[$key]) { $result[[string]$key] = [LdoJsonMerger]::WithoutNulls($value[$key]) } + } + return $result + } +} + +# Reading files and text --------------------------------------------------------------------- + +function Read-LdoJsonFile { + # Internal: a file's text, decoded as UTF-8 strictly, with any byte order mark kept. + [OutputType([string])] + param([Parameter(Mandatory)][string]$Path) + + if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "no such file: $Path" } + try { + $bytes = [System.IO.File]::ReadAllBytes((Resolve-Path -LiteralPath $Path).ProviderPath) + return [System.Text.UTF8Encoding]::new($false, $true).GetString($bytes) + } + catch { + throw "cannot read ${Path}: $($_.Exception.Message)" + } +} + +function Read-LdoJsonDocument { + # Internal: the documents in some text, repaired and expanded as asked, each repair and + # warning logged as "label:line:column: message". Errors say where, and what -Repair fixes. + [OutputType([object[]])] + param( + [Parameter(Mandatory)][AllowEmptyString()][string]$Text, + [Parameter(Mandatory)][string]$Label, + [switch]$Repair, + [switch]$Expand + ) + + try { + $parsed = [LdoJsonText]::Parse($Text, [bool]$Repair) + } + catch { + $cause = [LdoJsonText]::Cause($_.Exception) + if ($cause -isnot [LdoJsonError]) { throw } + throw (New-LdoJsonError -Exception $cause -Label $Label) + } + foreach ($note in $parsed.Notes) { + $level = if ($note.Severity -ceq 'fixed') { 'INFO' } else { 'WARN' } + Write-LdoLog -Level $level -Message "${Label}:$($note.Line):$($note.Column): $($note.Message)" + } + $documents = $parsed.Documents + if ($Expand) { + $counter = [int[]]@(0) + $documents = [LdoJsonText]::Expand($documents, $counter) + if ($counter[0] -gt 0) { Write-LdoLog -Level INFO -Message "${Label}: expanded $($counter[0]) string(s) holding JSON" } + } + return , [object[]]$documents +} + +function New-LdoJsonError { + # Internal: a not-JSON error as the caller sees it: where, and what -Repair would fix. + [OutputType([System.FormatException])] + param([Parameter(Mandatory)]$Exception, [Parameter(Mandatory)][string]$Label) + + $message = "${Label}: $($Exception.Message)" + if ($Exception.Repairable.Count -gt 0) { + $kinds = ($Exception.Repairable | ForEach-Object { [LdoJsonText]::Repairable[$_] }) -join ', ' + if ($Exception.Complete) { + $message += " (-Repair fixes $kinds, and notes each fix)" + } + else { + $message += " (-Repair fixes $kinds, but more than that is wrong: Test-LdoJson lists it all)" + } + } + $result = [LdoJsonError]::new($message) + $result.Repairable = $Exception.Repairable + $result.Complete = $Exception.Complete + $result.Empty = $Exception.Empty + return $result +} + +function Get-LdoJsonSource { + # Internal: what to read, as label and text: a file, or the content given. + [OutputType([pscustomobject])] + param([string]$Path, [string[]]$Content) + + if ($Path) { return [pscustomobject]@{ Label = $Path; Text = (Read-LdoJsonFile -Path $Path) } } + return [pscustomobject]@{ Label = 'content'; Text = ($Content -join "`n") } +} + +# Public ------------------------------------------------------------------------------------ + +function ConvertFrom-LdoJson { + <# + .SYNOPSIS + Reads JSON strictly, or repaired, into ordered, case-sensitive objects. + + .DESCRIPTION + Reads one JSON document, or several one after another (JSON Lines, or pretty-printed + documents back to back), and writes each to the pipeline as one object. Unlike + ConvertFrom-Json it keeps JSON as it is: objects are ordered dictionaries whose keys + are case-sensitive (so "a" and "A" are two keys, not an error), strings stay strings + (no dates), and numbers are [long], [System.Numerics.BigInteger] or [double], so a + big number keeps every digit. NaN and Infinity, which JSON cannot hold, are refused. + + Text that is nearly JSON is refused, saying where it broke and whether -Repair would + fix it. -Repair fixes what people paste and tools half-write: comments, trailing + commas, single-quoted strings, unquoted keys, Python's True, False and None, + JavaScript's undefined, NaN and Infinity (as null), and documents run together on + one line. Each fix is logged with its line and column, and so is a key given twice. + + The twin of the ldo CLI's ldo json show: both meet the same shared cases. + + .PARAMETER Path + A JSON or JSON Lines file. + + .PARAMETER Content + JSON text, or lines of it from the pipeline (Get-Content), which are joined. + + .PARAMETER Repair + Fix comments, trailing commas, single quotes, unquoted keys, True, False, None, + undefined, NaN, Infinity and documents run together first, logging each fix. + + .PARAMETER Expand + Unpack strings that hold a JSON object or array (a Logic App's definition, often) + into what they hold, however deep. + + .EXAMPLE + ConvertFrom-LdoJson -Path ./export.json -Expand + + .EXAMPLE + Get-Clipboard | ConvertFrom-LdoJson -Repair | ConvertTo-LdoYaml + + .OUTPUTS + System.Object + #> + [CmdletBinding(DefaultParameterSetName = 'Path')] + [OutputType([object])] + param( + [Parameter(Mandatory, ParameterSetName = 'Path', Position = 0)][ValidateNotNullOrEmpty()][string]$Path, + [Parameter(Mandatory, ParameterSetName = 'Content', ValueFromPipeline)][AllowEmptyString()][string[]]$Content, + [switch]$Repair, + [switch]$Expand + ) + + begin { $lines = [System.Collections.Generic.List[string]]::new() } + process { if ($PSCmdlet.ParameterSetName -eq 'Content') { $lines.AddRange($Content) } } + end { + $source = Get-LdoJsonSource -Path $Path -Content $lines + $documents = Read-LdoJsonDocument -Text $source.Text -Label $source.Label -Repair:$Repair -Expand:$Expand + foreach ($document in $documents) { $PSCmdlet.WriteObject($document, $false) } + } +} + +function Repair-LdoJson { + <# + .SYNOPSIS + Repairs text that is nearly JSON, and returns the JSON text. + + .DESCRIPTION + Fixes what people paste and tools half-write, keeping everything else as written + (spacing, order, numbers): comments are removed, trailing commas dropped, + single-quoted strings double-quoted, unquoted keys quoted, Python's True, False and + None and JavaScript's undefined written as JSON's, NaN and Infinity written as null, + and documents run together on one line put one to a line. Nothing inside a string is + touched. Each fix is logged with its line and column. + + Throws if the text is still not JSON once repaired, saying where. Test-LdoJson lists + every problem at once. + + .PARAMETER Path + A file of nearly JSON. + + .PARAMETER Content + Nearly JSON text, or lines of it from the pipeline, which are joined. + + .EXAMPLE + Repair-LdoJson -Path ./settings.jsonc | Set-Content ./settings.json + + .EXAMPLE + Get-Clipboard | Repair-LdoJson + + .OUTPUTS + System.String + #> + [CmdletBinding(DefaultParameterSetName = 'Path')] + [OutputType([string])] + param( + [Parameter(Mandatory, ParameterSetName = 'Path', Position = 0)][ValidateNotNullOrEmpty()][string]$Path, + [Parameter(Mandatory, ParameterSetName = 'Content', ValueFromPipeline)][AllowEmptyString()][string[]]$Content + ) + + begin { $lines = [System.Collections.Generic.List[string]]::new() } + process { if ($PSCmdlet.ParameterSetName -eq 'Content') { $lines.AddRange($Content) } } + end { + $source = Get-LdoJsonSource -Path $Path -Content $lines + try { + $parsed = [LdoJsonText]::Parse($source.Text, $true) + } + catch { + $cause = [LdoJsonText]::Cause($_.Exception) + if ($cause -isnot [LdoJsonError]) { throw } + throw (New-LdoJsonError -Exception $cause -Label $source.Label) + } + foreach ($note in $parsed.Notes) { + $level = if ($note.Severity -ceq 'fixed') { 'INFO' } else { 'WARN' } + Write-LdoLog -Level $level -Message "$($source.Label):$($note.Line):$($note.Column): $($note.Message)" + } + return $parsed.Text + } +} + +function Test-LdoJson { + <# + .SYNOPSIS + Checks JSON for what stops it being JSON, and what its readers lose or refuse. + + .DESCRIPTION + Lists each problem with its file, line and column. Errors: comments, trailing commas, + single quotes, unquoted keys, True, False, None and undefined, NaN and Infinity, + documents run together on one line (all of which -Repair fixes), and anything else + that is not JSON. Warnings: a key given twice (readers keep one, most often the last, + and say nothing), keys that differ only in case (ConvertFrom-Json refuses them), and + a byte order mark (Python's json and Go's encoding/json refuse it). + + The twin of the ldo CLI's ldo json check: both meet the same shared cases. + + .PARAMETER Path + JSON files, or folders (every .json file under each). + + .PARAMETER Content + JSON text to check. + + .PARAMETER Quiet + Return $true when there is no error (and, with -Strict, no warning), instead of the + problems. + + .PARAMETER Strict + With -Quiet, count warnings as failures too. + + .EXAMPLE + Test-LdoJson -Path ./exports | Format-Table + + .EXAMPLE + if (-not (Test-LdoJson -Path ./rule.json -Quiet -Strict)) { throw 'rule.json needs attention' } + + .OUTPUTS + System.Management.Automation.PSCustomObject, or System.Boolean with -Quiet + #> + [CmdletBinding(DefaultParameterSetName = 'Path')] + [OutputType([pscustomobject], [bool])] + param( + [Parameter(Mandatory, ParameterSetName = 'Path', Position = 0, ValueFromPipelineByPropertyName)] + [Alias('FullName')][ValidateNotNullOrEmpty()][string[]]$Path, + [Parameter(Mandatory, ParameterSetName = 'Content')][AllowEmptyString()][string]$Content, + [switch]$Quiet, + [switch]$Strict + ) + + begin { $found = [System.Collections.Generic.List[object]]::new() } + process { + $sources = if ($PSCmdlet.ParameterSetName -eq 'Content') { + [pscustomobject]@{ Label = 'content'; Text = $Content } + } + else { + foreach ($file in (Get-LdoJsonFileList -Path $Path)) { [pscustomobject]@{ Label = $file; Text = (Read-LdoJsonFile -Path $file) } } + } + foreach ($source in $sources) { + foreach ($note in [LdoJsonText]::Check($source.Text)) { + $found.Add([pscustomobject]@{ + File = $source.Label + Line = $note.Line + Column = $note.Column + Severity = $note.Severity + Rule = $note.Rule + Message = $note.Message + }) + } + } + } + end { + if (-not $Quiet) { return $found.ToArray() } + $failing = @($found | Where-Object { $_.Severity -ceq 'error' -or ($Strict -and $_.Severity -ceq 'warning') }) + return $failing.Count -eq 0 + } +} + +function Get-LdoJsonFileList { + # Internal: each path, with a folder standing for every .json file under it, sorted. + [OutputType([string[]])] + param([Parameter(Mandatory)][string[]]$Path) + + $files = foreach ($item in $Path) { + if (Test-Path -LiteralPath $item -PathType Container) { + $inside = @(Get-ChildItem -LiteralPath $item -Recurse -File -Filter '*.json' | Sort-Object FullName | ForEach-Object FullName) + if ($inside.Count -eq 0) { throw "no .json files under $item" } + $inside + } + else { + $item + } + } + return , [string[]]@($files) +} + +function Get-LdoJsonValue { + <# + .SYNOPSIS + Gets values out of JSON by path, ready to use or pipe on. + + .DESCRIPTION + Reads JSON (as ConvertFrom-LdoJson does) and returns what a path names in each + document: alert.severity, items[0], items[-1] (the last), items[].name (each item's), + ["key.with.dots"] for a key a plain name cannot spell, or . for all of it. A string + comes back as it is, so Get-LdoJsonValue rule.json query gives the query itself. + When nothing is there, the error says what is: the keys of the object, or the length + of the list. + + The twin of the ldo CLI's ldo json get: both read paths the same way, by the same + shared cases. + + .PARAMETER Path + A JSON file. + + .PARAMETER Content + JSON text. + + .PARAMETER InputObject + Objects already read (ConvertFrom-LdoJson's, ConvertFrom-Json's, or hashtables). + + .PARAMETER Field + The path to get, such as alert.mitre[].tactic. + + .PARAMETER Repair + Repair the JSON first, as ConvertFrom-LdoJson -Repair does. + + .PARAMETER Expand + Unpack strings holding JSON first, so the path can reach inside them. + + .PARAMETER Detailed + Return each value with the path that names it alone (alert.mitre[1].tactic), and its + file, instead of the values alone. + + .EXAMPLE + Get-LdoJsonValue -Path ./rule.json -Field query + + .EXAMPLE + Get-LdoJsonValue -Path ./export.json -Field 'properties.definition.actions' -Expand -Detailed + + .OUTPUTS + System.Object + #> + [CmdletBinding(DefaultParameterSetName = 'Path')] + [OutputType([object])] + param( + [Parameter(Mandatory, ParameterSetName = 'Path', Position = 0)][ValidateNotNullOrEmpty()][string]$Path, + [Parameter(Mandatory, ParameterSetName = 'Content')][AllowEmptyString()][string]$Content, + [Parameter(Mandatory, ParameterSetName = 'InputObject', ValueFromPipeline)][AllowNull()]$InputObject, + [Parameter(Mandatory, Position = 1)][ValidateNotNull()][string]$Field, + [switch]$Repair, + [switch]$Expand, + [switch]$Detailed + ) + + begin { + $steps = ConvertTo-LdoFieldStep -Field $Field + $documents = [System.Collections.Generic.List[object]]::new() + $label = $null + } + process { + if ($PSCmdlet.ParameterSetName -eq 'InputObject') { $documents.Add([LdoJsonData]::Convert($InputObject)) } + } + end { + if ($PSCmdlet.ParameterSetName -ne 'InputObject') { + $source = Get-LdoJsonSource -Path $Path -Content $Content + $label = $source.Label + $documents.AddRange([object[]](Read-LdoJsonDocument -Text $source.Text -Label $label -Repair:$Repair -Expand:$Expand)) + } + elseif ($Expand) { + $documents = [System.Collections.Generic.List[object]]::new([object[]][LdoJsonText]::Expand($documents.ToArray(), [int[]]@(0))) + } + foreach ($match in (Find-LdoJsonMatch -Document $documents.ToArray() -Step $steps)) { + if ($Detailed) { [pscustomobject]@{ File = $label; Path = $match.Path; Value = $match.Value } } + else { $PSCmdlet.WriteObject($match.Value, $false) } + } + } +} + +function ConvertTo-LdoFieldStep { + # Internal: a field path's steps, or an error saying where it cannot be read. + [OutputType([object[]])] + param([Parameter(Mandatory)][AllowEmptyString()][string]$Field) + + try { + return , [LdoFieldPath]::Parse($Field) + } + catch { + $cause = [LdoJsonText]::Cause($_.Exception) + if ($cause -isnot [LdoFieldPathError]) { throw } + throw [System.ArgumentException]::new($cause.Message, 'Field') + } +} + +function Find-LdoJsonMatch { + # Internal: what the steps reach in each document. Nothing in one of several documents is + # passed over; nothing in any is an error, saying what is there. + [OutputType([object[]])] + param([Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Document, [Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Step) + + $found = [System.Collections.Generic.List[object]]::new() + $missing = $null + foreach ($item in $Document) { + try { + $found.AddRange([LdoFieldPath]::Resolve($item, [LdoFieldStep[]]$Step)) + } + catch { + $cause = [LdoJsonText]::Cause($_.Exception) + if ($cause -isnot [LdoFieldPathMissing]) { throw } + if ($null -eq $missing) { $missing = $cause } + } + } + if ($found.Count -eq 0 -and $null -ne $missing) { + throw [System.Collections.Generic.KeyNotFoundException]::new("$($missing.Message): $($missing.Hint)") + } + return , $found.ToArray() +} + +function Merge-LdoJson { + <# + .SYNOPSIS + Merges JSON documents into one: a base, and each document after it laid over it. + + .DESCRIPTION + A deep merge by default: an object laid over an object merges key by key, all the + way down, and anything else the later document has wins, a list whole unless -Lists + says otherwise; null sets null. With -Patch it is a merge patch (RFC 7396), the + PATCH body of Azure's REST guidelines and kubectl patch --type merge: null deletes a + key, and a list is always replaced. Either way keys are case-sensitive, the base's + keys keep their order and new ones follow, and a value laid over an equal one (1.0 + over 1) is no change. + + -Strict refuses a key a later document adds that nothing before it had, or deletes + when it is not there: a misspelt key otherwise adds itself, and the change it meant + never happens. -Changes returns what each document added, changed and removed + instead of the result. + + The twin of the ldo CLI's ldo json merge: both meet the same shared cases. + + .PARAMETER Path + JSON files in the order they apply: the first is the base. A file holding several + documents gives each in turn. + + .PARAMETER InputObject + Documents already read, in order: ConvertFrom-LdoJson's, ConvertFrom-Json's, or + hashtables. Piped, each object is a document; given as a parameter + (-InputObject $base, $prod), each item of the list is. + + .PARAMETER Patch + Merge as a merge patch (RFC 7396): null deletes a key, and lists are replaced. + + .PARAMETER Lists + What a list laid over a list does in a deep merge: replace (the default), append, + unique (append only what is not already there), or by-key=FIELD (merge items whose + FIELD matches, such as by-key=name, and add the rest). + + .PARAMETER Strict + Refuse a key a later document adds, or deletes, that nothing before it had. + + .PARAMETER Changes + Return each change (Path, Change, From, To, Document, File) instead of the result. + + .PARAMETER Repair + Repair each file first, as ConvertFrom-LdoJson -Repair does. + + .PARAMETER Expand + Unpack strings holding JSON in each document first. + + .EXAMPLE + Merge-LdoJson -Path ./rule.json, ./prod.json -Strict | ConvertTo-Json -Depth 100 + + .EXAMPLE + Merge-LdoJson -Path ./base.json, ./prod.json -Lists by-key=name -Changes | Format-Table + + .OUTPUTS + System.Object + #> + [CmdletBinding(DefaultParameterSetName = 'Path')] + [OutputType([object], [object[]], [pscustomobject])] + param( + [Parameter(Mandatory, ParameterSetName = 'Path', Position = 0)][ValidateNotNullOrEmpty()][string[]]$Path, + [Parameter(Mandatory, ParameterSetName = 'InputObject', ValueFromPipeline)][AllowNull()][AllowEmptyCollection()]$InputObject, + [switch]$Patch, + [ValidateNotNullOrEmpty()][string]$Lists = 'replace', + [switch]$Strict, + [switch]$Changes, + [switch]$Repair, + [switch]$Expand + ) + + begin { + $documents = [System.Collections.Generic.List[object]]::new() + $labels = [System.Collections.Generic.List[string]]::new() + } + process { + if ($PSCmdlet.ParameterSetName -ne 'InputObject') { return } + # Piped, each object is a document; given as a parameter, a list is the documents. Set + # in each branch: an if used as a value would unroll a document that is a list. + if (-not $MyInvocation.ExpectingInput -and $InputObject -is [array]) { $given = $InputObject } + else { $given = @(, $InputObject) } + foreach ($document in $given) { + $documents.Add([LdoJsonData]::Convert($document)) + $labels.Add("document $($documents.Count)") + } + } + end { + if ($PSCmdlet.ParameterSetName -eq 'Path') { Add-LdoJsonMergeFile -Path $Path -Document $documents -Label $labels -Repair:$Repair -Expand:$Expand } + elseif ($Expand) { $documents = [System.Collections.Generic.List[object]]::new([object[]][LdoJsonText]::Expand($documents.ToArray(), [int[]]@(0))) } + $merger = [LdoJsonMerger]::new() + try { + $mode = [LdoJsonMerger]::ParseLists($Lists) + $merger.ListMode = $mode[0] + $merger.ListKey = $mode[1] + $merged = $merger.Merge($documents.ToArray(), [bool]$Patch, [bool]$Strict) + } + catch { + $cause = [LdoJsonText]::Cause($_.Exception) + if ($cause -isnot [LdoJsonMergeError]) { throw } + throw (New-LdoJsonMergeError -Exception $cause -Label $labels.ToArray()) + } + if (-not $Changes) { return , $merged } + foreach ($change in $merger.Changes) { + [pscustomobject]@{ + Path = $change.Path + Change = $change.Kind + From = $change.Before + To = $change.After + Document = $change.Document + File = $labels[$change.Document - 1] + } + } + } +} + +function Add-LdoJsonMergeFile { + # Internal: every document in each file, in order, and what to call each: its file, and + # which document of that file when it holds several. + [OutputType([void])] + param( + [Parameter(Mandatory)][string[]]$Path, + [Parameter(Mandatory)][AllowEmptyCollection()][System.Collections.Generic.List[object]]$Document, + [Parameter(Mandatory)][AllowEmptyCollection()][System.Collections.Generic.List[string]]$Label, + [switch]$Repair, + [switch]$Expand + ) + + foreach ($file in $Path) { + if (Test-Path -LiteralPath $file -PathType Container) { + throw "$file is a folder: Merge-LdoJson takes files, in the order they apply" + } + $found = Read-LdoJsonDocument -Text (Read-LdoJsonFile -Path $file) -Label $file -Repair:$Repair -Expand:$Expand + for ($i = 0; $i -lt $found.Count; $i++) { + $Document.Add($found[$i]) + $Label.Add($(if ($found.Count -eq 1) { $file } else { "$file (document $($i + 1))" })) + } + } +} + +function New-LdoJsonMergeError { + # Internal: a merge refused, as the caller sees it: a strict refusal names each key with + # its file. + [OutputType([System.ArgumentException])] + param([Parameter(Mandatory)]$Exception, [Parameter(Mandatory)][AllowEmptyCollection()][string[]]$Label) + + if ($Exception.Reason -cne 'strict') { return $Exception } + $lines = foreach ($change in $Exception.Unknown) { + $where = $Label[$change.Document - 1] + if ($change.Kind -ceq 'removed') { "${where}: deletes $($change.Path), which is not there" } + else { "${where}: adds $($change.Path), which nothing before had" } + } + $message = "$($Exception.Unknown.Count) key(s) the documents before had not got: $($lines -join '; '). Check each for spelling, or leave out -Strict to let them in" + $result = [LdoJsonMergeError]::new('strict', $message) + $result.Unknown = $Exception.Unknown + return $result +} diff --git a/LibreDevOpsHelpers/LibreDevOpsHelpers.Yaml/LibreDevOpsHelpers.Yaml.psm1 b/LibreDevOpsHelpers/LibreDevOpsHelpers.Yaml/LibreDevOpsHelpers.Yaml.psm1 index e585708..39b3f98 100644 --- a/LibreDevOpsHelpers/LibreDevOpsHelpers.Yaml/LibreDevOpsHelpers.Yaml.psm1 +++ b/LibreDevOpsHelpers/LibreDevOpsHelpers.Yaml/LibreDevOpsHelpers.Yaml.psm1 @@ -58,103 +58,242 @@ function ConvertFrom-LdoYaml { return ConvertFrom-Yaml -Yaml $raw } -function Test-LdoYamlPlainScalar { - # Internal: whether a string can be emitted unquoted in YAML without changing meaning. - param([string]$Value) - - if ($null -eq $Value -or $Value.Length -eq 0) { return $false } - if ($Value -ne $Value.Trim()) { return $false } - if ($Value -match '[\x00-\x1f]') { return $false } - # Reserved words and things a YAML parser would retype. - if ($Value -match '^(?i)(true|false|null|~|yes|no|on|off)$') { return $false } - if ($Value -match '^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$') { return $false } - # Leading characters and substrings with YAML syntax meaning. - if ($Value -match '^[\-?:,\[\]{}#&*!|>''"%@` ]') { return $false } - if ($Value -match '(:\s)|(:$)|(\s#)') { return $false } - return $true -} +class LdoYamlWriter { + # JSON-shaped data as YAML: the twin of the ldo CLI's core.yaml_text (libre-devops/ldo-cli), + # by the shared cases in tests/shared/yaml.json. A string is left plain only when no YAML + # reader could take it for anything else: yes, no, null, 1.0, 12:30, 2026-09-24 and a: b are + # all quoted, as JSON strings, which YAML 1.1 readers (PyYAML, Ansible) and YAML 1.2 readers + # (yq, Terraform) both read back as written. A multi-line string is a literal block whose + # chomping keeps its ending exactly: |- for none, | for one line break, |+ for more. + + # Plain only when it starts with a letter or underscore and holds nothing YAML reads + # specially; single spaces between words are fine. [\p{L}\p{N}_] is Python's \w. + static [regex]$Plain = [regex]::new('\A[A-Za-z_][\p{L}\p{N}_.\-/+@]*(?: [\p{L}\p{N}_.\-/+@]+)*\z') + # Words YAML 1.1 or 1.2 readers take for booleans or null, in any case. + static [string[]]$Words = @('true', 'false', 'yes', 'no', 'on', 'off', 'y', 'n', 'null', 'none', 'nan', 'inf') + # What a JSON string escapes: controls, the quote and the backslash. + static [regex]$JsonEscape = [regex]::new('[\x00-\x1f"\\]') + # What YAML will not take as it is inside a quoted string: C1 controls (U+0085 is a line + # break to YAML), the line and paragraph separators, non-characters, and a surrogate that is + # not half of a pair. + static [regex]$Unprintable = [regex]::new('[\x7f-\x9f\u2028\u2029\ufeff\ufffe\uffff]|[\ud800-\udbff](?![\udc00-\udfff])|(? @@ -185,16 +337,11 @@ function ConvertTo-LdoYaml { [OutputType([string])] param( [Parameter(Mandatory, ValueFromPipeline)][AllowNull()]$InputObject, - [int]$Depth = 32 + [int]$Depth = 32, + [ValidateRange(1, 8)][int]$Indent = 2 ) process { - $node = ConvertTo-LdoYamlNode -Value $InputObject -Level 0 -Depth $Depth - $text = switch ($node.Kind) { - 'inline' { $node.Text } - 'block' { (@('|') + $node.Lines) -join "`n" } - 'nested' { ($node.Lines -join "`n") } - } - return "$text`n" + return [LdoYamlWriter]::new($Indent, $Depth).Render($InputObject) } } diff --git a/LibreDevOpsHelpers/LibreDevOpsHelpers.psd1 b/LibreDevOpsHelpers/LibreDevOpsHelpers.psd1 index 3b213e2..6357a3e 100644 --- a/LibreDevOpsHelpers/LibreDevOpsHelpers.psd1 +++ b/LibreDevOpsHelpers/LibreDevOpsHelpers.psd1 @@ -86,6 +86,7 @@ 'LibreDevOpsHelpers.Github/LibreDevOpsHelpers.Github.psm1', 'LibreDevOpsHelpers.GitLab/LibreDevOpsHelpers.GitLab.psm1', 'LibreDevOpsHelpers.Graph/LibreDevOpsHelpers.Graph.psm1', + 'LibreDevOpsHelpers.Json/LibreDevOpsHelpers.Json.psm1', 'LibreDevOpsHelpers.Homebrew/LibreDevOpsHelpers.Homebrew.psm1', 'LibreDevOpsHelpers.Kql/LibreDevOpsHelpers.Kql.psm1', 'LibreDevOpsHelpers.Logger/LibreDevOpsHelpers.Logger.psm1', @@ -150,8 +151,10 @@ 'Convert-LdoTerraformPlanToJson', 'Invoke-LdoSplunkSearch', 'Send-LdoSplunkHecEvent', + 'Test-LdoJson', 'Test-LdoSplunkConnection', 'Test-LdoTerraformPlanChangesResource', + 'ConvertFrom-LdoJson', 'ConvertFrom-LdoLogicAppExport', 'ConvertFrom-LdoYaml', 'ConvertTo-LdoBoolean', @@ -185,6 +188,7 @@ 'Get-LdoGlabPipeline', 'Get-LdoGraphErrorDetail', 'Get-LdoGraphToken', + 'Get-LdoJsonValue', 'Get-LdoLogFormat', 'Get-LdoLogicAppConnection', 'Get-LdoLogicAppConnectionReference', @@ -252,6 +256,7 @@ 'Invoke-LdoUvRun', 'Invoke-LdoUvSync', 'Invoke-LdoWithRetry', + 'Merge-LdoJson', 'New-LdoCorrelationId', 'New-LdoGlabMergeRequest', 'New-LdoGlabRelease', @@ -266,6 +271,7 @@ 'Publish-LdoMachineConfigPackage', 'Push-LdoDockerImage', 'Register-LdoPesterAssertion', + 'Repair-LdoJson', 'Remove-LdoDetectionRuleId', 'Remove-LdoFunctionAppCurrentIpRule', 'Remove-LdoKeyVaultCurrentIpRule', diff --git a/README.md b/README.md index 833b058..848f4f2 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,37 @@ General purpose helpers shared across the toolkit. - `New-LdoPassword`, `New-LdoRandomSequence` - `ConvertTo-LdoBoolean`, `ConvertTo-LdoNull` +### Json +JSON read as people write it: keys kept in order and case-sensitive, every digit of a big number +kept, and strings never turned into dates. The twin of the ldo CLI's `ldo json` commands, and the +two agree exactly: both test suites run the same cases (`tests/shared`). +- `ConvertFrom-LdoJson` reads one document or several (JSON lines, or documents back to back) +- `Repair-LdoJson` fixes what is nearly JSON (comments, trailing commas, single quotes, unquoted + keys, Python's `True` and `None`, `NaN`) and returns the text, otherwise as written +- `Test-LdoJson` lists every problem in a file, or every `.json` under a folder, with its line and + column; `-Quiet` answers whether it passed +- `Get-LdoJsonValue` reads a field path such as `alert.mitre[].tactic` or `items[-1].name` +- `Merge-LdoJson` lays documents over each other: a deep merge by default, or an RFC 7396 merge + patch with `-Patch`; `-Lists` chooses how lists combine, and `-Strict` refuses a key nothing + before had (a typo in an overlay) + +`-Repair` (logging each fix with its line and column) and `-Expand` (JSON held in a string, such +as a Logic App definition) work on all of them. + +```powershell +# Each environment's settings, the base with its overlay laid over it. +Merge-LdoJson -Path ./base.json, ./prod.json -Lists by-key=name -Strict | ConvertTo-LdoYaml + +# What each overlay changed, and from what. +Merge-LdoJson -Path ./base.json, ./prod.json -Changes | Format-Table Path, Change, From, To, File +``` + +### Yaml +- `ConvertTo-LdoYaml` writes block-style YAML, quoting only what a YAML 1.1 or 1.2 reader could + read as something else (`yes`, `12:30`, `2026-09-24`, `0x1F`), and keeping a multi-line string's + ending exactly (`|-`, `|` or `|+`). It writes what `ldo json show --yaml` writes. +- `ConvertFrom-LdoYaml` reads YAML through yq, or the powershell-yaml module + ### Graph Resilient Microsoft Graph and Azure REST helpers. - `Invoke-LdoWithRetry`, `Invoke-LdoGraphRequest`, `Get-LdoGraphToken`, `Clear-LdoGraphTokenCache`, diff --git a/tests/Json.Tests.ps1 b/tests/Json.Tests.ps1 new file mode 100644 index 0000000..8bdb3cc --- /dev/null +++ b/tests/Json.Tests.ps1 @@ -0,0 +1,353 @@ +BeforeDiscovery { + Import-Module (Join-Path $PSScriptRoot '..' 'LibreDevOpsHelpers' 'LibreDevOpsHelpers.psd1') -Force + + # The shared cases (tests/shared, copied from ldo-cli's tests/fakes/shared): the contract + # this module and the ldo CLI both meet. Read with ConvertFrom-LdoJson, which keeps keys + # in order and case-sensitive, as the cases need. + function Get-SharedCase([string]$Name) { + $file = Join-Path $PSScriptRoot 'shared' "$Name.json" + foreach ($case in (ConvertFrom-LdoJson -Path $file).cases) { @{ Name = $case.name; Case = $case } } + } + $script:readCases = @(Get-SharedCase json | Where-Object { [string]::Equals($_.Case.kind, 'read') }) + $script:expandCases = @(Get-SharedCase json | Where-Object { [string]::Equals($_.Case.kind, 'expand') }) + $script:pathCases = @(Get-SharedCase paths) + $script:mergeCases = @(Get-SharedCase merge) +} + +BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..' 'LibreDevOpsHelpers' 'LibreDevOpsHelpers.psd1') -Force + + # A value as the cases compare it: key order kept, numbers by value, and true never 1. + function ConvertTo-Shape($Value) { + if ($null -eq $Value) { return 'null' } + if ($Value -is [bool]) { return "b:$Value" } + if ($Value -is [string]) { return 's:' + ($Value | ConvertTo-Json -Compress) } + if ($Value -is [System.Collections.IDictionary]) { + $parts = foreach ($key in $Value.Keys) { ($key | ConvertTo-Json -Compress) + '=' + (ConvertTo-Shape $Value[$key]) } + return '{' + ($parts -join ',') + '}' + } + if ($Value -is [System.Collections.IList]) { + $parts = foreach ($item in $Value) { ConvertTo-Shape $item } + return '[' + ($parts -join ',') + ']' + } + return 'n:' + ([double]$Value).ToString('R', [cultureinfo]::InvariantCulture) + } + + # Notes as the cases compare them: not-json ones by line alone, the rest in order. Each + # note is line:column:severity:rule. + function ConvertTo-NoteShape([string[]]$Notes) { + $Notes = @($Notes | Where-Object { $_ }) # no notes may arrive as one null + $lines = @($Notes | Where-Object { $_.EndsWith(':not-json') } | ForEach-Object { [int]$_.Split(':')[0] } | Sort-Object) + $others = @($Notes | Where-Object { -not $_.EndsWith(':not-json') }) + return "not-json lines: $($lines -join ',') | $($others -join ' ')" + } + + function ConvertTo-NoteText($Expected) { + return [string[]]@(foreach ($note in $Expected) { "$($note[0]):$($note[1]):$($note[2]):$($note[3])" }) + } + + # What reading the text gives, strictly or repaired, in the cases' terms. + function Get-ReadOutcome([string]$Text, [bool]$Repair) { + $json = (Get-Module LibreDevOpsHelpers).NestedModules | Where-Object Name -EQ 'LibreDevOpsHelpers.Json' + $result = & $json { + param($Text, $Repair) + try { + $parsed = [LdoJsonText]::Parse($Text, $Repair) + $notes = foreach ($note in $parsed.Notes) { "$($note.Line):$($note.Column):$($note.Severity):$($note.Rule)" } + [pscustomobject]@{ Documents = $parsed.Documents; Notes = [string[]]@($notes); Error = $null } + } + catch { + [pscustomobject]@{ Documents = $null; Notes = @(); Error = [LdoJsonText]::Cause($_.Exception) } + } + } $Text $Repair + if ($null -ne $result.Error) { + if ($result.Error.Empty) { return 'error: empty' } + return "error: repairable $($result.Error.Repairable -join ',') complete $($result.Error.Complete)" + } + return "documents: $(ConvertTo-Shape $result.Documents) notes: $(ConvertTo-NoteShape $result.Notes)" + } + + # The same, from what a case expects. + function Get-ExpectedOutcome($Expected) { + if ($Expected.Contains('error')) { + if ($Expected.error.Contains('empty')) { return 'error: empty' } + return "error: repairable $($Expected.error.repairable -join ',') complete $($Expected.error.complete)" + } + return "documents: $(ConvertTo-Shape $Expected.documents) notes: $(ConvertTo-NoteShape (ConvertTo-NoteText $Expected.notes))" + } + + function Invoke-InJsonModule([scriptblock]$Script, [object[]]$Arguments) { + $json = (Get-Module LibreDevOpsHelpers).NestedModules | Where-Object Name -EQ 'LibreDevOpsHelpers.Json' + return & $json $Script @Arguments + } +} + +Describe 'Json module surface' { + It 'exports <_>' -ForEach @('ConvertFrom-LdoJson', 'Repair-LdoJson', 'Test-LdoJson', 'Get-LdoJsonValue', 'Merge-LdoJson') { + Get-Command $_ -Module LibreDevOpsHelpers -ErrorAction SilentlyContinue | Should -Not -BeNullOrEmpty + } +} + +Describe 'Shared cases: reading, repairing and checking' { + It '' -ForEach $readCases { + Get-ReadOutcome -Text $Case.text -Repair $false | Should -BeExactly (Get-ExpectedOutcome $Case.strict) -Because 'reading strictly' + Get-ReadOutcome -Text $Case.text -Repair $true | Should -BeExactly (Get-ExpectedOutcome $Case.repaired) -Because 'reading repaired' + $checked = Invoke-InJsonModule { param($Text) foreach ($note in [LdoJsonText]::Check($Text)) { "$($note.Line):$($note.Column):$($note.Severity):$($note.Rule)" } } @($Case.text) + ConvertTo-NoteShape ([string[]]@($checked)) | Should -BeExactly (ConvertTo-NoteShape (ConvertTo-NoteText $Case.check)) -Because 'checking' + } +} + +Describe 'Shared cases: expanding' { + It '' -ForEach $expandCases { + $result = Invoke-InJsonModule { param($Value) $counter = [int[]]@(0); , @([LdoJsonText]::Expand($Value, $counter), $counter[0]) } @(, $Case.value) + ConvertTo-Shape $result[0] | Should -BeExactly (ConvertTo-Shape $Case.expanded) + $result[1] | Should -Be $Case.count + } +} + +Describe 'Shared cases: field paths' { + It '' -ForEach $pathCases { + if (-not $Case.Contains('error')) { + $found = Get-LdoJsonValue -InputObject $Case.document -Field $Case.path -Detailed + $matches = foreach ($match in $found) { [ordered]@{ path = $match.Path; value = $match.Value } } + ConvertTo-Shape @($matches) | Should -BeExactly (ConvertTo-Shape $Case.matches) + $display = Invoke-InJsonModule { param($Path) [LdoFieldPath]::Display([LdoFieldPath]::Parse($Path)) } @($Case.path) + $display | Should -BeExactly $Case.display + } + elseif ([string]::Equals($Case.error.kind, 'syntax')) { + $message = { Get-LdoJsonValue -InputObject $Case.document -Field $Case.path } | Should -Throw -PassThru + $at = [regex]::Match($message.Exception.Message, 'at character (\d+)') + $character = if ($at.Success) { [int]$at.Groups[1].Value } else { $null } + $character | Should -Be $Case.error.character + } + else { + $thrown = { Get-LdoJsonValue -InputObject $Case.document -Field $Case.path } | Should -Throw -PassThru + $thrown.Exception.Message | Should -BeExactly "$($Case.error.message): $($Case.error.hint)" + } + } +} + +Describe 'Shared cases: merging' { + It '' -ForEach $mergeCases { + $options = @{ Patch = [string]::Equals($Case.mode, 'patch'); Strict = [bool]($Case.Contains('strict') -and $Case.strict) } + if ($Case.Contains('lists')) { $options.Lists = $Case.lists } + if ($Case.Contains('error')) { + $thrown = { $Case.documents | Merge-LdoJson @options } | Should -Throw -PassThru + $thrown.Exception.Reason | Should -BeExactly $Case.error + if ([string]::Equals($Case.error, 'strict')) { + ($thrown.Exception.Unknown | ForEach-Object Path) -join ',' | Should -BeExactly ($Case.unknown -join ',') + } + return + } + $merged = $Case.documents | Merge-LdoJson @options + ConvertTo-Shape $merged | Should -BeExactly (ConvertTo-Shape $Case.result) + if ($Case.Contains('changes')) { + $changes = foreach ($change in ($Case.documents | Merge-LdoJson @options -Changes)) { + [ordered]@{ path = $change.Path; change = $change.Change; from = $change.From; to = $change.To; document = $change.Document } + } + ConvertTo-Shape @($changes) | Should -BeExactly (ConvertTo-Shape $Case.changes) + } + } +} + +Describe 'ConvertFrom-LdoJson' { + BeforeAll { + $folder = Join-Path $TestDrive 'read' + New-Item -ItemType Directory -Path $folder -Force | Out-Null + } + + It 'keeps keys that differ only in case, in order, and strings as strings' { + $document = ConvertFrom-LdoJson -Content '{"b": 1, "a": 2, "A": 3, "when": "2026-12-04T10:00:00Z"}' + @($document.Keys) | Should -Be @('b', 'a', 'A', 'when') + $document['A'] | Should -Be 3 + $document['when'] | Should -BeOfType [string] + } + + It 'keeps every digit of a big number' { + (ConvertFrom-LdoJson -Content '[12345678901234567890]')[0] | Should -BeOfType [System.Numerics.BigInteger] + } + + It 'writes each document as one object, a list included' { + $documents = @(ConvertFrom-LdoJson -Content "[1, 2]`n{`"a`": 1}") + $documents.Count | Should -Be 2 + $documents[0].Count | Should -Be 2 + } + + It 'joins lines piped in' { + $document = '{', ' "a": 1', '}' | ConvertFrom-LdoJson + $document['a'] | Should -Be 1 + } + + It 'refuses nearly JSON, saying where and that -Repair fixes it' { + { ConvertFrom-LdoJson -Content "{`n // note`n `"a`": 1`n}" } | + Should -Throw -ExpectedMessage 'content: not JSON: Expecting property name enclosed in double quotes at line 2, column 3 (-Repair fixes comments, and notes each fix)' + } + + It 'says when more is wrong than -Repair fixes' { + { ConvertFrom-LdoJson -Content '{"a": 1,,}' } | Should -Throw -ExpectedMessage '*but more than that is wrong: Test-LdoJson lists it all)' + } + + It 'repairs, logging each fix with its place' { + InModuleScope LibreDevOpsHelpers.Json { + Mock Write-LdoLog {} + $document = ConvertFrom-LdoJson -Content "{name: 'web01', on: True,}" -Repair + $document['name'] | Should -BeExactly 'web01' + $document['on'] | Should -BeTrue + Should -Invoke Write-LdoLog -ParameterFilter { $Level -eq 'INFO' -and $Message -ceq 'content:1:2: quoted the key name' } + Should -Invoke Write-LdoLog -ParameterFilter { $Message -ceq 'content:1:25: removed a trailing comma' } + } + } + + It 'warns of a key given twice' { + InModuleScope LibreDevOpsHelpers.Json { + Mock Write-LdoLog {} + ConvertFrom-LdoJson -Content '{"a": 1, "a": 2}' | Out-Null + Should -Invoke Write-LdoLog -ParameterFilter { $Level -eq 'WARN' -and $Message -like 'content:1:10: the key "a" again*' } + } + } + + It 'expands JSON held in a string' { + $document = ConvertFrom-LdoJson -Content '{"definition": "{\"actions\": {\"a\": 1}}"}' -Expand + $document['definition']['actions']['a'] | Should -Be 1 + } + + It 'reads a file, naming it in errors' { + $file = Join-Path $folder 'bad.json' + Set-Content -LiteralPath $file -Value '{"a": NaN}' -NoNewline + { ConvertFrom-LdoJson -Path $file } | Should -Throw -ExpectedMessage "${file}: not JSON: NaN at line 1, column 7, which JSON cannot hold (-Repair fixes NaN and Infinity, and notes each fix)" + { ConvertFrom-LdoJson -Path (Join-Path $folder 'none.json') } | Should -Throw -ExpectedMessage 'no such file:*' + } + + It 'refuses nothing at all' { + { ConvertFrom-LdoJson -Content ' ' } | Should -Throw -ExpectedMessage 'content: the input is empty' + } +} + +Describe 'Repair-LdoJson' { + It 'returns the text repaired, and otherwise as written' { + $text = "// exported`n{name: 'web01', ratio: NaN, tags: ['a',],}{`"next`": 1}" + Repair-LdoJson -Content $text | Should -BeExactly " `n{`"name`": `"web01`", `"ratio`": null, `"tags`": [`"a`"]}`n{`"next`": 1}" + } + + It 'refuses what repairing cannot fix, saying where' { + { Repair-LdoJson -Content '{"a": maybe}' } | Should -Throw -ExpectedMessage 'content: not JSON, even repaired: Expecting value at line 1, column 7' + } +} + +Describe 'Test-LdoJson' { + BeforeAll { + $folder = Join-Path $TestDrive 'check' + New-Item -ItemType Directory -Path (Join-Path $folder 'nested') -Force | Out-Null + Set-Content -LiteralPath (Join-Path $folder 'ok.json') -Value '{"a": 1}' -NoNewline + Set-Content -LiteralPath (Join-Path $folder 'nested' 'messy.json') -Value "{`n // note`n `"a`": 1, `"a`": 2`n}" -NoNewline + Set-Content -LiteralPath (Join-Path $folder 'notes.txt') -Value 'not json' -NoNewline + } + + It 'lists each problem under a folder with its file and place' { + $found = @(Test-LdoJson -Path $folder) + $found.Count | Should -Be 2 + $found[0].File | Should -BeLike '*messy.json' + "$($found[0].Line):$($found[0].Column) $($found[0].Severity) $($found[0].Rule)" | Should -BeExactly '2:3 error comment' + "$($found[1].Line):$($found[1].Column) $($found[1].Severity) $($found[1].Rule)" | Should -BeExactly '3:11 warning duplicate-key' + } + + It 'answers -Quiet with whether it passed, -Strict counting warnings' { + Test-LdoJson -Content '{"a": 1}' -Quiet | Should -BeTrue + Test-LdoJson -Content '{"a": 1,}' -Quiet | Should -BeFalse + Test-LdoJson -Content '{"a": 1, "A": 2}' -Quiet | Should -BeTrue + Test-LdoJson -Content '{"a": 1, "A": 2}' -Quiet -Strict | Should -BeFalse + } + + It 'sees a byte order mark' { + (Test-LdoJson -Content "$([char]0xFEFF){}").Rule | Should -BeExactly 'byte-order-mark' + } + + It 'refuses a folder with no JSON in it' { + $empty = Join-Path $TestDrive 'empty' + New-Item -ItemType Directory -Path $empty -Force | Out-Null + { Test-LdoJson -Path $empty } | Should -Throw -ExpectedMessage "no .json files under $empty" + } +} + +Describe 'Get-LdoJsonValue' { + BeforeAll { + $rule = Join-Path $TestDrive 'rule.json' + Set-Content -LiteralPath $rule -Value '{"query": "DeviceProcessEvents\n| take 1", "alert": {"mitre": [{"tactic": "Execution"}, {"tactic": "Persistence"}]}}' -NoNewline + } + + It 'gives text as it is' { + Get-LdoJsonValue -Path $rule -Field query | Should -BeExactly "DeviceProcessEvents`n| take 1" + } + + It 'gives each item''s value, with -Detailed its own path and file' { + Get-LdoJsonValue -Path $rule -Field 'alert.mitre[].tactic' | Should -Be @('Execution', 'Persistence') + $last = Get-LdoJsonValue -Path $rule -Field 'alert.mitre[-1]' -Detailed + $last.Path | Should -BeExactly 'alert.mitre[1]' + $last.File | Should -BeExactly $rule + } + + It 'says what is there when nothing is' { + { Get-LdoJsonValue -Path $rule -Field qurey } | Should -Throw -ExpectedMessage 'nothing at qurey: the document is an object with: query, alert' + } + + It 'refuses a path it cannot read, before reading anything' { + { Get-LdoJsonValue -Content 'not json' -Field 'a..b' } | Should -Throw -ExpectedMessage "cannot read the field path 'a..b' at character 2*" + } + + It 'reads objects already read, ConvertFrom-Json''s included' { + '{"a": {"b": [1, 2]}}' | ConvertFrom-Json | Get-LdoJsonValue -Field 'a.b[1]' | Should -Be 2 + } + + It 'reaches inside JSON held in a string with -Expand' { + Get-LdoJsonValue -Content '{"d": "{\"x\": 1}"}' -Field 'd.x' -Expand | Should -Be 1 + } +} + +Describe 'Merge-LdoJson' { + BeforeAll { + $base = Join-Path $TestDrive 'base.json' + $prod = Join-Path $TestDrive 'prod.json' + $typo = Join-Path $TestDrive 'typo.json' + Set-Content -LiteralPath $base -Value '{"rule": {"frequency": "PT1H", "severity": "medium"}, "actions": [{"name": "a", "v": 1}]}' -NoNewline + Set-Content -LiteralPath $prod -Value '{"rule": {"frequency": "PT0S"}, "actions": [{"name": "a", "v": 2}, {"name": "b", "v": 3}]}' -NoNewline + Set-Content -LiteralPath $typo -Value '{"rule": {"frequncy": "PT0S"}}' -NoNewline + } + + It 'lays each file over the last' { + $merged = Merge-LdoJson -Path $base, $prod + $merged['rule']['frequency'] | Should -BeExactly 'PT0S' + $merged['rule']['severity'] | Should -BeExactly 'medium' + $merged['actions'].Count | Should -Be 2 + } + + It 'merges lists by a key' { + $merged = Merge-LdoJson -Path $base, $prod -Lists by-key=name + ($merged['actions'] | ForEach-Object { "$($_['name'])=$($_['v'])" }) -join ',' | Should -BeExactly 'a=2,b=3' + } + + It 'refuses with -Strict a key nothing before had, naming its file' { + { Merge-LdoJson -Path $base, $prod, $typo -Strict } | + Should -Throw -ExpectedMessage "1 key(s) the documents before had not got: ${typo}: adds rule.frequncy, which nothing before had. Check each for spelling*" + } + + It 'lists what each file changed' { + $changes = @(Merge-LdoJson -Path $base, $prod -Changes) + $changes[0].Path | Should -BeExactly 'rule.frequency' + $changes[0].Change | Should -BeExactly 'changed' + $changes[0].File | Should -BeExactly $prod + } + + It 'takes a list of documents as a parameter, or documents piped' { + $merged = Merge-LdoJson -InputObject @{ a = 1 }, @{ b = 2 } + @($merged.Keys) | Should -Be @('a', 'b') + ([ordered]@{ a = 1 }, [ordered]@{ a = $null }) | Merge-LdoJson -Patch | ForEach-Object { $_.Count } | Should -Be 0 + } + + It 'refuses a folder' { + { Merge-LdoJson -Path $TestDrive } | Should -Throw -ExpectedMessage '*is a folder: Merge-LdoJson takes files, in the order they apply' + } + + It 'refuses a list mode it has not got' { + { Merge-LdoJson -Path $base, $prod -Lists sideways } | Should -Throw -ExpectedMessage "cannot merge lists by 'sideways'*" + } +} diff --git a/tests/README.md b/tests/README.md index ea3466f..abb8218 100644 --- a/tests/README.md +++ b/tests/README.md @@ -24,3 +24,12 @@ Invoke-Pester ./tests/Logger.Tests.ps1 CLIs. Mock those boundaries with `Mock`. - Import the module once in a `BeforeAll` block from the manifest so the prefixed command names resolve exactly as a consumer would see them. + +## Shared cases + +`tests/shared` holds cases the ldo CLI's tests run too, so the two agree exactly rather than +roughly: reading and repairing JSON (`json.json`), field paths (`paths.json`), merging +(`merge.json`) and writing YAML (`yaml.json`). They are copied from ldo-cli's +`tests/fakes/shared`, which is where they change; copy them here again after a change, and never +edit them only here. + diff --git a/tests/Yaml.Tests.ps1 b/tests/Yaml.Tests.ps1 index 6296549..4f7b5b4 100644 --- a/tests/Yaml.Tests.ps1 +++ b/tests/Yaml.Tests.ps1 @@ -1,5 +1,9 @@ BeforeDiscovery { Import-Module (Join-Path $PSScriptRoot '..' 'LibreDevOpsHelpers' 'LibreDevOpsHelpers.psd1') -Force + # The shared cases (tests/shared, copied from ldo-cli): the ldo CLI writes the same YAML. + $script:yamlCases = foreach ($case in (ConvertFrom-LdoJson -Path (Join-Path $PSScriptRoot 'shared' 'yaml.json')).cases) { + @{ Name = $case.name; Case = $case } + } $script:yamlReady = [bool](Get-Command yq -ErrorAction SilentlyContinue) -or [bool](Get-Module -ListAvailable powershell-yaml) } @@ -30,7 +34,8 @@ Describe 'ConvertTo-LdoYaml' { }) $text | Should -Match '(?m)^display_name: Simple rule$' - $text | Should -Match '(?m)^query: \|$' + # |-, not |: the query has no final line break, and | would read back with one. + $text | Should -Match '(?m)^query: \|-$' $text | Should -Match '(?m)^ \| project Timestamp, ReportId$' $text | Should -Match '(?m)^ - tactic: Execution$' # Key order is preserved: display_name before status before query. @@ -92,8 +97,40 @@ Describe 'ConvertTo-LdoYaml' { "$($parsed.display_name)" | Should -Be 'Round trip' "$($parsed.enabled_ish)" | Should -Be 'false' [int]$parsed.count | Should -Be 3 - "$($parsed.query)" | Should -Match '\| project Y' + "$($parsed.query)" | Should -BeExactly "A`n| where X == 1`n| project Y" @($parsed.nested.list).Count | Should -Be 2 "$($parsed.mappings[0].note)" | Should -Be 'a: b' } } + +Describe 'Shared cases: writing YAML' { + It '' -ForEach $yamlCases { + $written = ConvertFrom-LdoJson -Content $Case.json | ConvertTo-LdoYaml + # Ordinal: Should -BeExactly, like -ceq, takes control characters for nothing. + [string]::Equals($written, $Case.yaml) | Should -BeTrue -Because "it wrote:`n$written`nand the case wants:`n$($Case.yaml)" + } +} + +Describe 'ConvertTo-LdoYaml quoting' { + It 'quotes what YAML 1.1 readers would retype: <_>' -ForEach @('12:30', '2026-09-24', '0x1F', '.inf', 'yes', 'N', '@odata.context') { + ConvertTo-LdoYaml -InputObject ([ordered]@{ v = $_ }) | Should -BeExactly "v: `"$_`"`n" + } + + It 'keeps a block''s ending exactly: ' -ForEach @( + @{ Name = 'none'; Text = "a`nb"; Header = '|-' } + @{ Name = 'one'; Text = "a`nb`n"; Header = '|' } + @{ Name = 'two'; Text = "a`nb`n`n"; Header = '|+' } + ) { + ConvertTo-LdoYaml -InputObject ([ordered]@{ q = $Text }) | Should -Match ('(?m)^q: ' + [regex]::Escape($Header) + '$') + } + + It 'writes floats as Python does, and dates as ISO 8601' { + ConvertTo-LdoYaml -InputObject ([ordered]@{ a = 1.0; b = 1e-7; c = 1e16; d = [double]::NaN }) | Should -BeExactly "a: 1.0`nb: 1.0e-07`nc: 1.0e+16`nd: .nan`n" + ConvertTo-LdoYaml -InputObject ([ordered]@{ at = [datetime]::new(2026, 12, 4, 10, 0, 0, [DateTimeKind]::Utc) }) | Should -BeExactly "at: `"2026-12-04T10:00:00.0000000Z`"`n" + } + + It 'indents as asked' { + ConvertTo-LdoYaml -InputObject ([ordered]@{ a = [ordered]@{ b = 1 } }) -Indent 4 | Should -BeExactly "a:`n b: 1`n" + } +} + diff --git a/tests/shared/json.json b/tests/shared/json.json new file mode 100644 index 0000000..178e94a --- /dev/null +++ b/tests/shared/json.json @@ -0,0 +1,1564 @@ +{ + "about": "Reading, repairing and checking JSON text: the Python package's core.json_text and the PowerShell module's ConvertFrom-LdoJson, Repair-LdoJson and Test-LdoJson. A read case gives text, and what reading it strictly gives, what reading it repaired gives, and what checking it finds. Each is documents (compared with key order kept and numbers by value) and notes, or an error: for strict reading, the rules repairing would fix (repairable) and whether that would be all (complete). A note is [line, column, severity, rule], counted from 1 in the text as given, a column in characters (code points); a not-json note's column is null, since readers (and Python versions) place it differently, so not-json notes are compared by line alone, and the other notes in order. An expand case gives a value, what expanding it gives, and how many strings it unpacked.", + "version": 1, + "cases": [ + { + "name": "clean", + "kind": "read", + "text": "{\"a\": 1, \"b\": [true, false, null], \"c\": \"x\", \"d\": {}, \"e\": []}", + "strict": { + "documents": [ + { + "a": 1, + "b": [ + true, + false, + null + ], + "c": "x", + "d": {}, + "e": [] + } + ], + "notes": [] + }, + "repaired": { + "documents": [ + { + "a": 1, + "b": [ + true, + false, + null + ], + "c": "x", + "d": {}, + "e": [] + } + ], + "notes": [] + }, + "check": [] + }, + { + "name": "json-lines", + "kind": "read", + "text": "{\"a\": 1}\n{\"a\": 2}\n", + "strict": { + "documents": [ + { + "a": 1 + }, + { + "a": 2 + } + ], + "notes": [] + }, + "repaired": { + "documents": [ + { + "a": 1 + }, + { + "a": 2 + } + ], + "notes": [] + }, + "check": [] + }, + { + "name": "pretty-documents-back-to-back", + "kind": "read", + "text": "{\n \"a\": 1\n}\n{\n \"a\": 2\n}\n", + "strict": { + "documents": [ + { + "a": 1 + }, + { + "a": 2 + } + ], + "notes": [] + }, + "repaired": { + "documents": [ + { + "a": 1 + }, + { + "a": 2 + } + ], + "notes": [] + }, + "check": [] + }, + { + "name": "scalars-as-documents", + "kind": "read", + "text": "1\n\"two\"\ntrue\nnull\n", + "strict": { + "documents": [ + 1, + "two", + true, + null + ], + "notes": [] + }, + "repaired": { + "documents": [ + 1, + "two", + true, + null + ], + "notes": [] + }, + "check": [] + }, + { + "name": "numbers", + "kind": "read", + "text": "[0, -1, 1.5, -0.25, 1e3, 2E-2, 12345678901234567890, 0.1]", + "strict": { + "documents": [ + [ + 0, + -1, + 1.5, + -0.25, + 1000.0, + 0.02, + 12345678901234567890, + 0.1 + ] + ], + "notes": [] + }, + "repaired": { + "documents": [ + [ + 0, + -1, + 1.5, + -0.25, + 1000.0, + 0.02, + 12345678901234567890, + 0.1 + ] + ], + "notes": [] + }, + "check": [] + }, + { + "name": "unicode-and-escapes", + "kind": "read", + "text": "{\"city\": \"Zürich\", \"e\": \"\\u00e9\", \"q\": \"say \\\"hi\\\"\", \"t\": \"a\\tb\", \"s\": \"\\/\"}", + "strict": { + "documents": [ + { + "city": "Zürich", + "e": "é", + "q": "say \"hi\"", + "t": "a\tb", + "s": "/" + } + ], + "notes": [] + }, + "repaired": { + "documents": [ + { + "city": "Zürich", + "e": "é", + "q": "say \"hi\"", + "t": "a\tb", + "s": "/" + } + ], + "notes": [] + }, + "check": [] + }, + { + "name": "comments", + "kind": "read", + "text": "{\n // a line comment\n \"a\": 1, /* a block */ \"b\": 2\n /* two\n lines */\n}", + "strict": { + "error": { + "repairable": [ + "comment" + ], + "complete": true + } + }, + "repaired": { + "documents": [ + { + "a": 1, + "b": 2 + } + ], + "notes": [ + [ + 2, + 3, + "fixed", + "comment" + ], + [ + 3, + 11, + "fixed", + "comment" + ], + [ + 4, + 3, + "fixed", + "comment" + ] + ] + }, + "check": [ + [ + 2, + 3, + "error", + "comment" + ], + [ + 3, + 11, + "error", + "comment" + ], + [ + 4, + 3, + "error", + "comment" + ] + ] + }, + { + "name": "a-comment-does-not-join-tokens", + "kind": "read", + "text": "[1/* x */2]", + "strict": { + "error": { + "repairable": [ + "comment" + ], + "complete": false + } + }, + "repaired": { + "error": { + "repairable": [], + "complete": false + } + }, + "check": [ + [ + 1, + 3, + "error", + "comment" + ], + [ + 1, + null, + "error", + "not-json" + ] + ] + }, + { + "name": "trailing-commas", + "kind": "read", + "text": "{\"a\": [1, 2,], \"b\": 3,}", + "strict": { + "error": { + "repairable": [ + "trailing-comma" + ], + "complete": true + } + }, + "repaired": { + "documents": [ + { + "a": [ + 1, + 2 + ], + "b": 3 + } + ], + "notes": [ + [ + 1, + 12, + "fixed", + "trailing-comma" + ], + [ + 1, + 22, + "fixed", + "trailing-comma" + ] + ] + }, + "check": [ + [ + 1, + 12, + "error", + "trailing-comma" + ], + [ + 1, + 22, + "error", + "trailing-comma" + ] + ] + }, + { + "name": "trailing-comma-before-a-comment", + "kind": "read", + "text": "[1, // last\n]", + "strict": { + "error": { + "repairable": [ + "trailing-comma", + "comment" + ], + "complete": true + } + }, + "repaired": { + "documents": [ + [ + 1 + ] + ], + "notes": [ + [ + 1, + 3, + "fixed", + "trailing-comma" + ], + [ + 1, + 5, + "fixed", + "comment" + ] + ] + }, + "check": [ + [ + 1, + 3, + "error", + "trailing-comma" + ], + [ + 1, + 5, + "error", + "comment" + ] + ] + }, + { + "name": "single-quotes", + "kind": "read", + "text": "{'a': 'it\\'s \"x\"', 'b': 'q\\qz', 'n': 'l\\nm'}", + "strict": { + "error": { + "repairable": [ + "single-quote" + ], + "complete": true + } + }, + "repaired": { + "documents": [ + { + "a": "it's \"x\"", + "b": "qqz", + "n": "l\nm" + } + ], + "notes": [ + [ + 1, + 2, + "fixed", + "single-quote" + ], + [ + 1, + 7, + "fixed", + "single-quote" + ], + [ + 1, + 20, + "fixed", + "single-quote" + ], + [ + 1, + 25, + "fixed", + "single-quote" + ], + [ + 1, + 33, + "fixed", + "single-quote" + ], + [ + 1, + 38, + "fixed", + "single-quote" + ] + ] + }, + "check": [ + [ + 1, + 2, + "error", + "single-quote" + ], + [ + 1, + 7, + "error", + "single-quote" + ], + [ + 1, + 20, + "error", + "single-quote" + ], + [ + 1, + 25, + "error", + "single-quote" + ], + [ + 1, + 33, + "error", + "single-quote" + ], + [ + 1, + 38, + "error", + "single-quote" + ] + ] + }, + { + "name": "bare-keys", + "kind": "read", + "text": "{name: 1, $id: 2, _x: 3, True: 4}", + "strict": { + "error": { + "repairable": [ + "bare-key" + ], + "complete": true + } + }, + "repaired": { + "documents": [ + { + "name": 1, + "$id": 2, + "_x": 3, + "True": 4 + } + ], + "notes": [ + [ + 1, + 2, + "fixed", + "bare-key" + ], + [ + 1, + 11, + "fixed", + "bare-key" + ], + [ + 1, + 19, + "fixed", + "bare-key" + ], + [ + 1, + 26, + "fixed", + "bare-key" + ] + ] + }, + "check": [ + [ + 1, + 2, + "error", + "bare-key" + ], + [ + 1, + 11, + "error", + "bare-key" + ], + [ + 1, + 19, + "error", + "bare-key" + ], + [ + 1, + 26, + "error", + "bare-key" + ] + ] + }, + { + "name": "literals", + "kind": "read", + "text": "[True, False, None, undefined]", + "strict": { + "error": { + "repairable": [ + "literal" + ], + "complete": true + } + }, + "repaired": { + "documents": [ + [ + true, + false, + null, + null + ] + ], + "notes": [ + [ + 1, + 2, + "fixed", + "literal" + ], + [ + 1, + 8, + "fixed", + "literal" + ], + [ + 1, + 15, + "fixed", + "literal" + ], + [ + 1, + 21, + "fixed", + "literal" + ] + ] + }, + "check": [ + [ + 1, + 2, + "error", + "literal" + ], + [ + 1, + 8, + "error", + "literal" + ], + [ + 1, + 15, + "error", + "literal" + ], + [ + 1, + 21, + "error", + "literal" + ] + ] + }, + { + "name": "non-finite", + "kind": "read", + "text": "[NaN, Infinity, -Infinity, 1]", + "strict": { + "error": { + "repairable": [ + "non-finite" + ], + "complete": true + } + }, + "repaired": { + "documents": [ + [ + null, + null, + null, + 1 + ] + ], + "notes": [ + [ + 1, + 2, + "fixed", + "non-finite" + ], + [ + 1, + 7, + "fixed", + "non-finite" + ], + [ + 1, + 17, + "fixed", + "non-finite" + ] + ] + }, + "check": [ + [ + 1, + 2, + "error", + "non-finite" + ], + [ + 1, + 7, + "error", + "non-finite" + ], + [ + 1, + 17, + "error", + "non-finite" + ] + ] + }, + { + "name": "run-together", + "kind": "read", + "text": "{\"a\":1}{\"b\":2} [3]", + "strict": { + "error": { + "repairable": [ + "run-together" + ], + "complete": true + } + }, + "repaired": { + "documents": [ + { + "a": 1 + }, + { + "b": 2 + }, + [ + 3 + ] + ], + "notes": [ + [ + 1, + 8, + "fixed", + "run-together" + ], + [ + 1, + 16, + "fixed", + "run-together" + ] + ] + }, + "check": [ + [ + 1, + 8, + "error", + "run-together" + ], + [ + 1, + 16, + "error", + "run-together" + ] + ] + }, + { + "name": "run-together-scalars", + "kind": "read", + "text": "1 2", + "strict": { + "error": { + "repairable": [ + "run-together" + ], + "complete": true + } + }, + "repaired": { + "documents": [ + 1, + 2 + ], + "notes": [ + [ + 1, + 3, + "fixed", + "run-together" + ] + ] + }, + "check": [ + [ + 1, + 3, + "error", + "run-together" + ] + ] + }, + { + "name": "strings-are-untouched", + "kind": "read", + "text": "{\"url\": \"https://x//y\", \"c\": \"/* no */\", \"t\": \"True\", \"n\": \"NaN, 'x'\"}", + "strict": { + "documents": [ + { + "url": "https://x//y", + "c": "/* no */", + "t": "True", + "n": "NaN, 'x'" + } + ], + "notes": [] + }, + "repaired": { + "documents": [ + { + "url": "https://x//y", + "c": "/* no */", + "t": "True", + "n": "NaN, 'x'" + } + ], + "notes": [] + }, + "check": [] + }, + { + "name": "duplicate-keys", + "kind": "read", + "text": "{\"a\": 1,\n \"b\": {\"c\": 1, \"c\": 2},\n \"a\": 3}", + "strict": { + "documents": [ + { + "a": 3, + "b": { + "c": 2 + } + } + ], + "notes": [ + [ + 2, + 16, + "warning", + "duplicate-key" + ], + [ + 3, + 2, + "warning", + "duplicate-key" + ] + ] + }, + "repaired": { + "documents": [ + { + "a": 3, + "b": { + "c": 2 + } + } + ], + "notes": [ + [ + 2, + 16, + "warning", + "duplicate-key" + ], + [ + 3, + 2, + "warning", + "duplicate-key" + ] + ] + }, + "check": [ + [ + 2, + 16, + "warning", + "duplicate-key" + ], + [ + 3, + 2, + "warning", + "duplicate-key" + ] + ] + }, + { + "name": "case-only-keys", + "kind": "read", + "text": "{\"name\": 1, \"Name\": 2, \"NAME\": 3}", + "strict": { + "documents": [ + { + "name": 1, + "Name": 2, + "NAME": 3 + } + ], + "notes": [] + }, + "repaired": { + "documents": [ + { + "name": 1, + "Name": 2, + "NAME": 3 + } + ], + "notes": [] + }, + "check": [ + [ + 1, + 13, + "warning", + "case-only-key" + ], + [ + 1, + 24, + "warning", + "case-only-key" + ] + ] + }, + { + "name": "a-duplicate-and-a-case-only-key", + "kind": "read", + "text": "{\"a\": 1, \"A\": 2, \"a\": 3}", + "strict": { + "documents": [ + { + "a": 3, + "A": 2 + } + ], + "notes": [ + [ + 1, + 18, + "warning", + "duplicate-key" + ] + ] + }, + "repaired": { + "documents": [ + { + "a": 3, + "A": 2 + } + ], + "notes": [ + [ + 1, + 18, + "warning", + "duplicate-key" + ] + ] + }, + "check": [ + [ + 1, + 10, + "warning", + "case-only-key" + ], + [ + 1, + 18, + "warning", + "duplicate-key" + ] + ] + }, + { + "name": "keys-in-lists-of-objects-are-their-own", + "kind": "read", + "text": "[{\"a\": 1}, {\"a\": 2}]", + "strict": { + "documents": [ + [ + { + "a": 1 + }, + { + "a": 2 + } + ] + ], + "notes": [] + }, + "repaired": { + "documents": [ + [ + { + "a": 1 + }, + { + "a": 2 + } + ] + ], + "notes": [] + }, + "check": [] + }, + { + "name": "byte-order-mark", + "kind": "read", + "text": "{\"a\": 1}", + "strict": { + "documents": [ + { + "a": 1 + } + ], + "notes": [] + }, + "repaired": { + "documents": [ + { + "a": 1 + } + ], + "notes": [] + }, + "check": [ + [ + 1, + 1, + "warning", + "byte-order-mark" + ] + ] + }, + { + "name": "empty", + "kind": "read", + "text": " \n ", + "strict": { + "error": { + "empty": true + } + }, + "repaired": { + "error": { + "empty": true + } + }, + "check": [ + [ + 1, + null, + "error", + "not-json" + ] + ] + }, + { + "name": "two-commas", + "kind": "read", + "text": "{\"a\": 1,,}", + "strict": { + "error": { + "repairable": [ + "trailing-comma" + ], + "complete": false + } + }, + "repaired": { + "error": { + "repairable": [], + "complete": false + } + }, + "check": [ + [ + 1, + null, + "error", + "not-json" + ], + [ + 1, + 9, + "error", + "trailing-comma" + ] + ] + }, + { + "name": "a-word-that-is-not-a-value", + "kind": "read", + "text": "{\"a\": maybe}", + "strict": { + "error": { + "repairable": [], + "complete": false + } + }, + "repaired": { + "error": { + "repairable": [], + "complete": false + } + }, + "check": [ + [ + 1, + null, + "error", + "not-json" + ] + ] + }, + { + "name": "garbage-after", + "kind": "read", + "text": "{\"a\": 1}\nnot json\n", + "strict": { + "error": { + "repairable": [], + "complete": false + } + }, + "repaired": { + "error": { + "repairable": [], + "complete": false + } + }, + "check": [ + [ + 2, + null, + "error", + "not-json" + ] + ] + }, + { + "name": "unterminated-string", + "kind": "read", + "text": "{\"a\": \"b}", + "strict": { + "error": { + "repairable": [], + "complete": false + } + }, + "repaired": { + "error": { + "repairable": [], + "complete": false + } + }, + "check": [ + [ + 1, + null, + "error", + "not-json" + ] + ] + }, + { + "name": "missing-colon", + "kind": "read", + "text": "{\"a\" 1}", + "strict": { + "error": { + "repairable": [], + "complete": false + } + }, + "repaired": { + "error": { + "repairable": [], + "complete": false + } + }, + "check": [ + [ + 1, + null, + "error", + "not-json" + ] + ] + }, + { + "name": "missing-comma", + "kind": "read", + "text": "[1 2]", + "strict": { + "error": { + "repairable": [], + "complete": false + } + }, + "repaired": { + "error": { + "repairable": [], + "complete": false + } + }, + "check": [ + [ + 1, + null, + "error", + "not-json" + ] + ] + }, + { + "name": "unclosed", + "kind": "read", + "text": "{\"a\": [1, 2}", + "strict": { + "error": { + "repairable": [], + "complete": false + } + }, + "repaired": { + "error": { + "repairable": [], + "complete": false + } + }, + "check": [ + [ + 1, + null, + "error", + "not-json" + ] + ] + }, + { + "name": "everything-at-once", + "kind": "read", + "text": "// exported\n{\n name: 'web01', on: True, ratio: NaN,\n tags: ['a', 'b',],\n}\n{\"next\": 1}{\"x\": None}\n", + "strict": { + "error": { + "repairable": [ + "comment", + "bare-key", + "single-quote", + "literal", + "non-finite", + "trailing-comma", + "run-together" + ], + "complete": true + } + }, + "repaired": { + "documents": [ + { + "name": "web01", + "on": true, + "ratio": null, + "tags": [ + "a", + "b" + ] + }, + { + "next": 1 + }, + { + "x": null + } + ], + "notes": [ + [ + 1, + 1, + "fixed", + "comment" + ], + [ + 3, + 3, + "fixed", + "bare-key" + ], + [ + 3, + 9, + "fixed", + "single-quote" + ], + [ + 3, + 18, + "fixed", + "bare-key" + ], + [ + 3, + 22, + "fixed", + "literal" + ], + [ + 3, + 28, + "fixed", + "bare-key" + ], + [ + 3, + 35, + "fixed", + "non-finite" + ], + [ + 4, + 3, + "fixed", + "bare-key" + ], + [ + 4, + 10, + "fixed", + "single-quote" + ], + [ + 4, + 15, + "fixed", + "single-quote" + ], + [ + 4, + 18, + "fixed", + "trailing-comma" + ], + [ + 4, + 20, + "fixed", + "trailing-comma" + ], + [ + 6, + 12, + "fixed", + "run-together" + ], + [ + 6, + 18, + "fixed", + "literal" + ] + ] + }, + "check": [ + [ + 1, + 1, + "error", + "comment" + ], + [ + 3, + 3, + "error", + "bare-key" + ], + [ + 3, + 9, + "error", + "single-quote" + ], + [ + 3, + 18, + "error", + "bare-key" + ], + [ + 3, + 22, + "error", + "literal" + ], + [ + 3, + 28, + "error", + "bare-key" + ], + [ + 3, + 35, + "error", + "non-finite" + ], + [ + 4, + 3, + "error", + "bare-key" + ], + [ + 4, + 10, + "error", + "single-quote" + ], + [ + 4, + 15, + "error", + "single-quote" + ], + [ + 4, + 18, + "error", + "trailing-comma" + ], + [ + 4, + 20, + "error", + "trailing-comma" + ], + [ + 6, + 12, + "error", + "run-together" + ], + [ + 6, + 18, + "error", + "literal" + ] + ] + }, + { + "name": "expand-an-object-in-a-string", + "kind": "expand", + "value": { + "definition": "{\"a\": {\"b\": 1}}" + }, + "expanded": { + "definition": { + "a": { + "b": 1 + } + } + }, + "count": 1 + }, + { + "name": "expand-nested-twice", + "kind": "expand", + "value": { + "d": "{\"inner\": \"[1, 2]\"}" + }, + "expanded": { + "d": { + "inner": [ + 1, + 2 + ] + } + }, + "count": 2 + }, + { + "name": "expand-padded", + "kind": "expand", + "value": { + "d": " {\"a\": 1}\n" + }, + "expanded": { + "d": { + "a": 1 + } + }, + "count": 1 + }, + { + "name": "expand-an-arm-expression-is-left", + "kind": "expand", + "value": { + "e": "[concat('a', 'b')]", + "f": "[parameters('x')]" + }, + "expanded": { + "e": "[concat('a', 'b')]", + "f": "[parameters('x')]" + }, + "count": 0 + }, + { + "name": "expand-not-json-that-looks-like-it", + "kind": "expand", + "value": { + "e": "{not json}", + "f": "[1, 2", + "g": "{}", + "h": "[]" + }, + "expanded": { + "e": "{not json}", + "f": "[1, 2", + "g": {}, + "h": [] + }, + "count": 2 + }, + { + "name": "expand-scalars-are-left", + "kind": "expand", + "value": { + "n": "1", + "t": "true", + "s": "\"quoted\"", + "x": "NaN" + }, + "expanded": { + "n": "1", + "t": "true", + "s": "\"quoted\"", + "x": "NaN" + }, + "count": 0 + }, + { + "name": "expand-non-finite-inside-is-left", + "kind": "expand", + "value": { + "e": "[NaN]" + }, + "expanded": { + "e": "[NaN]" + }, + "count": 0 + }, + { + "name": "expand-in-a-list", + "kind": "expand", + "value": [ + "{\"a\": 1}", + "plain" + ], + "expanded": [ + { + "a": 1 + }, + "plain" + ], + "count": 1 + } + ] +} diff --git a/tests/shared/merge.json b/tests/shared/merge.json new file mode 100644 index 0000000..4813544 --- /dev/null +++ b/tests/shared/merge.json @@ -0,0 +1,140 @@ +{ + "about": "The cases JSON merging must meet. The Python package's core.json_merge and the PowerShell module's Merge-LdoJson each run every one, so the two merge alike (see shared_cases.py). Each case merges its documents left to right, deeply (mode deep) or as a merge patch (mode patch, RFC 7396), with lists (replace, append, unique or by-key=FIELD) and strict when given. It expects a result, compared with key order kept and numbers by value, or an error: strict (with the paths of the unknown keys, in order), nothing-to-merge, lists-with-patch or bad-lists. changes, when given, is every change, in order; document counts from 1, the base.", + "version": 1, + "cases": [ + {"name": "rfc7396-a01", "mode": "patch", "documents": [{"a": "b"}, {"a": "c"}], "result": {"a": "c"}}, + {"name": "rfc7396-a02", "mode": "patch", "documents": [{"a": "b"}, {"b": "c"}], "result": {"a": "b", "b": "c"}}, + {"name": "rfc7396-a03", "mode": "patch", "documents": [{"a": "b"}, {"a": null}], "result": {}}, + {"name": "rfc7396-a04", "mode": "patch", "documents": [{"a": "b", "b": "c"}, {"a": null}], "result": {"b": "c"}}, + {"name": "rfc7396-a05", "mode": "patch", "documents": [{"a": ["b"]}, {"a": "c"}], "result": {"a": "c"}}, + {"name": "rfc7396-a06", "mode": "patch", "documents": [{"a": "c"}, {"a": ["b"]}], "result": {"a": ["b"]}}, + {"name": "rfc7396-a07", "mode": "patch", "documents": [{"a": {"b": "c"}}, {"a": {"b": "d", "c": null}}], "result": {"a": {"b": "d"}}}, + {"name": "rfc7396-a08", "mode": "patch", "documents": [{"a": [{"b": "c"}]}, {"a": [1]}], "result": {"a": [1]}}, + {"name": "rfc7396-a09", "mode": "patch", "documents": [["a", "b"], ["c", "d"]], "result": ["c", "d"]}, + {"name": "rfc7396-a10", "mode": "patch", "documents": [{"a": "b"}, ["c"]], "result": ["c"]}, + {"name": "rfc7396-a11", "mode": "patch", "documents": [{"a": "foo"}, null], "result": null}, + {"name": "rfc7396-a12", "mode": "patch", "documents": [{"a": "foo"}, "bar"], "result": "bar"}, + {"name": "rfc7396-a13", "mode": "patch", "documents": [{"e": null}, {"a": 1}], "result": {"e": null, "a": 1}}, + {"name": "rfc7396-a14", "mode": "patch", "documents": [[1, 2], {"a": "b", "c": null}], "result": {"a": "b"}}, + {"name": "rfc7396-a15", "mode": "patch", "documents": [{}, {"a": {"bb": {"ccc": null}}}], "result": {"a": {"bb": {}}}}, + + { + "name": "patch-three-documents-and-their-changes", + "mode": "patch", + "documents": [{"a": 1, "b": 2}, {"b": null}, {"c": 3}], + "result": {"a": 1, "c": 3}, + "changes": [ + {"path": "b", "change": "removed", "from": 2, "to": null, "document": 2}, + {"path": "c", "change": "added", "from": null, "to": 3, "document": 3} + ] + }, + { + "name": "patch-a-non-object-replaces-the-document", + "mode": "patch", + "documents": [[1, 2], {"a": "b", "c": null}], + "result": {"a": "b"}, + "changes": [{"path": ".", "change": "changed", "from": [1, 2], "to": {"a": "b"}, "document": 2}] + }, + {"name": "patch-strict-refuses-a-new-key", "mode": "patch", "strict": true, "documents": [{"a": 1}, {"b": 2}], "error": "strict", "unknown": ["b"]}, + {"name": "patch-strict-refuses-deleting-what-is-not-there", "mode": "patch", "strict": true, "documents": [{"a": 1}, {"b": null}], "error": "strict", "unknown": ["b"]}, + {"name": "patch-strict-allows-known-keys", "mode": "patch", "strict": true, "documents": [{"a": {"b": 1}}, {"a": {"b": null}}], "result": {"a": {}}}, + {"name": "patch-refuses-a-list-mode", "mode": "patch", "lists": "append", "documents": [{"a": [1]}, {"a": [2]}], "error": "lists-with-patch"}, + + { + "name": "deep-objects-merge-key-by-key", + "mode": "deep", + "documents": [{"a": {"b": 1, "c": 2}}, {"a": {"c": 3, "d": 4}}], + "result": {"a": {"b": 1, "c": 3, "d": 4}}, + "changes": [ + {"path": "a.c", "change": "changed", "from": 2, "to": 3, "document": 2}, + {"path": "a.d", "change": "added", "from": null, "to": 4, "document": 2} + ] + }, + { + "name": "deep-null-sets-null", + "mode": "deep", + "documents": [{"a": 1, "b": 2}, {"a": null}], + "result": {"a": null, "b": 2}, + "changes": [{"path": "a", "change": "changed", "from": 1, "to": null, "document": 2}] + }, + {"name": "deep-lists-are-replaced-whole", "mode": "deep", "documents": [{"a": [1, 2]}, {"a": [3]}], "result": {"a": [3]}}, + {"name": "deep-a-value-of-another-type-replaces", "mode": "deep", "documents": [{"a": {"b": 1}}, {"a": "x"}], "result": {"a": "x"}}, + {"name": "deep-an-object-replaces-a-value", "mode": "deep", "documents": [{"a": "x"}, {"a": {"b": 1}}], "result": {"a": {"b": 1}}}, + {"name": "deep-keys-keep-their-order-and-new-ones-follow", "mode": "deep", "documents": [{"b": 1, "a": 2}, {"c": 3, "a": 4}], "result": {"b": 1, "a": 4, "c": 3}}, + {"name": "deep-keys-are-case-sensitive", "mode": "deep", "documents": [{"a": 1}, {"A": 2}], "result": {"a": 1, "A": 2}}, + {"name": "deep-numbers-are-equal-by-value", "mode": "deep", "documents": [{"a": 1}, {"a": 1.0}], "result": {"a": 1}, "changes": []}, + { + "name": "deep-true-is-not-one", + "mode": "deep", + "documents": [{"a": 1}, {"a": true}], + "result": {"a": true}, + "changes": [{"path": "a", "change": "changed", "from": 1, "to": true, "document": 2}] + }, + { + "name": "deep-three-documents-an-overlay-each", + "mode": "deep", + "documents": [ + {"rule": {"frequency": "PT1H", "severity": "medium"}}, + {"rule": {"frequency": "PT0S"}}, + {"rule": {"severity": "high"}} + ], + "result": {"rule": {"frequency": "PT0S", "severity": "high"}}, + "changes": [ + {"path": "rule.frequency", "change": "changed", "from": "PT1H", "to": "PT0S", "document": 2}, + {"path": "rule.severity", "change": "changed", "from": "medium", "to": "high", "document": 3} + ] + }, + { + "name": "deep-a-key-a-plain-name-cannot-spell", + "mode": "deep", + "documents": [{"x": 1}, {"@odata.context": "u"}], + "result": {"x": 1, "@odata.context": "u"}, + "changes": [{"path": "[\"@odata.context\"]", "change": "added", "from": null, "to": "u", "document": 2}] + }, + { + "name": "deep-a-scalar-document-replaces", + "mode": "deep", + "documents": [1, 2], + "result": 2, + "changes": [{"path": ".", "change": "changed", "from": 1, "to": 2, "document": 2}] + }, + {"name": "deep-one-document-is-itself", "mode": "deep", "documents": [{"a": 1}], "result": {"a": 1}, "changes": []}, + {"name": "deep-no-documents", "mode": "deep", "documents": [], "error": "nothing-to-merge"}, + {"name": "deep-strict-refuses-a-misspelt-key", "mode": "deep", "strict": true, "documents": [{"frequency": "PT1H"}, {"frequncy": "PT0S"}], "error": "strict", "unknown": ["frequncy"]}, + {"name": "deep-strict-names-only-the-new-key-not-what-is-under-it", "mode": "deep", "strict": true, "documents": [{"a": {}}, {"a": {"b": {"c": 1}}}], "error": "strict", "unknown": ["a.b"]}, + {"name": "deep-strict-allows-known-keys", "mode": "deep", "strict": true, "documents": [{"a": {"b": 1}}, {"a": {"b": 2}}], "result": {"a": {"b": 2}}}, + {"name": "deep-strict-allows-a-new-type-under-a-known-key", "mode": "deep", "strict": true, "documents": [{"a": [1]}, {"a": {"b": 1}}], "result": {"a": {"b": 1}}}, + + { + "name": "lists-append", + "mode": "deep", + "lists": "append", + "documents": [{"a": [1, 2]}, {"a": [2, 3]}], + "result": {"a": [1, 2, 2, 3]}, + "changes": [{"path": "a", "change": "changed", "from": [1, 2], "to": [1, 2, 2, 3], "document": 2}] + }, + {"name": "lists-unique-by-value", "mode": "deep", "lists": "unique", "documents": [{"a": [1, 2, {"x": 1}]}, {"a": [2, 3, {"x": 1.0}, 3]}], "result": {"a": [1, 2, {"x": 1}, 3]}}, + {"name": "lists-unique-adding-nothing-is-no-change", "mode": "deep", "lists": "unique", "documents": [{"a": ["x"]}, {"a": ["x"]}], "result": {"a": ["x"]}, "changes": []}, + { + "name": "lists-by-key-merges-matching-items-and-adds-the-rest", + "mode": "deep", + "lists": "by-key=name", + "documents": [ + {"actions": [{"name": "a", "v": 1}, {"name": "b", "v": 1}]}, + {"actions": [{"name": "b", "v": 2}, {"name": "c", "v": 3}, {"v": 4}]} + ], + "result": {"actions": [{"name": "a", "v": 1}, {"name": "b", "v": 2}, {"name": "c", "v": 3}, {"v": 4}]}, + "changes": [ + {"path": "actions[1].v", "change": "changed", "from": 1, "to": 2, "document": 2}, + {"path": "actions[2]", "change": "added", "from": null, "to": {"name": "c", "v": 3}, "document": 2}, + {"path": "actions[3]", "change": "added", "from": null, "to": {"v": 4}, "document": 2} + ] + }, + {"name": "lists-by-key-reaches-lists-inside-items", "mode": "deep", "lists": "by-key=id", "documents": [{"l": [{"id": 1, "m": [{"id": 9, "x": 1}]}]}, {"l": [{"id": 1, "m": [{"id": 9, "x": 2}]}]}], "result": {"l": [{"id": 1, "m": [{"id": 9, "x": 2}]}]}}, + {"name": "lists-by-key-strict-refuses-a-new-key-in-a-matched-item", "mode": "deep", "lists": "by-key=name", "strict": true, "documents": [{"l": [{"name": "a"}]}, {"l": [{"name": "a", "x": 1}]}], "error": "strict", "unknown": ["l[0].x"]}, + {"name": "lists-by-key-strict-allows-a-new-item", "mode": "deep", "lists": "by-key=name", "strict": true, "documents": [{"l": []}, {"l": [{"name": "z"}]}], "result": {"l": [{"name": "z"}]}}, + {"name": "lists-a-mode-that-does-not-exist", "mode": "deep", "lists": "sideways", "documents": [{}, {}], "error": "bad-lists"}, + {"name": "lists-by-key-without-a-field", "mode": "deep", "lists": "by-key", "documents": [{}, {}], "error": "bad-lists"}, + {"name": "lists-by-key-with-an-empty-field", "mode": "deep", "lists": "by-key=", "documents": [{}, {}], "error": "bad-lists"} + ] +} diff --git a/tests/shared/paths.json b/tests/shared/paths.json new file mode 100644 index 0000000..fd3ca75 --- /dev/null +++ b/tests/shared/paths.json @@ -0,0 +1,1201 @@ +{ + "about": "Field paths: the Python package's core.field_paths and the PowerShell module's Get-LdoJsonValue. Each case gives a document and a path, and the matches (each a path, written as display writes it, and a value), or an error: syntax (with the character it is at, from 1) or not-found (with its message and hint, which must match word for word).", + "version": 1, + "cases": [ + { + "name": "the-whole-document", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": ".", + "matches": [ + { + "path": ".", + "value": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + } + } + ], + "display": "." + }, + { + "name": "a-key", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "display_name", + "matches": [ + { + "path": "display_name", + "value": "Certutil download" + } + ], + "display": "display_name" + }, + { + "name": "a-key-with-a-leading-dot", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": ".display_name", + "matches": [ + { + "path": "display_name", + "value": "Certutil download" + } + ], + "display": "display_name" + }, + { + "name": "a-key-inside-a-key", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "alert.severity", + "matches": [ + { + "path": "alert.severity", + "value": "medium" + } + ], + "display": "alert.severity" + }, + { + "name": "an-item", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "alert.mitre[0]", + "matches": [ + { + "path": "alert.mitre[0]", + "value": { + "tactic": "CommandAndControl" + } + } + ], + "display": "alert.mitre[0]" + }, + { + "name": "the-last-item", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "alert.mitre[-1].tactic", + "matches": [ + { + "path": "alert.mitre[1].tactic", + "value": "Execution" + } + ], + "display": "alert.mitre[-1].tactic" + }, + { + "name": "each-item", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "alert.mitre[].tactic", + "matches": [ + { + "path": "alert.mitre[0].tactic", + "value": "CommandAndControl" + }, + { + "path": "alert.mitre[1].tactic", + "value": "Execution" + } + ], + "display": "alert.mitre[].tactic" + }, + { + "name": "each-item-misses-are-skipped", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "alert.mitre[].techniques[0]", + "matches": [ + { + "path": "alert.mitre[1].techniques[0]", + "value": "T1105" + } + ], + "display": "alert.mitre[].techniques[0]" + }, + { + "name": "each-value-of-an-object", + "document": { + "x": { + "a": 1, + "b": 2 + } + }, + "path": "x[]", + "matches": [ + { + "path": "x.a", + "value": 1 + }, + { + "path": "x.b", + "value": 2 + } + ], + "display": "x[]" + }, + { + "name": "a-double-quoted-key", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "[\"@odata.context\"]", + "matches": [ + { + "path": "[\"@odata.context\"]", + "value": "u" + } + ], + "display": "[\"@odata.context\"]" + }, + { + "name": "a-single-quoted-key", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "['display name']", + "matches": [ + { + "path": "[\"display name\"]", + "value": "spaced" + } + ], + "display": "[\"display name\"]" + }, + { + "name": "a-key-with-a-dot", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "[\"a.b\"]", + "matches": [ + { + "path": "[\"a.b\"]", + "value": "dotted" + } + ], + "display": "[\"a.b\"]" + }, + { + "name": "a-key-with-a-quote", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "[\"q\\\"k\"]", + "matches": [ + { + "path": "[\"q\\\"k\"]", + "value": "quoted key" + } + ], + "display": "[\"q\\\"k\"]" + }, + { + "name": "a-key-after-brackets", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "alert[\"mitre\"][1].techniques", + "matches": [ + { + "path": "alert.mitre[1].techniques", + "value": [ + "T1105" + ] + } + ], + "display": "alert.mitre[1].techniques" + }, + { + "name": "null-is-a-value", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "n", + "matches": [ + { + "path": "n", + "value": null + } + ], + "display": "n" + }, + { + "name": "an-empty-object", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "empty", + "matches": [ + { + "path": "empty", + "value": {} + } + ], + "display": "empty" + }, + { + "name": "a-list-at-the-top", + "document": [ + 10, + 20, + 30 + ], + "path": "[1]", + "matches": [ + { + "path": "[1]", + "value": 20 + } + ], + "display": "[1]" + }, + { + "name": "a-missing-key", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "qurey", + "error": { + "kind": "not-found", + "message": "nothing at qurey", + "hint": "the document is an object with: display_name, query, alert, [\"@odata.context\"], [\"display name\"], [\"a.b\"], [\"q\\\"k\"], empty, none, n" + } + }, + { + "name": "a-missing-key-deeper", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "alert.sev", + "error": { + "kind": "not-found", + "message": "nothing at alert.sev", + "hint": "alert is an object with: severity, mitre" + } + }, + { + "name": "past-the-end", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "alert.mitre[5]", + "error": { + "kind": "not-found", + "message": "nothing at alert.mitre[5]", + "hint": "alert.mitre is a list of 2: [0] to [1], or [] for each" + } + }, + { + "name": "before-the-start", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "alert.mitre[-3]", + "error": { + "kind": "not-found", + "message": "nothing at alert.mitre[-3]", + "hint": "alert.mitre is a list of 2: [0] to [1], or [] for each" + } + }, + { + "name": "into-a-string", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "query.text", + "error": { + "kind": "not-found", + "message": "nothing at query.text", + "hint": "query is a string, with no keys or items" + } + }, + { + "name": "into-null", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "n.x", + "error": { + "kind": "not-found", + "message": "nothing at n.x", + "hint": "n is null, with no keys or items" + } + }, + { + "name": "into-an-empty-object", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "empty.x", + "error": { + "kind": "not-found", + "message": "nothing at empty.x", + "hint": "empty is an empty object" + } + }, + { + "name": "into-an-empty-list", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "none[0]", + "error": { + "kind": "not-found", + "message": "nothing at none[0]", + "hint": "none is an empty list" + } + }, + { + "name": "a-key-of-a-list", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "alert.mitre.tactic", + "error": { + "kind": "not-found", + "message": "nothing at alert.mitre.tactic", + "hint": "alert.mitre is a list of 2: [0] to [1], or [] for each" + } + }, + { + "name": "an-index-of-an-object", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "alert[0]", + "error": { + "kind": "not-found", + "message": "nothing at alert[0]", + "hint": "alert is an object with: severity, mitre" + } + }, + { + "name": "many-keys-are-cut-short", + "document": { + "k00": 0, + "k01": 1, + "k02": 2, + "k03": 3, + "k04": 4, + "k05": 5, + "k06": 6, + "k07": 7, + "k08": 8, + "k09": 9, + "k10": 10, + "k11": 11, + "k12": 12, + "k13": 13, + "k14": 14, + "k15": 15, + "k16": 16, + "k17": 17, + "k18": 18, + "k19": 19, + "k20": 20, + "k21": 21, + "k22": 22, + "k23": 23, + "k24": 24 + }, + "path": "nope", + "error": { + "kind": "not-found", + "message": "nothing at nope", + "hint": "the document is an object with: k00, k01, k02, k03, k04, k05, k06, k07, k08, k09, k10, k11, k12, k13, k14, k15, k16, k17, k18, k19 and 5 more" + } + }, + { + "name": "each-of-nothing", + "document": { + "l": [] + }, + "path": "l[].x", + "error": { + "kind": "not-found", + "message": "nothing at l[]", + "hint": "l is an empty list" + } + }, + { + "name": "syntax-two-dots", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "a..b", + "error": { + "kind": "syntax", + "character": 2 + } + }, + { + "name": "syntax-no-dot-after-brackets", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "a[0]b", + "error": { + "kind": "syntax", + "character": 5 + } + }, + { + "name": "syntax-unclosed-bracket", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "a[0", + "error": { + "kind": "syntax", + "character": 2 + } + }, + { + "name": "syntax-a-space", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "a b", + "error": { + "kind": "syntax", + "character": 2 + } + }, + { + "name": "syntax-unquoted-in-brackets", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "a[b]", + "error": { + "kind": "syntax", + "character": 2 + } + }, + { + "name": "syntax-empty", + "document": { + "display_name": "Certutil download", + "query": "DeviceProcessEvents | take 1", + "alert": { + "severity": "medium", + "mitre": [ + { + "tactic": "CommandAndControl" + }, + { + "tactic": "Execution", + "techniques": [ + "T1105" + ] + } + ] + }, + "@odata.context": "u", + "display name": "spaced", + "a.b": "dotted", + "q\"k": "quoted key", + "empty": {}, + "none": [], + "n": null + }, + "path": "", + "error": { + "kind": "syntax", + "character": null + } + } + ] +} diff --git a/tests/shared/yaml.json b/tests/shared/yaml.json new file mode 100644 index 0000000..489b850 --- /dev/null +++ b/tests/shared/yaml.json @@ -0,0 +1,101 @@ +{ + "about": "Writing YAML: the Python package's core.yaml_text and the PowerShell module's ConvertTo-LdoYaml. Each case gives JSON text, which is read and written as YAML, and the YAML expected, character for character.", + "version": 1, + "cases": [ + { + "name": "plain-words", + "json": "{\"a\": \"web01\", \"b\": \"two words\", \"c\": \"a/b-c.d+e@f\", \"d\": \"_x\", \"e\": \"Zürich\"}", + "yaml": "a: web01\nb: two words\nc: a/b-c.d+e@f\nd: _x\ne: Zürich\n" + }, + { + "name": "words-yaml-would-retype", + "json": "[\"yes\", \"No\", \"ON\", \"off\", \"y\", \"N\", \"true\", \"False\", \"null\", \"None\", \"nan\", \"inf\", \"~\"]", + "yaml": "- \"yes\"\n- \"No\"\n- \"ON\"\n- \"off\"\n- \"y\"\n- \"N\"\n- \"true\"\n- \"False\"\n- \"null\"\n- \"None\"\n- \"nan\"\n- \"inf\"\n- \"~\"\n" + }, + { + "name": "numbers-as-text", + "json": "[\"1\", \"010\", \"1.0\", \"0x1F\", \"1e3\", \".inf\", \"-.inf\", \".nan\", \"1_000\", \"+1\", \"12:30\", \"2026-09-24\", \"2026-09-24T10:00:00Z\"]", + "yaml": "- \"1\"\n- \"010\"\n- \"1.0\"\n- \"0x1F\"\n- \"1e3\"\n- \".inf\"\n- \"-.inf\"\n- \".nan\"\n- \"1_000\"\n- \"+1\"\n- \"12:30\"\n- \"2026-09-24\"\n- \"2026-09-24T10:00:00Z\"\n" + }, + { + "name": "syntax-as-text", + "json": "[\"@odata.context\", \"a: b\", \"a:b\", \"#x\", \"x #y\", \"- x\", \"[a]\", \"{a}\", \"!tag\", \"&anchor\", \"*alias\", \"%x\", \"`x\", \"|\", \">\", \"'q'\", \"\\\"q\\\"\", \"a,b\", \"?x\"]", + "yaml": "- \"@odata.context\"\n- \"a: b\"\n- \"a:b\"\n- \"#x\"\n- \"x #y\"\n- \"- x\"\n- \"[a]\"\n- \"{a}\"\n- \"!tag\"\n- \"&anchor\"\n- \"*alias\"\n- \"%x\"\n- \"`x\"\n- \"|\"\n- \">\"\n- \"'q'\"\n- \"\\\"q\\\"\"\n- \"a,b\"\n- \"?x\"\n" + }, + { + "name": "spacing", + "json": "[\"\", \" lead\", \"trail \", \"two spaces\", \"tab\\there\"]", + "yaml": "- \"\"\n- \" lead\"\n- \"trail \"\n- \"two spaces\"\n- \"tab\\there\"\n" + }, + { + "name": "numbers", + "json": "[0, -1, 10, 12345678901234567890, 1.0, 1.5, -0.25, 0.1, 100.0, 1e-07, 1e16, 1e15, 2.5e-05, 1.5e300, 123456789.125]", + "yaml": "- 0\n- -1\n- 10\n- 12345678901234567890\n- 1.0\n- 1.5\n- -0.25\n- 0.1\n- 100.0\n- 1.0e-07\n- 1.0e+16\n- 1000000000000000.0\n- 2.5e-05\n- 1.5e+300\n- 123456789.125\n" + }, + { + "name": "booleans-and-null", + "json": "{\"t\": true, \"f\": false, \"n\": null}", + "yaml": "t: true\nf: false\n\"n\": null\n" + }, + { + "name": "empty-collections", + "json": "{\"o\": {}, \"l\": [], \"nested\": {\"o\": {}, \"l\": [[], {}]}}", + "yaml": "o: {}\nl: []\nnested:\n o: {}\n l:\n - []\n - {}\n" + }, + { + "name": "nesting", + "json": "{\"alert\": {\"severity\": \"low\", \"mitre\": [{\"tactic\": \"Execution\", \"techniques\": [\"T1204\", \"T1059\"]}]}, \"l\": [[1, 2], [3]]}", + "yaml": "alert:\n severity: low\n mitre:\n - tactic: Execution\n techniques:\n - T1204\n - T1059\nl:\n - - 1\n - 2\n - - 3\n" + }, + { + "name": "blocks-and-their-endings", + "json": "{\"none\": \"a\\nb\", \"one\": \"a\\nb\\n\", \"two\": \"a\\nb\\n\\n\", \"three\": \"a\\nb\\n\\n\\n\", \"blank-inside\": \"a\\n\\nb\"}", + "yaml": "\"none\": |-\n a\n b\none: |\n a\n b\ntwo: |+\n a\n b\n\nthree: |+\n a\n b\n\n\nblank-inside: |-\n a\n\n b\n" + }, + { + "name": "block-in-a-list", + "json": "[\"a\\nb\", {\"q\": \"x\\n| y\"}]", + "yaml": "- |-\n a\n b\n- q: |-\n x\n | y\n" + }, + { + "name": "not-blocks", + "json": "{\"lead\": \" a\\nb\", \"starts-blank\": \"\\na\", \"trail\": \"a \\nb\", \"tab-trail\": \"a\\t\\nb\", \"cr\": \"a\\r\\nb\", \"control\": \"a\\u0001\\nb\"}", + "yaml": "lead: \" a\\nb\"\nstarts-blank: \"\\na\"\ntrail: \"a \\nb\"\ntab-trail: \"a\\t\\nb\"\ncr: \"a\\r\\nb\"\ncontrol: \"a\\u0001\\nb\"\n" + }, + { + "name": "unprintable", + "json": "{\"c1\": \"a\\u0085b\", \"ls\": \"a\\u2028b\", \"del\": \"a\\u007fb\", \"bom\": \"\\ufeffx\", \"esc\": \"\\u001b[1m\"}", + "yaml": "c1: \"a\\u0085b\"\nls: \"a\\u2028b\"\ndel: \"a\\u007fb\"\nbom: \"\\ufeffx\"\nesc: \"\\u001b[1m\"\n" + }, + { + "name": "keys-are-quoted-the-same", + "json": "{\"yes\": 1, \"12:30\": 2, \"@odata.type\": 3, \"two words\": 4, \"\": 5}", + "yaml": "\"yes\": 1\n\"12:30\": 2\n\"@odata.type\": 3\ntwo words: 4\n\"\": 5\n" + }, + { + "name": "a-scalar-alone", + "json": "\"just text\"", + "yaml": "just text\n" + }, + { + "name": "a-block-alone", + "json": "\"a\\nb\\n\"", + "yaml": "|\n a\n b\n" + }, + { + "name": "a-number-alone", + "json": "1.0", + "yaml": "1.0\n" + }, + { + "name": "an-empty-list-alone", + "json": "[]", + "yaml": "[]\n" + }, + { + "name": "a-query", + "json": "{\"query\": \"DeviceRegistryEvents\\n| where RegistryKey has @\\\"Image File Execution Options\\\"\\n| project Timestamp, DeviceName\"}", + "yaml": "query: |-\n DeviceRegistryEvents\n | where RegistryKey has @\"Image File Execution Options\"\n | project Timestamp, DeviceName\n" + } + ] +}