cocheck 0.0.0-stage → 0.4.0

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.
Files changed (305) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/THIRD_PARTY_NOTICES.md +279 -0
  4. package/bin/cocheck.mjs +8 -0
  5. package/dist/agent-transcripts.js +541 -0
  6. package/dist/attribution/basis.js +31 -0
  7. package/dist/attribution/evidence.js +311 -0
  8. package/dist/attribution/hooks/cocheck-preload.cjs +254 -0
  9. package/dist/attribution/hooks/sitecustomize.py +245 -0
  10. package/dist/attribution/names.js +163 -0
  11. package/dist/attribution/reconstruct.js +128 -0
  12. package/dist/attribution/tag.js +246 -0
  13. package/dist/attribution/write-scope-win.js +615 -0
  14. package/dist/attribution/write-scope.js +1668 -0
  15. package/dist/build-info.json +1 -0
  16. package/dist/cli-main.js +8 -0
  17. package/dist/cli.js +193 -0
  18. package/dist/codex-config.js +107 -0
  19. package/dist/connector/after-gap.js +56 -0
  20. package/dist/connector/after-snapshot.js +244 -0
  21. package/dist/connector/before-snapshot.js +168 -0
  22. package/dist/connector/builtins.js +93 -0
  23. package/dist/connector/changes-v1.js +276 -0
  24. package/dist/connector/claimed-state.js +40 -0
  25. package/dist/connector/claimed.js +86 -0
  26. package/dist/connector/conformance.js +458 -0
  27. package/dist/connector/diff-object.js +81 -0
  28. package/dist/connector/diff-samples.js +64 -0
  29. package/dist/connector/diff.js +273 -0
  30. package/dist/connector/doc-level.js +20 -0
  31. package/dist/connector/enabled-types.js +87 -0
  32. package/dist/connector/export-view.js +13 -0
  33. package/dist/connector/file-capture.js +265 -0
  34. package/dist/connector/frozen.js +213 -0
  35. package/dist/connector/installed-manifests.js +72 -0
  36. package/dist/connector/installed-match.js +161 -0
  37. package/dist/connector/local-process.js +119 -0
  38. package/dist/connector/nothing-changed-rule.js +23 -0
  39. package/dist/connector/old-rows.js +66 -0
  40. package/dist/connector/png-pixels.js +4 -0
  41. package/dist/connector/registry.js +78 -0
  42. package/dist/connector/requires.js +30 -0
  43. package/dist/connector/row-doc.js +54 -0
  44. package/dist/connector/run-argv.js +25 -0
  45. package/dist/connector/runner.js +325 -0
  46. package/dist/connector/schema.js +242 -0
  47. package/dist/connector/subject.js +8 -0
  48. package/dist/connector/subjects.js +113 -0
  49. package/dist/connector/validate.js +200 -0
  50. package/dist/connector-auth.js +101 -0
  51. package/dist/connector-create.js +55 -0
  52. package/dist/connector-doctor.js +167 -0
  53. package/dist/connector-test-cli.js +627 -0
  54. package/dist/connector-types-cli.js +43 -0
  55. package/dist/connectors/microsoft-excel/cocheck-connector.json +13 -0
  56. package/dist/connectors/microsoft-excel/connector.mjs +11 -0
  57. package/dist/connectors/microsoft-powerpoint/cocheck-connector.json +13 -0
  58. package/dist/connectors/microsoft-powerpoint/connector.mjs +11 -0
  59. package/dist/connectors/microsoft-word/cocheck-connector.json +13 -0
  60. package/dist/connectors/microsoft-word/connector.mjs +11 -0
  61. package/dist/copies.js +151 -0
  62. package/dist/copilot-helpers.js +246 -0
  63. package/dist/coverage.js +277 -0
  64. package/dist/credit-guard.js +330 -0
  65. package/dist/display.js +78 -0
  66. package/dist/file-lock.js +145 -0
  67. package/dist/fingerprint.js +25 -0
  68. package/dist/formats/files/align.js +84 -0
  69. package/dist/formats/files/csv.js +78 -0
  70. package/dist/formats/files/layer.js +274 -0
  71. package/dist/formats/files/scan.js +86 -0
  72. package/dist/formats/files/textlike.js +21 -0
  73. package/dist/formats/layer.js +48 -0
  74. package/dist/helpers/pdfpages +0 -0
  75. package/dist/home-page.js +173 -0
  76. package/dist/home-perms.js +59 -0
  77. package/dist/hook-adapter.js +3415 -0
  78. package/dist/hook-cli.js +505 -0
  79. package/dist/hook-journal.js +147 -0
  80. package/dist/hook.js +25 -0
  81. package/dist/hosts/claude.js +250 -0
  82. package/dist/hosts/codex-bin-macos.js +2 -0
  83. package/dist/hosts/codex-bin.js +35 -0
  84. package/dist/hosts/codex-trust-probe.js +52 -0
  85. package/dist/hosts/codex-trust.js +46 -0
  86. package/dist/hosts/codex.js +355 -0
  87. package/dist/hosts/copilot.js +236 -0
  88. package/dist/hosts/index.js +52 -0
  89. package/dist/hosts/session-titles.js +327 -0
  90. package/dist/hosts/shared.js +31 -0
  91. package/dist/hosts/types.js +26 -0
  92. package/dist/html.js +4 -0
  93. package/dist/install.js +676 -0
  94. package/dist/items.js +105 -0
  95. package/dist/ledger.js +2097 -0
  96. package/dist/narration.js +202 -0
  97. package/dist/normalize.js +82 -0
  98. package/dist/office/connector/apps.js +34 -0
  99. package/dist/office/connector/docx/layer.js +247 -0
  100. package/dist/office/connector/docx/reader.js +284 -0
  101. package/dist/office/connector/excel/align.js +284 -0
  102. package/dist/office/connector/excel/answer.js +352 -0
  103. package/dist/office/connector/excel/diff.js +1310 -0
  104. package/dist/office/connector/excel/errors.js +44 -0
  105. package/dist/office/connector/excel/look.js +121 -0
  106. package/dist/office/connector/excel/print-boxes.js +432 -0
  107. package/dist/office/connector/excel/print-grid-previous.js +206 -0
  108. package/dist/office/connector/excel/print-setup.js +168 -0
  109. package/dist/office/connector/excel/workbook.js +374 -0
  110. package/dist/office/connector/export-driver.js +9 -0
  111. package/dist/office/connector/helpers/cocheck-screen +0 -0
  112. package/dist/office/connector/issues.js +31 -0
  113. package/dist/office/connector/mac-guard.js +16 -0
  114. package/dist/office/connector/main.js +23 -0
  115. package/dist/office/connector/nothing-changed.js +18 -0
  116. package/dist/office/connector/office-job.js +416 -0
  117. package/dist/office/connector/office-macos.js +473 -0
  118. package/dist/office/connector/office-win-export.js +107 -0
  119. package/dist/office/connector/office-win-lifecycle.js +194 -0
  120. package/dist/office/connector/office-win.js +209 -0
  121. package/dist/office/connector/office-win.ps1 +451 -0
  122. package/dist/office/connector/open-watch.js +46 -0
  123. package/dist/office/connector/pictures.js +156 -0
  124. package/dist/office/connector/pptx/diff.js +589 -0
  125. package/dist/office/connector/pptx/frames.js +105 -0
  126. package/dist/office/connector/pptx/layer.js +148 -0
  127. package/dist/office/connector/pptx/links.js +59 -0
  128. package/dist/office/connector/pptx/reader.js +744 -0
  129. package/dist/office/connector/pptx/spans.js +70 -0
  130. package/dist/office/connector/pptx/tags.js +86 -0
  131. package/dist/office/connector/pptx/xml.js +96 -0
  132. package/dist/office/connector/pptx/zip.js +223 -0
  133. package/dist/office/connector/pptx-boxes.js +238 -0
  134. package/dist/office/connector/print-copy-cap.js +19 -0
  135. package/dist/office/connector/print-copy.js +13 -0
  136. package/dist/office/connector/program.js +291 -0
  137. package/dist/office/connector/reach.js +27 -0
  138. package/dist/office/connector/refusal.js +16 -0
  139. package/dist/office/connector/screen-macos.js +193 -0
  140. package/dist/office/connector/screen-windows.js +34 -0
  141. package/dist/office/connector/shared/chart-diff.js +376 -0
  142. package/dist/office/connector/shared/docprops-noise.js +13 -0
  143. package/dist/office/connector/shared/lock.js +107 -0
  144. package/dist/office/connector/shared/ooxml-names.js +347 -0
  145. package/dist/office/connector/shared/owner.js +57 -0
  146. package/dist/office/connector/shared/package-media.js +703 -0
  147. package/dist/office/connector/shared/preflight.js +226 -0
  148. package/dist/office/connector/shared/structure-check.js +623 -0
  149. package/dist/office/connector/word-boxes.js +364 -0
  150. package/dist/office/connector/word-print-copy.js +234 -0
  151. package/dist/office/connector/xlsx/diff.js +1038 -0
  152. package/dist/office/connector/xlsx/formula.js +410 -0
  153. package/dist/office/connector/xlsx/layer.js +621 -0
  154. package/dist/office/connector/xlsx/memo.js +39 -0
  155. package/dist/office/connector/xlsx/numbers.js +31 -0
  156. package/dist/office/connector/xlsx/numfmt.js +913 -0
  157. package/dist/office/connector/xlsx/parts.js +66 -0
  158. package/dist/office/connector/xlsx/reader.js +394 -0
  159. package/dist/office/connector/xlsx/types.js +20 -0
  160. package/dist/office/connector/xlsx/written.js +446 -0
  161. package/dist/open-pick.js +99 -0
  162. package/dist/patch-secrets.js +194 -0
  163. package/dist/paths.js +65 -0
  164. package/dist/platform/darwin.js +179 -0
  165. package/dist/platform/index.js +61 -0
  166. package/dist/platform/spawn.js +115 -0
  167. package/dist/platform/stub.js +21 -0
  168. package/dist/platform/task-folder.js +41 -0
  169. package/dist/platform/types.js +20 -0
  170. package/dist/platform/win32-docrender.js +7 -0
  171. package/dist/platform/win32.js +265 -0
  172. package/dist/preferences.js +49 -0
  173. package/dist/reason.js +103 -0
  174. package/dist/region-delivery.js +148 -0
  175. package/dist/registry.js +68 -0
  176. package/dist/reveal.js +45 -0
  177. package/dist/review-process.js +154 -0
  178. package/dist/review-refresh-process.js +17 -0
  179. package/dist/review-refresh.js +120 -0
  180. package/dist/review-server.js +2079 -0
  181. package/dist/review-view-server.js +106 -0
  182. package/dist/review.js +8 -0
  183. package/dist/seal.js +315 -0
  184. package/dist/secret-files.js +34 -0
  185. package/dist/secret-hashes.js +27 -0
  186. package/dist/secret-rules.generated.js +3519 -0
  187. package/dist/secret-scan.js +127 -0
  188. package/dist/session-context.js +18 -0
  189. package/dist/signoff.js +419 -0
  190. package/dist/skill.js +110 -0
  191. package/dist/states.js +192 -0
  192. package/dist/tasks.js +1001 -0
  193. package/dist/timeline/attribution.js +207 -0
  194. package/dist/timeline/broken.js +55 -0
  195. package/dist/timeline/describe.js +413 -0
  196. package/dist/timeline/generic.js +195 -0
  197. package/dist/timeline/load.js +464 -0
  198. package/dist/timeline/loading.js +49 -0
  199. package/dist/timeline/notes.js +208 -0
  200. package/dist/timeline/page.js +178 -0
  201. package/dist/timeline/picture.js +303 -0
  202. package/dist/timeline/rail/assets/cocheck-icon.svg +1 -0
  203. package/dist/timeline/rail/assets/files-view.js +198 -0
  204. package/dist/timeline/rail/assets/loaders/icon-intro.json +1 -0
  205. package/dist/timeline/rail/assets/loaders/loader-orbit.json +1 -0
  206. package/dist/timeline/rail/assets/loaders/loader-spin.json +1 -0
  207. package/dist/timeline/rail/assets/review.css +992 -0
  208. package/dist/timeline/rail/assets/review.js +3365 -0
  209. package/dist/timeline/rail/assets/view-table.js +683 -0
  210. package/dist/timeline/rail/failure-line.js +26 -0
  211. package/dist/timeline/rail/files-model.js +45 -0
  212. package/dist/timeline/rail/live.js +49 -0
  213. package/dist/timeline/rail/made-pictures.js +48 -0
  214. package/dist/timeline/rail/mcp-card.js +307 -0
  215. package/dist/timeline/rail/model.js +1317 -0
  216. package/dist/timeline/rail/page.js +167 -0
  217. package/dist/timeline/rail/passes.js +106 -0
  218. package/dist/timeline/rail/regions.js +26 -0
  219. package/dist/timeline/rail/send-back.js +154 -0
  220. package/dist/timeline/rail/stop-status.js +164 -0
  221. package/dist/timeline/read-signal.js +743 -0
  222. package/dist/timeline/render/claimed.js +13 -0
  223. package/dist/timeline/render/fallback.js +36 -0
  224. package/dist/timeline/render/pdf-helper.js +71 -0
  225. package/dist/timeline/render/pdf.js +410 -0
  226. package/dist/timeline/render/pixel-pages.js +168 -0
  227. package/dist/timeline/render/png-crop.js +281 -0
  228. package/dist/timeline/render/registry.js +7 -0
  229. package/dist/timeline/render/text.js +366 -0
  230. package/dist/timeline/render/types.js +1 -0
  231. package/dist/timeline/render/view-v1.js +148 -0
  232. package/dist/timeline/render/whole.js +6 -0
  233. package/dist/timeline/rollout-failures.js +40 -0
  234. package/dist/timeline/runs.js +836 -0
  235. package/dist/timeline/stored-image.js +34 -0
  236. package/dist/timeline/subject-display.js +44 -0
  237. package/dist/timeline/timeline.js +1114 -0
  238. package/dist/timeline/write-signal.js +403 -0
  239. package/dist/tool-label.js +201 -0
  240. package/dist/tracking.js +87 -0
  241. package/dist/vendor/pdfjs/LICENSE +177 -0
  242. package/dist/vendor/pdfjs/pdf.min.mjs +27 -0
  243. package/dist/vendor/pdfjs/pdf.worker.min.mjs +27 -0
  244. package/package.json +66 -4
  245. package/public-kit/GUIDE.md +189 -0
  246. package/public-kit/README.md +10 -0
  247. package/public-kit/conformance/README.md +13 -0
  248. package/public-kit/conformance/cases/C1.json +12 -0
  249. package/public-kit/conformance/cases/C10.json +15 -0
  250. package/public-kit/conformance/cases/C11.json +16 -0
  251. package/public-kit/conformance/cases/C12.json +18 -0
  252. package/public-kit/conformance/cases/C13.json +23 -0
  253. package/public-kit/conformance/cases/C14.json +16 -0
  254. package/public-kit/conformance/cases/C16.json +15 -0
  255. package/public-kit/conformance/cases/C17.json +25 -0
  256. package/public-kit/conformance/cases/C2.json +13 -0
  257. package/public-kit/conformance/cases/C3.json +44 -0
  258. package/public-kit/conformance/cases/C4.json +13 -0
  259. package/public-kit/conformance/cases/C5.json +16 -0
  260. package/public-kit/conformance/cases/C6.json +58 -0
  261. package/public-kit/conformance/generate-large.mjs +15 -0
  262. package/public-kit/examples/toy-export/cocheck-connector.json +10 -0
  263. package/public-kit/examples/toy-export/connector.mjs +28 -0
  264. package/public-kit/examples/toy-helpers/cocheck-connector.json +10 -0
  265. package/public-kit/examples/toy-helpers/connector.mjs +69 -0
  266. package/public-kit/examples/toy-level-1/cocheck-connector.json +10 -0
  267. package/public-kit/examples/toy-level-1/connector.mjs +61 -0
  268. package/public-kit/examples/toy-level-3/cocheck-connector.json +10 -0
  269. package/public-kit/examples/toy-level-3/connector.mjs +82 -0
  270. package/public-kit/examples/toy-tracker/cocheck-connector.json +14 -0
  271. package/public-kit/examples/toy-tracker/connector.mjs +46 -0
  272. package/public-kit/examples/toy-tracker/samples/history.json +10 -0
  273. package/public-kit/examples/toy-tracker/samples/samples.json +7 -0
  274. package/public-kit/examples/toy-vendor/cocheck-connector.json +15 -0
  275. package/public-kit/examples/toy-vendor/connector.mjs +62 -0
  276. package/public-kit/helpers/pdf-text-layout.d.mts +35 -0
  277. package/public-kit/helpers/pdf-text-layout.mjs +602 -0
  278. package/public-kit/helpers/pdf-text.d.mts +56 -0
  279. package/public-kit/helpers/pdf-text.mjs +375 -0
  280. package/public-kit/helpers/pdf.d.mts +61 -0
  281. package/public-kit/helpers/pdf.mjs +251 -0
  282. package/public-kit/helpers/png.d.mts +15 -0
  283. package/public-kit/helpers/png.mjs +88 -0
  284. package/public-kit/helpers/spec.d.mts +4 -0
  285. package/public-kit/helpers/spec.mjs +2 -0
  286. package/public-kit/scaffold/README.md +23 -0
  287. package/public-kit/scaffold/template/README.md +13 -0
  288. package/public-kit/scaffold/template/cocheck-connector.json +10 -0
  289. package/public-kit/scaffold/template/connector.mjs +50 -0
  290. package/public-kit/spec/README.md +408 -0
  291. package/public-kit/spec/v1.md +598 -0
  292. package/public-kit/toy-product/README.md +7 -0
  293. package/public-kit/toy-product/notes-store.mjs +30 -0
  294. package/public-kit/toy-product/states/create.after.json +16 -0
  295. package/public-kit/toy-product/states/create.before.json +12 -0
  296. package/public-kit/toy-product/states/delete.after.json +8 -0
  297. package/public-kit/toy-product/states/delete.before.json +12 -0
  298. package/public-kit/toy-product/states/edit.after.json +12 -0
  299. package/public-kit/toy-product/states/edit.before.json +12 -0
  300. package/public-kit/toy-product/states/malformed.after.json +1 -0
  301. package/public-kit/toy-product/states/malformed.before.json +12 -0
  302. package/public-kit/toy-product/states/no-change.after.json +12 -0
  303. package/public-kit/toy-product/states/no-change.before.json +12 -0
  304. package/scripts/hook-launch.mjs +58 -0
  305. package/scripts/hook-launch.sh +52 -0
@@ -0,0 +1,451 @@
1
+ # CoCheck's Windows Office host. office-win.ts starts one powershell.exe per job (-NoProfile -NonInteractive -Sta
2
+ # -ExecutionPolicy Bypass) and loads this file as a scriptblock. Protocol: one JSON object per line each way. Request {id, op, args};
3
+ # reply {id, ok:true, ...} or {id, ok:false, why}. The host exits on stdin EOF, on the exit op, or when Node stops its pid.
4
+ # .NET only: no compiled helpers, no Add-Type. The host only ever holds Office objects it created itself; it never attaches to an
5
+ # Office the person has open (no active-object lookup of any kind).
6
+ # Adding an op: one entry in $Ops below (a scriptblock taking the request's args and returning a hashtable merged into the reply),
7
+ # plus one typed method in office-win.ts.
8
+
9
+ $ErrorActionPreference = 'Stop'
10
+ $utf8 = New-Object System.Text.UTF8Encoding $false
11
+ # Our own UTF-8 readers and writers on the raw streams, so non-ASCII paths survive whatever the console code page is.
12
+ $stdin = New-Object System.IO.StreamReader([Console]::OpenStandardInput(), $utf8)
13
+ $stdout = New-Object System.IO.StreamWriter([Console]::OpenStandardOutput(), $utf8)
14
+ $stdout.AutoFlush = $true
15
+ $script:Quit = $false
16
+
17
+ function Send-Reply([hashtable]$Reply) {
18
+ $stdout.WriteLine((ConvertTo-Json -InputObject $Reply -Compress -Depth 8))
19
+ }
20
+
21
+ # COM calls an Office app turns away while it is busy (RPC_E_CALL_REJECTED 0x80010001, RPC_E_SERVERCALL_RETRYLATER 0x8001010A):
22
+ # retried for up to $Ms milliseconds, then the error stands. Every other error stands at once.
23
+ function Test-Busy($Err) {
24
+ $e = $Err.Exception
25
+ while ($null -ne $e) {
26
+ if ($e.HResult -eq -2147418111 -or $e.HResult -eq -2147417846) { return $true }
27
+ $e = $e.InnerException
28
+ }
29
+ return $false
30
+ }
31
+ function Invoke-Busy([scriptblock]$Call, [int]$Ms = 2000) {
32
+ $watch = [System.Diagnostics.Stopwatch]::StartNew()
33
+ while ($true) {
34
+ try {
35
+ return & $Call
36
+ } catch {
37
+ if (-not (Test-Busy $_) -or $watch.ElapsedMilliseconds -ge $Ms) { throw }
38
+ Start-Sleep -Milliseconds 100
39
+ }
40
+ }
41
+ }
42
+
43
+ $Ops = @{
44
+ hello = {
45
+ param($a)
46
+ @{ version = $PSVersionTable.PSVersion.ToString(); mode = [string]$ExecutionContext.SessionState.LanguageMode }
47
+ }
48
+ selftest = {
49
+ param($a)
50
+ # the busy helper on a stub call that is turned away once, then answers
51
+ $script:tries = 0
52
+ $got = Invoke-Busy {
53
+ $script:tries++
54
+ if ($script:tries -lt 2) { throw (New-Object System.Runtime.InteropServices.COMException 'busy', -2147418111) }
55
+ 'answered'
56
+ }
57
+ @{ retried = $script:tries - 1; got = $got; text = [string]$a.text }
58
+ }
59
+ exit = {
60
+ param($a)
61
+ $script:Quit = $true
62
+ @{}
63
+ }
64
+ }
65
+
66
+ # --- lifecycle ops ---
67
+ # One entry per Office app this host may launch: $script:Apps[$key] = @{ com; pid; startedAtMs } exists only for an Application object this
68
+ # host created AND whose process launch proved new (exactly one new pid of the image, started after the launch began). Anything else is
69
+ # released at once and never touched again. Start times are epoch ms (UTC), so Node compares them whatever the TZ or locale.
70
+ if ($null -eq $script:Apps) { $script:Apps = @{} }
71
+ $script:OfficeSpec = @{
72
+ excel = @{ progId = 'Excel.Application'; image = 'EXCEL' }
73
+ word = @{ progId = 'Word.Application'; image = 'WINWORD' }
74
+ powerpoint = @{ progId = 'PowerPoint.Application'; image = 'POWERPNT' }
75
+ }
76
+ function Get-OfficeSpec([string]$Key) {
77
+ $s = $script:OfficeSpec[$Key]
78
+ if ($null -eq $s) { throw "unknown app: $Key" }
79
+ $s
80
+ }
81
+ function Get-StartMs([System.Diagnostics.Process]$P) {
82
+ (New-Object System.DateTimeOffset ($P.StartTime.ToUniversalTime())).ToUnixTimeMilliseconds()
83
+ }
84
+ function Get-ImagePids([string]$Image) {
85
+ @(Get-Process -Name $Image -ErrorAction SilentlyContinue | ForEach-Object { $_.Id })
86
+ }
87
+ function Release-Com($O) {
88
+ if ($null -ne $O) { try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($O) } catch { } }
89
+ }
90
+ function Get-Launched([string]$Key) {
91
+ $e = $script:Apps[$Key]
92
+ if ($null -eq $e -or $null -eq $e.com) { throw 'not launched' }
93
+ $e
94
+ }
95
+ function Get-DocCount([string]$Key, $C) {
96
+ if ($Key -eq 'excel') { return [int]$C.Workbooks.Count }
97
+ if ($Key -eq 'word') { return [int]$C.Documents.Count }
98
+ [int]$C.Presentations.Count
99
+ }
100
+ function Drop-App([string]$Key) {
101
+ $e = $script:Apps[$Key]
102
+ if ($null -ne $e) { Release-Com $e.com }
103
+ $script:Apps.Remove($Key)
104
+ }
105
+
106
+ $Ops['isRunning'] = {
107
+ param($a)
108
+ $s = Get-OfficeSpec ([string]$a.app)
109
+ @{ running = ((Get-ImagePids $s.image).Count -gt 0) }
110
+ }
111
+ $Ops['launch'] = {
112
+ param($a)
113
+ $key = [string]$a.app
114
+ $s = Get-OfficeSpec $key
115
+ if ($null -ne $script:Apps[$key]) { throw 'already launched' }
116
+ $began = [System.DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
117
+ $before = Get-ImagePids $s.image
118
+ $com = New-Object -ComObject $s.progId
119
+ $new = @(Get-Process -Name $s.image -ErrorAction SilentlyContinue | Where-Object { $before -notcontains $_.Id })
120
+ # No new process: COM handed back an instance that was already running (possibly the person's). Released, never touched.
121
+ if ($new.Count -eq 0) { Release-Com $com; return @{ pid = $null } }
122
+ $started = $null
123
+ if ($new.Count -eq 1) { try { $started = Get-StartMs $new[0] } catch { $started = $null } }
124
+ # Two new pids, an unreadable start time, or a start before the launch began: not provably ours. Released, never touched.
125
+ if ($new.Count -ne 1 -or $null -eq $started -or $started -lt $began) { Release-Com $com; return @{ notOurs = $true } }
126
+ $script:Apps[$key] = @{ com = $com; pid = [int]$new[0].Id; startedAtMs = [long]$started }
127
+ @{ pid = [int]$new[0].Id; startedAtMs = [long]$started }
128
+ }
129
+ $Ops['ready'] = {
130
+ param($a)
131
+ $key = [string]$a.app
132
+ $c = (Get-Launched $key).com
133
+ # PowerPoint's Application is not made invisible (it refuses); its documents open WithWindow 0 instead.
134
+ if ($key -ne 'powerpoint') { Invoke-Busy { $c.Visible = $false } | Out-Null }
135
+ if ($key -eq 'excel') { Invoke-Busy { $c.DisplayAlerts = $false } | Out-Null }
136
+ elseif ($key -eq 'word') { Invoke-Busy { $c.DisplayAlerts = 0 } | Out-Null } # wdAlertsNone
137
+ else { Invoke-Busy { $c.DisplayAlerts = 1 } | Out-Null } # ppAlertsNone
138
+ Invoke-Busy { $c.AutomationSecurity = 3 } | Out-Null # msoAutomationSecurityForceDisable
139
+ $v = Invoke-Busy { [string]$c.Version }
140
+ @{ ready = $true; version = $v }
141
+ }
142
+ $Ops['documentCount'] = {
143
+ param($a)
144
+ $key = [string]$a.app
145
+ $c = (Get-Launched $key).com
146
+ @{ count = [int](Invoke-Busy { Get-DocCount $key $c }) }
147
+ }
148
+ $Ops['quit'] = {
149
+ param($a)
150
+ $key = [string]$a.app
151
+ $c = (Get-Launched $key).com
152
+ $n = [int](Invoke-Busy { Get-DocCount $key $c })
153
+ $uc = $false
154
+ # Excel and Word expose UserControl; PowerPoint's Application may not [I, check live], so only there a failed read counts as false.
155
+ try { $uc = [bool](Invoke-Busy { $c.UserControl }) } catch { if ($key -ne 'powerpoint') { throw } }
156
+ if ($n -ne 0 -or $uc) {
157
+ # The person has documents in it or took it over: it is theirs now. Released, never touched again.
158
+ Drop-App $key
159
+ return @{ refused = $true; documents = $n; userControl = $uc }
160
+ }
161
+ Invoke-Busy { $c.Quit() } | Out-Null
162
+ Drop-App $key
163
+ @{ quit = $true }
164
+ }
165
+ $Ops['procInfo'] = {
166
+ param($a)
167
+ $p = Get-Process -Id ([int]$a.pid) -ErrorAction SilentlyContinue
168
+ if ($null -eq $p) { return @{ gone = $true } }
169
+ # MainWindowHandle is non-zero only for a visible, unowned top-level window. An unreadable start time throws: Node then refuses.
170
+ @{ image = [string]$p.ProcessName; startedAtMs = [long](Get-StartMs $p); visibleWindow = ($p.MainWindowHandle -ne [IntPtr]::Zero) }
171
+ }
172
+
173
+ # --- export ops ---
174
+ # exportPdf {app, input, pdf, printer} and openDocuments {app} act only on the Office this host launched ($script:Apps[$key].com, set
175
+ # by launch); pdfPrinter {app} reads what Node needs to pick the PDF printer. Recipes are the ones proven on a real Windows machine: every COM argument typed, the pdf's folder made before the export, every
176
+ # call through Invoke-Busy. The person's Windows default printer is never changed: Word is redirected only with FilePrintSetup and
177
+ # DoNotSetAsSysDefault = 1 (its ActivePrinter is only ever read: assigning it changes the Windows default); Excel's ActivePrinter is set
178
+ # on the open workbook's instance. A redirect whose read-back does not name the PDF printer exports nothing (caveat no-local-pdf-printer),
179
+ # so an export never waits on a dead network printer.
180
+ $script:WordPrinter = $null
181
+ $DummyPassword = 'cocheck-no-password'
182
+ $NoPrinter = @{ ok = $false; why = 'no local PDF printer'; caveat = 'no-local-pdf-printer' }
183
+ $NoSetup = @{ ok = $false; why = 'PDF printer setup did not take'; caveat = 'pdf-printer-setup-failed' }
184
+
185
+ function Get-OurApp([string]$Key) {
186
+ $e = $script:Apps[$Key]
187
+ if ($null -eq $e -or $null -eq $e.com) { return $null }
188
+ return $e.com
189
+ }
190
+
191
+ # The read-back names the printer: the full '<name> <on> <port>', or (Word only, as the laptop read it) the bare name.
192
+ function Test-ReadBack([string]$Got, $p, [bool]$BareOk) {
193
+ if ($null -eq $p) { return $false }
194
+ return ($Got -eq [string]$p.full) -or ($BareOk -and $Got -eq [string]$p.name)
195
+ }
196
+
197
+ function Export-PowerPoint($com, $a) {
198
+ $doc = Invoke-Busy { $com.Presentations.Open([string]$a.input, [int]-1, [int]0, [int]0) }
199
+ try {
200
+ [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName([string]$a.pdf))
201
+ Invoke-Busy { $doc.SaveCopyAs([string]$a.pdf, [int]32) }
202
+ } finally {
203
+ Invoke-Busy { $doc.Close() }
204
+ }
205
+ @{}
206
+ }
207
+
208
+ function Export-Word($com, $a) {
209
+ $p = $a.printer
210
+ if ($null -eq $p) { return $NoPrinter }
211
+ if ($script:WordPrinter -ne [string]$p.full) {
212
+ # once per host, before any document: FilePrintSetup with typed, named arguments (the WordBasic call takes no positional ones)
213
+ $wb = Invoke-Busy { $com.WordBasic }
214
+ Invoke-Busy { [void]$wb.GetType().InvokeMember('FilePrintSetup', [Reflection.BindingFlags]::InvokeMethod, $null, $wb, [object[]]@([string]$p.full, [int]1), $null, $null, [string[]]@('Printer', 'DoNotSetAsSysDefault')) }
215
+ $got = [string](Invoke-Busy { $com.ActivePrinter })
216
+ if (-not (Test-ReadBack $got $p $true)) { return $NoSetup }
217
+ $script:WordPrinter = [string]$p.full
218
+ }
219
+ $doc = Invoke-Busy { $com.Documents.Open([string]$a.input, [bool]$false, [bool]$true, [bool]$false, [string]$DummyPassword) }
220
+ try {
221
+ [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName([string]$a.pdf))
222
+ Invoke-Busy { $doc.ExportAsFixedFormat([string]$a.pdf, [int]17) }
223
+ } finally {
224
+ Invoke-Busy { $doc.Close([int]0) }
225
+ }
226
+ @{}
227
+ }
228
+
229
+ function Export-Excel($com, $a) {
230
+ $p = $a.printer
231
+ if ($null -eq $p) { return $NoPrinter }
232
+ $doc = Invoke-Busy { $com.Workbooks.Open([string]$a.input, [int]0, [bool]$true, [Type]::Missing, [string]$DummyPassword) }
233
+ try {
234
+ # after the open (with no workbook it fails 0x800A03EC); the instance's printer, not Windows' default
235
+ $got = Set-ExcelPrinter $com $p
236
+ if (-not (Test-ReadBack $got $p $false)) { return $NoSetup }
237
+ [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName([string]$a.pdf))
238
+ Invoke-Busy { $doc.ExportAsFixedFormat([int]0, [string]$a.pdf) }
239
+ } finally {
240
+ Invoke-Busy { $doc.Close([bool]$false) }
241
+ }
242
+ @{}
243
+ }
244
+
245
+ $Ops['pdfPrinter'] = {
246
+ param($a)
247
+ $com = Get-OurApp ([string]$a.app)
248
+ if ($null -eq $com) { return @{ ok = $false; why = 'not launched' } }
249
+ $devices = @{}
250
+ $key = 'HKCU:\Software\Microsoft\Windows NT\CurrentVersion\Devices'
251
+ if (Test-Path -LiteralPath $key) {
252
+ $item = Get-Item -LiteralPath $key
253
+ foreach ($n in $item.GetValueNames()) { $devices[[string]$n] = [string]$item.GetValue($n) }
254
+ }
255
+ $active = ''
256
+ try { $active = [string](Invoke-Busy { $com.ActivePrinter }) } catch { $active = '' }
257
+ @{ devices = $devices; active = $active }
258
+ }
259
+
260
+ $Ops['exportPdf'] = {
261
+ param($a)
262
+ $key = [string]$a.app
263
+ $com = Get-OurApp $key
264
+ if ($null -eq $com) { return @{ ok = $false; why = 'not launched' } }
265
+ switch ($key) {
266
+ 'powerpoint' { Export-PowerPoint $com $a }
267
+ 'word' { Export-Word $com $a }
268
+ 'excel' { Export-Excel $com $a }
269
+ default { @{ ok = $false; why = "unknown app: $key" } }
270
+ }
271
+ }
272
+
273
+ $Ops['openDocuments'] = {
274
+ param($a)
275
+ $key = [string]$a.app
276
+ $com = Get-OurApp $key
277
+ if ($null -eq $com) { return @{ ok = $false; why = 'not launched' } }
278
+ $coll = switch ($key) { 'excel' { Invoke-Busy { $com.Workbooks } } 'word' { Invoke-Busy { $com.Documents } } default { Invoke-Busy { $com.Presentations } } }
279
+ $names = @()
280
+ foreach ($d in $coll) { $names += [string](Invoke-Busy { $d.FullName }) }
281
+ @{ names = [object[]]$names }
282
+ }
283
+ # --- window list ---
284
+ # Read-only: the top-level windows of one pid AND every descendant element of ControlType Window under them (an app's owned modal dialogs are
285
+ # children of their owner window in UI Automation, not of the desktop), through .NET UI Automation loaded by assembly name. Reads properties
286
+ # only; it never touches a window. Cost bound: the descendant query is limited to the Window control type and every property read comes from
287
+ # one CacheRequest, so each row costs no further cross-process calls; the client also holds the whole call to its 5 s timeout. A window whose
288
+ # property read throws is skipped, not a failed list. Rows with handle 0 are skipped; a handle is listed once.
289
+ $Ops['windows'] = {
290
+ param($a)
291
+ [void][System.Reflection.Assembly]::Load('UIAutomationTypes, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35')
292
+ [void][System.Reflection.Assembly]::Load('UIAutomationClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35')
293
+ $procId = [int]$a.pid
294
+ $AE = [System.Windows.Automation.AutomationElement]
295
+ $pidCond = New-Object System.Windows.Automation.PropertyCondition($AE::ProcessIdProperty, $procId)
296
+ $winCond = New-Object System.Windows.Automation.PropertyCondition($AE::ControlTypeProperty, [System.Windows.Automation.ControlType]::Window)
297
+ $cache = New-Object System.Windows.Automation.CacheRequest
298
+ $cache.Add($AE::NativeWindowHandleProperty)
299
+ $cache.Add($AE::NameProperty)
300
+ $cache.Add($AE::BoundingRectangleProperty)
301
+ $cache.Add($AE::IsOffscreenProperty)
302
+ $cache.Add([System.Windows.Automation.WindowPattern]::WindowVisualStateProperty)
303
+ $cache.Add([System.Windows.Automation.WindowPattern]::Pattern)
304
+ $cache.TreeScope = [System.Windows.Automation.TreeScope]::Element
305
+ $els = New-Object System.Collections.ArrayList
306
+ $cache.Push()
307
+ try {
308
+ $tops = $AE::RootElement.FindAll([System.Windows.Automation.TreeScope]::Children, $pidCond)
309
+ foreach ($t in $tops) {
310
+ [void]$els.Add($t)
311
+ try {
312
+ $nested = $t.FindAll([System.Windows.Automation.TreeScope]::Descendants, $winCond)
313
+ foreach ($n in $nested) { [void]$els.Add($n) }
314
+ } catch { continue }
315
+ }
316
+ } finally { $cache.Pop() }
317
+ $list = New-Object System.Collections.ArrayList
318
+ $seen = @{}
319
+ foreach ($el in $els) {
320
+ try {
321
+ $cur = $el.Cached
322
+ $handle = [int]$cur.NativeWindowHandle
323
+ if ($handle -eq 0 -or $seen.ContainsKey($handle)) { continue }
324
+ $seen[$handle] = $true
325
+ $r = $cur.BoundingRectangle
326
+ $fin = { param($v) if ([double]::IsInfinity($v) -or [double]::IsNaN($v)) { 0 } else { [int]$v } }
327
+ $minimized = $false
328
+ $pat = $null
329
+ if ($el.TryGetCachedPattern([System.Windows.Automation.WindowPattern]::Pattern, [ref]$pat)) {
330
+ $minimized = ($pat.Cached.WindowVisualState -eq [System.Windows.Automation.WindowVisualState]::Minimized)
331
+ }
332
+ [void]$list.Add(@{
333
+ id = $handle
334
+ layer = 0
335
+ title = [string]$cur.Name
336
+ bounds = @{ x = (& $fin $r.X); y = (& $fin $r.Y); w = (& $fin $r.Width); h = (& $fin $r.Height) }
337
+ onscreen = ((-not $cur.IsOffscreen) -and (-not $minimized))
338
+ })
339
+ } catch { continue }
340
+ }
341
+ @{ windows = @($list) }
342
+ }
343
+ # --- end window list ---
344
+
345
+ # --- export targets ---
346
+ # exportTargets {app, input, targets, pdfs, printer}: Excel only, one PDF per target sheet from one read-only open of the workbook
347
+ # (the same Workbooks.Open and printer redirect as Export-Excel). Per target: PrintCommunication off, that sheet's PageSetup (PrintArea
348
+ # from area for a worksheet; Zoom as an int, which makes Excel ignore the fit-to-pages properties, so those are never touched; Orientation
349
+ # landscape 2 / portrait 1; a chart sheet takes Orientation only, landscape as on the Mac), PrintCommunication on and read back,
350
+ # PrintArea read back, then that sheet's own ExportAsFixedFormat. No sheet's visibility is touched. PrintCommunication is restored in
351
+ # a finally on every path, and once more before the workbook closes (unsaved). A failed target is {ok=false, why}; the rest go on.
352
+ # Excel's one ActivePrinter assignment (shared by Export-Excel and exportTargets): the instance's printer, returning what Excel reads back.
353
+ function Set-ExcelPrinter($com, $p) {
354
+ Invoke-Busy { $com.ActivePrinter = [string]$p.full }
355
+ return [string](Invoke-Busy { $com.ActivePrinter })
356
+ }
357
+
358
+ function Export-ExcelTarget($com, $doc, $t, [string]$pdf) {
359
+ $sh = Invoke-Busy { $doc.Sheets.Item([string]$t.sheet) }
360
+ $isChart = ([string]$t.kind -eq 'chartsheet')
361
+ $orient = if ($isChart -or [bool]$t.landscape) { [int]2 } else { [int]1 }
362
+ $zoom = [int][Math]::Max(10, [Math]::Min(400, [Math]::Round([double]$t.zoom)))
363
+ try {
364
+ Invoke-Busy { $com.PrintCommunication = [bool]$false }
365
+ $ps = Invoke-Busy { $sh.PageSetup }
366
+ if (-not $isChart) {
367
+ Invoke-Busy { $ps.PrintTitleRows = '' }
368
+ Invoke-Busy { $ps.PrintTitleColumns = '' }
369
+ Invoke-Busy { $ps.PrintArea = [string]$t.area }
370
+ # Headings and gridlines on, as on the Mac: the box finder places changes by the printed row and column headings.
371
+ Invoke-Busy { $ps.PrintHeadings = [bool]$true }
372
+ Invoke-Busy { $ps.PrintGridlines = [bool]$true }
373
+ Invoke-Busy { $ps.BlackAndWhite = [bool]$false }
374
+ Invoke-Busy { $ps.CenterHorizontally = [bool]$false }
375
+ Invoke-Busy { $ps.CenterVertically = [bool]$false }
376
+ Invoke-Busy { $ps.Draft = [bool]$false }
377
+ Invoke-Busy { $ps.Zoom = $zoom }
378
+ }
379
+ Invoke-Busy { $ps.Orientation = $orient }
380
+ } finally {
381
+ Invoke-Busy { $com.PrintCommunication = [bool]$true }
382
+ if (-not [bool](Invoke-Busy { $com.PrintCommunication })) { throw 'PrintCommunication did not turn back on' }
383
+ }
384
+ $back = ''
385
+ if (-not $isChart) {
386
+ # Read back as on the Mac: the zoom and the four flags are the file's own print settings that would otherwise leak into the picture.
387
+ $zb = Invoke-Busy { $ps.Zoom }
388
+ if ([int]$zb -ne $zoom) { throw "the print zoom read back as $zb, not $zoom" }
389
+ if ([bool](Invoke-Busy { $ps.BlackAndWhite })) { throw 'the print setting black and white read back as true, not false' }
390
+ if ([bool](Invoke-Busy { $ps.CenterHorizontally })) { throw 'the print setting center horizontally read back as true, not false' }
391
+ if ([bool](Invoke-Busy { $ps.CenterVertically })) { throw 'the print setting center vertically read back as true, not false' }
392
+ if ([bool](Invoke-Busy { $ps.Draft })) { throw 'the print setting draft read back as true, not false' }
393
+ $back = [string](Invoke-Busy { $ps.PrintArea })
394
+ }
395
+ [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($pdf))
396
+ Invoke-Busy { $sh.ExportAsFixedFormat([int]0, [string]$pdf) }
397
+ return $back
398
+ }
399
+
400
+ $Ops['exportTargets'] = {
401
+ param($a)
402
+ $com = Get-OurApp ([string]$a.app)
403
+ if ($null -eq $com) { return @{ ok = $false; why = 'not launched' } }
404
+ if ([string]$a.app -ne 'excel') { return @{ ok = $false; why = 'cannot print sheets one by one' } }
405
+ $p = $a.printer
406
+ if ($null -eq $p) { return $NoPrinter }
407
+ $doc = Invoke-Busy { $com.Workbooks.Open([string]$a.input, [int]0, [bool]$true, [Type]::Missing, [string]$DummyPassword) }
408
+ $results = @()
409
+ try {
410
+ $got = Set-ExcelPrinter $com $p
411
+ if (-not (Test-ReadBack $got $p $false)) { return $NoSetup }
412
+ $i = 0
413
+ foreach ($t in @($a.targets)) {
414
+ try {
415
+ $back = Export-ExcelTarget $com $doc $t ([string]@($a.pdfs)[$i])
416
+ $r = @{ ok = $true }
417
+ if ($back -ne '') { $r.readBack = $back }
418
+ $results += ,$r
419
+ } catch {
420
+ $results += ,@{ ok = $false; why = [string]$_.Exception.Message }
421
+ }
422
+ $i++
423
+ }
424
+ } finally {
425
+ try { Invoke-Busy { $com.PrintCommunication = [bool]$true } } catch { }
426
+ Invoke-Busy { $doc.Close([bool]$false) }
427
+ }
428
+ @{ results = [object[]]$results }
429
+ }
430
+
431
+ while (-not $script:Quit) {
432
+ $line = $stdin.ReadLine()
433
+ if ($null -eq $line) { break }
434
+ if ($line.Trim() -eq '') { continue }
435
+ $id = $null
436
+ try {
437
+ $req = ConvertFrom-Json $line
438
+ $id = $req.id
439
+ $op = $Ops[[string]$req.op]
440
+ if ($null -eq $op) {
441
+ Send-Reply @{ id = $id; ok = $false; why = "unknown op: $($req.op)" }
442
+ continue
443
+ }
444
+ $r = & $op $req.args | Where-Object { $_ -is [hashtable] } | Select-Object -Last 1
445
+ $reply = @{ id = $id; ok = $true }
446
+ if ($null -ne $r) { foreach ($k in $r.Keys) { $reply[$k] = $r[$k] } }
447
+ Send-Reply $reply
448
+ } catch {
449
+ Send-Reply @{ id = $id; ok = $false; why = $_.Exception.Message }
450
+ }
451
+ }
@@ -0,0 +1,46 @@
1
+ export const PROMPT_TICK_MS = 250;
2
+ export const PROMPT_HOLD_MS = 1_500;
3
+ export const PROMPT_CONFIRMATIONS = 2;
4
+ export const PROMPT_CONFIRM_MS = 1_500;
5
+ const stray = (w, before, names) => w.layer === 0 && w.bounds.w > 1 && w.bounds.h > 1 && !before.has(w.id) && !names.some((n) => n !== "" && w.title.includes(n));
6
+ /**
7
+ * Races the open `call` against the window list. Answers `{ done }` when the call settles first, or `{ prompt }` once a stray window has stayed listed `holdMs` while the call is
8
+ * still pending. The call is never cancelled here: after a prompt the caller stops the app it launched (which ends the call), and nothing in the prompt is ever clicked.
9
+ */
10
+ export async function watchedOpen(call, o) {
11
+ const now = o.now ?? Date.now;
12
+ const tick = o.tickMs ?? PROMPT_TICK_MS, hold = o.holdMs ?? PROMPT_HOLD_MS;
13
+ const t0 = now();
14
+ let settled;
15
+ let failure;
16
+ const done = call.then((v) => { settled = { v }; }, (e) => { failure = { e }; });
17
+ let since, absent = 0;
18
+ const pending = () => settled === undefined && failure === undefined;
19
+ for (;;) {
20
+ const waited = await Promise.race([done.then(() => true), new Promise((r) => setTimeout(() => r(false), tick))]);
21
+ if (waited || !pending())
22
+ break;
23
+ const list = await o.helper.windows(o.pid).catch(() => ({ ok: false, why: "no answer" }));
24
+ if (!pending())
25
+ break;
26
+ const found = list.ok ? list.windows.filter((w) => stray(w, o.before, o.names)) : [];
27
+ if (found.length === 0) {
28
+ since = undefined;
29
+ absent = 0;
30
+ continue;
31
+ }
32
+ since ??= now();
33
+ if (now() - since < hold || o.confirm === undefined)
34
+ continue;
35
+ // the window held: the app must also answer its document list, without the copy, while the open is still pending
36
+ const said = await o.confirm(o.confirmMs ?? PROMPT_CONFIRM_MS).catch(() => "no-answer");
37
+ if (!pending())
38
+ break;
39
+ absent = said === "absent" ? absent + 1 : 0;
40
+ if (absent >= (o.confirmations ?? PROMPT_CONFIRMATIONS))
41
+ return { prompt: { afterMs: since - t0, windows: found.map((w) => ({ id: w.id, w: w.bounds.w, h: w.bounds.h })) } };
42
+ }
43
+ if (failure !== undefined)
44
+ throw failure.e;
45
+ return { done: settled.v };
46
+ }
@@ -0,0 +1,156 @@
1
+ // Office's PDF pages as level-2 `image` pictures. The app's own PDF is the picture: CoCheck never renders an Office page itself. The shipped pdfpages helper rasterizes it (Word's paragraph finding is pdf.js in public-kit/helpers/pdf-text.mjs, used by word-boxes.ts). No boxes here: this file draws pages only.
2
+ //
3
+ // Changed or unchanged, kept simple: page n of one side is `unchanged` only when the other side has a page n whose text runs (from
4
+ // `pdfpages <pdf>`) are the same and whose PNG bytes are identical; anything else, including a page the other side does not have or whose
5
+ // picture was left out, is `changed`. A false "unchanged" must never happen, so every doubt reads "changed".
6
+ import { createHash } from "node:crypto";
7
+ import { hostPlatform } from "../../platform/index.js";
8
+ import { renderPdfBytesPages, renderPdfPage } from "../../../public-kit/helpers/pdf.mjs";
9
+ import { findPdfParagraphs, readDrawnPdfText } from "../../../public-kit/helpers/pdf-text.mjs";
10
+ /** The published helpers: page text and the finder from the pdf.js reader (pdf-text.mjs), pages drawn by this OS's backend (pdf.mjs). */
11
+ export const helperPager = {
12
+ async pages(pdf) {
13
+ const r = await readDrawnPdfText(pdf);
14
+ return r.pages === null ? null : r.pages.map((p) => p.runs.map((x) => x.text).join("\n"));
15
+ },
16
+ png: (pdf, n) => renderPdfPage(pdf, n),
17
+ // Windows only: one powershell.exe call per side instead of one per page. The Mac has no `pngs` and keeps its one pdfpages call per page.
18
+ ...(hostPlatform()?.name === "win32" ? { pngs: (pdf, pages, timeoutMs) => renderPdfBytesPages(pdf, pages, timeoutMs === undefined ? {} : { timeoutMs }) } : {}),
19
+ find: (pdf, queries) => findPdfParagraphs(pdf, queries),
20
+ };
21
+ /**
22
+ * Who drew an Office connector's pictures: the app's name, the version the driver reads (`appVersion`, which never starts or wakes the app) or
23
+ * "unknown", and the OS name. Never an empty string.
24
+ */
25
+ export async function renderedByFor(app, driver) {
26
+ let version;
27
+ try {
28
+ version = (await driver?.appVersion?.(app))?.trim();
29
+ }
30
+ catch {
31
+ version = undefined;
32
+ }
33
+ return { tool: app.name, version: version ? version : "unknown", os: hostPlatform()?.name || "unknown" };
34
+ }
35
+ /** Puts `renderedBy` on every picture of `doc` that has none (placeholders too: no picture is sent without it). */
36
+ export async function stampRenderedBy(doc, app, driver) {
37
+ const list = doc.pictures;
38
+ if (list === undefined || list.length === 0)
39
+ return;
40
+ const rb = await renderedByFor(app, driver);
41
+ for (const p of list)
42
+ if (p.renderedBy === undefined)
43
+ p.renderedBy = { ...rb };
44
+ }
45
+ /** Spec: an image is limited to 4 MiB. */
46
+ export const MAX_PICTURE_BYTES = 4 * 1024 * 1024;
47
+ /** Pages drawn per side at most; the rest are named in a caveat (keeps the job inside diffMs, with the time limit `drawBy`). */
48
+ export const MAX_PAGES_PER_SIDE = 30;
49
+ const PNG_PREFIX = "data:image/png;base64,";
50
+ /** Width and height from a PNG's IHDR, or undefined. */
51
+ export function pngSize(png) {
52
+ if (png.length < 24 || png.readUInt32BE(0) !== 0x89504e47 || png.toString("latin1", 12, 16) !== "IHDR")
53
+ return undefined;
54
+ return { width: png.readUInt32BE(16), height: png.readUInt32BE(20) };
55
+ }
56
+ const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
57
+ const ranges = (ns) => {
58
+ const out = [];
59
+ for (let i = 0; i < ns.length;) {
60
+ let j = i;
61
+ while (j + 1 < ns.length && ns[j + 1] === ns[j] + 1)
62
+ j++;
63
+ out.push(i === j ? `${ns[i]}` : `${ns[i]}-${ns[j]}`);
64
+ i = j + 1;
65
+ }
66
+ return out.join(", ");
67
+ };
68
+ /**
69
+ * Pictures for the sides that have a PDF, within `budget` bytes of data URLs (the answer line must stay under 16 MB). Pages are taken in the
70
+ * order before 1, after 1, before 2, after 2, ..., so a cut leaves both sides' first pages. `appName` names who drew them in caveats. No page
71
+ * is started at or after `drawBy` (epoch ms): the rest are left out with the same caveat.
72
+ */
73
+ export async function pdfPictures(pdfs, pager, budget, appName, time = {}) {
74
+ const now = time.now ?? Date.now;
75
+ const late = () => time.drawBy !== undefined && now() >= time.drawBy;
76
+ const caveats = [];
77
+ const sides = ["before", "after"].filter((s) => pdfs[s] !== undefined);
78
+ const texts = {};
79
+ for (const s of sides) {
80
+ const t = await pager.pages(pdfs[s]);
81
+ if (t === null)
82
+ caveats.push(`${cap(s)}: ${appName}'s PDF could not be read, so no page is shown.`);
83
+ else if (t.length === 0)
84
+ caveats.push(`${cap(s)}: ${appName}'s PDF has no pages.`);
85
+ else
86
+ texts[s] = t;
87
+ }
88
+ const pngs = { before: new Map(), after: new Map() };
89
+ const left = { before: [], after: [] };
90
+ // A batch pager draws each side's wanted pages in one call, before the budget is applied (a page over the budget is drawn and dropped).
91
+ const batch = { before: new Map(), after: new Map() };
92
+ if (pager.pngs !== undefined) {
93
+ for (const s of sides) {
94
+ const t = texts[s];
95
+ if (t === undefined || late())
96
+ continue;
97
+ const wanted = Array.from({ length: Math.min(t.length, MAX_PAGES_PER_SIDE) }, (_, i) => i + 1);
98
+ const limit = time.drawBy === undefined ? undefined : Math.max(1, time.drawBy - now());
99
+ try {
100
+ batch[s] = await pager.pngs(pdfs[s], wanted, limit);
101
+ }
102
+ catch {
103
+ batch[s] = new Map();
104
+ }
105
+ }
106
+ }
107
+ let used = 0;
108
+ const most = Math.max(texts.before?.length ?? 0, texts.after?.length ?? 0);
109
+ for (let n = 1; n <= most; n++) {
110
+ for (const s of sides) {
111
+ const t = texts[s];
112
+ if (t === undefined || n > t.length)
113
+ continue;
114
+ if (n > MAX_PAGES_PER_SIDE || late()) {
115
+ left[s].push(n);
116
+ continue;
117
+ }
118
+ const png = pager.pngs !== undefined ? (batch[s].get(n) ?? null) : await pager.png(pdfs[s], n);
119
+ const cost = png === null ? 0 : PNG_PREFIX.length + Math.ceil(png.length / 3) * 4;
120
+ if (png === null || png.length > MAX_PICTURE_BYTES || used + cost > budget) {
121
+ left[s].push(n);
122
+ continue;
123
+ }
124
+ used += cost;
125
+ pngs[s].set(n, png);
126
+ }
127
+ }
128
+ for (const s of sides)
129
+ if (left[s].length > 0)
130
+ caveats.push(`${cap(s)}: page${left[s].length === 1 ? "" : "s"} ${ranges(left[s])} of ${texts[s].length} not shown (over the page or size limit of one answer, or not drawn).`);
131
+ const sha = (b) => createHash("sha256").update(b).digest("hex");
132
+ const pictures = [];
133
+ for (const s of sides) {
134
+ const t = texts[s];
135
+ if (t === undefined)
136
+ continue;
137
+ const other = s === "before" ? "after" : "before";
138
+ for (const [n, png] of [...pngs[s]].sort((a, b) => a[0] - b[0])) {
139
+ const o = pngs[other].get(n);
140
+ const same = o !== undefined && texts[other]?.[n - 1] === t[n - 1] && sha(o) === sha(png);
141
+ const size = pngSize(png);
142
+ pictures.push({
143
+ id: `${s}:page${n}`,
144
+ side: s,
145
+ type: "image",
146
+ src: PNG_PREFIX + png.toString("base64"),
147
+ label: `${cap(s)}, page ${n} of ${t.length}`,
148
+ ...(size ?? {}),
149
+ page: n,
150
+ pageCount: t.length,
151
+ ...(same ? { unchanged: true } : { changed: true }),
152
+ });
153
+ }
154
+ }
155
+ return { pictures, caveats };
156
+ }