dsh-builtin-browser 1.0.1 → 1.0.3

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 (360) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/assets/browser-panel-locales.mjs +37 -5
  4. package/assets/browser-policy.d.mts +29 -0
  5. package/assets/browser-policy.mjs +40 -0
  6. package/desktop-bridge/desktop-discovery.d.mts +1 -1
  7. package/desktop-bridge/desktop-discovery.mjs +59 -9
  8. package/desktop-bridge/desktop-identity.json +12 -0
  9. package/desktop-bridge/install.mjs +14 -7
  10. package/desktop-bridge/plugin-browser-bridge.js +19 -7
  11. package/docs/acceptance-2026-11-27.md +67 -0
  12. package/docs/architecture.md +1 -1
  13. package/docs/development.md +33 -4
  14. package/docs/dsh-0.2.3-host-patch-task.md +34 -0
  15. package/docs/hardcoding-audit.md +28 -8
  16. package/docs/known-issues.md +26 -0
  17. package/docs/limitations.md +6 -2
  18. package/docs/tool-reference.md +1 -1
  19. package/docs/v1.1.0-bu-data-batching-task.md +66 -0
  20. package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
  21. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  22. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  23. package/dsh-host-patch/README.md +4 -0
  24. package/dsh-host-patch/apply.mjs +61 -13
  25. package/dsh-host-patch/rc3-revision9.json.gz +0 -0
  26. package/dsh-host-patch/rc5-revision9.json.gz +0 -0
  27. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  28. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  29. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  30. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  31. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  32. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  33. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  34. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  35. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  36. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  37. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  38. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  39. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  40. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  41. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  42. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  43. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  44. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  45. package/dsh-host-patch/sources/manifest.json +218 -0
  46. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  47. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  48. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  49. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  50. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  51. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  52. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  53. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  54. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  55. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  56. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  57. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  58. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  59. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  60. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  61. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  62. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  63. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  64. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  65. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  66. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  67. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  68. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  69. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  70. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  71. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  72. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  73. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  74. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  75. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  76. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  77. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  78. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  79. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  80. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  81. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  82. package/dsh-host-patch/sources/series.json +260 -0
  83. package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
  84. package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
  85. package/dsh-host-patch/tauri-revision1.json +39 -0
  86. package/dsh-host-patch/tauri.json +43 -0
  87. package/dsh-host-patch/v023-alpha2.json +153 -0
  88. package/lib/browser/anti-bot.js +215 -0
  89. package/lib/browser/deep-dom.js +39 -0
  90. package/lib/browser/runtime.js +15 -0
  91. package/lib/browser/takeover-target.js +13 -6
  92. package/lib/browser/types.js +30 -1
  93. package/lib/browser-electron/authenticated-route.js +16 -2
  94. package/lib/browser-electron/automatic-maintenance.js +16 -10
  95. package/lib/browser-electron/bridge-connection.js +3 -8
  96. package/lib/browser-electron/bridge-install.js +2 -1
  97. package/lib/browser-electron/bridge-status.js +55 -26
  98. package/lib/browser-electron/desktop-bridge-host.js +7 -6
  99. package/lib/browser-electron/desktop-identity.js +28 -5
  100. package/lib/browser-electron/desktop-shell.js +64 -0
  101. package/lib/browser-electron/electron-provision.js +105 -18
  102. package/lib/browser-electron/entry.js +129 -44
  103. package/lib/browser-electron/extension-browser.js +4 -4
  104. package/lib/browser-electron/foreground-watch.js +134 -0
  105. package/lib/browser-electron/guest-cookie-jar.js +13 -13
  106. package/lib/browser-electron/guest-route.js +181 -32
  107. package/lib/browser-electron/guest-runtime.js +61 -10
  108. package/lib/browser-electron/guest-storage.js +2 -2
  109. package/lib/browser-electron/history-store.js +1 -5
  110. package/lib/browser-electron/host-main.js +8 -4
  111. package/lib/browser-electron/host-patch-maintenance.js +14 -8
  112. package/lib/browser-electron/maintenance-route.js +2 -1
  113. package/lib/browser-electron/missing-system-browser.js +5 -9
  114. package/lib/browser-electron/preferred-browser.js +7 -3
  115. package/lib/browser-electron/preview-route.js +9 -13
  116. package/lib/browser-electron/process-ownership.js +1 -1
  117. package/lib/browser-electron/profile-command.js +2 -1
  118. package/lib/browser-electron/profile-extension.js +5 -0
  119. package/lib/browser-electron/profile-lease.js +152 -47
  120. package/lib/browser-electron/provider-core.js +527 -0
  121. package/lib/browser-electron/provider-interaction.js +963 -0
  122. package/lib/browser-electron/provider-media.js +518 -0
  123. package/lib/browser-electron/provider-navigation.js +301 -0
  124. package/lib/browser-electron/provider-observation.js +623 -0
  125. package/lib/browser-electron/provider-tabs.js +372 -0
  126. package/lib/browser-electron/provider.js +150 -3301
  127. package/lib/browser-electron/reference-route.js +9 -18
  128. package/lib/browser-electron/remote-host.js +79 -34
  129. package/lib/browser-electron/runtime-status.js +56 -6
  130. package/lib/browser-electron/settings-store.js +3 -6
  131. package/lib/browser-electron/sidebar-only-host.js +1 -1
  132. package/lib/browser-electron/system-browser.js +539 -172
  133. package/lib/browser-electron/tauri-host.js +208 -0
  134. package/lib/browser-electron/virtual-cursor.js +23 -13
  135. package/lib/browser-reference/service.js +22 -4
  136. package/lib/browser-reference/web-sources.js +1 -1
  137. package/lib/client.js +43409 -0
  138. package/lib/compat/host-features.js +75 -0
  139. package/lib/reference-source.js +1 -1
  140. package/lib/reference-text.js +23 -1
  141. package/lib/takeover-protocol.js +1 -1
  142. package/lib/tool-browser/block-recovery.js +69 -0
  143. package/lib/tool-browser/code-tool.js +170 -19
  144. package/lib/tool-browser/code-worker.js +115 -20
  145. package/lib/tool-browser/errors.js +34 -0
  146. package/lib/tool-browser/index.js +66 -3593
  147. package/lib/tool-browser/page-probe.js +227 -28
  148. package/lib/tool-browser/panel-page.js +2 -1
  149. package/lib/tool-browser/probe-client.js +157 -0
  150. package/lib/tool-browser/screenshot-annotations.js +108 -0
  151. package/lib/tool-browser/state.js +337 -0
  152. package/lib/tool-browser/takeover.js +1 -1
  153. package/lib/tool-browser/tools-debug.js +862 -0
  154. package/lib/tool-browser/tools-interaction.js +993 -0
  155. package/lib/tool-browser/tools-navigation.js +807 -0
  156. package/lib/tool-browser/tools-observation.js +461 -0
  157. package/lib/tool-browser/tools-reference.js +293 -0
  158. package/lib/web-guest.js +1 -0
  159. package/package.json +15 -53
  160. package/README.en.md +0 -89
  161. package/browser-extension/constants.mjs +0 -20
  162. package/browser-extension/controller.mjs +0 -293
  163. package/browser-extension/locales.mjs +0 -15
  164. package/browser-extension/manifest.json +0 -12
  165. package/browser-extension/options.html +0 -14
  166. package/browser-extension/options.mjs +0 -9
  167. package/browser-extension/permission-guard.mjs +0 -13
  168. package/browser-extension/worker.mjs +0 -74
  169. package/dist/client.cjs +0 -43167
  170. package/lib/browser-reference/submission-receipts.js +0 -139
  171. package/scripts/build.mjs +0 -66
  172. package/scripts/bundle-host.mjs +0 -28
  173. package/scripts/fix-exports.mjs +0 -50
  174. package/scripts/install-electron.mjs +0 -51
  175. package/scripts/verify-exports.mjs +0 -47
  176. package/scripts/verify-preview-sdk.mjs +0 -93
  177. package/skills/dsh-builtin-browser/SKILL.md +0 -73
  178. package/skills/dsh-builtin-browser/references/batch.md +0 -53
  179. package/skills/dsh-builtin-browser/references/deliver.md +0 -31
  180. package/skills/dsh-builtin-browser/references/locate.md +0 -11
  181. package/skills/dsh-builtin-browser/references/recover.md +0 -11
  182. package/skills/dsh-builtin-browser/references/verify.md +0 -13
  183. package/skills/dsh-debug-host/SKILL.md +0 -56
  184. package/skills/dsh-debug-self/SKILL.md +0 -50
  185. package/src/bridge-compatibility.ts +0 -39
  186. package/src/browser/handles.ts +0 -89
  187. package/src/browser/runtime.ts +0 -560
  188. package/src/browser/takeover-target.ts +0 -36
  189. package/src/browser/types.ts +0 -817
  190. package/src/browser-electron/authenticated-route.ts +0 -84
  191. package/src/browser-electron/automatic-maintenance.ts +0 -726
  192. package/src/browser-electron/bridge-auto.ts +0 -159
  193. package/src/browser-electron/bridge-connection.ts +0 -385
  194. package/src/browser-electron/bridge-endpoint.ts +0 -129
  195. package/src/browser-electron/bridge-install.ts +0 -289
  196. package/src/browser-electron/bridge-maintenance.ts +0 -189
  197. package/src/browser-electron/bridge-status.ts +0 -347
  198. package/src/browser-electron/desktop-bridge-host.ts +0 -251
  199. package/src/browser-electron/desktop-identity.ts +0 -320
  200. package/src/browser-electron/document-readiness.ts +0 -45
  201. package/src/browser-electron/electron-provision.ts +0 -261
  202. package/src/browser-electron/entry.ts +0 -1299
  203. package/src/browser-electron/ephemeral-profile.ts +0 -189
  204. package/src/browser-electron/extension-browser.ts +0 -223
  205. package/src/browser-electron/extension-setup.ts +0 -67
  206. package/src/browser-electron/file-write.ts +0 -31
  207. package/src/browser-electron/guest-cookie-jar.ts +0 -176
  208. package/src/browser-electron/guest-cookie-store.ts +0 -59
  209. package/src/browser-electron/guest-css-runtime.ts +0 -76
  210. package/src/browser-electron/guest-css.ts +0 -68
  211. package/src/browser-electron/guest-route.ts +0 -568
  212. package/src/browser-electron/guest-runtime.ts +0 -357
  213. package/src/browser-electron/guest-storage-runtime.ts +0 -54
  214. package/src/browser-electron/guest-storage.ts +0 -117
  215. package/src/browser-electron/history-store.ts +0 -227
  216. package/src/browser-electron/host-main.ts +0 -1381
  217. package/src/browser-electron/host-patch-maintenance.ts +0 -112
  218. package/src/browser-electron/http-body.ts +0 -65
  219. package/src/browser-electron/json-reply.ts +0 -47
  220. package/src/browser-electron/maintenance-broker.ts +0 -166
  221. package/src/browser-electron/maintenance-lifecycle.ts +0 -91
  222. package/src/browser-electron/maintenance-route.ts +0 -67
  223. package/src/browser-electron/missing-system-browser.ts +0 -113
  224. package/src/browser-electron/open-slot.ts +0 -49
  225. package/src/browser-electron/paths.ts +0 -25
  226. package/src/browser-electron/preferred-browser.ts +0 -120
  227. package/src/browser-electron/preview-route.ts +0 -218
  228. package/src/browser-electron/process-ownership.ts +0 -168
  229. package/src/browser-electron/process.ts +0 -23
  230. package/src/browser-electron/profile-checkpoint.ts +0 -187
  231. package/src/browser-electron/profile-command.ts +0 -46
  232. package/src/browser-electron/profile-extension.ts +0 -124
  233. package/src/browser-electron/profile-lease.ts +0 -115
  234. package/src/browser-electron/profile-residue.ts +0 -49
  235. package/src/browser-electron/provider.ts +0 -4571
  236. package/src/browser-electron/reference-route.ts +0 -608
  237. package/src/browser-electron/remote-host.ts +0 -1462
  238. package/src/browser-electron/rpc-input.ts +0 -13
  239. package/src/browser-electron/rpc-ops.ts +0 -41
  240. package/src/browser-electron/runtime-diagnostics.ts +0 -38
  241. package/src/browser-electron/runtime-route.ts +0 -105
  242. package/src/browser-electron/runtime-status.ts +0 -242
  243. package/src/browser-electron/settings-route.ts +0 -64
  244. package/src/browser-electron/settings-store.ts +0 -589
  245. package/src/browser-electron/shortcuts-route.ts +0 -112
  246. package/src/browser-electron/sidebar-only-host.ts +0 -298
  247. package/src/browser-electron/startpage-shortcuts.ts +0 -213
  248. package/src/browser-electron/system-browser.ts +0 -1497
  249. package/src/browser-electron/timing.ts +0 -16
  250. package/src/browser-electron/virtual-cursor.ts +0 -152
  251. package/src/browser-electron/windows-system.ts +0 -24
  252. package/src/browser-reference/delivery.ts +0 -384
  253. package/src/browser-reference/entry.ts +0 -631
  254. package/src/browser-reference/export.ts +0 -339
  255. package/src/browser-reference/import.ts +0 -303
  256. package/src/browser-reference/page-script.ts +0 -1537
  257. package/src/browser-reference/service.ts +0 -1315
  258. package/src/browser-reference/store.ts +0 -172
  259. package/src/browser-reference/submission-receipts.ts +0 -122
  260. package/src/browser-reference/text-quote.ts +0 -219
  261. package/src/browser-reference/types.ts +0 -195
  262. package/src/browser-reference/visible.ts +0 -367
  263. package/src/browser-reference/web-sources.ts +0 -103
  264. package/src/client/browser/BrowserController.ts +0 -693
  265. package/src/client/browser/BrowserFrame.ts +0 -78
  266. package/src/client/browser/BrowserNavigation.ts +0 -169
  267. package/src/client/browser/BrowserPage.ts +0 -23
  268. package/src/client/browser/BrowserPersistence.ts +0 -44
  269. package/src/client/browser/IframeImpl.ts +0 -176
  270. package/src/client/browser/child-tabs.ts +0 -14
  271. package/src/client/browser/iframe-reference.ts +0 -67
  272. package/src/client/browser/initialization.ts +0 -262
  273. package/src/client/browser/omnibox.ts +0 -243
  274. package/src/client/browser/store.ts +0 -38
  275. package/src/client/browser/takeover-channel.ts +0 -72
  276. package/src/client/browser/url.ts +0 -46
  277. package/src/client/browser/web-reference-source.ts +0 -52
  278. package/src/client/css-modules.d.ts +0 -4
  279. package/src/client/definition.tsx +0 -30
  280. package/src/client/electron/ElectronWebViewImpl.ts +0 -364
  281. package/src/client/electron/ElectronWebviewPresentation.ts +0 -138
  282. package/src/client/electron/NativeChildPresentation.ts +0 -45
  283. package/src/client/electron/NativeViewPage.ts +0 -251
  284. package/src/client/electron/pages.ts +0 -23
  285. package/src/client/electron/reference-overlay.ts +0 -53
  286. package/src/client/electron/workspace.ts +0 -33
  287. package/src/client/index.ts +0 -293
  288. package/src/client/locales.ts +0 -857
  289. package/src/client/pages.ts +0 -28
  290. package/src/client/reference/client/BrowserRefLink.tsx +0 -142
  291. package/src/client/reference/client/draft-reference.ts +0 -167
  292. package/src/client/reference/client/index.ts +0 -7
  293. package/src/client/reference/client/ordered-submission.ts +0 -108
  294. package/src/client/reference/client/pending-delivery.ts +0 -216
  295. package/src/client/reference/client/plugin.ts +0 -189
  296. package/src/client/reference/client/production/ReferenceCapsules.tsx +0 -345
  297. package/src/client/reference/client/production/ReferenceDock.module.css +0 -193
  298. package/src/client/reference/client/production/ReferenceDock.tsx +0 -6
  299. package/src/client/reference/client/production/ReferenceFeedback.tsx +0 -15
  300. package/src/client/reference/client/production/ReferenceMath.tsx +0 -44
  301. package/src/client/reference/client/production/ReferenceText.tsx +0 -36
  302. package/src/client/reference/client/production/assembly.ts +0 -471
  303. package/src/client/reference/client/production/asset-store.ts +0 -144
  304. package/src/client/reference/client/production/availability.ts +0 -74
  305. package/src/client/reference/client/production/bytes.ts +0 -36
  306. package/src/client/reference/client/production/delivery-client.ts +0 -211
  307. package/src/client/reference/client/production/draft-adapter.ts +0 -508
  308. package/src/client/reference/client/production/http-transport.ts +0 -217
  309. package/src/client/reference/client/production/production-submission.ts +0 -310
  310. package/src/client/reference/client/production/protocol.ts +0 -231
  311. package/src/client/reference/client/production/reference-card.ts +0 -240
  312. package/src/client/reference/client/production/reference-labels.ts +0 -29
  313. package/src/client/reference/client/production/reply-link-bridge.ts +0 -222
  314. package/src/client/reference/client/production/reveal.ts +0 -215
  315. package/src/client/reference/client/production/runtime.ts +0 -1101
  316. package/src/client/reference/client/production/snapshot-adapter.ts +0 -154
  317. package/src/client/reference/client/production/source-marker.ts +0 -63
  318. package/src/client/reference/client/production/source-opener.ts +0 -55
  319. package/src/client/reference/client/production/styles.ts +0 -104
  320. package/src/client/reference/client/production/user-text-rule.ts +0 -58
  321. package/src/client/reference/client/reveal.ts +0 -107
  322. package/src/client/reference/client/scheme.ts +0 -114
  323. package/src/client/reference/client/types.ts +0 -168
  324. package/src/client/reference/css-modules.d.ts +0 -4
  325. package/src/client/reference/index.ts +0 -11
  326. package/src/client/reference-capture-owner.ts +0 -162
  327. package/src/client/reference-intents.ts +0 -36
  328. package/src/client/settings/index.ts +0 -34
  329. package/src/client/settings/panel.ts +0 -2657
  330. package/src/client/shortcut-open.ts +0 -30
  331. package/src/client/startpage/binding.ts +0 -99
  332. package/src/client/startpage/controller.ts +0 -303
  333. package/src/client/startpage/model.ts +0 -279
  334. package/src/client/view/Browser.module.css +0 -751
  335. package/src/client/view/BrowserBody.tsx +0 -314
  336. package/src/client/view/BrowserPresentation.ts +0 -9
  337. package/src/client/view/BrowserTitle.tsx +0 -17
  338. package/src/client/view/IframePresentation.ts +0 -344
  339. package/src/client/view/StartPage.tsx +0 -597
  340. package/src/client/view/TakeoverBanner.tsx +0 -21
  341. package/src/index.ts +0 -110
  342. package/src/reference-owner.ts +0 -5
  343. package/src/reference-page.ts +0 -9
  344. package/src/reference-source.ts +0 -3
  345. package/src/reference-text.ts +0 -197
  346. package/src/startpage-settings.ts +0 -103
  347. package/src/startpage.ts +0 -71
  348. package/src/takeover-protocol.ts +0 -19
  349. package/src/tool-browser/code-tool.ts +0 -401
  350. package/src/tool-browser/code-worker.ts +0 -639
  351. package/src/tool-browser/element-fields.ts +0 -167
  352. package/src/tool-browser/index.ts +0 -3733
  353. package/src/tool-browser/page-probe.ts +0 -474
  354. package/src/tool-browser/panel-page.ts +0 -124
  355. package/src/tool-browser/screenshot-image.ts +0 -49
  356. package/src/tool-browser/takeover.ts +0 -198
  357. package/src/types/electron-shim.d.ts +0 -144
  358. package/src/types.ts +0 -85
  359. package/src/web-guest.ts +0 -34
  360. package/tools/accept-desktop.mjs +0 -148
@@ -1,1537 +0,0 @@
1
- /**
2
- * Page-side scripts for browser references: read the current selection as ordered
3
- * parts, rebuild the page's visible text map for a text-quote locate, draw a
4
- * non-interactive highlight, and rasterise one image element when its source
5
- * cannot be fetched.
6
- *
7
- * WHY ONE LIBRARY OF STRINGS
8
- * Every script travels through the same `execute` path every carrier already
9
- * has, so no carrier needs a new CDP method. The page half is untrusted: it
10
- * returns data, never code, and the host validates every field before a
11
- * reference is stored. Keeping the DOM helpers in one string means capture and
12
- * reveal agree on what "visible text" means — a map built differently in the two
13
- * places would make every anchor miss.
14
- *
15
- * Capture and reveal share a text map with semantic block/line separators.
16
- * Text nodes and atomic formulas carry DOM ranges; separators occupy map offsets.
17
- * Hidden subtrees, script,
18
- * style, template and the plugin's own highlight overlay are excluded.
19
- * @module dsh-browser/browser-reference/page-script
20
- */
21
-
22
- import type { ReferenceTextNode } from '../reference-text.ts'
23
-
24
- /** Options the capture script accepts as its single argument. */
25
- export interface CaptureScriptOptions {
26
- /** Characters of context kept on each side of a selected run. */
27
- readonly context?: number
28
- /** Text-map character budget; anything past it is reported as truncated. */
29
- readonly maxChars?: number
30
- /** Most table cells captured per table. */
31
- readonly maxCells?: number
32
- /** Capture this table whole even when it is not part of the selection. */
33
- readonly tableSelector?: string
34
- /**
35
- * Agent excerpt: with no live selection, register the first occurrence of this
36
- * text instead. Two occurrences make the result ambiguous and are refused.
37
- */
38
- readonly excerptText?: string
39
- }
40
-
41
- /** One raw reference part as the page produced it, before host validation. */
42
- export interface RawCaptureEvent {
43
- readonly kind?: string
44
- readonly exact?: string
45
- readonly content?: readonly ReferenceTextNode[]
46
- readonly prefix?: string
47
- readonly suffix?: string
48
- readonly src?: string
49
- readonly currentSrc?: string
50
- readonly attributeSrc?: string
51
- readonly alt?: string
52
- readonly caption?: string
53
- readonly selector?: string
54
- readonly path?: readonly number[]
55
- readonly svg?: boolean
56
- readonly canvas?: boolean
57
- /** Canvas pixels captured in the page; validated and hashed host-side. */
58
- readonly dataUrl?: string
59
- readonly width?: number
60
- readonly height?: number
61
- readonly geometry?: { readonly x: number; readonly y: number; readonly w: number; readonly h: number }
62
- readonly table?: RawTable
63
- }
64
-
65
- /** Raw table snapshot; cell shapes are validated host-side. */
66
- export interface RawTable {
67
- readonly rowCount?: number
68
- readonly columnCount?: number
69
- readonly caption?: string
70
- readonly completeness?: string
71
- readonly truncated?: boolean
72
- readonly cells?: readonly RawCell[]
73
- }
74
-
75
- /** Raw cell snapshot, including inline runs. */
76
- export interface RawCell {
77
- readonly row?: number
78
- readonly column?: number
79
- readonly rowSpan?: number
80
- readonly columnSpan?: number
81
- readonly role?: string
82
- readonly text?: string
83
- readonly content?: readonly ReferenceTextNode[]
84
- readonly includedAs?: string
85
- readonly partialText?: boolean
86
- readonly inlineContent?: readonly RawCellRun[]
87
- }
88
-
89
- /** One inline run inside a cell: text, or an image the host will materialise. */
90
- export interface RawCellRun {
91
- readonly type?: string
92
- readonly text?: string
93
- readonly src?: string
94
- readonly currentSrc?: string
95
- readonly alt?: string
96
- }
97
-
98
- /** Capture result. A refusal is a status, not an exception. */
99
- export interface RawCaptureResult {
100
- readonly ok: boolean
101
- readonly reason?: string
102
- readonly url?: string
103
- readonly frameUrl?: string
104
- readonly title?: string
105
- readonly multipleRanges?: boolean
106
- readonly truncated?: boolean
107
- readonly ambiguousExcerpt?: boolean
108
- readonly events?: readonly RawCaptureEvent[]
109
- }
110
-
111
- /** Page text map: what a text-quote locate searches. */
112
- export interface RawPageTextResult {
113
- readonly ok: boolean
114
- readonly reason?: string
115
- readonly url?: string
116
- readonly title?: string
117
- readonly text?: string
118
- readonly truncated?: boolean
119
- }
120
-
121
- /** Result of drawing a highlight. */
122
- export interface RawHighlightResult {
123
- readonly ok: boolean
124
- readonly reason?: string
125
- readonly rects?: number
126
- readonly scrolled?: boolean
127
- }
128
-
129
- /** Result of locating one element (image or table) and highlighting it. */
130
- export interface RawElementRevealResult {
131
- readonly ok: boolean
132
- readonly status?: string
133
- readonly reason?: string
134
- readonly matches?: number
135
- readonly described?: string
136
- readonly rects?: number
137
- readonly scrolled?: boolean
138
- }
139
-
140
- /** Result of rasterising one image element in the page. */
141
- export interface RawRasterResult {
142
- readonly ok: boolean
143
- readonly reason?: string
144
- readonly dataUrl?: string
145
- readonly width?: number
146
- readonly height?: number
147
- }
148
-
149
- /**
150
- * DOM helpers shared by every script below.
151
- *
152
- * No backticks and no `${` inside: the whole block is embedded in a template
153
- * literal. `String.raw` keeps the regex escapes intact.
154
- */
155
- const PAGE_LIB = String.raw`
156
- var SKIP_TAGS = { SCRIPT: 1, STYLE: 1, NOSCRIPT: 1, TEMPLATE: 1, TEXTAREA: 1 }
157
- var HIGHLIGHT_ID = '__dsh-ref-highlight'
158
- var visibilityCache = typeof WeakMap === 'function' ? new WeakMap() : null
159
-
160
- function pageBody() { return document.body || document.documentElement }
161
-
162
- function collapse(value, limit) {
163
- var text = String(value == null ? '' : value).replace(/\s+/g, ' ').trim()
164
- return limit && text.length > limit ? text.slice(0, limit) : text
165
- }
166
-
167
- function elementHidden(el) {
168
- if (!el || el.nodeType !== 1) return false
169
- try {
170
- if (el.hidden === true) return true
171
- var style = window.getComputedStyle ? window.getComputedStyle(el) : null
172
- if (!style) return false
173
- if (style.display === 'none') return true
174
- if (style.opacity === '0' && el.getClientRects && el.getClientRects().length === 0) return true
175
- if (style.display !== 'contents' && el.getBoundingClientRect) {
176
- var box = el.getBoundingClientRect()
177
- if (box.width === 0 && box.height === 0 && style.position !== 'fixed') return true
178
- }
179
- } catch (error) { return false }
180
- return false
181
- }
182
-
183
- function visibleNode(node) {
184
- var el = node.nodeType === 1 ? node : node.parentElement
185
- var seen = []
186
- var verdict = true
187
- while (el && el !== document.documentElement) {
188
- if (visibilityCache) {
189
- var cached = visibilityCache.get(el)
190
- if (cached === false) { verdict = false; break }
191
- if (cached === true) break
192
- }
193
- if (elementHidden(el)) {
194
- if (visibilityCache) visibilityCache.set(el, false)
195
- verdict = false
196
- break
197
- }
198
- seen.push(el)
199
- el = el.parentElement
200
- }
201
- if (verdict && visibilityCache) {
202
- for (var i = 0; i < seen.length; i++) visibilityCache.set(seen[i], true)
203
- }
204
- return verdict
205
- }
206
-
207
- function textVisible(node) {
208
- var parent = node.parentElement
209
- if (!parent) return false
210
- try {
211
- var style = window.getComputedStyle ? window.getComputedStyle(parent) : null
212
- if (style && (style.visibility === 'hidden' || style.visibility === 'collapse')) return false
213
- } catch (error) { /* no style engine: fall through to the ancestor walk */ }
214
- return visibleNode(parent)
215
- }
216
-
217
- function skippedText(node) {
218
- var el = node.parentElement
219
- var depth = 0
220
- while (el && depth < 64) {
221
- if (SKIP_TAGS[el.tagName] || el.id === HIGHLIGHT_ID) return true
222
- el = el.parentElement
223
- depth += 1
224
- }
225
- return false
226
- }
227
-
228
- var MATH_SELECTOR = '.katex-display, .katex, .MathJax, .MathJax_Display, .MathJax_SVG, .MathJax_SVG_Display, .MathJax_CHTML, .MathJax_CHTML_Display, mjx-container, math'
229
-
230
- function mathMLText(node, depth) {
231
- if ((depth || 0) > 64) return '[math truncated]'
232
- if (node.nodeType === 3) return node.nodeValue || ''
233
- var tag = String(node.localName || '').toLowerCase()
234
- if (tag === 'annotation' || tag === 'annotation-xml') return ''
235
- var children = Array.prototype.filter.call(node.childNodes || [], function (child) {
236
- return child.nodeType === 1 || /^(mi|mn|mo|mtext|ms)$/.test(tag)
237
- }).map(function (child) { return mathMLText(child, (depth || 0) + 1) })
238
- if (tag === 'mfrac') return '\\frac{' + (children[0] || '') + '}{' + (children[1] || '') + '}'
239
- if (tag === 'msup' || tag === 'msub' || tag === 'mover' || tag === 'munder') return (children[0] || '') + (tag === 'msup' || tag === 'mover' ? '^{' : '_{') + (children[1] || '') + '}'
240
- if (tag === 'msubsup' || tag === 'munderover') return (children[0] || '') + '_{' + (children[1] || '') + '}^{' + (children[2] || '') + '}'
241
- if (tag === 'msqrt') return '\\sqrt{' + children.join('') + '}'
242
- if (tag === 'mroot') return '\\sqrt[' + (children[1] || '') + ']{' + (children[0] || '') + '}'
243
- return children.join('')
244
- }
245
-
246
- function mathSource(node) {
247
- var tag = String(node.tagName || '').toUpperCase()
248
- var matches = function (selector) { return node.matches && node.matches(selector) }
249
- var script = tag === 'SCRIPT' && /^math\/tex/i.test(node.getAttribute('type') || '')
250
- if (script && node.previousElementSibling && node.previousElementSibling.matches(MATH_SELECTOR)) return null
251
- if (!script && !matches(MATH_SELECTOR)) return null
252
- var annotations = node.querySelectorAll('annotation')
253
- var annotation = ''
254
- for (var a = 0; a < annotations.length; a++) {
255
- if (/^(application\/(x-tex|x-latex)|text\/(x-tex|tex))$/i.test(String(annotations[a].getAttribute('encoding') || '').split(';')[0].trim())) {
256
- annotation = String(annotations[a].textContent || '').trim()
257
- if (annotation) break
258
- }
259
- }
260
- var data = node.getAttribute('data-latex') || (node.querySelector('[data-latex]') || {}).getAttribute?.('data-latex')
261
- var next = node.nextElementSibling
262
- var sourceScript = next && /^math\/tex/i.test(next.getAttribute('type') || '') ? next : null
263
- var math = tag === 'MATH' ? node : node.querySelector('math')
264
- var sourceTex = script ? String(node.textContent || '').trim() : annotation || String(data || '').trim() || String(sourceScript ? sourceScript.textContent || '' : '').trim()
265
- var latex = sourceTex || (math ? mathMLText(math) : '[math source unavailable]')
266
- return { latex: String(latex || '[math source unavailable]').trim() || '[math source unavailable]',
267
- mathml: math && !sourceTex && String(math.outerHTML || '').length <= 64000 ? String(math.outerHTML) : undefined,
268
- display: matches('.katex-display, .MathJax_Display, .MathJax_SVG_Display, .MathJax_CHTML_Display') || node.getAttribute('display') === 'block' || node.getAttribute('display') === 'true' || /mode\s*=\s*display/i.test((script ? node : sourceScript)?.getAttribute('type') || '') }
269
- }
270
-
271
- function flatTextMap(maxChars, structured, legacy, root) {
272
- var body = root || pageBody()
273
- var out = { text: '', nodes: [], content: [], truncated: false }
274
- if (!body || typeof document.createTreeWalker !== 'function') return out
275
- var limit = maxChars && maxChars > 0 ? maxChars : 2000000
276
- function append(value) {
277
- var room = Math.max(0, limit - out.text.length)
278
- if (value.length > room) out.truncated = true
279
- out.text += value.slice(0, room)
280
- }
281
- function boundary(value) {
282
- if (legacy || !out.text) return []
283
- var overlap = 0
284
- for (var i = 1; i <= value.length; i++) if (out.text.endsWith(value.slice(0, i))) overlap = i
285
- var start = out.text.length
286
- append(value.slice(overlap))
287
- var end = out.text.length
288
- return structured && end > start ? [{ type: 'text', text: out.text.slice(start, end), start: start, end: end }] : []
289
- }
290
- function visit(node, depth) {
291
- if (out.truncated) return []
292
- if (depth > 64) { out.truncated = true; return [] }
293
- if (node.nodeType === 3) {
294
- var value = node.nodeValue || ''
295
- if (!value || skippedText(node) || !textVisible(node)) return []
296
- var start = out.text.length
297
- append(value)
298
- var end = out.text.length
299
- if (end === start) return []
300
- out.nodes.push({ node: node, start: start, end: end })
301
- return structured ? [{ type: 'text', text: out.text.slice(start, end), start: start, end: end }] : []
302
- }
303
- if (node.nodeType !== 1 || node.id === HIGHLIGHT_ID) return []
304
- var formula = !legacy && mathSource(node)
305
- if (formula) {
306
- if (node.tagName !== 'SCRIPT' && !visibleNode(node)) return []
307
- if (formula.latex.length > limit - out.text.length) { out.truncated = true; return [] }
308
- var at = out.text.length
309
- append(formula.latex)
310
- out.nodes.push({ node: node, start: at, end: out.text.length, atomic: true })
311
- return structured ? [Object.assign({ type: 'math', latex: formula.latex, display: Boolean(formula.display), start: at, end: out.text.length }, formula.mathml === undefined ? {} : { mathml: formula.mathml })] : []
312
- }
313
- if (SKIP_TAGS[node.tagName] || !visibleNode(node)) return []
314
- var tag = node.tagName
315
- if (!legacy && tag === 'RP') return []
316
- if (tag === 'HR' && !legacy) {
317
- var at = out.text.length
318
- append('\n---\n')
319
- out.nodes.push({ node: node, start: at, end: out.text.length, atomic: true })
320
- return structured ? [{ type: 'rule', start: at, end: out.text.length }] : []
321
- }
322
- if (tag === 'BR') {
323
- if (legacy) return []
324
- var at = out.text.length
325
- append('\n')
326
- return structured ? [{ type: 'break', start: at, end: out.text.length }] : []
327
- }
328
- var block = /^(P|DIV|MAIN|ASIDE|NAV|SECTION|ARTICLE|HEADER|FOOTER|FIGURE|FIGCAPTION|DL|DT|DD|H[1-6]|UL|OL|PRE|BLOCKQUOTE|TABLE)$/.test(tag)
329
- if (block) boundary('\n\n')
330
- if (tag === 'LI') boundary('\n')
331
- var prefix = tag === 'TR' ? boundary('\n') : []
332
- if ((tag === 'TD' || tag === 'TH') && !out.text.endsWith('\n')) prefix = boundary('\t')
333
- var start = out.text.length
334
- var children = []
335
- for (var child = node.firstChild; child; child = child.nextSibling) {
336
- var added = visit(child, depth + 1)
337
- for (var a = 0; a < added.length; a++) children.push(added[a])
338
- }
339
- var end = out.text.length
340
- if (block) boundary('\n\n')
341
- if (tag === 'LI') boundary('\n')
342
- var suffix = tag === 'TR' ? boundary('\n') : []
343
- if (!children.length) return prefix.concat(suffix)
344
- var types = { P: 'paragraph', DIV: 'paragraph', H1: 'heading', H2: 'heading', H3: 'heading', H4: 'heading', H5: 'heading', H6: 'heading', STRONG: 'strong', B: 'strong', EM: 'emphasis', I: 'emphasis', CODE: 'code', PRE: 'pre', BLOCKQUOTE: 'blockquote', LI: 'list-item', UL: 'list', OL: 'list', DL: 'definition-list', DT: 'term', DD: 'definition', SUP: 'sup', SUB: 'sub', RUBY: 'ruby', RT: 'ruby-text' }
345
- var type = types[tag] || (block ? 'block' : undefined)
346
- if (tag === 'DIV') type = 'block'
347
- var result = { type: type, children: children, start: start, end: end }
348
- if (type === 'heading') result.level = Number(tag.slice(1))
349
- if (type === 'pre') {
350
- var code = node.querySelector('code') || node
351
- var language = /(?:^|\s)(?:language-|lang-)([\w+-]{1,64})(?=\s|$)/.exec(code.className || node.className || '')
352
- if (language) result.language = language[1]
353
- }
354
- if (type === 'list-item' && node.hasAttribute('value')) {
355
- var value = Number(node.getAttribute('value'))
356
- if (Number.isSafeInteger(value) && Math.abs(value) <= 1000000) result.value = value
357
- }
358
- if (tag === 'A' && /^https?:\/\//i.test(node.href || '')) { result.type = 'link'; result.href = String(node.href).slice(0, 4000) }
359
- if (type === 'list') {
360
- result.ordered = tag === 'OL'
361
- var first = Number(node.getAttribute('start') || 1)
362
- result.listStart = Number.isSafeInteger(first) && Math.abs(first) <= 1000000 ? first : 1
363
- result.children = children.filter(function (child) { return child.type === 'list-item' })
364
- }
365
- return prefix.concat(result.type ? [result] : children, suffix)
366
- }
367
- for (var child = body.firstChild; child && !out.truncated; child = child.nextSibling) {
368
- var added = visit(child, 0)
369
- for (var a = 0; a < added.length; a++) out.content.push(added[a])
370
- }
371
- return out
372
- }
373
-
374
- function selectedContent(nodes, start, end, preserveWhitespace) {
375
- var result = []
376
- for (var i = 0; i < nodes.length; i++) {
377
- var node = nodes[i]
378
- if (node.end <= start || node.start >= end) continue
379
- if (node.type === 'text') {
380
- result.push({ type: 'text', text: node.text.slice(Math.max(0, start - node.start), Math.min(node.text.length, end - node.start)) })
381
- } else if (node.type === 'break' || node.type === 'rule') result.push({ type: node.type })
382
- else if (node.type === 'math') result.push(Object.assign({ type: 'math', latex: node.latex, display: node.display }, node.mathml === undefined ? {} : { mathml: node.mathml }))
383
- else {
384
- var children = selectedContent(node.children, start, end, preserveWhitespace || node.type === 'pre' || node.type === 'code')
385
- if (!children.length) continue
386
- var part = { type: node.type, children: children }
387
- if (node.level !== undefined) part.level = node.level
388
- if (node.language !== undefined) part.language = node.language
389
- if (node.value !== undefined) part.value = node.value
390
- if (node.type === 'link') part.href = node.href
391
- if (node.type === 'list') {
392
- part.ordered = node.ordered
393
- part.start = node.listStart
394
- for (var li = 0; li < node.children.length && node.children[li].end <= start; li++) {
395
- if (node.children[li].value !== undefined) part.start = node.children[li].value
396
- part.start += 1
397
- }
398
- }
399
- result.push(part)
400
- }
401
- }
402
- if (preserveWhitespace) return result
403
- function block(node) {
404
- return node && /^(block|paragraph|heading|list|list-item|definition-list|term|definition|pre|blockquote|rule)$/.test(node.type)
405
- }
406
- return result.filter(function (node, index) {
407
- return node.type !== 'text' || !/^\s*$/.test(node.text)
408
- || (!block(result[index - 1]) && !block(result[index + 1]))
409
- })
410
- }
411
-
412
- function safeStart(text, index) {
413
- if (index > 0 && index < text.length) {
414
- var code = text.charCodeAt(index)
415
- if (code >= 0xdc00 && code <= 0xdfff) return index - 1
416
- }
417
- return index
418
- }
419
-
420
- function safeEnd(text, index) {
421
- if (index > 0 && index < text.length) {
422
- var code = text.charCodeAt(index)
423
- if (code >= 0xdc00 && code <= 0xdfff) return index + 1
424
- }
425
- return index
426
- }
427
-
428
- function rangeContainsNode(range, node) {
429
- try {
430
- if (!range.intersectsNode(node)) return false
431
- var box = document.createRange()
432
- box.selectNode(node)
433
- return range.compareBoundaryPoints(0, box) <= 0 && range.compareBoundaryPoints(3, box) >= 0
434
- } catch (error) { return false }
435
- }
436
-
437
- function selectedPart(range, entry) {
438
- var node = entry.node
439
- if (entry.atomic) {
440
- try { return range.intersectsNode(node) ? { start: entry.start, end: entry.end, node: node } : null } catch (error) { return null }
441
- }
442
- var value = node.nodeValue || ''
443
- var length = Math.min(value.length, entry.end === undefined ? value.length : entry.end - entry.start)
444
- var start = 0
445
- var end = length
446
- try {
447
- if (range.startContainer === node) start = Math.max(0, Math.min(range.startOffset, length))
448
- else if (range.comparePoint(node, 0) === 1) return null
449
- if (range.endContainer === node) end = Math.max(0, Math.min(range.endOffset, length))
450
- else if (range.comparePoint(node, length) === -1) return null
451
- } catch (error) { return null }
452
- if (end <= start) return null
453
- return { start: entry.start + start, end: entry.start + end, node: node }
454
- }
455
-
456
- function mergeRanges(ranges, text) {
457
- ranges.sort(function (a, b) { return a.start - b.start })
458
- var out = []
459
- for (var i = 0; i < ranges.length; i++) {
460
- var run = ranges[i]
461
- var last = out.length ? out[out.length - 1] : null
462
- if (last && (run.start <= last.end || (text !== undefined && /^\s*$/.test(text.slice(last.end, run.start))))) last.end = Math.max(last.end, run.end)
463
- else out.push({ start: run.start, end: run.end, node: run.node })
464
- }
465
- return out
466
- }
467
-
468
- function pathOf(node) {
469
- var body = pageBody()
470
- var path = []
471
- var current = node
472
- while (current && current !== body) {
473
- var parent = current.parentNode
474
- if (!parent) return null
475
- var index = 0
476
- var child = parent.firstChild
477
- while (child && child !== current) { child = child.nextSibling; index += 1 }
478
- if (!child) return null
479
- path.unshift(index)
480
- current = parent
481
- }
482
- return current === body ? path : null
483
- }
484
-
485
- function nodeAtPath(path) {
486
- var node = pageBody()
487
- if (!node || !path || !path.length) return node
488
- for (var i = 0; i < path.length; i++) {
489
- if (!node || !node.childNodes || path[i] < 0 || path[i] >= node.childNodes.length) return null
490
- node = node.childNodes[path[i]]
491
- }
492
- return node
493
- }
494
-
495
- function selectorOf(el) {
496
- if (!el || el.nodeType !== 1) return ''
497
- try {
498
- if (el.id && /^[A-Za-z][A-Za-z0-9_-]*$/.test(el.id)) return '#' + el.id
499
- var parts = []
500
- var node = el
501
- var depth = 0
502
- while (node && node.nodeType === 1 && depth < 6) {
503
- var tag = node.tagName.toLowerCase()
504
- var index = 1
505
- var sibling = node.previousElementSibling
506
- while (sibling) { if (sibling.tagName === node.tagName) index += 1; sibling = sibling.previousElementSibling }
507
- if (node.id && /^[A-Za-z][A-Za-z0-9_-]*$/.test(node.id)) { parts.unshift('#' + node.id); break }
508
- parts.unshift(tag + (index > 1 ? ':nth-of-type(' + index + ')' : ''))
509
- node = node.parentElement
510
- depth += 1
511
- }
512
- return parts.join(' > ')
513
- } catch (error) { return '' }
514
- }
515
-
516
- function documentOrder(a, b) {
517
- if (a === b) return 0
518
- try {
519
- var position = a.compareDocumentPosition(b)
520
- if (position & 4) return -1
521
- if (position & 2) return 1
522
- } catch (error) { /* fall through */ }
523
- return 0
524
- }
525
-
526
- function geometryOf(el) {
527
- try {
528
- var box = el.getBoundingClientRect()
529
- return { x: Math.round(box.left), y: Math.round(box.top), w: Math.round(box.width), h: Math.round(box.height) }
530
- } catch (error) { return { x: 0, y: 0, w: 0, h: 0 } }
531
- }
532
-
533
- function isInside(node, ancestor) {
534
- var el = node.parentElement
535
- while (el) {
536
- if (el === ancestor) return true
537
- el = el.parentElement
538
- }
539
- return false
540
- }
541
-
542
- function captionOf(el) {
543
- var node = el.parentElement
544
- var depth = 0
545
- while (node && depth < 8) {
546
- if (node.tagName === 'FIGURE') {
547
- var caption = node.querySelector ? node.querySelector('figcaption') : null
548
- return caption ? collapse(caption.innerText || caption.textContent, 500) : ''
549
- }
550
- node = node.parentElement
551
- depth += 1
552
- }
553
- return ''
554
- }
555
-
556
- function isSvg(el) {
557
- return String(el.tagName).toLowerCase() === 'svg'
558
- }
559
-
560
- function cellImageRuns(cell) {
561
- var runs = []
562
- if (!cell || typeof document.createTreeWalker !== 'function') return runs
563
- var walker = document.createTreeWalker(cell, 5, null, false)
564
- var node = walker.nextNode()
565
- while (node) {
566
- if (node.nodeType === 3) {
567
- var text = collapse(node.nodeValue, 2000)
568
- if (text !== '') {
569
- var last = runs.length ? runs[runs.length - 1] : null
570
- if (last && last.type === 'text') last.text = collapse(last.text + ' ' + text, 2000)
571
- else runs.push({ type: 'text', text: text })
572
- }
573
- } else if (String(node.tagName).toUpperCase() === 'IMG') {
574
- runs.push({
575
- type: 'image',
576
- src: String(node.currentSrc || node.src || ''),
577
- currentSrc: String(node.currentSrc || ''),
578
- alt: collapse(node.getAttribute('alt'), 500),
579
- })
580
- }
581
- node = walker.nextNode()
582
- }
583
- return runs
584
- }
585
-
586
- function cellFacts(cell, ranges) {
587
- var selected = false
588
- var contained = false
589
- for (var i = 0; i < ranges.length; i++) {
590
- var range = ranges[i]
591
- try {
592
- if (!range.intersectsNode(cell)) continue
593
- } catch (error) { continue }
594
- selected = true
595
- if (rangeContainsNode(range, cell)) contained = true
596
- }
597
- if (!selected) return { selected: false, partial: false }
598
- if (contained) return { selected: true, partial: false }
599
- var full = ''
600
- var picked = ''
601
- if (typeof document.createTreeWalker === 'function') {
602
- var walker = document.createTreeWalker(cell, 4, null, false)
603
- var node = walker.nextNode()
604
- while (node) {
605
- var value = node.nodeValue || ''
606
- full += value
607
- for (var r = 0; r < ranges.length; r++) {
608
- var part = selectedPart(ranges[r], { node: node, start: 0, end: value.length })
609
- if (part) picked += value.slice(part.start, part.end)
610
- }
611
- node = walker.nextNode()
612
- }
613
- }
614
- return { selected: true, partial: collapse(picked, 0) !== collapse(full, 0) }
615
- }
616
-
617
- function dataTable(table) {
618
- var role = String(table.getAttribute && table.getAttribute('role') || '').toLowerCase()
619
- if (role === 'presentation' || role === 'none') return false
620
- if (role === 'table' || role === 'grid' || table.caption) return true
621
- var rows = table.rows || []
622
- for (var r = 0; r < rows.length; r++) {
623
- var cells = rows[r].cells || []
624
- for (var c = 0; c < cells.length; c++) {
625
- if (String(cells[c].tagName).toUpperCase() === 'TH') return true
626
- }
627
- }
628
- if (rows.length < 2) return false
629
- var columns = 0
630
- for (var r = 0; r < rows.length; r++) {
631
- var cells = rows[r].cells || []
632
- if (cells.length < 2) return false
633
- var width = 0
634
- for (var c = 0; c < cells.length; c++) {
635
- if (cells[c].querySelector && cells[c].querySelector('h1,h2,h3,h4,h5,h6,ul,ol,nav,main,article,section,aside,form,table')) return false
636
- width += Math.max(1, Number(cells[c].colSpan) || 1)
637
- }
638
- if (r === 0) columns = width
639
- else if (width !== columns) return false
640
- }
641
- return true
642
- }
643
-
644
- function tableSnapshot(table, ranges, spec) {
645
- // An explicit right-click table target is a whole-table action too: the
646
- // selection was cleared on purpose, so judging cells by "selected" would
647
- // return null and silently drop the very object the user right-clicked.
648
- var wholeTable = Boolean(spec.tableSelector)
649
- || Boolean(spec.target && typeof spec.target === 'object' && String(spec.target.kind) === 'table')
650
- var scope = wholeTable ? 'table' : 'selection'
651
- var rows = []
652
- try { rows = table.rows ? Array.prototype.slice.call(table.rows) : [] } catch (error) { rows = [] }
653
- var grid = []
654
- var cells = []
655
- var selectedAny = false
656
- var maxColumns = 0
657
- var maxRow = 0
658
- var truncated = false
659
- var maxCells = Math.max(1, Math.min(Number(spec.maxCells) || 2000, 5000))
660
- for (var r = 0; r < rows.length; r++) {
661
- var row = rows[r]
662
- var rowCells = row && row.cells ? row.cells : []
663
- var column = 0
664
- for (var c = 0; c < rowCells.length; c++) {
665
- var cell = rowCells[c]
666
- var rowSpan = Math.max(1, Math.min(Number(cell.rowSpan) || 1, 1000))
667
- var columnSpan = Math.max(1, Math.min(Number(cell.colSpan) || 1, 200))
668
- if (!grid[r]) grid[r] = []
669
- while (grid[r][column]) column += 1
670
- for (var dr = 0; dr < rowSpan; dr++) {
671
- if (!grid[r + dr]) grid[r + dr] = []
672
- for (var dc = 0; dc < columnSpan; dc++) grid[r + dr][column + dc] = true
673
- }
674
- column += columnSpan
675
- if (column > maxColumns) maxColumns = column
676
- if (r + rowSpan > maxRow) maxRow = r + rowSpan
677
- var rowIsHead = cell.parentElement && cell.parentElement.parentElement && String(cell.parentElement.parentElement.tagName).toUpperCase() === 'THEAD'
678
- var role = String(cell.tagName).toUpperCase() === 'TH' || rowIsHead ? 'header' : 'data'
679
- var facts = cellFacts(cell, ranges)
680
- if (facts.selected) selectedAny = true
681
- if (scope === 'selection' && !facts.selected && role !== 'header') continue
682
- if (cells.length >= maxCells) { truncated = true; continue }
683
- var cellMap = flatTextMap(2000, true, false, cell)
684
- cells.push({
685
- row: r,
686
- column: column - columnSpan,
687
- rowSpan: rowSpan,
688
- columnSpan: columnSpan,
689
- role: role,
690
- text: collapse(cellMap.text, 2000),
691
- content: selectedContent(cellMap.content, 0, cellMap.text.length),
692
- includedAs: facts.selected || scope === 'table' ? 'selection' : 'header-context',
693
- partialText: facts.selected ? facts.partial : false,
694
- inlineContent: cellImageRuns(cell),
695
- })
696
- }
697
- }
698
- if (scope === 'selection' && !selectedAny) return null
699
- var declaredRows = Number(table.getAttribute && table.getAttribute('aria-rowcount')) || 0
700
- var completeness = scope === 'table'
701
- ? declaredRows > rows.length ? 'visible-rows' : 'dom-table'
702
- : 'selected-cells'
703
- return {
704
- rowCount: truncated ? maxRow : Math.max(maxRow, rows.length),
705
- columnCount: maxColumns,
706
- caption: collapse(table.caption ? table.caption.innerText || table.caption.textContent : '', 500),
707
- completeness: completeness,
708
- truncated: truncated,
709
- cells: cells,
710
- }
711
- }
712
-
713
- function ownedByGrid(element, grid) {
714
- var node = element.parentElement
715
- while (node && node !== grid) {
716
- var role = String(node.getAttribute && node.getAttribute('role') || '')
717
- if (role === 'grid' || role === 'table') return false
718
- node = node.parentElement
719
- }
720
- return node === grid
721
- }
722
-
723
- function closestRoleRow(element, grid) {
724
- var node = element
725
- while (node && node !== grid) {
726
- if (String(node.getAttribute && node.getAttribute('role') || '') === 'row') return node
727
- node = node.parentElement
728
- }
729
- return null
730
- }
731
-
732
- // ARIA grids are not HTML tables: rows and cells are role-named elements.
733
- // The snapshot keeps the declared row/column indices so a virtualised grid
734
- // can still be located after re-render.
735
- function ariaTableSnapshot(grid, ranges, spec) {
736
- var rows = []
737
- try { rows = grid.querySelectorAll ? Array.prototype.slice.call(grid.querySelectorAll('[role="row"]')) : [] } catch (error) { rows = [] }
738
- var cells = []
739
- var selectedAny = false
740
- var maxCells = Math.max(1, Math.min(Number(spec.maxCells) || 2000, 5000))
741
- var truncated = false
742
- var maxColumns = 0
743
- var declaredRows = Number(grid.getAttribute && grid.getAttribute('aria-rowcount')) || 0
744
- for (var r = 0; r < rows.length; r++) {
745
- var row = rows[r]
746
- if (!ownedByGrid(row, grid)) continue
747
- var all = row.querySelectorAll ? row.querySelectorAll('[role="gridcell"], [role="cell"], [role="columnheader"], [role="rowheader"]') : []
748
- var column = 0
749
- for (var c = 0; c < all.length; c++) {
750
- var cell = all[c]
751
- if (closestRoleRow(cell, grid) !== row) continue
752
- var rowSpan = Math.max(1, Math.min(Number(cell.getAttribute('aria-rowspan')) || 1, 1000))
753
- var columnSpan = Math.max(1, Math.min(Number(cell.getAttribute('aria-colspan')) || 1, 200))
754
- var declaredColumn = Number(cell.getAttribute('aria-colindex'))
755
- if (declaredColumn > 0) column = declaredColumn - 1
756
- var declaredRow = Number(cell.getAttribute('aria-rowindex'))
757
- var rowIndex = declaredRow > 0 ? declaredRow - 1 : r
758
- var roleName = String(cell.getAttribute('role') || '')
759
- var role = roleName === 'columnheader' || roleName === 'rowheader' ? 'header' : 'data'
760
- var facts = cellFacts(cell, ranges)
761
- if (facts.selected) selectedAny = true
762
- if (!facts.selected && role !== 'header') { column += columnSpan; continue }
763
- if (cells.length >= maxCells) { truncated = true; column += columnSpan; continue }
764
- cells.push({
765
- row: rowIndex,
766
- column: column,
767
- rowSpan: rowSpan,
768
- columnSpan: columnSpan,
769
- role: role,
770
- text: collapse(cell.innerText || cell.textContent, 2000),
771
- includedAs: facts.selected ? 'selection' : 'header-context',
772
- partialText: facts.selected ? facts.partial : false,
773
- inlineContent: cellImageRuns(cell),
774
- })
775
- if (column + columnSpan > maxColumns) maxColumns = column + columnSpan
776
- column += columnSpan
777
- }
778
- }
779
- if (!selectedAny) return null
780
- var rowCount = declaredRows > 0 ? declaredRows : rows.length
781
- return {
782
- rowCount: Math.max(rowCount, rows.length),
783
- columnCount: maxColumns,
784
- caption: collapse(grid.getAttribute && grid.getAttribute('aria-label') || '', 500),
785
- completeness: declaredRows > rows.length ? 'visible-rows' : 'aria-grid',
786
- truncated: truncated,
787
- cells: cells,
788
- }
789
- }
790
-
791
- function trimmedRun(map, start, end) {
792
- function preformatted(offset) {
793
- for (var i = 0; i < map.nodes.length; i++) {
794
- var entry = map.nodes[i]
795
- if (offset >= entry.start && offset < entry.end) {
796
- var parent = entry.node.parentElement
797
- return parent && parent.closest && parent.closest('pre, code')
798
- }
799
- }
800
- return false
801
- }
802
- while (start < end && /\s/.test(map.text.charAt(start)) && !preformatted(start)) start += 1
803
- while (end > start && /\s/.test(map.text.charAt(end - 1)) && !preformatted(end - 1)) end -= 1
804
- return end > start ? { start: start, end: end } : null
805
- }
806
-
807
- function subtractSpans(run, spans) {
808
- var pieces = [{ start: run.start, end: run.end }]
809
- for (var i = 0; i < spans.length; i++) {
810
- var next = []
811
- for (var p = 0; p < pieces.length; p++) {
812
- var piece = pieces[p]
813
- if (spans[i].end <= piece.start || spans[i].start >= piece.end) { next.push(piece); continue }
814
- if (spans[i].start > piece.start) next.push({ start: piece.start, end: spans[i].start })
815
- if (spans[i].end < piece.end) next.push({ start: spans[i].end, end: piece.end })
816
- }
817
- pieces = next
818
- }
819
- return pieces
820
- }
821
-
822
- function excerptRun(map, needle) {
823
- if (!needle) return null
824
- var first = map.text.indexOf(needle)
825
- if (first === -1) return null
826
- var second = map.text.indexOf(needle, first + 1)
827
- if (second !== -1) return { ambiguous: true, start: first, end: first + needle.length }
828
- return { ambiguous: false, start: first, end: first + needle.length }
829
- }
830
-
831
- function capture(spec) {
832
- var body = pageBody()
833
- if (!body) return { ok: false, reason: 'no-document' }
834
- var selection = window.getSelection ? window.getSelection() : null
835
- var ranges = []
836
- if (selection && selection.rangeCount > 0 && !selection.isCollapsed) {
837
- for (var i = 0; i < selection.rangeCount; i++) {
838
- try { ranges.push(selection.getRangeAt(i).cloneRange()) } catch (error) { /* a lost range is skipped */ }
839
- }
840
- }
841
- var tableSelector = spec.tableSelector ? String(spec.tableSelector) : ''
842
- var targetTable = null
843
- // An explicit right-click target (§3.2 / §3.3): capture THIS image or THIS
844
- // table even when the selection collapsed while the native menu was open.
845
- var target = spec.target && typeof spec.target === 'object' ? spec.target : null
846
- var targetImage = null
847
- if (target && String(target.kind) === 'image') {
848
- var wanted = String(target.srcUrl || '')
849
- var candidates = body.querySelectorAll ? body.querySelectorAll('img, svg, canvas') : []
850
- for (var ci = 0; ci < candidates.length && ci < 400; ci++) {
851
- var candidate = candidates[ci]
852
- var candidateSrc = String(candidate.currentSrc || candidate.src
853
- || (candidate.getAttribute && candidate.getAttribute('src')) || '')
854
- if (wanted && candidateSrc && (candidateSrc === wanted
855
- || candidateSrc.indexOf(wanted) >= 0 || wanted.indexOf(candidateSrc) >= 0)) {
856
- targetImage = candidate
857
- break
858
- }
859
- }
860
- if (!targetImage && target.x !== undefined && target.y !== undefined && document.elementFromPoint) {
861
- try {
862
- var hitNode = document.elementFromPoint(Number(target.x), Number(target.y))
863
- targetImage = hitNode && hitNode.closest ? hitNode.closest('img, svg, canvas') : null
864
- } catch (error) { targetImage = null }
865
- }
866
- if (!targetImage) return { ok: false, reason: 'image-target-not-found' }
867
- } else if (target && String(target.kind) === 'table' && !tableSelector) {
868
- if (target.x !== undefined && target.y !== undefined && document.elementFromPoint) {
869
- try {
870
- var tableHit = document.elementFromPoint(Number(target.x), Number(target.y))
871
- targetTable = tableHit && tableHit.closest ? tableHit.closest('table') : null
872
- } catch (error) { targetTable = null }
873
- }
874
- if (!targetTable && ranges.length > 0) {
875
- var rangeBase = ranges[0].commonAncestorContainer
876
- var rangeElement = rangeBase && rangeBase.nodeType === 1 ? rangeBase : (rangeBase && rangeBase.parentElement)
877
- targetTable = rangeElement && rangeElement.closest ? rangeElement.closest('table') : null
878
- }
879
- if (!targetTable) return { ok: false, reason: 'table-target-not-found' }
880
- }
881
- if (tableSelector) {
882
- try { targetTable = document.querySelector(tableSelector) } catch (error) { targetTable = null }
883
- if (!targetTable || String(targetTable.tagName).toUpperCase() !== 'TABLE') return { ok: false, reason: 'table-not-found' }
884
- }
885
- // Any explicit target is a whole-object action: the selection is not part of it.
886
- if (targetTable || targetImage) ranges = []
887
- var excerpt = null
888
- if (ranges.length === 0 && !targetTable && !targetImage) {
889
- if (!spec.excerptText) return { ok: false, reason: 'no-selection' }
890
- }
891
-
892
- var map = flatTextMap(spec.maxChars, true)
893
- if (ranges.length === 0 && !targetTable && !targetImage) {
894
- excerpt = excerptRun(map, String(spec.excerptText))
895
- if (!excerpt) return { ok: false, reason: 'excerpt-not-found' }
896
- if (excerpt.ambiguous) return { ok: false, reason: 'excerpt-ambiguous' }
897
- }
898
-
899
- var textRuns = []
900
- for (var r = 0; r < ranges.length; r++) {
901
- var found = []
902
- for (var n = 0; n < map.nodes.length; n++) {
903
- var part = selectedPart(ranges[r], map.nodes[n])
904
- if (part) found.push(part)
905
- }
906
- var merged = mergeRanges(found, map.text)
907
- for (var m = 0; m < merged.length; m++) textRuns.push(merged[m])
908
- }
909
- if (excerpt) textRuns = [{ start: excerpt.start, end: excerpt.end, node: nodeForOffset(map, excerpt.start) }]
910
- textRuns = mergeRanges(textRuns)
911
-
912
- var tables = []
913
- if (targetTable) tables.push(targetTable)
914
- else {
915
- var allTables = body.querySelectorAll ? body.querySelectorAll('table') : []
916
- for (var t = 0; t < allTables.length && t < 200; t++) {
917
- if (!dataTable(allTables[t])) continue
918
- for (var q = 0; q < ranges.length; q++) {
919
- var hitTable = false
920
- try { hitTable = ranges[q].intersectsNode(allTables[t]) } catch (error) { hitTable = false }
921
- if (hitTable) { tables.push(allTables[t]); break }
922
- }
923
- }
924
- }
925
- var topTables = []
926
- for (var t2 = 0; t2 < tables.length; t2++) {
927
- var nested = false
928
- for (var t3 = 0; t3 < tables.length; t3++) {
929
- if (t3 !== t2 && isInside(tables[t2], tables[t3])) { nested = true; break }
930
- }
931
- if (!nested) topTables.push(tables[t2])
932
- }
933
- tables = topTables
934
-
935
- if (!targetTable) {
936
- var ariaGrids = body.querySelectorAll ? body.querySelectorAll('[role="grid"], [role="table"]') : []
937
- for (var ag = 0; ag < ariaGrids.length && ag < 50; ag++) {
938
- var grid = ariaGrids[ag]
939
- if (String(grid.tagName || '').toUpperCase() === 'TABLE') continue
940
- var hitGrid = false
941
- for (var qg = 0; qg < ranges.length; qg++) {
942
- try { hitGrid = ranges[qg].intersectsNode(grid) } catch (error) { hitGrid = false }
943
- if (hitGrid) break
944
- }
945
- if (!hitGrid) continue
946
- var insideSelected = false
947
- for (var ht = 0; ht < tables.length; ht++) {
948
- if (isInside(grid, tables[ht])) { insideSelected = true; break }
949
- }
950
- if (!insideSelected) tables.push(grid)
951
- }
952
- }
953
-
954
- var images = []
955
- if (targetImage) images.push(targetImage)
956
- else if (!targetTable) {
957
- var allImages = body.querySelectorAll ? body.querySelectorAll('img, svg, canvas') : []
958
- for (var g = 0; g < allImages.length && g < 400; g++) {
959
- var image = allImages[g]
960
- if (image.closest && image.closest(MATH_SELECTOR)) continue
961
- var canvasImage = String(image.tagName || '').toUpperCase() === 'CANVAS'
962
- if (!canvasImage && isSvg(image) && image.parentElement && isSvg(image.parentElement)) continue
963
- if (!visibleNode(image)) continue
964
- var hitImage = false
965
- for (var w = 0; w < ranges.length; w++) {
966
- try { hitImage = ranges[w].intersectsNode(image) } catch (error) { hitImage = false }
967
- if (hitImage) break
968
- }
969
- if (!hitImage) continue
970
- var box = geometryOf(image)
971
- if (box.w < 8 || box.h < 8) continue
972
- var insideTable = false
973
- for (var it = 0; it < tables.length; it++) {
974
- if (isInside(image, tables[it])) { insideTable = true; break }
975
- }
976
- if (insideTable) continue
977
- images.push(image)
978
- }
979
- }
980
-
981
- // A selected table's text belongs to the table part. The flat map runs straight through
982
- // it (cells contribute their text like any other node), so a run that spans a table would
983
- // carry that text a second time; cut each table's span out and keep the text on both sides.
984
- var tableSpans = []
985
- if (typeof Map === 'function' && typeof document.createTreeWalker === 'function') {
986
- for (var ts = 0; ts < tables.length; ts++) {
987
- var min = Infinity
988
- var max = -1
989
- for (var tn = 0; tn < map.nodes.length; tn++) {
990
- var offset = map.nodes[tn]
991
- if (isInside(offset.node, tables[ts])) {
992
- if (offset.start < min) min = offset.start
993
- if (offset.end > max) max = offset.end
994
- }
995
- }
996
- if (max > min) tableSpans.push({ start: min, end: max })
997
- }
998
- }
999
- var keptRuns = []
1000
- for (var kr = 0; kr < textRuns.length; kr++) {
1001
- var pieces = subtractSpans(textRuns[kr], tableSpans)
1002
- for (var kp = 0; kp < pieces.length; kp++) {
1003
- var trimmed = trimmedRun(map, pieces[kp].start, pieces[kp].end)
1004
- if (trimmed) keptRuns.push({ start: trimmed.start, end: trimmed.end, node: nodeForOffset(map, trimmed.start) })
1005
- }
1006
- }
1007
-
1008
- var events = []
1009
- var context = Math.max(0, Math.min(Number(spec.context) || 32, 512))
1010
- for (var tr = 0; tr < keptRuns.length; tr++) {
1011
- var run = keptRuns[tr]
1012
- var start = safeStart(map.text, run.start)
1013
- var end = safeEnd(map.text, run.end)
1014
- var exact = map.text.slice(start, end)
1015
- if (collapse(exact, 0) === '') continue
1016
- events.push({
1017
- node: run.node,
1018
- payload: {
1019
- kind: 'text',
1020
- exact: exact,
1021
- content: selectedContent(map.content, start, end),
1022
- prefix: map.text.slice(safeStart(map.text, Math.max(0, start - context)), start),
1023
- suffix: map.text.slice(end, safeEnd(map.text, Math.min(map.text.length, end + context))),
1024
- },
1025
- })
1026
- }
1027
- for (var im = 0; im < images.length; im++) {
1028
- var element = images[im]
1029
- var elementCanvas = String(element.tagName || '').toUpperCase() === 'CANVAS'
1030
- var canvasData = ''
1031
- if (elementCanvas) {
1032
- try { canvasData = String(element.toDataURL('image/png') || '') } catch (error) { canvasData = '' }
1033
- }
1034
- events.push({
1035
- node: element,
1036
- payload: {
1037
- kind: 'image',
1038
- src: elementCanvas ? canvasData : String(element.currentSrc || element.src || ''),
1039
- currentSrc: elementCanvas ? canvasData : String(element.currentSrc || ''),
1040
- attributeSrc: elementCanvas ? canvasData : element.getAttribute ? String(element.getAttribute('src') || '') : '',
1041
- dataUrl: canvasData,
1042
- alt: collapse(element.getAttribute ? element.getAttribute('alt') : '', 500),
1043
- caption: captionOf(element),
1044
- selector: selectorOf(element),
1045
- path: pathOf(element),
1046
- svg: isSvg(element),
1047
- canvas: elementCanvas,
1048
- width: elementCanvas ? (Number(element.width) || 0) : (Number(element.naturalWidth) || 0),
1049
- height: elementCanvas ? (Number(element.height) || 0) : (Number(element.naturalHeight) || 0),
1050
- geometry: geometryOf(element),
1051
- },
1052
- })
1053
- }
1054
- for (var tb = 0; tb < tables.length; tb++) {
1055
- var gridRole = String(tables[tb].getAttribute && tables[tb].getAttribute('role') || '').toLowerCase()
1056
- var ariaGrid = gridRole === 'grid' || gridRole === 'table'
1057
- var snapshot = ariaGrid ? ariaTableSnapshot(tables[tb], ranges, spec) : tableSnapshot(tables[tb], ranges, spec)
1058
- if (snapshot === null) continue
1059
- events.push({
1060
- node: tables[tb],
1061
- payload: {
1062
- kind: 'table',
1063
- selector: selectorOf(tables[tb]),
1064
- path: pathOf(tables[tb]),
1065
- geometry: geometryOf(tables[tb]),
1066
- table: snapshot,
1067
- },
1068
- })
1069
- }
1070
- events.sort(function (a, b) { return documentOrder(a.node, b.node) })
1071
-
1072
- return {
1073
- ok: true,
1074
- url: String(location.href),
1075
- frameUrl: String(location.href),
1076
- title: String(document.title || ''),
1077
- multipleRanges: ranges.length > 1,
1078
- truncated: map.truncated,
1079
- ambiguousExcerpt: excerpt ? excerpt.ambiguous : false,
1080
- events: events.map(function (entry) { return entry.payload }),
1081
- }
1082
- }
1083
-
1084
- function nodeForOffset(map, offset) {
1085
- for (var i = 0; i < map.nodes.length; i++) {
1086
- if (offset >= map.nodes[i].start && offset < map.nodes[i].end) return map.nodes[i].node
1087
- }
1088
- return map.nodes.length ? map.nodes[0].node : null
1089
- }
1090
-
1091
- function highlightRects(rects, spec) {
1092
- clearHighlight()
1093
- var host = document.createElement('div')
1094
- host.id = HIGHLIGHT_ID
1095
- host.style.cssText = 'position:absolute;top:0;left:0;width:0;height:0;pointer-events:none;z-index:2147483646'
1096
- var scrollX = window.scrollX || window.pageXOffset || 0
1097
- var scrollY = window.scrollY || window.pageYOffset || 0
1098
- var fill = spec.fill || 'rgba(255,214,0,0.35)'
1099
- var line = spec.line || 'rgba(214,158,0,0.9)'
1100
- for (var i = 0; i < rects.length; i++) {
1101
- var rect = rects[i]
1102
- if (!rect || rect.width <= 0 || rect.height <= 0) continue
1103
- var box = document.createElement('div')
1104
- box.style.cssText = 'position:absolute;pointer-events:none;border-radius:2px'
1105
- box.style.background = fill
1106
- box.style.outline = '1px solid ' + line
1107
- box.style.left = (rect.left + scrollX) + 'px'
1108
- box.style.top = (rect.top + scrollY) + 'px'
1109
- box.style.width = rect.width + 'px'
1110
- box.style.height = rect.height + 'px'
1111
- host.appendChild(box)
1112
- }
1113
- if (!host.firstChild) return 0
1114
- ;(document.body || document.documentElement).appendChild(host)
1115
- var count = host.childNodes.length
1116
- var events = ['pointerdown', 'keydown', 'touchstart', 'wheel', 'resize']
1117
- var dispose = function () {
1118
- for (var i = 0; i < events.length; i++) window.removeEventListener(events[i], clearHighlight, true)
1119
- if (host.parentNode) host.parentNode.removeChild(host)
1120
- }
1121
- window.__dshRefHighlightDispose = dispose
1122
- for (var j = 0; j < events.length; j++) window.addEventListener(events[j], clearHighlight, true)
1123
- return count
1124
- }
1125
-
1126
- function clearHighlight() {
1127
- var dispose = window.__dshRefHighlightDispose
1128
- delete window.__dshRefHighlightDispose
1129
- if (typeof dispose === 'function') dispose()
1130
- var existing = document.getElementById(HIGHLIGHT_ID)
1131
- if (existing && existing.parentNode) existing.parentNode.removeChild(existing)
1132
- }
1133
-
1134
- function visibleRect(rects) {
1135
- for (var i = 0; i < rects.length; i++) {
1136
- var rect = rects[i]
1137
- if (rect.width > 0 && rect.height > 0 && rect.bottom > 0 && rect.top < window.innerHeight
1138
- && rect.right > 0 && rect.left < window.innerWidth) return true
1139
- }
1140
- return false
1141
- }
1142
-
1143
- function scrollRect(rect) {
1144
- if (!rect) return false
1145
- try {
1146
- var height = window.innerHeight || 0
1147
- if (height > 0 && (rect.top < 48 || rect.bottom > height - 48)) {
1148
- var target = (window.scrollY || 0) + rect.top - height / 2 + rect.height / 2
1149
- window.scrollTo({ left: window.scrollX || 0, top: Math.max(0, target), behavior: 'instant' })
1150
- return true
1151
- }
1152
- } catch (error) { /* a page that refuses scrolling still gets the highlight */ }
1153
- return false
1154
- }
1155
-
1156
- function highlightText(spec) {
1157
- var map = flatTextMap(spec.maxChars, false, spec.legacy)
1158
- var start = Math.max(0, Math.min(Number(spec.start) || 0, map.text.length))
1159
- var end = Math.max(0, Math.min(Number(spec.end) || 0, map.text.length))
1160
- if (end <= start) return { ok: false, reason: 'range-not-found' }
1161
- var startEntry = null
1162
- var endEntry = null
1163
- for (var i = 0; i < map.nodes.length; i++) {
1164
- var entry = map.nodes[i]
1165
- if (start >= entry.start && start < entry.end) startEntry = { node: entry.node, offset: start - entry.start, atomic: entry.atomic }
1166
- if (end > entry.start && end <= entry.end) endEntry = { node: entry.node, offset: end - entry.start, atomic: entry.atomic }
1167
- }
1168
- if (!startEntry || !endEntry) return { ok: false, reason: 'range-not-found' }
1169
- var range = document.createRange()
1170
- if (startEntry.atomic) range.setStartBefore(startEntry.node)
1171
- else range.setStart(startEntry.node, startEntry.offset)
1172
- if (endEntry.atomic) range.setEndAfter(endEntry.node)
1173
- else range.setEnd(endEntry.node, endEntry.offset)
1174
- var parent = startEntry.node.parentElement
1175
- if (parent && parent.scrollIntoView) {
1176
- try { parent.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' }) } catch (error) {}
1177
- }
1178
- var rects = range.getClientRects ? range.getClientRects() : []
1179
- var first = rects.length ? rects[0] : range.getBoundingClientRect()
1180
- scrollRect(first)
1181
- rects = range.getClientRects ? range.getClientRects() : []
1182
- if (!visibleRect(rects)) return { ok: false, reason: 'range-not-visible', rects: 0, scrolled: false }
1183
- var count = highlightRects(rects, spec)
1184
- if (!count) return { ok: false, reason: 'highlight-not-drawn', rects: 0, scrolled: false }
1185
- var selection = window.getSelection()
1186
- if (selection) {
1187
- selection.removeAllRanges()
1188
- selection.addRange(range)
1189
- }
1190
- return { ok: true, rects: count, scrolled: true }
1191
- }
1192
-
1193
- function loadImage(url) {
1194
- return new Promise(function (resolve) {
1195
- var image = new Image()
1196
- if (!/^data:image\/svg\+xml/i.test(url)) image.crossOrigin = 'anonymous'
1197
- var done = false
1198
- var timer = setTimeout(function () {
1199
- if (done) return
1200
- done = true
1201
- resolve({ ok: false, reason: 'image-timeout' })
1202
- }, 5000)
1203
- image.onload = function () {
1204
- if (done) return
1205
- done = true
1206
- clearTimeout(timer)
1207
- resolve({ ok: true, image: image, width: image.naturalWidth || image.width, height: image.naturalHeight || image.height })
1208
- }
1209
- image.onerror = function () {
1210
- if (done) return
1211
- done = true
1212
- clearTimeout(timer)
1213
- resolve({ ok: false, reason: 'image-load-failed' })
1214
- }
1215
- image.src = url
1216
- })
1217
- }
1218
-
1219
- function rasterize(spec) {
1220
- var node = spec.path ? nodeAtPath(spec.path) : (spec.selector ? document.querySelector(spec.selector) : null)
1221
- if (!node) return Promise.resolve({ ok: false, reason: 'element-not-found' })
1222
- var url = ''
1223
- var canvasNode = String(node.tagName || '').toUpperCase() === 'CANVAS'
1224
- try {
1225
- if (isSvg(node)) {
1226
- var xml = new XMLSerializer().serializeToString(node)
1227
- url = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(xml)
1228
- } else if (canvasNode) {
1229
- url = node.toDataURL('image/png')
1230
- } else {
1231
- url = node.currentSrc || node.src || ''
1232
- }
1233
- } catch (error) { return Promise.resolve({ ok: false, reason: 'no-image-source' }) }
1234
- if (!url) return Promise.resolve({ ok: false, reason: 'no-image-source' })
1235
- return loadImage(url).then(function (loaded) {
1236
- if (!loaded.ok) return { ok: false, reason: loaded.reason }
1237
- var width = canvasNode ? Number(node.width) || 0 : Number(node.naturalWidth) || loaded.width || 0
1238
- var height = canvasNode ? Number(node.height) || 0 : Number(node.naturalHeight) || loaded.height || 0
1239
- if (!width || !height) {
1240
- var box = geometryOf(node)
1241
- width = box.w
1242
- height = box.h
1243
- }
1244
- if (!width || !height) return { ok: false, reason: 'no-image-size' }
1245
- if (canvasNode) {
1246
- var capDirect = Math.max(64, Math.min(Number(spec.maxDimension) || 1600, 4096))
1247
- if (Math.max(width, height) <= capDirect) {
1248
- try {
1249
- return { ok: true, dataUrl: node.toDataURL('image/png'), width: width, height: height }
1250
- } catch (error) { return { ok: false, reason: 'canvas-tainted' } }
1251
- }
1252
- }
1253
- var cap = Math.max(64, Math.min(Number(spec.maxDimension) || 1600, 4096))
1254
- var scale = Math.min(1, cap / Math.max(width, height))
1255
- var canvas = document.createElement('canvas')
1256
- canvas.width = Math.max(1, Math.round(width * scale))
1257
- canvas.height = Math.max(1, Math.round(height * scale))
1258
- var context = canvas.getContext ? canvas.getContext('2d') : null
1259
- if (!context) return { ok: false, reason: 'no-canvas' }
1260
- try {
1261
- context.drawImage(loaded.image, 0, 0, canvas.width, canvas.height)
1262
- var dataUrl = canvas.toDataURL('image/png')
1263
- return { ok: true, dataUrl: dataUrl, width: canvas.width, height: canvas.height }
1264
- } catch (error) {
1265
- return { ok: false, reason: 'canvas-tainted' }
1266
- }
1267
- })
1268
- }
1269
-
1270
- function revealElement(spec) {
1271
- var anchor = spec.anchor || {}
1272
- var kind = spec.kind
1273
- var best = null
1274
- var bestScore = 0
1275
- var ties = 0
1276
- var pool = []
1277
- var wantedTag = kind === 'image' ? 'img' : 'table'
1278
- var imageTags = ['IMG', 'SVG', 'CANVAS']
1279
- if (anchor.selector) {
1280
- try {
1281
- var direct = document.querySelector(anchor.selector)
1282
- var directTag = direct ? String(direct.tagName).toUpperCase() : ''
1283
- if (direct && (kind === 'image' ? imageTags.indexOf(directTag) !== -1 : directTag === wantedTag.toUpperCase())) pool.push(direct)
1284
- } catch (error) { /* an invalid stored selector is only a miss */ }
1285
- }
1286
- var all = pageBody().querySelectorAll ? pageBody().querySelectorAll(kind === 'image' ? 'img, svg, canvas' : 'table, [role="grid"], [role="table"]') : []
1287
- for (var i = 0; i < all.length && i < 400; i++) {
1288
- if (pool.indexOf(all[i]) === -1) pool.push(all[i])
1289
- }
1290
- for (var p = 0; p < pool.length; p++) {
1291
- var candidate = pool[p]
1292
- var score = 0
1293
- if (kind === 'image') {
1294
- var src = String(candidate.currentSrc || candidate.src || '')
1295
- if (anchor.currentSrc && src === anchor.currentSrc) score += 4
1296
- if (anchor.src && (src === anchor.src || String(candidate.getAttribute('src') || '') === anchor.src)) score += 3
1297
- if (anchor.alt && collapse(candidate.getAttribute('alt'), 500) === anchor.alt) score += 2
1298
- if (anchor.selector && selectorOf(candidate) === anchor.selector) score += 1
1299
- } else {
1300
- var caption = collapse(candidate.caption ? candidate.caption.innerText || candidate.caption.textContent : (candidate.getAttribute ? candidate.getAttribute('aria-label') || '' : ''), 500)
1301
- if (anchor.caption && caption === anchor.caption) score += 6
1302
- if (anchor.headers && anchor.headers.length) {
1303
- var headRow = candidate.rows && candidate.rows.length ? candidate.rows[0] : null
1304
- var headText = []
1305
- if (headRow) {
1306
- for (var hc = 0; hc < headRow.cells.length; hc++) headText.push(collapse(headRow.cells[hc].innerText || headRow.cells[hc].textContent, 200))
1307
- } else if (candidate.querySelectorAll) {
1308
- var headCells = candidate.querySelectorAll('[role="columnheader"], [role="rowheader"]')
1309
- for (var hh = 0; hh < headCells.length && hh < 64; hh++) headText.push(collapse(headCells[hh].innerText || headCells[hh].textContent, 200))
1310
- }
1311
- if (headText.length > 0) {
1312
- var matched = 0
1313
- for (var ah = 0; ah < anchor.headers.length; ah++) {
1314
- if (headText.indexOf(anchor.headers[ah]) !== -1) matched += 1
1315
- }
1316
- if (matched === anchor.headers.length) score += 4
1317
- else score += matched * 0.5
1318
- }
1319
- }
1320
- if (anchor.firstCells && anchor.firstCells.length) {
1321
- var firstText = []
1322
- if (candidate.rows && candidate.rows.length) {
1323
- var firstRow = candidate.rows[0]
1324
- for (var fc = 0; fc < firstRow.cells.length; fc++) firstText.push(collapse(firstRow.cells[fc].innerText || firstRow.cells[fc].textContent, 200))
1325
- } else if (candidate.querySelectorAll) {
1326
- var firstCells = candidate.querySelectorAll('[role="gridcell"], [role="cell"]')
1327
- for (var ff = 0; ff < firstCells.length && ff < 64; ff++) firstText.push(collapse(firstCells[ff].innerText || firstCells[ff].textContent, 200))
1328
- }
1329
- var firstMatched = 0
1330
- for (var af = 0; af < anchor.firstCells.length; af++) {
1331
- if (firstText[af] === anchor.firstCells[af]) firstMatched += 1
1332
- }
1333
- if (firstMatched > 0) score += firstMatched * 0.5
1334
- }
1335
- if (anchor.selector && selectorOf(candidate) === anchor.selector) score += 1
1336
- }
1337
- if (score > bestScore) { best = candidate; bestScore = score; ties = 1 }
1338
- else if (score === bestScore && score > 0 && candidate !== best) ties += 1
1339
- }
1340
- if (!best || bestScore <= 0) return { ok: true, status: 'missing', matches: 0, reason: 'no-candidate' }
1341
- if (ties > 1) return { ok: true, status: 'ambiguous', matches: ties, reason: 'several-candidates' }
1342
- var target = best
1343
- var selectedCells = []
1344
- if (kind === 'table' && Array.isArray(spec.cells)) {
1345
- for (var sc = 0; sc < spec.cells.length && sc < 5000; sc++) {
1346
- var selectedCell = cellAt(best, spec.cells[sc].row, spec.cells[sc].column)
1347
- if (selectedCell && selectedCells.indexOf(selectedCell) === -1) selectedCells.push(selectedCell)
1348
- }
1349
- selectedCells.sort(documentOrder)
1350
- }
1351
- if (kind === 'table' && anchor.cell) {
1352
- var at = cellAt(best, anchor.cell.row, anchor.cell.column)
1353
- if (at) target = at
1354
- }
1355
- try { target.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' }) } catch (error) {
1356
- try { target.scrollIntoView() } catch (ignored) { /* highlight still lands */ }
1357
- }
1358
- var rects = []
1359
- var targets = selectedCells.length ? selectedCells : [target]
1360
- for (var sr = 0; sr < targets.length; sr++) {
1361
- var selectedRects = targets[sr].getClientRects ? targets[sr].getClientRects() : []
1362
- if (!selectedRects.length) selectedRects = [targets[sr].getBoundingClientRect()]
1363
- for (var cr = 0; cr < selectedRects.length; cr++) rects.push(selectedRects[cr])
1364
- }
1365
- if (!visibleRect(rects)) return { ok: false, status: 'missing', matches: 1, reason: 'element-not-visible' }
1366
- var count = highlightRects(rects, spec)
1367
- if (kind === 'table' && count > 0) {
1368
- var selectionRange = document.createRange()
1369
- selectionRange.selectNodeContents(selectedCells.length ? selectedCells[0] : target)
1370
- if (selectedCells.length) {
1371
- var lastCell = selectedCells[selectedCells.length - 1]
1372
- selectionRange.setEnd(lastCell, lastCell.childNodes.length)
1373
- }
1374
- var selection = window.getSelection()
1375
- if (selection) { selection.removeAllRanges(); selection.addRange(selectionRange) }
1376
- }
1377
- return { ok: count > 0, status: count > 0 ? 'found' : 'missing', matches: 1, described: selectorOf(target), rects: count, scrolled: count > 0 }
1378
- }
1379
-
1380
- function cellAt(table, row, column) {
1381
- var rows = table.rows || []
1382
- if (rows.length === 0 && table.querySelectorAll) {
1383
- var ariaCells = table.querySelectorAll('[role="gridcell"], [role="cell"], [role="columnheader"], [role="rowheader"]')
1384
- for (var ai = 0; ai < ariaCells.length && ai < 5000; ai++) {
1385
- var ariaRow = Number(ariaCells[ai].getAttribute('aria-rowindex'))
1386
- var ariaColumn = Number(ariaCells[ai].getAttribute('aria-colindex'))
1387
- if (ariaRow === row + 1 && ariaColumn === column + 1) return ariaCells[ai]
1388
- }
1389
- return null
1390
- }
1391
- if (row < 0 || row >= rows.length) return null
1392
- var occupied = []
1393
- for (var r = 0; r <= row; r++) {
1394
- if (r === row && occupied[column] && occupied[column].end > r) return occupied[column].cell
1395
- var cells = rows[r].cells || []
1396
- var at = 0
1397
- for (var i = 0; i < cells.length; i++) {
1398
- while (occupied[at] && occupied[at].end > r) at++
1399
- var span = Math.max(1, Math.min(Number(cells[i].colSpan) || 1, 200))
1400
- if (r === row && at <= column && column < at + span) return cells[i]
1401
- var end = r + Math.max(1, Math.min(Number(cells[i].rowSpan) || 1, 1000))
1402
- for (var c = at; c < at + span; c++) occupied[c] = { end: end, cell: cells[i] }
1403
- at += span
1404
- }
1405
- }
1406
- return null
1407
- }
1408
- `
1409
-
1410
- function script(body: string): string {
1411
- return `(function (spec) { ${PAGE_LIB} try { ${body} } catch (error) { return JSON.stringify({ ok: false, reason: 'script-error: ' + String(error) }) } })(arguments[0] || {})`
1412
- }
1413
-
1414
- /** The capture script: selection (or one table / one excerpt) to ordered parts. */
1415
- export function captureScript(): string {
1416
- return script('return JSON.stringify(capture(spec))')
1417
- }
1418
-
1419
- /**
1420
- * Show one short sentence inside the page, then let it fade.
1421
- *
1422
- * The bar used to disappear in silence when the host refused a capture (the
1423
- * page had navigated, the selection was lost, the fragment limit was hit), so
1424
- * the click looked like it did nothing. The host calls this with the reason; a
1425
- * missing overlay still gets a plain toast, so the notice survives a re-inject.
1426
- *
1427
- * @param text - one sentence for the reader; bounded here, not by the caller.
1428
- */
1429
- export function noticeScript(text: string): string {
1430
- const payload = JSON.stringify(String(text ?? '').slice(0, 200))
1431
- return script([
1432
- `var text = ${payload}`,
1433
- 'var id = "__dsh-ref-notice"',
1434
- 'var toast = document.getElementById(id)',
1435
- 'if (!toast) {',
1436
- ' toast = document.createElement("div")',
1437
- ' toast.id = id',
1438
- ' toast.setAttribute("role", "status")',
1439
- ' toast.style.cssText = "position:fixed;left:50%;bottom:16px;transform:translateX(-50%);z-index:2147483646;max-width:min(420px,calc(100vw - 24px));padding:6px 10px;border-radius:8px;background:Canvas;color:CanvasText;border:.5px solid GrayText;font:500 12px/18px system-ui,sans-serif;box-shadow:0 6px 20px rgba(0,0,0,.18)"',
1440
- ' ;(document.body || document.documentElement).appendChild(toast)',
1441
- '}',
1442
- 'toast.textContent = text',
1443
- 'toast.style.display = "block"',
1444
- 'if (toast.__dshHide) clearTimeout(toast.__dshHide)',
1445
- 'toast.__dshHide = setTimeout(function () { toast.style.display = "none" }, 4200)',
1446
- 'return JSON.stringify({ ok: true })',
1447
- ].join('\n'))
1448
- }
1449
-
1450
- /**
1451
- * The SAME capture as a resident page function, so the comment bar can freeze a
1452
- * selection before its own focus destroys it.
1453
- *
1454
- * A text-only freeze cannot survive a rich selection: an image or a table would
1455
- * be reduced to its words, and re-locating by the frozen text afterwards either
1456
- * misses (the page changed) or silently picks another occurrence of the same
1457
- * words. Freezing the complete ordered capture — text runs, assets and table
1458
- * ranges, with their anchors — keeps the source identity attached to what the
1459
- * human actually selected. It returns the raw object, not a JSON string,
1460
- * because the caller hands it back to the host unchanged.
1461
- */
1462
- export function captureEntrySource(): string {
1463
- return `(function (spec) { ${PAGE_LIB} try { return capture(spec) } catch (error) { return { ok: false, reason: 'script-error: ' + String(error) } } })`
1464
- }
1465
-
1466
- /** Bound for the frozen capture a page hands back; a real table can be large. */
1467
- export const MAX_FROZEN_CAPTURE_CHARS = 4_000_000
1468
- /**
1469
- * Hard safety bound on a frozen capture's event count. Deliberately ABOVE the
1470
- * service's `maxParts` (64): truncating here would silently drop fragments and
1471
- * turn an honest `too-many-parts` refusal into a reference missing its tail.
1472
- * Only a payload this large is rejected outright.
1473
- */
1474
- export const MAX_FROZEN_CAPTURE_EVENTS = 512
1475
-
1476
- /**
1477
- * Validate the frozen capture a page bar reports, field by field.
1478
- *
1479
- * A page is low-trust: the payload is size-bounded and only the fields the
1480
- * service reads are kept. Every part is validated again by the service's own
1481
- * text/image/table checks, so a malformed event is refused there, not trusted
1482
- * here.
1483
- */
1484
- export function validateFrozenCapture(value: unknown): RawCaptureResult | undefined {
1485
- if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
1486
- const row = value as Record<string, unknown>
1487
- if (row.ok !== true) return undefined
1488
- let serialized: string
1489
- try { serialized = JSON.stringify(row) } catch { return undefined }
1490
- if (serialized.length > MAX_FROZEN_CAPTURE_CHARS) return undefined
1491
- const events = Array.isArray(row.events) ? row.events : []
1492
- if (events.length === 0 || events.length > MAX_FROZEN_CAPTURE_EVENTS) return undefined
1493
- return {
1494
- ok: true,
1495
- ...typeof row.url === 'string' && row.url !== '' ? { url: row.url.slice(0, 4_000) } : {},
1496
- ...typeof row.frameUrl === 'string' && row.frameUrl !== '' ? { frameUrl: row.frameUrl.slice(0, 4_000) } : {},
1497
- ...typeof row.title === 'string' ? { title: row.title.slice(0, 500) } : {},
1498
- // Not truncated: the service applies its own part bound and refuses an
1499
- // oversized group as a whole, which is visible to the user.
1500
- events: events as readonly RawCaptureEvent[],
1501
- }
1502
- }
1503
-
1504
- /** Read the page's visible text, for a host-side text-quote locate. */
1505
- export function pageTextScript(): string {
1506
- return script(`var map = flatTextMap(spec.maxChars, false, spec.legacy)
1507
- return JSON.stringify({ ok: true, url: String(location.href), title: String(document.title || ''), text: map.text, truncated: map.truncated })`)
1508
- }
1509
-
1510
- /** Facts needed to decide whether the page is still the one a reference came from. */
1511
- export function pageFactsScript(): string {
1512
- return script(`return JSON.stringify({ ok: true, url: String(location.href), title: String(document.title || '') })`)
1513
- }
1514
-
1515
- /** Highlight one flat [start, end) range of the page text. */
1516
- export function highlightScript(): string {
1517
- return script('return JSON.stringify(highlightText(spec))')
1518
- }
1519
-
1520
- export function guestReferenceHandlerScript(): string {
1521
- return `function (operation, spec) { ${PAGE_LIB}
1522
- if (operation === 'text') { var map = flatTextMap(spec.maxChars, false, spec.legacy); return { ok: true, text: map.text } }
1523
- if (operation === 'highlight') return highlightText(spec)
1524
- if (operation === 'element') return revealElement(spec)
1525
- throw new Error('unsupported reference operation')
1526
- }`
1527
- }
1528
-
1529
- /** Locate one image or table by its stored anchor, scroll to it and highlight it. */
1530
- export function revealElementScript(): string {
1531
- return script('return JSON.stringify(revealElement(spec))')
1532
- }
1533
-
1534
- /** Rasterise one image element to a PNG data URL, for images whose bytes cannot be fetched. */
1535
- export function rasterizeScript(): string {
1536
- return script('return rasterize(spec).then(function (result) { return JSON.stringify(result) })')
1537
- }