dsh-native-uia 0.6.2 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,10 +10,9 @@ function Cmd-Ping($A) {
10
10
  try { $script:dpiMode = [Native]::MakeAware() } catch { }
11
11
  }
12
12
  # The station size comes from the ONE authoritative measurement (Get-VirtScreen: the virtual
13
- # screen with its measured fallback chain). Ping used to re-derive it from its own SM_CXSCREEN
14
- # read plus the WinForms primary-screen bounds, and also reported a dead "logical" pair no
15
- # consumer ever read — a second opinion that disagreed with the pointer channel's answer on
16
- # multi-monitor boxes, exactly the silent drift the "measure, never hardcode" rule exists for.
13
+ # screen with its measured fallback chain). A second derivation (SM_CXSCREEN plus WinForms
14
+ # primary-screen bounds) disagrees with the pointer channel on multi-monitor boxes — exactly the
15
+ # silent drift the "measure, never hardcode" rule exists for.
17
16
  # MakeAware has already run at startup (and above), so the metrics are physical.
18
17
  $v = Get-VirtScreen
19
18
  $w = [int]$v.w; $h = [int]$v.h
@@ -389,14 +388,13 @@ function Cmd-PrepareBatch($A) {
389
388
  }
390
389
  $actName = [string]$s.Item('action')
391
390
  # Validate the verb at prepare time. Prepare is the dry run: its whole job is to answer
392
- # "would this batch work?" before a single event reaches the desktop. It used to copy the
393
- # action through untouched, so "fly" resolved happily and only commit_batch refused it —
394
- # the model paid for two round-trips and a revision to learn a typo it could have heard
395
- # about immediately.
391
+ # "would this batch work?" before a single event reaches the desktop. Copying the action
392
+ # through untouched would let "fly" resolve here and be refused only by commit_batch — two
393
+ # round-trips and a revision for a typo prepare can name immediately.
396
394
  if ($actName -eq '') { Err 'missing_arg' ("step " + $i + " needs an action") }
397
395
  # PowerShell's switch is case-INSENSITIVE by default, but the values it compares come from
398
- # model-authored JSON and a "Invoke" used to sail through prepare while the case-sensitive
399
- # hashtable check later refused it. Normalise once here so prepare and commit agree.
396
+ # model-authored JSON and the hashtable check below is case-sensitive: without normalisation
397
+ # "Invoke" passes prepare and is refused at commit. Normalise once here so both agree.
400
398
  $actName = $actName.ToLowerInvariant()
401
399
  if (-not $script:W.actionNames.ContainsKey($actName)) {
402
400
  Err 'unknown_action' ("step " + $i + " action '" + $actName + "' is not one of " + (($script:W.actionNames.Keys | Sort-Object) -join '|'))
@@ -622,8 +620,8 @@ function Cmd-CommitBatch($A) {
622
620
  }
623
621
  }
624
622
  # Every step the batch never reached still gets a result entry, so the reply carries one line
625
- # per step. Previously the tail was invisible: the model only had performedCount and one stop
626
- # sentence, and could not tell which planned steps were skipped. not_executed means an earlier
623
+ # per step. Without it the model only has performedCount and one stop sentence, and cannot tell
624
+ # which planned steps were skipped. not_executed means an earlier
627
625
  # step failed or the run was cancelled; the fixed Chinese wording is rendered on the Node side
628
626
  # (this file is parsed as ANSI, so Chinese string literals here would corrupt the parser).
629
627
  if ($stoppedAt -ge 0) {
@@ -719,8 +717,8 @@ function Cmd-Wait($A) {
719
717
  }
720
718
 
721
719
  function Wait-Window($entry, $cond, $timeoutMs) {
722
- # Window-level waits. "did the dialog appear" was previously only expressible as a sleep plus a
723
- # list_windows round trip, which is exactly the guesswork computer_wait exists to remove.
720
+ # Window-level waits: "did the dialog appear" otherwise takes a sleep plus a list_windows round
721
+ # trip, which is exactly the guesswork computer_wait exists to remove.
724
722
  # window_appears — a top-level window matching titleContains/class/pid exists; returns its windowId
725
723
  # window_gone — the given windowId closed, or no window matches the criteria any more
726
724
  # window_title_contains — one known window's title now contains the text (retitle, save-as path)
@@ -1084,20 +1082,18 @@ function Cmd-FindText($A) {
1084
1082
  $matchedTotal = 0
1085
1083
  $truncated = $false
1086
1084
  foreach ($c in $all) {
1087
- # Same per-element guard as before, but a timeout no longer DISCARDS the command: every hit
1088
- # already collected is still true, so the partial list returns marked truncated (the old
1089
- # deadline_exceeded error threw away all of it — the model paid for a full scan and got
1090
- # nothing back).
1085
+ # Same per-element guard, but a timeout does not discard the command: every hit already
1086
+ # collected is still true, so the partial list returns marked truncated instead of a
1087
+ # deadline_exceeded error that throws away a full scan.
1091
1088
  if ($script:W.dl -ne [Int64]::MaxValue -and (TickNow) -gt $script:W.dl) { $truncated = $true; break }
1092
1089
  try { $cp = if ($usedCached) { $c.Cached } else { $c.Current } } catch { continue }
1093
1090
  $n = [string]$cp.Name
1094
1091
  $ctn = ''
1095
1092
  if ($n -eq '') {
1096
1093
  # A nameless Edit/Document/Text can still carry the text the caller is after (a label-less
1097
- # input box's content lives in its value, not its name). This used to read $cp.Value — a
1098
- # property AutomationElementInformation does not HAVE — so it silently returned '' forever
1099
- # and the documented value search never fired. Read the value from ValuePattern, for that
1100
- # narrow type set only, so the extra pattern call stays rare on container-heavy trees.
1094
+ # input box's content lives in its value, not its name). AutomationElementInformation has no
1095
+ # Value property, so read it from ValuePattern — for that narrow type set only, so the extra
1096
+ # pattern call stays rare on container-heavy trees.
1101
1097
  try { $ctn = ControlTypeName $cp.ControlType } catch { $ctn = '' }
1102
1098
  if ($ctn -eq 'Edit' -or $ctn -eq 'Document' -or $ctn -eq 'Text') {
1103
1099
  try {
@@ -1151,10 +1147,10 @@ function Cmd-FindText($A) {
1151
1147
  }
1152
1148
  if ([string]$node.automationId -ne '') { $byDesc['automationId'] = [string]$node.automationId }
1153
1149
  if ($nth -gt 1) { $byDesc['nth'] = $nth }
1154
- # Issue a ref for every hit. find_text used to return only coordinates and a by-descriptor, so
1155
- # computer_act (which takes a ref and nothing else) could not be driven from a search result —
1156
- # the model had to fall back to a physical computer_click, moving the real cursor for what
1157
- # should have been a background action. Refs cost one table entry each and make the two tools
1150
+ # Issue a ref for every hit. Coordinates plus a by-descriptor alone cannot drive computer_act
1151
+ # (which takes a ref and nothing else), so the model would fall back to a physical
1152
+ # computer_click and move the real cursor for what should be a background action. Refs cost one
1153
+ # table entry each and make the two tools
1158
1154
  # compose.
1159
1155
  $refRec = $null
1160
1156
  try { $refRec = New-Ref $entry $c $cp $node } catch { $refRec = $null }
@@ -1171,8 +1167,8 @@ function Cmd-FindText($A) {
1171
1167
  patterns = $node.patterns
1172
1168
  ref = $(if ($null -ne $refRec) { $refRec.ref } else { $null })
1173
1169
  center = @{ x = ($rc.x + [int]($rc.w / 2)); y = ($rc.y + [int]($rc.h / 2)) }
1174
- # nth is only meaningful once a duplicate exists; a unique hit keeps the old 1-field shape
1175
- # and nth=1 so recipes saved before this change still replay against the same element.
1170
+ # nth is only meaningful once a duplicate exists; a unique hit keeps nth=1 and a single
1171
+ # by-descriptor field, so existing recipes replay against the same element.
1176
1172
  nth = $nth
1177
1173
  by = $byDesc
1178
1174
  }
@@ -606,8 +606,8 @@ function Cmd-Key($A) {
606
606
  }
607
607
  $script:W.stats.actionsPerformed += 1
608
608
  # Field name is `combo`, not `keys`: a dictionary field literally named "keys" is shadowed by
609
- # PowerShell member lookup ($dict.Keys) and used to serialize as {}. JsonOf now uses an enumerator,
610
- # and the name stays clear of the collision anyway.
609
+ # PowerShell member lookup ($dict.Keys) and serialises as {}. JsonOf enumerates entries
610
+ # explicitly, and the name stays clear of the collision anyway.
611
611
  return [ordered]@{ combo = $combo; via = 'physical'; repeat = [int]$repeat; holdMs = [int]$holdMs; ms = [Math]::Round((MsFrom $st), 1) }
612
612
  }
613
613
 
@@ -1,173 +1,173 @@
1
- # ps-stdio.ps1 -- stdio JSON framing helpers shared verbatim by the two resident
2
- # PowerShell processes: uia-worker.ps1 (the UIA worker) and indicator-server.ps1
3
- # (the overlay indicator).
4
- #
5
- # Each host loads this file at the top of its framing/io section:
6
- # . (Join-Path $PSScriptRoot 'ps-stdio.ps1')
7
- # Dot-sourcing keeps the caller's scope, so the functions below run against the
8
- # host's script scope and the $script:escCache initialised below lands there.
9
- # (scripts/regression-worker.ps1 loads these functions by AST extraction instead,
10
- # which skips top-level assignments, so it initialises $script:escCache itself.)
11
- #
12
- # HOST-AGNOSTIC RULE: none of these functions may reference $script:W, $script:S
13
- # or any other host-owned variable. A dot-sourced function body resolves $script:
14
- # against whichever host loaded it, so one host-specific reference would silently
15
- # break in the other process.
16
- #
17
- # Send-Ok / Send-Err are deliberately NOT shared: the worker writes $script:W.stats,
18
- # the indicator writes $script:S.stats and decorates every result with exStyles and
19
- # the last palette. Those shapes are per-host contracts, so they stay in their hosts.
20
- #
21
- # SAVED AS UTF-8 WITH BOM, CONTENT ASCII-ONLY: Windows PowerShell 5.1 decodes a
22
- # BOM-less .ps1 with the system codepage, so an unlabelled file is one editor save
23
- # away from mojibake. ASCII-only source cannot be corrupted that way.
24
- #
25
- # Escaping contract: every response line is escaped to pure ASCII -- chars > 0x7E
26
- # become \uXXXX so the byte stream on the pipe is 7-bit clean regardless of the
27
- # codepage the pipe was created with. JsonOf preserves the "absent vs null"
28
- # distinction: a field explicitly marked [DBNull]::Value is emitted as JSON null,
29
- # ordinary $null values stay dropped.
30
-
31
- $script:escCache = @{}
32
-
33
- function Esc([string]$s) {
34
- if ($null -eq $s) { return '' }
35
- $t = $s.Replace('\', '\\').Replace('"', '\"')
36
- $t = $t.Replace("`b", '\b').Replace("`f", '\f').Replace("`n", '\n').Replace("`r", '\r').Replace("`t", '\t')
37
- if ($t.Length -gt 0 -and $t -notmatch '[^\x20-\x7E]') { return $t }
38
- $sb = New-Object System.Text.StringBuilder
39
- $chars = $t.ToCharArray()
40
- for ($i = 0; $i -lt $chars.Length; $i++) {
41
- $c = $chars[$i]
42
- $code = [int]$c
43
- if ($code -ge 32 -and $code -le 126) {
44
- [void]$sb.Append($c)
45
- } else {
46
- $key = [string]$code
47
- $rep = $script:escCache.Item($key)
48
- if ($null -eq $rep) { $rep = '\u' + $code.ToString('x4'); $script:escCache[$key] = $rep }
49
- [void]$sb.Append($rep)
50
- }
51
- }
52
- return $sb.ToString()
53
- }
54
-
55
- function JsonOf($o) {
56
- if ($null -eq $o) { return 'null' }
57
- if ($o -is [bool]) { if ($o) { return 'true' } else { return 'false' } }
58
- if ($o -is [string]) { return '"' + (Esc $o) + '"' }
59
- if ($o -is [System.Collections.IDictionary]) {
60
- $parts = New-Object System.Collections.Generic.List[string]
61
- # GetEnumerator(), never $o.Keys: PowerShell's member lookup resolves `$dict.Keys` to the VALUE
62
- # of a dictionary entry literally named "keys" before it resolves the .Keys property, so a
63
- # result field called `keys` serialized as {} (the iteration walked the string 'shift' and
64
- # indexed the dictionary by character). Enumerator entries are immune to member shadowing.
65
- foreach ($entry in $o.GetEnumerator()) {
66
- $k = $entry.Key
67
- $v = $entry.Value
68
- # A field explicitly marked [DBNull]::Value is emitted as JSON null. Ordinary $null values
69
- # stay dropped (many consumers distinguish "absent" from "null", e.g. act.before/after), so
70
- # an intentional null has to be opted into case by case.
71
- if ($v -is [System.DBNull]) { [void]$parts.Add('"' + (Esc ([string]$k)) + '":null'); continue }
72
- # Reference equality, not value equality: PowerShell answers TRUE to
73
- # `$null -eq $false`, `$null -eq 0`, `$null -eq @()` and `$null -eq ''`, so a
74
- # value test silently deletes performedCount=0, truncated=false and empty
75
- # names as well. The "absent vs null" contract is preserved for real nulls.
76
- if ([Object]::ReferenceEquals($v, $null)) { continue }
77
- [void]$parts.Add('"' + (Esc ([string]$k)) + '":' + (JsonOf $v))
78
- }
79
- if ($parts.Count -eq 0) { return '{}' }
80
- return '{' + ([string]::Join(',', $parts)) + '}'
81
- }
82
- if ($o -is [System.Management.Automation.PSCustomObject]) {
83
- $parts = New-Object System.Collections.Generic.List[string]
84
- foreach ($kk in $o.PSObject.Properties) {
85
- if ($null -eq $kk.Value) { continue }
86
- [void]$parts.Add('"' + (Esc $kk.Name) + '":' + (JsonOf $kk.Value))
87
- }
88
- if ($parts.Count -eq 0) { return '{}' }
89
- return '{' + ([string]::Join(',', $parts)) + '}'
90
- }
91
- if ($o -is [byte] -or $o -is [int16] -or $o -is [int32] -or $o -is [int64] -or $o -is [uint32] -or $o -is [sbyte] -or $o -is [uint16] -or $o -is [uint64]) {
92
- return [string]([long]$o)
93
- }
94
- if ($o -is [double] -or $o -is [single] -or $o -is [decimal]) {
95
- $d = [double]$o
96
- if ([double]::IsNaN($d) -or [double]::IsInfinity($d)) { return 'null' }
97
- if ($d -eq [Math]::Floor($d) -and [Math]::Abs($d) -lt 9.0E+15) { return ([long]$d).ToString([System.Globalization.CultureInfo]::InvariantCulture) }
98
- return $d.ToString('R', [System.Globalization.CultureInfo]::InvariantCulture)
99
- }
100
- if ($o -is [System.Collections.IEnumerable]) {
101
- $parts = New-Object System.Collections.Generic.List[string]
102
- foreach ($it in $o) { [void]$parts.Add((JsonOf $it)) }
103
- return '[' + ([string]::Join(',', $parts)) + ']'
104
- }
105
- return '"' + (Esc ([string]$o)) + '"'
106
- }
107
-
108
- function OneLine([string]$s) {
109
- if ($null -eq $s) { return '' }
110
- $t = $s.Replace("`r", ' ').Replace("`n", ' ')
111
- if ($t.Length -gt 400) { $t = $t.Substring(0, 400) + '~' }
112
- return $t
113
- }
114
-
115
- function Err($code, $message) {
116
- throw ('ERR|' + $code + '|' + $message)
117
- }
118
-
119
- function ArgOf($A, $name) { if ($null -eq $A) { return $null } ; if (-not $A.Contains($name)) { return $null }; return $A[$name] }
120
- function IntArg($A, $name, $default) {
121
- $v = ArgOf $A $name
122
- if ($null -eq $v -or $v -is [string] -and ([string]$v).Length -eq 0) { return $default }
123
- try { return [int][double]$v } catch { return $default }
124
- }
125
- function StrArg($A, $name, $default) {
126
- $v = ArgOf $A $name
127
- if ($null -eq $v) { return $default }
128
- if ($v -is [string]) { return $v }
129
- return [string]$v
130
- }
131
- function BoolArg($A, $name, $default) {
132
- $v = ArgOf $A $name
133
- if ($null -eq $v) { return $default }
134
- if ($v -is [bool]) { return $v }
135
- $s = ([string]$v).ToLowerInvariant()
136
- if ($s -eq 'true' -or $s -eq '1' -or $s -eq 'yes') { return $true }
137
- if ($s -eq 'false' -or $s -eq '0' -or $s -eq 'no') { return $false }
138
- return $default
139
- }
140
-
141
- # Normalises a handler argument that may arrive as PSCustomObject into a hashtable.
142
- # Scalars pass through unchanged; every caller gates on -is [IDictionary] before use,
143
- # so the loose return is safe in both hosts.
144
- function Dict($o) {
145
- if ($null -eq $o) { return $null }
146
- if ($o -is [System.Collections.IDictionary]) { return $o }
147
- if ($o -is [System.Management.Automation.PSCustomObject]) {
148
- $h = @{}
149
- foreach ($kk in $o.PSObject.Properties) { $h[$kk.Name] = (Dict $kk.Value) }
150
- return $h
151
- }
152
- return $o
153
- }
154
-
155
- # Splits a caught ErrorRecord into (code, message). ERR|-thrown errors keep their
156
- # declared code; raw exceptions are classified -- a released UIA element is
157
- # element_gone, COM/method failures surface as uia_error, anything else is
158
- # internal_error.
159
- function Split-Err($errRecord) {
160
- $msg = $errRecord.Exception.Message
161
- if ($null -eq $msg) { $msg = '' }
162
- if ($msg.StartsWith('ERR|')) {
163
- $parts = $msg.Split('|', 3)
164
- if ($parts.Count -ge 3) { return @($parts[1], $parts[2]) }
165
- if ($parts.Count -eq 2) { return @($parts[1], '') }
166
- }
167
- $ex = $errRecord.Exception
168
- $code = 'internal_error'
169
- if ($ex -is [System.Runtime.InteropServices.InvalidComObjectException]) { $code = 'element_gone' }
170
- elseif ($ex -is [System.Runtime.InteropServices.COMException]) { $code = 'uia_error' }
171
- elseif ($ex -is [System.Management.Automation.MethodInvocationException]) { $code = 'uia_error' }
172
- return @($code, $msg)
173
- }
1
+ # ps-stdio.ps1 -- stdio JSON framing helpers shared verbatim by the two resident
2
+ # PowerShell processes: uia-worker.ps1 (the UIA worker) and indicator-server.ps1
3
+ # (the overlay indicator).
4
+ #
5
+ # Each host loads this file at the top of its framing/io section:
6
+ # . (Join-Path $PSScriptRoot 'ps-stdio.ps1')
7
+ # Dot-sourcing keeps the caller's scope, so the functions below run against the
8
+ # host's script scope and the $script:escCache initialised below lands there.
9
+ # (scripts/regression-worker.ps1 loads these functions by AST extraction instead,
10
+ # which skips top-level assignments, so it initialises $script:escCache itself.)
11
+ #
12
+ # HOST-AGNOSTIC RULE: none of these functions may reference $script:W, $script:S
13
+ # or any other host-owned variable. A dot-sourced function body resolves $script:
14
+ # against whichever host loaded it, so one host-specific reference would silently
15
+ # break in the other process.
16
+ #
17
+ # Send-Ok / Send-Err are deliberately NOT shared: the worker writes $script:W.stats,
18
+ # the indicator writes $script:S.stats and decorates every result with exStyles and
19
+ # the last palette. Those shapes are per-host contracts, so they stay in their hosts.
20
+ #
21
+ # SAVED AS UTF-8 WITH BOM, CONTENT ASCII-ONLY: Windows PowerShell 5.1 decodes a
22
+ # BOM-less .ps1 with the system codepage, so an unlabelled file is one editor save
23
+ # away from mojibake. ASCII-only source cannot be corrupted that way.
24
+ #
25
+ # Escaping contract: every response line is escaped to pure ASCII -- chars > 0x7E
26
+ # become \uXXXX so the byte stream on the pipe is 7-bit clean regardless of the
27
+ # codepage the pipe was created with. JsonOf preserves the "absent vs null"
28
+ # distinction: a field explicitly marked [DBNull]::Value is emitted as JSON null,
29
+ # ordinary $null values stay dropped.
30
+
31
+ $script:escCache = @{}
32
+
33
+ function Esc([string]$s) {
34
+ if ($null -eq $s) { return '' }
35
+ $t = $s.Replace('\', '\\').Replace('"', '\"')
36
+ $t = $t.Replace("`b", '\b').Replace("`f", '\f').Replace("`n", '\n').Replace("`r", '\r').Replace("`t", '\t')
37
+ if ($t.Length -gt 0 -and $t -notmatch '[^\x20-\x7E]') { return $t }
38
+ $sb = New-Object System.Text.StringBuilder
39
+ $chars = $t.ToCharArray()
40
+ for ($i = 0; $i -lt $chars.Length; $i++) {
41
+ $c = $chars[$i]
42
+ $code = [int]$c
43
+ if ($code -ge 32 -and $code -le 126) {
44
+ [void]$sb.Append($c)
45
+ } else {
46
+ $key = [string]$code
47
+ $rep = $script:escCache.Item($key)
48
+ if ($null -eq $rep) { $rep = '\u' + $code.ToString('x4'); $script:escCache[$key] = $rep }
49
+ [void]$sb.Append($rep)
50
+ }
51
+ }
52
+ return $sb.ToString()
53
+ }
54
+
55
+ function JsonOf($o) {
56
+ if ($null -eq $o) { return 'null' }
57
+ if ($o -is [bool]) { if ($o) { return 'true' } else { return 'false' } }
58
+ if ($o -is [string]) { return '"' + (Esc $o) + '"' }
59
+ if ($o -is [System.Collections.IDictionary]) {
60
+ $parts = New-Object System.Collections.Generic.List[string]
61
+ # GetEnumerator(), never $o.Keys: PowerShell's member lookup resolves `$dict.Keys` to the VALUE
62
+ # of a dictionary entry literally named "keys" before it resolves the .Keys property, so a
63
+ # result field called `keys` serialized as {} (the iteration walked the string 'shift' and
64
+ # indexed the dictionary by character). Enumerator entries are immune to member shadowing.
65
+ foreach ($entry in $o.GetEnumerator()) {
66
+ $k = $entry.Key
67
+ $v = $entry.Value
68
+ # A field explicitly marked [DBNull]::Value is emitted as JSON null. Ordinary $null values
69
+ # stay dropped (many consumers distinguish "absent" from "null", e.g. act.before/after), so
70
+ # an intentional null has to be opted into case by case.
71
+ if ($v -is [System.DBNull]) { [void]$parts.Add('"' + (Esc ([string]$k)) + '":null'); continue }
72
+ # Reference equality, not value equality: PowerShell answers TRUE to
73
+ # `$null -eq $false`, `$null -eq 0`, `$null -eq @()` and `$null -eq ''`, so a
74
+ # value test silently deletes performedCount=0, truncated=false and empty
75
+ # names as well. The "absent vs null" contract is preserved for real nulls.
76
+ if ([Object]::ReferenceEquals($v, $null)) { continue }
77
+ [void]$parts.Add('"' + (Esc ([string]$k)) + '":' + (JsonOf $v))
78
+ }
79
+ if ($parts.Count -eq 0) { return '{}' }
80
+ return '{' + ([string]::Join(',', $parts)) + '}'
81
+ }
82
+ if ($o -is [System.Management.Automation.PSCustomObject]) {
83
+ $parts = New-Object System.Collections.Generic.List[string]
84
+ foreach ($kk in $o.PSObject.Properties) {
85
+ if ($null -eq $kk.Value) { continue }
86
+ [void]$parts.Add('"' + (Esc $kk.Name) + '":' + (JsonOf $kk.Value))
87
+ }
88
+ if ($parts.Count -eq 0) { return '{}' }
89
+ return '{' + ([string]::Join(',', $parts)) + '}'
90
+ }
91
+ if ($o -is [byte] -or $o -is [int16] -or $o -is [int32] -or $o -is [int64] -or $o -is [uint32] -or $o -is [sbyte] -or $o -is [uint16] -or $o -is [uint64]) {
92
+ return [string]([long]$o)
93
+ }
94
+ if ($o -is [double] -or $o -is [single] -or $o -is [decimal]) {
95
+ $d = [double]$o
96
+ if ([double]::IsNaN($d) -or [double]::IsInfinity($d)) { return 'null' }
97
+ if ($d -eq [Math]::Floor($d) -and [Math]::Abs($d) -lt 9.0E+15) { return ([long]$d).ToString([System.Globalization.CultureInfo]::InvariantCulture) }
98
+ return $d.ToString('R', [System.Globalization.CultureInfo]::InvariantCulture)
99
+ }
100
+ if ($o -is [System.Collections.IEnumerable]) {
101
+ $parts = New-Object System.Collections.Generic.List[string]
102
+ foreach ($it in $o) { [void]$parts.Add((JsonOf $it)) }
103
+ return '[' + ([string]::Join(',', $parts)) + ']'
104
+ }
105
+ return '"' + (Esc ([string]$o)) + '"'
106
+ }
107
+
108
+ function OneLine([string]$s) {
109
+ if ($null -eq $s) { return '' }
110
+ $t = $s.Replace("`r", ' ').Replace("`n", ' ')
111
+ if ($t.Length -gt 400) { $t = $t.Substring(0, 400) + '~' }
112
+ return $t
113
+ }
114
+
115
+ function Err($code, $message) {
116
+ throw ('ERR|' + $code + '|' + $message)
117
+ }
118
+
119
+ function ArgOf($A, $name) { if ($null -eq $A) { return $null } ; if (-not $A.Contains($name)) { return $null }; return $A[$name] }
120
+ function IntArg($A, $name, $default) {
121
+ $v = ArgOf $A $name
122
+ if ($null -eq $v -or $v -is [string] -and ([string]$v).Length -eq 0) { return $default }
123
+ try { return [int][double]$v } catch { return $default }
124
+ }
125
+ function StrArg($A, $name, $default) {
126
+ $v = ArgOf $A $name
127
+ if ($null -eq $v) { return $default }
128
+ if ($v -is [string]) { return $v }
129
+ return [string]$v
130
+ }
131
+ function BoolArg($A, $name, $default) {
132
+ $v = ArgOf $A $name
133
+ if ($null -eq $v) { return $default }
134
+ if ($v -is [bool]) { return $v }
135
+ $s = ([string]$v).ToLowerInvariant()
136
+ if ($s -eq 'true' -or $s -eq '1' -or $s -eq 'yes') { return $true }
137
+ if ($s -eq 'false' -or $s -eq '0' -or $s -eq 'no') { return $false }
138
+ return $default
139
+ }
140
+
141
+ # Normalises a handler argument that may arrive as PSCustomObject into a hashtable.
142
+ # Scalars pass through unchanged; every caller gates on -is [IDictionary] before use,
143
+ # so the loose return is safe in both hosts.
144
+ function Dict($o) {
145
+ if ($null -eq $o) { return $null }
146
+ if ($o -is [System.Collections.IDictionary]) { return $o }
147
+ if ($o -is [System.Management.Automation.PSCustomObject]) {
148
+ $h = @{}
149
+ foreach ($kk in $o.PSObject.Properties) { $h[$kk.Name] = (Dict $kk.Value) }
150
+ return $h
151
+ }
152
+ return $o
153
+ }
154
+
155
+ # Splits a caught ErrorRecord into (code, message). ERR|-thrown errors keep their
156
+ # declared code; raw exceptions are classified -- a released UIA element is
157
+ # element_gone, COM/method failures surface as uia_error, anything else is
158
+ # internal_error.
159
+ function Split-Err($errRecord) {
160
+ $msg = $errRecord.Exception.Message
161
+ if ($null -eq $msg) { $msg = '' }
162
+ if ($msg.StartsWith('ERR|')) {
163
+ $parts = $msg.Split('|', 3)
164
+ if ($parts.Count -ge 3) { return @($parts[1], $parts[2]) }
165
+ if ($parts.Count -eq 2) { return @($parts[1], '') }
166
+ }
167
+ $ex = $errRecord.Exception
168
+ $code = 'internal_error'
169
+ if ($ex -is [System.Runtime.InteropServices.InvalidComObjectException]) { $code = 'element_gone' }
170
+ elseif ($ex -is [System.Runtime.InteropServices.COMException]) { $code = 'uia_error' }
171
+ elseif ($ex -is [System.Management.Automation.MethodInvocationException]) { $code = 'uia_error' }
172
+ return @($code, $msg)
173
+ }
@@ -481,7 +481,7 @@ public static class Native {
481
481
  return sb.ToString();
482
482
  }
483
483
 
484
- // win32 truth about where the input focus and the caret actually are. Used to prove that a
484
+ // win32 truth about where the input focus and the caret actually are; this proves that a
485
485
  // physical click landed in a document, rather than only proving that an event was queued.
486
486
  [StructLayout(LayoutKind.Sequential)]
487
487
  public struct GUITHREADINFO {