@arcgis/core 5.2.0-next.124 → 5.2.0-next.126

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 (417) hide show
  1. package/analysis/ElevationProfile/ElevationProfileDisplayUnits.d.ts +3 -2
  2. package/analysis/VolumeMeasurement/VolumeMeasurementDisplayUnits.d.ts +1 -0
  3. package/arcade/functions/string.js +1 -1
  4. package/arcgisGlobal.d.ts +2 -0
  5. package/assets/esri/core/workers/RemoteClient.js +1 -1
  6. package/assets/esri/core/workers/chunks/05afa8c2b5929ce0545a.js +1 -0
  7. package/assets/esri/core/workers/chunks/0a20f84b5f004a77a9f9.js +1 -0
  8. package/assets/esri/core/workers/chunks/{97cd4145c016cf379120.js → 0a2b7c691a577cb3d189.js} +1 -1
  9. package/assets/esri/core/workers/chunks/0ccd4200c5a2a5de6e16.js +1 -0
  10. package/assets/esri/core/workers/chunks/{064445e6f9512817ac87.js → 12b5a645c0987a0efe54.js} +2 -2
  11. package/assets/esri/core/workers/chunks/{bdf012e591a8476db467.js → 1406a884241809b62bff.js} +1 -1
  12. package/assets/esri/core/workers/chunks/168b45c5d8233f23793e.js +2 -0
  13. package/assets/esri/core/workers/chunks/17218d714cb07b607c2f.js +1 -0
  14. package/assets/esri/core/workers/chunks/1d040aa8951fff3141d9.js +1 -0
  15. package/assets/esri/core/workers/chunks/{ce08e3369641da0d7a27.js → 1dbb3e25e005a8220779.js} +2 -2
  16. package/assets/esri/core/workers/chunks/{c39ebd8d469f1e8bb61e.js → 25e212fe9a2ea37c9e81.js} +1 -1
  17. package/assets/esri/core/workers/chunks/{216d8cb86548e92a8196.js → 2e3fd81653dc0d86456c.js} +1 -1
  18. package/assets/esri/core/workers/chunks/30604a29df320d7a4c6b.js +1 -0
  19. package/assets/esri/core/workers/chunks/3a40146568e6dd0b1828.js +1 -0
  20. package/assets/esri/core/workers/chunks/3ef367c9b7bf1588307d.js +1 -0
  21. package/assets/esri/core/workers/chunks/4327d2c39a660bd89da7.js +1 -0
  22. package/assets/esri/core/workers/chunks/4678a8170d8a3ccd1a7b.js +1 -0
  23. package/assets/esri/core/workers/chunks/{45d87af48a21644590c2.js → 4716693eca44e8f89f5c.js} +1 -1
  24. package/assets/esri/core/workers/chunks/474d9541d387b31ad275.js +1 -0
  25. package/assets/esri/core/workers/chunks/{20e4277a4a6c57957202.js → 4d18451e0ea6ca54101a.js} +1 -1
  26. package/assets/esri/core/workers/chunks/{26bc509a031788bfa678.js → 4f464047c6f6c9486efd.js} +1 -1
  27. package/assets/esri/core/workers/chunks/{58528ccb7f72ae76d52b.js → 540f60e31b19d85e9371.js} +1 -1
  28. package/assets/esri/core/workers/chunks/{44857a76be2c0ac65bb9.js → 55a560fd872f7463b33d.js} +1 -1
  29. package/assets/esri/core/workers/chunks/56acda1eed3a013430e2.js +1 -0
  30. package/assets/esri/core/workers/chunks/56e97b98dcb8a3f2bcb7.js +1 -0
  31. package/assets/esri/core/workers/chunks/{eb7f45736c852725b0bb.js → 57ab87e70ef85b9405f9.js} +122 -122
  32. package/assets/esri/core/workers/chunks/{59cd139712d919e6a738.js → 5adf2792416b22cd602f.js} +1 -1
  33. package/assets/esri/core/workers/chunks/5fe5ef5ccf480634d159.js +1 -0
  34. package/assets/esri/core/workers/chunks/67678054342178b601cf.js +1 -0
  35. package/assets/esri/core/workers/chunks/67dcf9b873cb037b2647.js +1 -0
  36. package/assets/esri/core/workers/chunks/6c3535aa7250c08b9e5b.js +1 -0
  37. package/assets/esri/core/workers/chunks/6e8187a77846239ed112.js +2 -0
  38. package/assets/esri/core/workers/chunks/76548469fe1b9c3b2051.js +1 -0
  39. package/assets/esri/core/workers/chunks/{52744dfd430cd0c0edfb.js → 78abd6c42f39e6f6ffbb.js} +1 -1
  40. package/assets/esri/core/workers/chunks/{5993db944b9e7825e0bc.js → 7926faab76a721a2e1c4.js} +1 -1
  41. package/assets/esri/core/workers/chunks/7d6da4e89aa951e6523f.js +1 -0
  42. package/assets/esri/core/workers/chunks/7dd94567833386dc74de.js +1 -0
  43. package/assets/esri/core/workers/chunks/{dc0816f064be576a2fa6.js → 7fcee3a1b900ddc9a5e3.js} +1 -1
  44. package/assets/esri/core/workers/chunks/806f96ad09e882be41af.js +1 -0
  45. package/assets/esri/core/workers/chunks/8190fcb1dd10ad20feed.js +1 -0
  46. package/assets/esri/core/workers/chunks/84db05e872dbf35c80a2.js +1 -0
  47. package/assets/esri/core/workers/chunks/85739ed6af0f0a3cb302.js +1 -0
  48. package/assets/esri/core/workers/chunks/{b22de8bf4a4a739bc36d.js → 97602019a1ccad22a03a.js} +1 -1
  49. package/assets/esri/core/workers/chunks/9ca98fffd43e63d5ade3.js +1 -0
  50. package/assets/esri/core/workers/chunks/9d6a96e4c7ccedcb0c13.js +1 -0
  51. package/assets/esri/core/workers/chunks/9ec04faad97be55309b8.js +1 -0
  52. package/assets/esri/core/workers/chunks/a08385ebf1715414c1a6.js +1 -0
  53. package/assets/esri/core/workers/chunks/{e22a013ec38989caf9de.js → a790fc6b22acf651574b.js} +1 -1
  54. package/assets/esri/core/workers/chunks/{2f52ad525744b8793d49.js → a8258636096416c837a2.js} +1 -1
  55. package/assets/esri/core/workers/chunks/{770ca70d363184e39d60.js → ab8a1140bf31f46f8ebf.js} +1 -1
  56. package/assets/esri/core/workers/chunks/{813dd84933b407c8fe86.js → b34305474a861aaf6ccb.js} +1 -1
  57. package/assets/esri/core/workers/chunks/{dc923e50958b68a50014.js → b96358d475dc98034aa4.js} +1 -1
  58. package/assets/esri/core/workers/chunks/ba435cc73956d9c64a11.js +1 -0
  59. package/assets/esri/core/workers/chunks/c5b733c3a5b2680042a2.js +1 -0
  60. package/assets/esri/core/workers/chunks/{f0709c48daca93e759c8.js → c692e583e87af58f6d91.js} +1 -1
  61. package/assets/esri/core/workers/chunks/{39985c51465b79ff0910.js → c77496c350004ee66eb2.js} +1 -1
  62. package/assets/esri/core/workers/chunks/{9e5b30b907102bc0c201.js → cb7cb7d57c4e7f76600f.js} +1 -1
  63. package/assets/esri/core/workers/chunks/{58a17fb3c0dd07c63d57.js → cfaba0470619786e1ef8.js} +2 -2
  64. package/assets/esri/core/workers/chunks/d371d9279b30548efa02.js +1 -0
  65. package/assets/esri/core/workers/chunks/d5f0fed415b5b155d57c.js +1 -0
  66. package/assets/esri/core/workers/chunks/{d3d48401462ef3bf0ad9.js → d5f72670634e73c0b53a.js} +1 -1
  67. package/assets/esri/core/workers/chunks/d6e914f6ed45ea59034e.js +1 -0
  68. package/assets/esri/core/workers/chunks/{5afc12671a9a1bb6c56c.js → dc52e036547612949d32.js} +1 -1
  69. package/assets/esri/core/workers/chunks/e0894a308c84d5c158b0.js +1 -0
  70. package/assets/esri/core/workers/chunks/e1ae83ff3e0225708d4d.js +1 -0
  71. package/assets/esri/core/workers/chunks/e35eb93c0fb1f6de8db0.js +1 -0
  72. package/assets/esri/core/workers/chunks/{df79c00b5ddbef7148a0.js → eaa7cb3ffa8c11706a09.js} +1 -1
  73. package/assets/esri/core/workers/chunks/eebbc86a15ae3adb5f38.js +1 -0
  74. package/assets/esri/core/workers/chunks/{eb780f2dafa14f776166.js → f71ec8a260405ed07958.js} +1 -1
  75. package/assets/esri/core/workers/chunks/fdbda3d2afea25142b86.js +1 -0
  76. package/assets/esri/libs/pdfjs/pdf.worker.mjs +4 -63051
  77. package/assets/esri/themes/base/_FocusRegionOverlayItem.scss +18 -0
  78. package/assets/esri/themes/base/_View.scss +4 -0
  79. package/assets/esri/themes/base/_core.scss +1 -0
  80. package/assets/esri/themes/base/widgets/_OrientedImageryViewer.scss +13 -0
  81. package/assets/esri/themes/dark/main.css +1 -1
  82. package/assets/esri/themes/light/main.css +1 -1
  83. package/assets/esri/themes/light/view.css +1 -1
  84. package/assets/esri/widgets/Editor/t9n/messages.ar.json +1 -1
  85. package/assets/esri/widgets/Editor/t9n/messages.bg.json +1 -1
  86. package/assets/esri/widgets/Editor/t9n/messages.bs.json +1 -1
  87. package/assets/esri/widgets/Editor/t9n/messages.ca.json +1 -1
  88. package/assets/esri/widgets/Editor/t9n/messages.cs.json +1 -1
  89. package/assets/esri/widgets/Editor/t9n/messages.da.json +1 -1
  90. package/assets/esri/widgets/Editor/t9n/messages.de.json +1 -1
  91. package/assets/esri/widgets/Editor/t9n/messages.el.json +1 -1
  92. package/assets/esri/widgets/Editor/t9n/messages.en.json +1 -1
  93. package/assets/esri/widgets/Editor/t9n/messages.es.json +1 -1
  94. package/assets/esri/widgets/Editor/t9n/messages.et.json +1 -1
  95. package/assets/esri/widgets/Editor/t9n/messages.fi.json +1 -1
  96. package/assets/esri/widgets/Editor/t9n/messages.fr.json +1 -1
  97. package/assets/esri/widgets/Editor/t9n/messages.he.json +1 -1
  98. package/assets/esri/widgets/Editor/t9n/messages.hr.json +1 -1
  99. package/assets/esri/widgets/Editor/t9n/messages.hu.json +1 -1
  100. package/assets/esri/widgets/Editor/t9n/messages.id.json +1 -1
  101. package/assets/esri/widgets/Editor/t9n/messages.it.json +1 -1
  102. package/assets/esri/widgets/Editor/t9n/messages.ja.json +1 -1
  103. package/assets/esri/widgets/Editor/t9n/messages.ko.json +1 -1
  104. package/assets/esri/widgets/Editor/t9n/messages.lt.json +1 -1
  105. package/assets/esri/widgets/Editor/t9n/messages.lv.json +1 -1
  106. package/assets/esri/widgets/Editor/t9n/messages.nl.json +1 -1
  107. package/assets/esri/widgets/Editor/t9n/messages.no.json +1 -1
  108. package/assets/esri/widgets/Editor/t9n/messages.pl.json +1 -1
  109. package/assets/esri/widgets/Editor/t9n/messages.pt-BR.json +1 -1
  110. package/assets/esri/widgets/Editor/t9n/messages.pt-PT.json +1 -1
  111. package/assets/esri/widgets/Editor/t9n/messages.ro.json +1 -1
  112. package/assets/esri/widgets/Editor/t9n/messages.ru.json +1 -1
  113. package/assets/esri/widgets/Editor/t9n/messages.sk.json +1 -1
  114. package/assets/esri/widgets/Editor/t9n/messages.sl.json +1 -1
  115. package/assets/esri/widgets/Editor/t9n/messages.sr.json +1 -1
  116. package/assets/esri/widgets/Editor/t9n/messages.sv.json +1 -1
  117. package/assets/esri/widgets/Editor/t9n/messages.th.json +1 -1
  118. package/assets/esri/widgets/Editor/t9n/messages.tr.json +1 -1
  119. package/assets/esri/widgets/Editor/t9n/messages.uk.json +1 -1
  120. package/assets/esri/widgets/Editor/t9n/messages.vi.json +1 -1
  121. package/assets/esri/widgets/Editor/t9n/messages.zh-CN.json +1 -1
  122. package/assets/esri/widgets/Editor/t9n/messages.zh-HK.json +1 -1
  123. package/assets/esri/widgets/Editor/t9n/messages.zh-TW.json +1 -1
  124. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.ar.json +1 -1
  125. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.bg.json +1 -1
  126. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.bs.json +1 -1
  127. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.ca.json +1 -1
  128. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.cs.json +1 -1
  129. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.da.json +1 -1
  130. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.de.json +1 -1
  131. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.el.json +1 -1
  132. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.es.json +1 -1
  133. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.et.json +1 -1
  134. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.fi.json +1 -1
  135. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.fr.json +1 -1
  136. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.he.json +1 -1
  137. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.hr.json +1 -1
  138. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.hu.json +1 -1
  139. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.id.json +1 -1
  140. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.it.json +1 -1
  141. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.ja.json +1 -1
  142. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.ko.json +1 -1
  143. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.lt.json +1 -1
  144. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.lv.json +1 -1
  145. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.nl.json +1 -1
  146. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.no.json +1 -1
  147. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.pl.json +1 -1
  148. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.pt-BR.json +1 -1
  149. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.pt-PT.json +1 -1
  150. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.ro.json +1 -1
  151. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.ru.json +1 -1
  152. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.sk.json +1 -1
  153. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.sl.json +1 -1
  154. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.sr.json +1 -1
  155. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.sv.json +1 -1
  156. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.th.json +1 -1
  157. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.tr.json +1 -1
  158. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.uk.json +1 -1
  159. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.vi.json +1 -1
  160. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.zh-CN.json +1 -1
  161. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.zh-HK.json +1 -1
  162. package/assets/esri/widgets/support/SelectionToolbar/t9n/messages.zh-TW.json +1 -1
  163. package/chunks/GaussianSplatColorComposition.glsl.js +2 -0
  164. package/chunks/GaussianSplatEmissionComposition.glsl.js +11 -0
  165. package/chunks/GlobalIllumination.glsl.js +9 -9
  166. package/chunks/GlobalIlluminationBlur.glsl.js +8 -8
  167. package/chunks/HeatmapDensity.glsl.js +5 -5
  168. package/chunks/Pattern.glsl.js +30 -30
  169. package/chunks/RibbonLine.glsl.js +19 -19
  170. package/chunks/earcut.js +1 -1
  171. package/chunks/portal.js +1 -1
  172. package/config.js +1 -1
  173. package/core/accessorSupport/types.d.ts +5 -1
  174. package/graphic/MapImageGraphicOrigin.js +1 -1
  175. package/graphic/TileGraphicOrigin.js +1 -1
  176. package/interfaces.d.ts +8 -0
  177. package/kernel.js +1 -1
  178. package/layers/OrientedImageryLayer.js +1 -1
  179. package/layers/ParquetLayer.d.ts +3 -2
  180. package/layers/ParquetLayer.js +1 -1
  181. package/layers/SceneLayer.js +1 -1
  182. package/layers/geospatialPDF/GeospatialPDFFrame.js +1 -1
  183. package/layers/geospatialPDF/GeospatialPDFLayerWorker.js +2 -2
  184. package/layers/geospatialPDF/GeospatialPDFWorkerClient.js +1 -1
  185. package/layers/geospatialPDF/LGIDictMapFrame.js +1 -1
  186. package/layers/geospatialPDF/ViewportMeasureFrame.js +1 -1
  187. package/layers/geospatialPDF/geospatialPDFParserUtils.js +2 -0
  188. package/layers/geospatialPDF/projectionToWKTUtils.js +2 -0
  189. package/layers/geospatialPDF/renderExtentUtils.js +1 -1
  190. package/layers/geospatialPDF/sharedUtils.js +1 -1
  191. package/layers/mixins/ArcGISImageService.js +1 -1
  192. package/layers/mixins/TemporalLayer.js +1 -1
  193. package/layers/orientedImagery/transformations/imageToWorld.js +1 -1
  194. package/layers/orientedImagery/transformations/utils.js +1 -1
  195. package/layers/raster/datasets/GeospatialPDFRaster.js +1 -1
  196. package/layers/raster/types.d.ts +6 -0
  197. package/layers/support/TimeInfo.js +1 -1
  198. package/layers/support/TimeSeriesCalculation.d.ts +32 -0
  199. package/layers/support/TimeSeriesCalculation.js +2 -0
  200. package/layers/support/TimeSeriesInfo.d.ts +19 -0
  201. package/layers/support/TimeSeriesInfo.js +1 -1
  202. package/layers/support/commonProperties.js +1 -1
  203. package/layers/support/layersMapping.js +1 -1
  204. package/layers/support/timeSeriesUtils.d.ts +25 -1
  205. package/layers/support/timeSeriesUtils.js +1 -1
  206. package/layers/types.d.ts +1 -0
  207. package/package.json +2 -2
  208. package/popup/FeatureContentCollection.d.ts +12 -2
  209. package/popup/FeatureContentCollection.js +1 -1
  210. package/popup/types.d.ts +14 -3
  211. package/portal/schemas/definitions.js +1 -1
  212. package/portal/schemas/sceneLayerItem.js +1 -1
  213. package/renderers/support/AuthoringInfo.d.ts +8 -1
  214. package/renderers/support/AuthoringInfo.js +1 -1
  215. package/renderers/support/AuthoringInfoVisualVariable.d.ts +8 -1
  216. package/renderers/support/AuthoringInfoVisualVariable.js +1 -1
  217. package/rest/imageService/fetchRasterInfo.js +1 -1
  218. package/rest/knowledgeGraph/DataModel.js +1 -1
  219. package/smartMapping/renderers/color.d.ts +12 -0
  220. package/smartMapping/renderers/color.js +1 -1
  221. package/smartMapping/renderers/opacity.d.ts +6 -0
  222. package/smartMapping/renderers/opacity.js +1 -1
  223. package/smartMapping/renderers/size.d.ts +12 -0
  224. package/smartMapping/renderers/size.js +1 -1
  225. package/smartMapping/renderers/support/regenerateUtils.js +1 -1
  226. package/smartMapping/renderers/support/rendererUtils.js +1 -1
  227. package/smartMapping/renderers/support/timeSeriesUtils.js +1 -1
  228. package/smartMapping/renderers/type.d.ts +6 -0
  229. package/smartMapping/renderers/type.js +1 -1
  230. package/smartMapping/renderers/univariateColorSize.d.ts +6 -0
  231. package/smartMapping/renderers/univariateColorSize.js +1 -1
  232. package/support/revision.js +1 -1
  233. package/symbols/support/gfxUtils.js +1 -1
  234. package/symbols/support/previewSymbol3D.js +1 -1
  235. package/symbols/support/svgUtils.js +1 -1
  236. package/time/timeZoneUtils.js +1 -1
  237. package/views/2d/analysis/AreaMeasurement/AreaMeasurementTool.js +1 -1
  238. package/views/2d/analysis/AreaMeasurementAnalysisView2D.d.ts +8 -0
  239. package/views/2d/analysis/AreaMeasurementAnalysisView2D.js +1 -1
  240. package/views/2d/analysis/DistanceMeasurement/DistanceMeasurementTool.js +1 -1
  241. package/views/2d/analysis/DistanceMeasurementAnalysisView2D.d.ts +8 -0
  242. package/views/2d/analysis/DistanceMeasurementAnalysisView2D.js +1 -1
  243. package/views/2d/analysis/ElevationProfileAnalysisView2D.d.ts +3 -2
  244. package/views/3d/analysis/AreaMeasurementAnalysisView3D.js +1 -1
  245. package/views/3d/analysis/Dimension/DimensionController.js +1 -1
  246. package/views/3d/analysis/DirectLineMeasurementAnalysisView3D.js +1 -1
  247. package/views/3d/analysis/ElevationProfileAnalysisView3D.d.ts +3 -2
  248. package/views/3d/analysis/LineOfSight/LineOfSightEditTool.js +1 -1
  249. package/views/3d/analysis/LineOfSight/LineOfSightItemTool.js +1 -1
  250. package/views/3d/analysis/LineOfSight/lineOfSightPlacementUtils.js +1 -1
  251. package/views/3d/analysis/Viewshed/ViewshedEditTool.js +1 -1
  252. package/views/3d/analysis/Viewshed/ViewshedPlacementController.js +1 -1
  253. package/views/3d/analysis/VolumeMeasurement/VolumeMeasurementShiftTool.js +1 -1
  254. package/views/3d/analysis/VolumeMeasurementAnalysisView3D.d.ts +1 -0
  255. package/views/3d/analysis/VolumeMeasurementAnalysisView3D.js +1 -1
  256. package/views/3d/input/handlers/DragRotate.js +1 -1
  257. package/views/3d/input/handlers/PinchAndPanNavigation.js +1 -1
  258. package/views/3d/input/handlers/ground/GroundDoubleClickMove.js +1 -1
  259. package/views/3d/input/handlers/ground/GroundNavigation.js +1 -1
  260. package/views/3d/interactive/measurementTools/areaMeasurement3D/AreaMeasurement3DTool.js +1 -1
  261. package/views/3d/interactive/measurementTools/directLineMeasurement3D/DirectLineMeasurement3DTool.js +1 -1
  262. package/views/3d/interactive/placementTools/GroundNavigationPlacementTool3D.js +2 -0
  263. package/views/3d/navigation/Navigation3D.d.ts +7 -0
  264. package/views/3d/navigation/Navigation3D.js +1 -1
  265. package/views/3d/navigation/modes/navigationModeUtils.d.ts +32 -0
  266. package/views/3d/navigation/modes/navigationModeUtils.js +2 -0
  267. package/views/3d/state/Constraints.js +1 -1
  268. package/views/3d/state/controllers/GroundNavigationController.js +1 -1
  269. package/views/3d/state/controllers/RotateController.js +1 -1
  270. package/views/3d/state/utils/groundNavigationUtils.js +1 -1
  271. package/views/3d/support/engineContent/line.js +1 -1
  272. package/views/3d/support/planarDistanceToGroundRatio.js +2 -0
  273. package/views/3d/terrain/OverlayManager.js +1 -1
  274. package/views/3d/terrain/OverlayRenderer.js +1 -1
  275. package/views/3d/webgl-engine/core/shaderLibrary/shading/LineStipple.glsl.js +13 -13
  276. package/views/3d/webgl-engine/core/shaderLibrary/shading/MarkerSizing.glsl.js +2 -2
  277. package/views/3d/webgl-engine/effects/globalIllumination/GlobalIllumination.glsl.js +1 -1
  278. package/views/3d/webgl-engine/effects/globalIllumination/GlobalIllumination.js +1 -1
  279. package/views/3d/webgl-engine/lib/BindParameters.js +1 -1
  280. package/views/3d/webgl-engine/lib/GaussianSplatRenderUtils.js +1 -1
  281. package/views/3d/webgl-engine/lib/GaussianSplatRenderer.js +1 -1
  282. package/views/3d/webgl-engine/lib/GaussianSplatShadows.js +1 -1
  283. package/views/3d/webgl-engine/lib/SortedRenderGeometryRenderer.js +1 -1
  284. package/views/3d/webgl-engine/materials/RibbonLineMaterial.js +1 -1
  285. package/views/3d/webgl-engine/shaders/GaussianSplatColorComposition.glsl.js +2 -0
  286. package/views/3d/webgl-engine/shaders/GaussianSplatColorCompositionTechnique.js +2 -0
  287. package/views/3d/webgl-engine/shaders/GaussianSplatDepthPolicy.js +1 -1
  288. package/views/3d/webgl-engine/shaders/{GaussianSplatComposition.glsl.js → GaussianSplatEmissionComposition.glsl.js} +1 -1
  289. package/views/3d/webgl-engine/shaders/GaussianSplatEmissionCompositionTechnique.js +2 -0
  290. package/views/3d/webgl-engine/shaders/GaussianSplatTechnique.js +1 -1
  291. package/views/DOMContainer.d.ts +27 -0
  292. package/views/DOMContainer.js +1 -1
  293. package/views/PopupView.d.ts +1 -1
  294. package/views/View.d.ts +10 -1
  295. package/views/View.js +1 -1
  296. package/views/analysis/ElevationProfile/ElevationProfileController.js +1 -1
  297. package/views/analysis/LengthDimensionResult.d.ts +4 -1
  298. package/views/draw/support/managers/TooltipManager.js +1 -1
  299. package/views/input/types.d.ts +46 -0
  300. package/views/interactive/options/SnappingOptions.d.ts +4 -2
  301. package/views/interactive/options/SnappingOptions.js +1 -1
  302. package/views/interactive/options/ViewOptions.d.ts +18 -0
  303. package/views/interactive/options/bindViewToolOptions.js +2 -0
  304. package/views/interactive/snapping/SnappingManagerPool.js +1 -1
  305. package/views/interactive/snapping/allLayerSnapping.js +1 -1
  306. package/views/overlay/FocusRegionOverlayItem.js +2 -0
  307. package/views/selection/SelectionOperation.d.ts +27 -1
  308. package/views/selection/types.d.ts +8 -20
  309. package/views/webgl/renderState.js +1 -1
  310. package/widgets/AreaMeasurement2D/AreaMeasurement2DViewModel.d.ts +1 -0
  311. package/widgets/AreaMeasurement2D/AreaMeasurement2DViewModel.js +1 -1
  312. package/widgets/AreaMeasurement2D.js +1 -1
  313. package/widgets/BasemapLayerList/BasemapLayerListViewModel.d.ts +1 -0
  314. package/widgets/BasemapLayerList.d.ts +1 -0
  315. package/widgets/BatchAttributeForm/expressions/types.d.ts +1 -0
  316. package/widgets/BatchAttributeForm/inputs/FieldInput.d.ts +2 -0
  317. package/widgets/BatchAttributeForm/types.d.ts +5 -1
  318. package/widgets/BatchAttributeForm.d.ts +1 -0
  319. package/widgets/Bookmarks/BookmarksViewModel.d.ts +1 -0
  320. package/widgets/Bookmarks.d.ts +1 -0
  321. package/widgets/CatalogLayerList/CatalogLayerListViewModel.d.ts +1 -0
  322. package/widgets/CatalogLayerList.d.ts +1 -0
  323. package/widgets/DistanceMeasurement2D/DistanceMeasurement2DViewModel.d.ts +1 -0
  324. package/widgets/DistanceMeasurement2D/DistanceMeasurement2DViewModel.js +1 -1
  325. package/widgets/DistanceMeasurement2D.js +1 -1
  326. package/widgets/Editor.d.ts +1 -0
  327. package/widgets/Editor.js +1 -1
  328. package/widgets/FeatureForm.d.ts +1 -0
  329. package/widgets/FeatureTable/FeatureTableViewModel.d.ts +37 -1
  330. package/widgets/FeatureTable/FeatureTableViewModel.js +1 -1
  331. package/widgets/FeatureTable/support/FeatureStore.d.ts +26 -2
  332. package/widgets/FeatureTable/support/FeatureStore.js +1 -1
  333. package/widgets/FeatureTable.d.ts +12 -1
  334. package/widgets/FeatureTable.js +1 -1
  335. package/widgets/FeatureTemplates.d.ts +1 -0
  336. package/widgets/Features/FeaturesViewModel.d.ts +1 -0
  337. package/widgets/Features.d.ts +2 -1
  338. package/widgets/HistogramRangeSlider.d.ts +1 -0
  339. package/widgets/Home/HomeViewModel.d.ts +1 -0
  340. package/widgets/Home.d.ts +1 -0
  341. package/widgets/LayerList/LayerListViewModel.d.ts +1 -0
  342. package/widgets/LayerList.d.ts +1 -0
  343. package/widgets/Locate/LocateViewModel.d.ts +1 -0
  344. package/widgets/Locate.d.ts +1 -0
  345. package/widgets/OrientedImageryViewer/adapters/view/SceneViewAdapter.js +1 -1
  346. package/widgets/OrientedImageryViewer/components/Alert.js +1 -1
  347. package/widgets/OrientedImageryViewer/navigation/NavigationManagerPanoramic.js +1 -1
  348. package/widgets/OrientedImageryViewer/types.d.ts +4 -1
  349. package/widgets/OrientedImageryViewer.d.ts +4 -1
  350. package/widgets/OrientedImageryViewer.js +1 -1
  351. package/widgets/Popup/types.d.ts +7 -0
  352. package/widgets/Popup.d.ts +1 -0
  353. package/widgets/Print/PrintViewModel.d.ts +1 -0
  354. package/widgets/Print.d.ts +1 -0
  355. package/widgets/Search.d.ts +1 -0
  356. package/widgets/Sketch.d.ts +1 -0
  357. package/widgets/Slider.d.ts +4 -0
  358. package/widgets/TimeSlider.d.ts +1 -0
  359. package/widgets/Track/TrackViewModel.d.ts +1 -0
  360. package/widgets/Track.d.ts +1 -0
  361. package/widgets/UtilityNetworkTrace/UtilityNetworkTraceViewModel.d.ts +1 -0
  362. package/widgets/UtilityNetworkTrace.d.ts +1 -0
  363. package/widgets/ValuePicker/types.d.ts +1 -0
  364. package/widgets/ValuePicker.d.ts +1 -0
  365. package/widgets/smartMapping/SmartMappingSliderBase.d.ts +1 -0
  366. package/widgets/support/SelectionList/types.d.ts +2 -0
  367. package/widgets/support/SelectionToolbar/SelectionToolbarViewModel.d.ts +2 -1
  368. package/assets/esri/core/workers/chunks/0148cb611bf7c8c5fe8a.js +0 -1
  369. package/assets/esri/core/workers/chunks/033debcbf6b3683dc4fe.js +0 -2
  370. package/assets/esri/core/workers/chunks/0acc754907395e83bbc6.js +0 -1
  371. package/assets/esri/core/workers/chunks/1c38ce72160d5a4e4b3d.js +0 -1
  372. package/assets/esri/core/workers/chunks/1e46703cb566c25458ad.js +0 -1
  373. package/assets/esri/core/workers/chunks/23279303cd7698314c56.js +0 -1
  374. package/assets/esri/core/workers/chunks/25c90092def215949db9.js +0 -1
  375. package/assets/esri/core/workers/chunks/29ae19206bbeb480be0f.js +0 -1
  376. package/assets/esri/core/workers/chunks/2f829321bfbd3bacd64f.js +0 -1
  377. package/assets/esri/core/workers/chunks/38890ac5917942374ab8.js +0 -1
  378. package/assets/esri/core/workers/chunks/463d69f596d1d34ef275.js +0 -2
  379. package/assets/esri/core/workers/chunks/475906b079f4f1ddacf2.js +0 -1
  380. package/assets/esri/core/workers/chunks/49affbed22e201f7c32b.js +0 -1
  381. package/assets/esri/core/workers/chunks/4c4ba466e23159991322.js +0 -1
  382. package/assets/esri/core/workers/chunks/4f58e0322707f63f5bf2.js +0 -1
  383. package/assets/esri/core/workers/chunks/606ac9358f508bda94f2.js +0 -1
  384. package/assets/esri/core/workers/chunks/724ea2e2843e6dac0a90.js +0 -1
  385. package/assets/esri/core/workers/chunks/7285a37cd5359aa4bac5.js +0 -1
  386. package/assets/esri/core/workers/chunks/753d1ff177ecee8e2377.js +0 -1
  387. package/assets/esri/core/workers/chunks/781fa83e8063b8f685dc.js +0 -1
  388. package/assets/esri/core/workers/chunks/78c1b75b1a8937eaa3cd.js +0 -1
  389. package/assets/esri/core/workers/chunks/7ff536284942c5284a16.js +0 -1
  390. package/assets/esri/core/workers/chunks/83c7c4218bc6ba2f16ee.js +0 -1
  391. package/assets/esri/core/workers/chunks/8984d02c0ce828fd223a.js +0 -1
  392. package/assets/esri/core/workers/chunks/8e102a2e134ce6ce0724.js +0 -1
  393. package/assets/esri/core/workers/chunks/92c852700ad1006f1e76.js +0 -1
  394. package/assets/esri/core/workers/chunks/9af36ee6a0df224859bc.js +0 -1
  395. package/assets/esri/core/workers/chunks/a3ab53b534e2872131be.js +0 -1
  396. package/assets/esri/core/workers/chunks/ac7af417ebf7721d7400.js +0 -1
  397. package/assets/esri/core/workers/chunks/aed479c14d93955f4798.js +0 -1
  398. package/assets/esri/core/workers/chunks/bb5ed2a796a45c41b0b4.js +0 -1
  399. package/assets/esri/core/workers/chunks/be52c319a0a81ce1ba36.js +0 -1
  400. package/assets/esri/core/workers/chunks/c0ec87800faf99cbd8bd.js +0 -1
  401. package/assets/esri/core/workers/chunks/c3008b20cb5fd38bd900.js +0 -1
  402. package/assets/esri/core/workers/chunks/ca5a4f62b09cc8579dc0.js +0 -1
  403. package/assets/esri/core/workers/chunks/d090baaa974e1e83fa44.js +0 -1
  404. package/assets/esri/core/workers/chunks/d25210574168ead2f813.js +0 -1
  405. package/assets/esri/core/workers/chunks/e4e1db4e9e5f13167401.js +0 -1
  406. package/assets/esri/core/workers/chunks/e9f8325a4cf89ae816cc.js +0 -1
  407. package/assets/esri/core/workers/chunks/ed7d4e8725aaa0ca4589.js +0 -1
  408. package/chunks/GaussianSplatComposition.glsl.js +0 -22
  409. package/layers/geospatialPDF/GeospatialPDFParserUtils.js +0 -2
  410. package/layers/geospatialPDF/Projection.js +0 -2
  411. package/views/3d/webgl-engine/shaders/GaussianSplatCompositionTechnique.js +0 -2
  412. package/views/3d/webgl-engine/shaders/GaussianSplatCompositionTechniqueConfiguration.js +0 -2
  413. /package/assets/esri/core/workers/chunks/{064445e6f9512817ac87.js.LICENSE.txt → 12b5a645c0987a0efe54.js.LICENSE.txt} +0 -0
  414. /package/assets/esri/core/workers/chunks/{033debcbf6b3683dc4fe.js.LICENSE.txt → 168b45c5d8233f23793e.js.LICENSE.txt} +0 -0
  415. /package/assets/esri/core/workers/chunks/{463d69f596d1d34ef275.js.LICENSE.txt → 1dbb3e25e005a8220779.js.LICENSE.txt} +0 -0
  416. /package/assets/esri/core/workers/chunks/{ce08e3369641da0d7a27.js.LICENSE.txt → 6e8187a77846239ed112.js.LICENSE.txt} +0 -0
  417. /package/assets/esri/core/workers/chunks/{58a17fb3c0dd07c63d57.js.LICENSE.txt → cfaba0470619786e1ef8.js.LICENSE.txt} +0 -0
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{getAssetUrl as t}from"../../assets.js";import e from"../../request.js";import s from"../../core/Error.js";import{throwIfAborted as i}from"../../core/promiseUtils.js";import{create as n,fromValues as r}from"../../core/libs/gl-matrix-2/factories/mat2df64.js";import{invert as a}from"../../core/libs/gl-matrix-2/math/mat2d.js";import o from"../../geometry/Extent.js";import{projectIsLoaded as h,projectLoad as l}from"../../geometry/operators/projectOperator.js";import{renderBitmap as c}from"./renderExtentUtils.js";const d=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),u=[1/0,1/0,-1/0,-1/0],p=new Float32Array(u),g=[.001,0,0,.001,0,0],m=1.35,f=1,b=2,y=4,A=16,w=32,v=64,_=128,x=256,S={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},C="pdfjs_internal_id_",k="pdfjs_internal_editor_",T={NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101},M={CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},E=0,P=1,D=2,I=3,F=3,N=4,R={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},O=1,B=2,L=3,U=4,j=5,H={WARNINGS:1,INFOS:5},$={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},z=0,G=1,W=2,V=3,X=4;let Y=H.WARNINGS;function q(t){Number.isInteger(t)&&(Y=t)}function K(){return Y}function Q(t){Y>=H.INFOS&&console.info(`Info: ${t}`)}function J(t){Y>=H.WARNINGS&&console.warn(`Warning: ${t}`)}function Z(t){throw new Error(t)}function tt(t,e){t||Z(e)}function et(t,e=null,s=null){if(!t)return null;if(s&&"string"==typeof t){if(s.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(s.tryConvertEncoding)try{t=function(t){return decodeURIComponent(escape(t))}(t)}catch{}}const i=e?URL.parse(t,e):URL.parse(t);return function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(i)?i:null}function st(t,e,s=!1){const i=URL.parse(t);return i?(i.hash=e,i.href):s&&et(t,"http://example.com")?t.split("#",1)[0]+"":""}function it(t,e,s,i=!1){return Object.defineProperty(t,e,{value:s,enumerable:!i,configurable:!0,writable:!1}),s}const nt=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}();class rt extends nt{constructor(t,e){super(t,"PasswordException"),this.code=e}}class at extends nt{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class ot extends nt{constructor(t){super(t,"InvalidPDFException")}}class ht extends nt{constructor(t,e,s){super(t,"ResponseException"),this.status=e,this.missing=s}}class lt extends nt{constructor(t){super(t,"FormatError")}}class ct extends nt{constructor(t){super(t,"AbortException")}}function dt(t){"string"!=typeof t&&Z("Invalid argument for stringToBytes");const e=t.length,s=new Uint8Array(e);for(let i=0;i<e;++i)s[i]=255&t.charCodeAt(i);return s}class ut{static get isLittleEndian(){const t=new Uint8Array(4);return t[0]=1,it(this,"isLittleEndian",1===new Uint32Array(t.buffer,0,1)[0])}static get isOffscreenCanvasSupported(){return it(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return it(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get isFloat16ArraySupported(){return it(this,"isFloat16ArraySupported","undefined"!=typeof Float16Array)}static get isSanitizerSupported(){return it(this,"isSanitizerSupported","undefined"!=typeof Sanitizer)}static get platform(){const{platform:t,userAgent:e}=navigator;return it(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCanvasFilterSupported(){let t;return this.isOffscreenCanvasSupported?t=new OffscreenCanvas(1,1).getContext("2d"):"undefined"!=typeof document&&(t=document.createElement("canvas").getContext("2d")),it(this,"isCanvasFilterSupported",void 0!==t?.filter)}static get isAlphaColorInputSupported(){return it(this,"isAlphaColorInputSupported",(()=>{if("undefined"==typeof document)return!1;const t=document.createElement("input");return t.type="color",t.setAttribute("alpha",""),t.value="#ff000080","#ff0000"!==t.value})())}}class pt{static get hexNums(){return it(this,"hexNums",Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0")))}static makeHexColor(t,e,s){return`#${this.hexNums[t]}${this.hexNums[e]}${this.hexNums[s]}`}static domMatrixToTransform(t){return[t.a,t.b,t.c,t.d,t.e,t.f]}static scaleMinMax(t,e){let s;t[0]?(t[0]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[3],e[3]*=t[3]):(s=e[0],e[0]=e[1],e[1]=s,s=e[2],e[2]=e[3],e[3]=s,t[1]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static multiplyByDOMMatrix(t,e){return[t[0]*e.a+t[2]*e.b,t[1]*e.a+t[3]*e.b,t[0]*e.c+t[2]*e.d,t[1]*e.c+t[3]*e.d,t[0]*e.e+t[2]*e.f+t[4],t[1]*e.e+t[3]*e.f+t[5]]}static applyTransform(t,e,s=0){const i=t[s],n=t[s+1];t[s]=i*e[0]+n*e[2]+e[4],t[s+1]=i*e[1]+n*e[3]+e[5]}static applyTransformToBezier(t,e,s=0){const i=e[0],n=e[1],r=e[2],a=e[3],o=e[4],h=e[5];for(let l=0;l<6;l+=2){const e=t[s+l],c=t[s+l+1];t[s+l]=e*i+c*r+o,t[s+l+1]=e*n+c*a+h}}static applyInverseTransform(t,e){const s=t[0],i=t[1],n=e[0]*e[3]-e[1]*e[2];t[0]=(s*e[3]-i*e[2]+e[2]*e[5]-e[4]*e[3])/n,t[1]=(-s*e[1]+i*e[0]+e[4]*e[1]-e[5]*e[0])/n}static axialAlignedBoundingBox(t,e,s){const i=e[0],n=e[1],r=e[2],a=e[3],o=e[4],h=e[5],l=t[0],c=t[1],d=t[2],u=t[3];let p=i*l+o,g=p,m=i*d+o,f=m,b=a*c+h,y=b,A=a*u+h,w=A;if(0!==n||0!==r){const t=n*l,e=n*d,s=r*c,i=r*u;p+=s,f+=s,m+=i,g+=i,b+=t,w+=t,A+=e,y+=e}s[0]=Math.min(s[0],p,m,g,f),s[1]=Math.min(s[1],b,A,y,w),s[2]=Math.max(s[2],p,m,g,f),s[3]=Math.max(s[3],b,A,y,w)}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t,e){const s=t[0],i=t[1],n=t[2],r=t[3],a=s**2+i**2,o=s*n+i*r,h=n**2+r**2,l=(a+h)/2,c=Math.sqrt(l**2-(a*h-o**2));e[0]=Math.sqrt(l+c||1),e[1]=Math.sqrt(l-c||1)}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>r?null:[s,n,i,r]}static pointBoundingBox(t,e,s){s[0]=Math.min(s[0],t),s[1]=Math.min(s[1],e),s[2]=Math.max(s[2],t),s[3]=Math.max(s[3],e)}static rectBoundingBox(t,e,s,i,n){n[0]=Math.min(n[0],t,s),n[1]=Math.min(n[1],e,i),n[2]=Math.max(n[2],t,s),n[3]=Math.max(n[3],e,i)}static#t(t,e,s,i,n,r,a,o,h,l){if(h<=0||h>=1)return;const c=1-h,d=h*h,u=d*h,p=c*(c*(c*t+3*h*e)+3*d*s)+u*i,g=c*(c*(c*n+3*h*r)+3*d*a)+u*o;l[0]=Math.min(l[0],p),l[1]=Math.min(l[1],g),l[2]=Math.max(l[2],p),l[3]=Math.max(l[3],g)}static#e(t,e,s,i,n,r,a,o,h,l,c,d){if(Math.abs(h)<1e-12)return void(Math.abs(l)>=1e-12&&this.#t(t,e,s,i,n,r,a,o,-c/l,d));const u=l**2-4*c*h;if(u<0)return;const p=Math.sqrt(u),g=2*h;this.#t(t,e,s,i,n,r,a,o,(-l+p)/g,d),this.#t(t,e,s,i,n,r,a,o,(-l-p)/g,d)}static bezierBoundingBox(t,e,s,i,n,r,a,o,h){h[0]=Math.min(h[0],t,a),h[1]=Math.min(h[1],e,o),h[2]=Math.max(h[2],t,a),h[3]=Math.max(h[3],e,o),this.#e(t,s,n,a,e,i,r,o,3*(3*(s-n)-t+a),6*(t-2*s+n),3*(s-t),h),this.#e(t,s,n,a,e,i,r,o,3*(3*(i-r)-e+o),6*(e-2*i+r),3*(i-e),h)}}function gt(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);return crypto.getRandomValues(t),function(t){"object"==typeof t&&void 0!==t?.length||Z("Invalid argument for bytesToString");const e=t.length,s=8192;if(e<s)return String.fromCharCode.apply(null,t);const i=[];for(let n=0;n<e;n+=s){const r=Math.min(n+s,e),a=t.subarray(n,r);i.push(String.fromCharCode.apply(null,a))}return i.join("")}(t)}const mt=()=>[],ft=()=>new Map,bt=()=>Object.create(null);function yt(t,e,s){return Math.min(Math.max(t,e),s)}class At{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};return function t(s){if(!s)return;let i=null;const n=s.name;if("#text"===n)i=s.value;else{if(!At.shouldBuildText(n))return;s?.attributes?.textContent?i=s.attributes.textContent:s.value&&(i=s.value)}if(null!==i&&e.push({str:i}),s.children)for(const e of s.children)t(e)}(t),s}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}class wt{static setupStorage(t,e,s,i,n){const r=i.getValue(e,{value:null});switch(s.name){case"textarea":if(null!==r.value&&(t.textContent=r.value),"print"===n)break;t.addEventListener("input",t=>{i.setValue(e,{value:t.target.value})});break;case"input":if("radio"===s.attributes.type||"checkbox"===s.attributes.type){if(r.value===s.attributes.xfaOn?t.setAttribute("checked",!0):r.value===s.attributes.xfaOff&&t.removeAttribute("checked"),"print"===n)break;t.addEventListener("change",t=>{i.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})})}else{if(null!==r.value&&t.setAttribute("value",r.value),"print"===n)break;t.addEventListener("input",t=>{i.setValue(e,{value:t.target.value})})}break;case"select":if(null!==r.value){t.setAttribute("value",r.value);for(const t of s.children)t.attributes.value===r.value?t.attributes.selected=!0:Object.hasOwn(t.attributes,"selected")&&delete t.attributes.selected}t.addEventListener("input",t=>{const s=t.target.options,n=-1===s.selectedIndex?"":s[s.selectedIndex].value;i.setValue(e,{value:n})})}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,a=t instanceof HTMLAnchorElement;"radio"===r.type&&(r.name=`${r.name}-${i}`);for(const[o,h]of Object.entries(r))if(null!=h)switch(o){case"class":h.length&&t.setAttribute(o,h.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",h);break;case"style":Object.assign(t.style,h);break;case"textContent":t.textContent=h;break;default:(!a||"href"!==o&&"newWindow"!==o)&&t.setAttribute(o,h)}a&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:s});const a="richText"!==n,o=t.div;if(o.append(r),t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}a&&o.setAttribute("class","xfaLayer xfaFont");const h=[];if(0===i.children.length){if(i.value){const t=document.createTextNode(i.value);r.append(t),a&&At.shouldBuildText(i.name)&&h.push(t)}return{textDivs:h}}const l=[[i,-1,r]];for(;l.length>0;){const[t,i,r]=l.at(-1);if(i+1===t.children.length){l.pop();continue}const o=t.children[++l.at(-1)[1]];if(null===o)continue;const{name:c}=o;if("#text"===c){const t=document.createTextNode(o.value);h.push(t),r.append(t);continue}const d=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,c):document.createElement(c);if(r.append(d),o.attributes&&this.setAttributes({html:d,element:o,storage:e,intent:n,linkService:s}),o.children?.length>0)l.push([o,-1,d]);else if(o.value){const t=document.createTextNode(o.value);a&&At.shouldBuildText(c)&&h.push(t),d.append(t)}}for(const c of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))c.setAttribute("readOnly",!0);return{textDivs:h}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const vt="http://www.w3.org/2000/svg";class _t{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function xt(t,e="text"){if(Et(t,document.baseURI)){const s=await fetch(t);if(!s.ok)throw new Error(s.statusText);switch(e){case"blob":return s.blob();case"bytes":return s.bytes();case"json":return s.json()}return s.text()}return new Promise((s,i)=>{const n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType="bytes"===e?"arraybuffer":e,n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)i(new Error(n.statusText));else{switch(e){case"bytes":return void s(new Uint8Array(n.response));case"blob":case"json":return void s(n.response)}s(n.responseText)}},n.send(null)})}class St{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t,this.userUnit=e,this.scale=s,this.rotation=i,this.offsetX=n,this.offsetY=r,s*=e;const o=(t[2]+t[0])/2,h=(t[3]+t[1])/2;let l,c,d,u,p,g,m,f;switch((i%=360)<0&&(i+=360),i){case 180:l=-1,c=0,d=0,u=1;break;case 90:l=0,c=1,d=1,u=0;break;case 270:l=0,c=-1,d=-1,u=0;break;case 0:l=1,c=0,d=0,u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,u=-u),0===l?(p=Math.abs(h-t[1])*s+n,g=Math.abs(o-t[0])*s+r,m=(t[3]-t[1])*s,f=(t[2]-t[0])*s):(p=Math.abs(o-t[0])*s+n,g=Math.abs(h-t[1])*s+r,m=(t[2]-t[0])*s,f=(t[3]-t[1])*s),this.transform=[l*s,c*s,d*s,u*s,p-l*s*o-d*s*h,g-c*s*o-u*s*h],this.width=m,this.height=f}get rawDims(){const t=this.viewBox;return it(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new St({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){const s=[t,e];return pt.applyTransform(s,this.transform),s}convertToViewportRectangle(t){const e=[t[0],t[1]];pt.applyTransform(e,this.transform);const s=[t[2],t[3]];return pt.applyTransform(s,this.transform),[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){const s=[t,e];return pt.applyInverseTransform(s,this.transform),s}}class Ct extends nt{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function kt(t){const e=t.length;let s=0;for(;s<e&&""===t[s].trim();)s++;return"data:"===t.substring(s,s+5).toLowerCase()}function Tt(t){return"string"==typeof t&&/\.pdf$/i.test(t)}class Mt{#s=new Map;times=[];time(t){this.#s.has(t)&&J(`Timer is already running for ${t}`),this.#s.set(t,Date.now())}timeEnd(t){this.#s.has(t)||J(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.#s.get(t),end:Date.now()}),this.#s.delete(t)}toString(){const t=Math.max(...this.times.map(t=>t.name.length));return this.times.map(e=>`${e.name.padEnd(t)} ${e.end-e.start}ms\n`).join("")}}function Et(t,e){const s=e?URL.parse(t,e):URL.parse(t);return/https?:/.test(s?.protocol??"")}function Pt(t){t.preventDefault()}function Dt(t){t.preventDefault(),t.stopPropagation()}class It{static#i;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#i||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#i.exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let a=parseInt(e[5],10);a=a>=0&&a<=59?a:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const h=e[7]||"Z";let l=parseInt(e[8],10);l=l>=0&&l<=23?l:0;let c=parseInt(e[9],10)||0;return c=c>=0&&c<=59?c:0,"-"===h?(r+=l,a+=c):"+"===h&&(r-=l,a-=c),new Date(Date.UTC(s,i,n,r,a,o))}}function Ft(t){if(t.startsWith("#")){const e=t.slice(1);return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16),e.length>=8?parseInt(e.slice(6,8),16)/255:1]}if(t.startsWith("rgb(")){const[e,s,i]=t.slice(4,-1).split(",").map(t=>parseInt(t,10));return[e,s,i,1]}if(t.startsWith("rgba(")){const e=t.slice(5,-1).split(",");return[parseInt(e[0],10),parseInt(e[1],10),parseInt(e[2],10),parseFloat(e[3])]}const e=t.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return e?[Math.round(255*parseFloat(e[1])),Math.round(255*parseFloat(e[2])),Math.round(255*parseFloat(e[3])),void 0!==e[4]&&"none"!==e[4]?parseFloat(e[4]):1]:null}function Nt(t){const e=Ft(t);return e?e.slice(0,3):(J(`Not a valid color format: "${t}"`),[0,0,0])}function Rt(t){const{a:e,b:s,c:i,d:n,e:r,f:a}=t.getTransform();return[e,s,i,n,r,a]}function Ot(t){const{a:e,b:s,c:i,d:n,e:r,f:a}=t.getTransform().invertSelf();return[e,s,i,n,r,a]}function Bt(t,e,s=!1,i=!0){if(e instanceof St){const{pageWidth:i,pageHeight:n}=e.rawDims,{style:r}=t,a=`round(down, var(--total-scale-factor) * ${i}px, var(--scale-round-x))`,o=`round(down, var(--total-scale-factor) * ${n}px, var(--scale-round-y))`;s&&e.rotation%180!=0?(r.width=o,r.height=a):(r.width=a,r.height=o)}i&&t.setAttribute("data-main-rotation",e.rotation)}class Lt{constructor(){const{pixelRatio:t}=Lt;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,s,i,n=-1){let r=1/0,a=1/0,o=1/0;(s=Lt.capPixels(s,n))>0&&(r=Math.sqrt(s/(t*e))),-1!==i&&(a=i/t,o=i/e);const h=Math.min(r,a,o);return(this.sx>h||this.sy>h)&&(this.sx=h,this.sy=h,!0)}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const s=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,s):s}return t}}const Ut=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class jt{static get isDarkMode(){return it(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}function Ht({html:t,dir:e,className:s},i){const n=document.createDocumentFragment();if("string"==typeof t){const s=document.createElement("p");s.dir=e||"auto";const i=t.split(/(?:\r\n?|\n)/);for(let t=0,e=i.length;t<e;++t){const n=i[t];s.append(document.createTextNode(n)),t<e-1&&s.append(document.createElement("br"))}n.append(s)}else wt.render({xfaHtml:t,div:n,intent:"richText"});n.firstElementChild.classList.add("richText",s),i.append(n)}function $t(t){const e=new Path2D;if(!t)return e;for(let s=0,i=t.length;s<i;)switch(t[s++]){case z:e.moveTo(t[s++],t[s++]);break;case G:e.lineTo(t[s++],t[s++]);break;case W:e.bezierCurveTo(t[s++],t[s++],t[s++],t[s++],t[s++],t[s++]);break;case V:e.quadraticCurveTo(t[s++],t[s++],t[s++],t[s++]);break;case X:e.closePath();break;default:J(`Unrecognized drawing path operator: ${t[s-1]}`)}return e}class zt{#n=null;#r=null;#a;#o=null;#h=null;#l=null;#c=null;#d=null;static#u=null;constructor(t){this.#a=t,zt.#u||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"})}render(){const t=this.#n=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("contextmenu",Pt,{signal:e}),t.addEventListener("pointerdown",zt.#p,{signal:e}));const s=this.#o=document.createElement("div");s.className="buttons",t.append(s);const i=this.#a.toolbarPosition;if(i){const{style:e}=t,s="ltr"===this.#a._uiManager.direction?1-i[0]:i[0];e.insetInlineEnd=100*s+"%",e.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return t}get div(){return this.#n}static#p(t){t.stopPropagation()}#g(t){this.#a._focusEventsAllowed=!1,Dt(t)}#m(t){this.#a._focusEventsAllowed=!0,Dt(t)}#f(t){const e=this.#a._uiManager._signal;return e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("focusin",this.#g.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#m.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",Pt,{signal:e}),!0)}hide(){this.#n.classList.add("hidden"),this.#r?.hideDropdown()}show(){this.#n.classList.remove("hidden"),this.#h?.shown(),this.#l?.shown()}addDeleteButton(){const{editorType:t,_uiManager:e}=this.#a,s=document.createElement("button");s.classList.add("basic","deleteButton"),s.tabIndex=0,s.setAttribute("data-l10n-id",zt.#u[t]),this.#f(s)&&s.addEventListener("click",t=>{e.delete()},{signal:e._signal}),this.#o.append(s)}get#b(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#f(e),this.#o.append(e,this.#b),this.#h=t}addComment(t,e=null){if(this.#l)return;const s=t.renderForToolbar();if(!s)return;this.#f(s);const i=this.#c=this.#b;e?(this.#o.insertBefore(s,e),this.#o.insertBefore(i,e)):this.#o.append(s,i),this.#l=t,t.toolbar=this}addColorPicker(t){if(this.#r)return;this.#r=t;const e=t.renderButton();this.#f(e),this.#o.append(e,this.#b)}async addEditSignatureButton(t){const e=this.#d=await t.renderEditButton(this.#a);this.#f(e),this.#o.append(e,this.#b)}removeButton(t){"comment"===t&&(this.#l?.removeToolbarCommentButton(),this.#l=null,this.#c?.remove(),this.#c=null)}async addButton(t,e){switch(t){case"colorPicker":e&&this.addColorPicker(e);break;case"altText":e&&await this.addAltText(e);break;case"editSignature":e&&await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":e&&this.addComment(e)}}async addButtonBefore(t,e,s){if(!e&&"comment"===t)return;const i=this.#o.querySelector(s);i&&"comment"===t&&this.addComment(e,i)}updateEditSignatureButton(t){this.#d&&(this.#d.title=t)}remove(){this.#n.remove(),this.#r?.destroy(),this.#r=null}}class Gt{#o=null;#n=null;#y;constructor(t){this.#y=t}#A(){const t=this.#n=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar");const e=this.#y._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",Pt,{signal:e});const s=this.#o=document.createElement("div");return s.className="buttons",t.append(s),this.#y.hasCommentManager()&&this.#w("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#y.commentSelection("floating_button")}),this.#w("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#y.highlightSelection("floating_button")}),t}#v(t,e){let s=0,i=0;for(const n of t){const t=n.y+n.height;if(t<s)continue;const r=n.x+(e?n.width:0);t>s?(i=r,s=t):e?r>i&&(i=r):r<i&&(i=r)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#v(e,s),{style:r}=this.#n||=this.#A();t.append(this.#n),r.insetInlineEnd=100*i+"%",r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#n.remove()}#w(t,e,s,i){const n=document.createElement("button");n.classList.add("basic",t),n.tabIndex=0,n.setAttribute("data-l10n-id",e);const r=document.createElement("span");n.append(r),r.className="visuallyHidden",r.setAttribute("data-l10n-id",s);const a=this.#y._signal;a instanceof AbortSignal&&!a.aborted&&(n.addEventListener("contextmenu",Pt,{signal:a}),n.addEventListener("click",i,{signal:a})),this.#o.append(n)}}function Wt(t,e,s){for(const i of s)e.addEventListener(i,t[i].bind(t))}class Vt{static#_=NaN;static#x=null;static#S=NaN;static#C=null;static initializeAndAddPointerId(t){(Vt.#x||=new Set).add(t)}static setPointer(t,e){Vt.#_||=e,Vt.#C??=t}static setTimeStamp(t){Vt.#S=t}static isSamePointerId(t){return Vt.#_===t}static isSamePointerIdOrRemove(t){return Vt.#_===t||(Vt.#x?.delete(t),!1)}static isSamePointerType(t){return Vt.#C===t}static isInitializedAndDifferentPointerType(t){return null!==Vt.#C&&!Vt.isSamePointerType(t)}static isSameTimeStamp(t){return Vt.#S===t}static isUsingMultiplePointers(){return Vt.#x?.size>=1}static clearPointerType(){Vt.#C=null}static clearPointerIds(){Vt.#_=NaN,Vt.#x=null}static clearTimeStamp(){Vt.#S=NaN}}class Xt{#k=0;get id(){return`${k}${this.#k++}`}}class Yt{#T=gt();#k=0;#M=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;return e.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>',it(this,"_isSVGFittingCanvas",e.decode().then(()=>(t.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0])))}async#E(t,e){this.#M||=new Map;let s=this.#M.get(t);if(null===s)return null;if(s?.bitmap)return s.refCounter+=1,s;try{let t;if(s||={bitmap:null,id:`image_${this.#T}_${this.#k++}`,refCounter:0,isSvg:!1},"string"==typeof e?(s.url=e,t=await xt(e,"blob")):e instanceof File?t=s.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){const e=Yt._isSVGFittingCanvas,i=new FileReader,n=new Image,r=new Promise((t,r)=>{n.onload=()=>{s.bitmap=n,s.isSvg=!0,t()},i.onload=async()=>{const t=s.svgUrl=i.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=i.onerror=r});i.readAsDataURL(t),await r}else s.bitmap=await createImageBitmap(t);s.refCounter=1}catch(t){J(t),s=null}return this.#M.set(t,s),s&&this.#M.set(s.id,s),s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#E(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#E(t,t)}async getFromBlob(t,e){const s=await e;return this.#E(t,s)}async getFromId(t){this.#M||=new Map;const e=this.#M.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#M||=new Map;let s=this.#M.get(t);if(s?.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${this.#T}_${this.#k++}`,refCounter:1,isSvg:!1},this.#M.set(t,s),this.#M.set(s.id,s),s}getSvgUrl(t){const e=this.#M.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#M||=new Map;const e=this.#M.get(t);if(!e)return;if(e.refCounter-=1,0!==e.refCounter)return;const{bitmap:s}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(s.width,s.height);t.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=t.convertToBlob()}s.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#T}_`)}}class qt{#P=[];#D=!1;#I;#F=-1;constructor(t=128){this.#I=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){if(i&&t(),this.#D)return;const o={cmd:t,undo:e,post:s,type:n};if(-1===this.#F)return this.#P.length>0&&(this.#P.length=0),this.#F=0,void this.#P.push(o);if(r&&this.#P[this.#F].type===n)return a&&(o.undo=this.#P[this.#F].undo),void(this.#P[this.#F]=o);const h=this.#F+1;h===this.#I?this.#P.splice(0,1):(this.#F=h,h<this.#P.length&&this.#P.splice(h)),this.#P.push(o)}undo(){if(-1===this.#F)return;this.#D=!0;const{undo:t,post:e}=this.#P[this.#F];t(),e?.(),this.#D=!1,this.#F-=1}redo(){if(this.#F<this.#P.length-1){this.#F+=1,this.#D=!0;const{cmd:t,post:e}=this.#P[this.#F];t(),e?.(),this.#D=!1}}hasSomethingToUndo(){return-1!==this.#F}hasSomethingToRedo(){return this.#F<this.#P.length-1}cleanType(t){if(-1!==this.#F){for(let e=this.#F;e>=0;e--)if(this.#P[e].type!==t)return this.#P.splice(e+1,this.#F-e),void(this.#F=e);this.#P.length=0,this.#F=-1}}destroy(){this.#P=null}}class Kt{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=ut.platform;for(const[s,i,n={}]of t)for(const t of s){const s=t.startsWith("mac+");e&&s?(this.callbacks.set(t.slice(4),{callback:i,options:n}),this.allKeys.add(t.split("+").at(-1))):e||s||(this.callbacks.set(t,{callback:i,options:n}),this.allKeys.add(t.split("+").at(-1)))}}#N(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(this.#N(e));if(!s)return;const{callback:i,options:{bubbles:n=!1,args:r=[],checker:a=null}}=s;a&&!a(t,e)||(i.bind(t,...r,e)(),n||Dt(e))}}class Qt{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return function(t){const e=document.createElement("span");e.style.visibility="hidden",e.style.colorScheme="only light",document.body.append(e);for(const s of t.keys()){e.style.color=s;const i=window.getComputedStyle(e).color;t.set(s,Nt(i))}e.remove()}(t),it(this,"_colors",t)}convert(t){const e=Nt(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[s,i]of this._colors)if(i.every((t,s)=>t===e[s]))return Qt._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?pt.makeHexColor(...e):t}}class Jt{#R=new AbortController;#O=null;#B=null;#L=new Map;#U=new Map;#j=null;#H=null;#$=null;#z=null;#G=new qt;#W=null;#V=null;#X=null;#Y=0;#q=new Set;#K=null;#Q=null;#J=new Set;_editorUndoBar=null;#Z=!1;#tt=!1;#et=!1;#st=null;#it=null;#nt=null;#rt=null;#at=!1;#ot=null;#ht=new Xt;#lt=!1;#ct=!1;#dt=!1;#ut=null;#pt=null;#gt=null;#mt=null;#ft=null;#bt=T.NONE;#yt=new Set;#At=null;#wt=null;#vt=null;#_t=null;#xt=null;#St={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#Ct=[0,0];#kt=null;#Tt=null;#Mt=null;#Et=null;#Pt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=Jt.prototype,e=t=>t.#Tt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),s=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return it(this,"_keyboardManager",new Kt([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],t.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:s}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#Tt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#Tt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,s,i,n,r,a,o,h,l,c,d,u,p,g,m){const f=this._signal=this.#R.signal;this.#Tt=t,this.#Mt=e,this.#Et=s,this.#H=i,this.#W=n,this.#wt=r,this.#xt=o,this._eventBus=a,a._on("editingaction",this.onEditingAction.bind(this),{signal:f}),a._on("pagechanging",this.onPageChanging.bind(this),{signal:f}),a._on("scalechanging",this.onScaleChanging.bind(this),{signal:f}),a._on("rotationchanging",this.onRotationChanging.bind(this),{signal:f}),a._on("setpreference",this.onSetPreference.bind(this),{signal:f}),a._on("switchannotationeditorparams",t=>this.updateParams(t.type,t.value),{signal:f}),window.addEventListener("pointerdown",()=>{this.#ct=!0},{capture:!0,signal:f}),window.addEventListener("pointerup",()=>{this.#ct=!1},{capture:!0,signal:f}),window.addEventListener("beforeunload",this.#Dt.bind(this),{capture:!0,signal:f}),this.#It(),this.#Ft(),this.#Nt(),this.#$=o.annotationStorage,this.#st=o.filterFactory,this.#vt=h,this.#rt=l||null,this.#Z=c,this.#tt=d,this.#et=u,this.#ft=p||null,this.viewParameters={realScale:_t.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=g||null,this._supportsPinchToZoom=!1!==m,n?.setSidebarUiManager(this)}destroy(){this.#Pt?.resolve(),this.#Pt=null,this.#R?.abort(),this.#R=null,this._signal=null;for(const t of this.#U.values())t.destroy();this.#U.clear(),this.#L.clear(),this.#J.clear(),this.#mt?.clear(),this.#O=null,this.#yt.clear(),this.#G.destroy(),this.#H?.destroy(),this.#W?.destroy(),this.#wt?.destroy(),this.#ot?.hide(),this.#ot=null,this.#gt?.destroy(),this.#gt=null,this.#B=null,this.#it&&(clearTimeout(this.#it),this.#it=null),this.#kt&&(clearTimeout(this.#kt),this.#kt=null),this._editorUndoBar?.destroy(),this.#xt=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#ft}get useNewAltTextFlow(){return this.#tt}get useNewAltTextWhenAddingImage(){return this.#et}get hcmFilter(){return it(this,"hcmFilter",this.#vt?this.#st.addHCMFilter(this.#vt.foreground,this.#vt.background):"none")}get direction(){return it(this,"direction",getComputedStyle(this.#Tt).direction)}get _highlightColors(){return it(this,"_highlightColors",this.#rt?new Map(this.#rt.split(",").map(t=>((t=t.split("=").map(t=>t.trim()))[1]=t[1].toUpperCase(),t))):null)}get highlightColors(){const{_highlightColors:t}=this;if(!t)return it(this,"highlightColors",null);const e=new Map,s=!!this.#vt;for(const[i,n]of t){const t=i.endsWith("_HCM");s&&t?e.set(i.replace("_HCM",""),n):s||t||e.set(i,n)}return it(this,"highlightColors",e)}get highlightColorNames(){return it(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}getNonHCMColor(t){if(!this._highlightColors)return t;const e=this.highlightColorNames.get(t);return this._highlightColors.get(e)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#X=t}setMainHighlightColorPicker(t){this.#gt=t}editAltText(t,e=!1){this.#H?.editAltText(this,t,e)}hasCommentManager(){return!!this.#W}editComment(t,e,s,i){this.#W?.showDialog(this,t,e,s,i)}selectComment(t,e){const s=this.#U.get(t),i=s?.getEditorByUID(e);i?.toggleComment(!0,!0)}updateComment(t){this.#W?.updateComment(t.getData())}updatePopupColor(t){this.#W?.updatePopupColor(t)}removeComment(t){this.#W?.removeComments([t.uid])}deleteComment(t,e){const s=()=>{t.comment=e};this.addCommands({cmd:()=>{this._editorUndoBar?.show(s,"comment"),this.toggleComment(null),t.comment=null},undo:s,mustExec:!0})}toggleComment(t,e,s=void 0){this.#W?.toggleCommentPopup(t,e,s)}makeCommentColor(t,e){return t&&this.#W?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#W?.dialogElement||null}async waitForEditorsRendered(t){if(this.#U.has(t-1))return;const{resolve:e,promise:s}=Promise.withResolvers(),i=s=>{s.pageNumber===t&&(this._eventBus._off("editorsrendered",i),e())};this._eventBus.on("editorsrendered",i),await s}getSignature(t){this.#wt?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#wt}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){"enableNewAltTextWhenAddingImage"===t&&(this.#et=e)}onPageChanging({pageNumber:t}){this.#Y=t-1}deletePage(t){for(const e of this.getEditors(t))e.remove();this.#U.delete(t),this.#Y===t&&(this.#Y=0)}focusMainContainer(){this.#Tt.focus()}findParent(t,e){for(const s of this.#U.values()){const{x:i,y:n,width:r,height:a}=s.div.getBoundingClientRect();if(t>=i&&t<=i+r&&e>=n&&e<=n+a)return s}return null}disableUserSelect(t=!1){this.#Mt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#J.add(t)}removeShouldRescale(t){this.#J.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*_t.PDF_TO_CSS_UNITS;for(const e of this.#J)e.onScaleChanging();this.#X?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#Rt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Ot(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of this.#U.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t="",e=!1){const s=document.getSelection();if(!s||s.isCollapsed)return;const{anchorNode:i,anchorOffset:n,focusNode:r,focusOffset:a}=s,o=s.toString(),h=this.#Rt(s).closest(".textLayer"),l=this.getSelectionBoxes(h);if(!l)return;s.empty();const c=this.#Ot(h),d=this.#bt===T.NONE,u=()=>{const s=c?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:n,focusNode:r,focusOffset:a,text:o});d&&this.showAllEditors("highlight",!0,!0),e&&s?.editComment()};d?this.switchToMode(T.HIGHLIGHT,u):u()}commentSelection(t=""){this.highlightSelection(t,!0)}#Dt(t){this.commitOrRemove(),this.currentLayer?.endDrawingSession(!1)}#Bt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#Rt(t).closest(".textLayer"),s=this.getSelectionBoxes(e);s&&(this.#ot||=new Gt(this),this.#ot.show(e,s,"ltr"===this.direction))}getAndRemoveDataFromAnnotationStorage(t){if(!this.#$)return null;const e=`${k}${t}`,s=this.#$.getRawValue(e);return s&&this.#$.remove(e),s}addToAnnotationStorage(t){t.isEmpty()||!this.#$||this.#$.has(t.id)||this.#$.setValue(t.id,t)}a11yAlert(t,e=null){const s=this.#Et;s&&(s.setAttribute("data-l10n-id",t),e?s.setAttribute("data-l10n-args",JSON.stringify(e)):s.removeAttribute("data-l10n-args"))}#Lt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#At&&(this.#ot?.hide(),this.#At=null,this.#Ut({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#At)return;const s=this.#Rt(t).closest(".textLayer");if(s){if(this.#ot?.hide(),this.#At=e,this.#Ut({hasSelectedText:!0}),(this.#bt===T.HIGHLIGHT||this.#bt===T.NONE)&&(this.#bt===T.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#at=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#bt===T.HIGHLIGHT?this.#Ot(s):null;if(t?.toggleDrawing(),this.#ct){const e=new AbortController,s=this.combinedSignal(e),i=s=>{"pointerup"===s.type&&0!==s.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===s.type&&this.#jt("main_toolbar"))};window.addEventListener("pointerup",i,{signal:s}),window.addEventListener("blur",i,{signal:s})}else t?.toggleDrawing(!0),this.#jt("main_toolbar")}}else this.#At&&(this.#ot?.hide(),this.#At=null,this.#Ut({hasSelectedText:!1}))}#jt(t=""){this.#bt===T.HIGHLIGHT?this.highlightSelection(t):this.#Z&&this.#Bt()}#It(){document.addEventListener("selectionchange",this.#Lt.bind(this),{signal:this._signal})}#Ht(){if(this.#nt)return;this.#nt=new AbortController;const t=this.combinedSignal(this.#nt);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#$t(){this.#nt?.abort(),this.#nt=null}blur(){if(this.isShiftKeyDown=!1,this.#at&&(this.#at=!1,this.#jt("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#yt)if(e.div.contains(t)){this.#pt=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#pt)return;const[t,e]=this.#pt;this.#pt=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#Nt(){if(this.#ut)return;this.#ut=new AbortController;const t=this.combinedSignal(this.#ut);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#zt(){this.#ut?.abort(),this.#ut=null}#Gt(){if(this.#V)return;this.#V=new AbortController;const t=this.combinedSignal(this.#V);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Wt(){this.#V?.abort(),this.#V=null}#Ft(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Nt(),this.setEditingState(!0)}removeEditListeners(){this.#zt(),this.setEditingState(!1)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#Q)if(s.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const s of this.#Q)if(s.isHandlingMimeForPasting(e.type))return s.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#O?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const s of this.#yt){const t=s.serialize(!0);t&&e.push(t)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const n of e.items)for(const t of this.#Q)if(t.isHandlingMimeForPasting(n.type))return void t.paste(n,this.currentLayer);let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(t){return void J(`paste: "${t.message}".`)}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const t=[];for(const r of s){const e=await i.deserialize(r);if(!e)return;t.push(e)}const e=()=>{for(const e of t)this.#Vt(e);this.#Xt(t)},n=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:n,mustExec:!0})}catch(t){J(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#bt===T.NONE||this.isEditorHandlingKeyboard||Jt._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#at&&(this.#at=!1,this.#jt("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu")}}updatePageIndex(t,e){for(const i of this.getEditors(t))i.pageIndex=e;const s=this.#j.get(t);s&&(s.pageIndex=e,this.#U.set(e,s),this.#lt?s.enable():s.disable())}startUpdatePages(){this.#j=new Map(this.#U),this.#U.clear()}endUpdatePages(){this.#j=null}clonePage(t,e){for(const s of this.getEditors(t)){const t=s.serialize(s.mode!==T.HIGHLIGHT);t&&(t.pageIndex=e,t.id=this.getId(),t.isClone=!0,delete t.popupRef,this.#$.setValue(t.id,t))}}findClonesForPage(t){const e=[],{pageIndex:s}=t;for(const[i,n]of this.#$)n.pageIndex===s&&n.isClone&&(this.#$.remove(i),e.push(t.deserialize(n).then(e=>{e&&(e.isClone=!0,t.addOrRebuild(e))})));return Promise.all(e)}#Ut(t){Object.entries(t).some(([t,e])=>this.#St[t]!==e)&&(this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(this.#St,t)}),this.#bt===T.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Yt([[M.HIGHLIGHT_FREE,!0]]))}#Yt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#Ht(),this.#Gt(),this.#Ut({isEditing:this.#bt!==T.NONE,isEmpty:this.#qt(),hasSomethingToUndo:this.#G.hasSomethingToUndo(),hasSomethingToRedo:this.#G.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#$t(),this.#Wt(),this.#Ut({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#Q){this.#Q=t;for(const t of this.#Q)this.#Yt(t.defaultPropertiesToUpdate)}}getId(){return this.#ht.id}get currentLayer(){return this.#U.get(this.#Y)}getLayer(t){return this.#U.get(t)}get currentPageIndex(){return this.#Y}addLayer(t){this.#U.set(t.pageIndex,t),this.#lt?t.enable():t.disable()}removeLayer(t){this.#U.delete(t.pageIndex)}async updateMode(t,e=null,s=!1,i=!1,n=!1,r=!1){if(this.#bt!==t){if(this.#Pt&&(await this.#Pt.promise,!this.#Pt))return;if(this.#Pt=Promise.withResolvers(),this.#X?.commitOrRemove(),this.#bt===T.POPUP&&this.#W?.hideSidebar(),this.#W?.destroyPopup(),this.#bt=t,t!==T.NONE){for(const t of this.#L.values())t.addStandaloneCommentButton();t===T.SIGNATURE&&await(this.#wt?.loadSignatures()),s&&Vt.clearPointerType(),this.setEditingState(!0),await this.#Kt(),this.unselectAll();for(const e of this.#U.values())e.updateMode(t);if(t===T.POPUP){this.#B||=await this.#xt.getAnnotationsByType(new Set(this.#Q.map(t=>t._editorType)));const t=new Set,e=[];for(const s of this.#L.values()){const{annotationElementId:i,hasComment:n,deleted:r}=s;i&&t.add(i),n&&!r&&e.push(s.getData())}for(const s of this.#B){const{id:i,popupRef:n,contentsObj:r}=s;n&&r?.str&&!t.has(i)&&!this.#q.has(i)&&e.push(s)}this.#W?.showSidebar(e)}if(e){for(const t of this.#L.values())t.uid===e?(this.setSelected(t),r?t.editComment():n?t.enterInEditMode():t.focus()):t.unselect();this.#Pt.resolve()}else i&&this.addNewEditorFromKeyboard(),this.#Pt.resolve()}else{this.setEditingState(!1),this.#Qt();for(const t of this.#L.values())t.hideStandaloneCommentButton();this._editorUndoBar?.hide(),this.toggleComment(null),this.#Pt.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#bt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#Q){switch(t){case M.CREATE:return void this.currentLayer.addNewEditor(e);case M.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#_t||=new Map).set(t,e),this.showAllEditors("highlight",e)}if(this.hasSelection)for(const s of this.#yt)s.updateParams(t,e);else for(const s of this.#Q)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const i of this.#L.values())i.editorType===t&&i.show(e);(this.#_t?.get(M.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Yt([[M.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#dt!==t){this.#dt=t;for(const e of this.#U.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#Kt(){if(!this.#lt){this.#lt=!0;const t=[];for(const e of this.#U.values())t.push(e.enable());await Promise.all(t);for(const e of this.#L.values())e.enable()}}#Qt(){if(this.unselectAll(),this.#lt){this.#lt=!1;for(const t of this.#U.values())t.disable();for(const t of this.#L.values())t.disable()}}*getEditors(t){for(const e of this.#L.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#L.get(t)}addEditor(t){this.#L.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#it&&clearTimeout(this.#it),this.#it=setTimeout(()=>{this.focusMainContainer(),this.#it=null},0)),this.#L.delete(t.id),t.annotationElementId&&this.#mt?.delete(t.annotationElementId),this.unselect(t),t.annotationElementId&&this.#q.has(t.annotationElementId)||this.#$?.remove(t.id)}addDeletedAnnotationElement(t){this.#q.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#q.has(t)}removeDeletedAnnotationElement(t){this.#q.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#Vt(t){const e=this.#U.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#O!==t&&(this.#O=t,t&&this.#Yt(t.propertiesToUpdate))}get#Jt(){let t=null;for(t of this.#yt);return t}updateUI(t){this.#Jt===t&&this.#Yt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Yt(t.defaultPropertiesToUpdate)}toggleSelected(t){this.#yt.has(t)?(this.#yt.delete(t),t.unselect(),this.#Ut({hasSelectedEditor:this.hasSelection})):(this.#yt.add(t),t.select(),this.#Yt(t.propertiesToUpdate),this.#Ut({hasSelectedEditor:!0}))}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.uid}),this.#X?.commitOrRemove();for(const e of this.#yt)e!==t&&e.unselect();this.#W?.destroyPopup(),this.#yt.clear(),this.#yt.add(t),t.select(),this.#Yt(t.propertiesToUpdate),this.#Ut({hasSelectedEditor:!0})}isSelected(t){return this.#yt.has(t)}get firstSelectedEditor(){return this.#yt.values().next().value}unselect(t){t.unselect(),this.#yt.delete(t),this.#Ut({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#yt.size}get isEnterHandled(){return 1===this.#yt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#G.undo(),this.#Ut({hasSomethingToUndo:this.#G.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#qt()}),this._editorUndoBar?.hide()}redo(){this.#G.redo(),this.#Ut({hasSomethingToUndo:!0,hasSomethingToRedo:this.#G.hasSomethingToRedo(),isEmpty:this.#qt()})}addCommands(t){this.#G.add(t),this.#Ut({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#qt()})}cleanUndoStack(t){this.#G.cleanType(t)}#qt(){if(0===this.#L.size)return!0;if(1===this.#L.size)for(const t of this.#L.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#yt],s=()=>{for(const t of e)this.#Vt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(s,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo:s,mustExec:!0})}commitOrRemove(){this.#O?.commitOrRemove()}hasSomethingToControl(){return this.#O||this.hasSelection}#Xt(t){for(const e of this.#yt)e.unselect();this.#yt.clear();for(const e of t)e.isEmpty()||(this.#yt.add(e),e.select());this.#Ut({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#yt)t.commit();this.#Xt(this.#L.values())}unselectAll(){if((!this.#O||(this.#O.commitOrRemove(),this.#bt===T.NONE))&&!this.#X?.commitOrRemove()&&(this.#W?.destroyPopup(),this.hasSelection)){for(const t of this.#yt)t.unselect();this.#yt.clear(),this.#Ut({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#Ct[0]+=t,this.#Ct[1]+=e;const[i,n]=this.#Ct,r=[...this.#yt];this.#kt&&clearTimeout(this.#kt),this.#kt=setTimeout(()=>{this.#kt=null,this.#Ct[0]=this.#Ct[1]=0,this.addCommands({cmd:()=>{for(const t of r)this.#L.has(t.id)&&(t.translateInPage(i,n),t.translationDone())},undo:()=>{for(const t of r)this.#L.has(t.id)&&(t.translateInPage(-i,-n),t.translationDone())},mustExec:!1})},1e3);for(const a of r)a.translateInPage(t,e),a.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#K=new Map;for(const t of this.#yt)this.#K.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#K)return!1;this.disableUserSelect(!1);const t=this.#K;this.#K=null;let e=!1;for(const[{x:i,y:n,pageIndex:r},a]of t)a.newX=i,a.newY=n,a.newPageIndex=r,e||=i!==a.savedX||n!==a.savedY||r!==a.savedPageIndex;if(!e)return!1;const s=(t,e,s,i)=>{if(this.#L.has(t.id)){const n=this.#U.get(i);n?t._setParentAndPosition(n,e,s):(t.pageIndex=i,t.x=e,t.y=s)}};return this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:n,newPageIndex:r}]of t)s(e,i,n,r)},undo:()=>{for(const[e,{savedX:i,savedY:n,savedPageIndex:r}]of t)s(e,i,n,r)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#K)for(const s of this.#K.keys())s.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#yt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#O===t}getActive(){return this.#O}getMode(){return this.#bt}isEditingMode(){return this.#bt!==T.NONE}get imageManager(){return it(this,"imageManager",new Yt)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let h=0,l=e.rangeCount;h<l;h++)if(!t.contains(e.getRangeAt(h).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let a;switch(t.getAttribute("data-main-rotation")){case"90":a=(t,e,a,o)=>({x:(e-i)/r,y:1-(t+a-s)/n,width:o/r,height:a/n});break;case"180":a=(t,e,a,o)=>({x:1-(t+a-s)/n,y:1-(e+o-i)/r,width:a/n,height:o/r});break;case"270":a=(t,e,a,o)=>({x:1-(e+o-i)/r,y:(t-s)/n,width:o/r,height:a/n});break;default:a=(t,e,a,o)=>({x:(t-s)/n,y:(e-i)/r,width:a/n,height:o/r})}const o=[];for(let h=0,l=e.rangeCount;h<l;h++){const t=e.getRangeAt(h);if(!t.collapsed)for(const{x:e,y:s,width:i,height:n}of t.getClientRects())0!==i&&0!==n&&o.push(a(e,s,i,n))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#z||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#z?.delete(t)}renderAnnotationElement(t){const e=this.#z?.get(t.data.id);if(!e)return;const s=this.#$.getRawValue(e);s&&(this.#bt!==T.NONE||s.hasBeenModified)&&s.renderAnnotationElement(t)}setMissingCanvas(t,e,s){const i=this.#mt?.get(t);i&&(i.setCanvas(e,s),this.#mt.delete(t))}addMissingCanvas(t,e){(this.#mt||=new Map).set(t,e)}}class Zt{#h=null;#Zt=!1;#te=null;#ee=null;#se=null;#ie=null;#ne=!1;#re=null;#a=null;#ae=null;#oe=null;#he=!1;static#le=null;static _l10n=null;constructor(t){this.#a=t,this.#he=t._uiManager.useNewAltTextFlow,Zt.#le||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){Zt._l10n??=t}async render(){const t=this.#te=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#ee=document.createElement("span");t.append(e),this.#he?(t.classList.add("new"),t.setAttribute("data-l10n-id",Zt.#le.missing),e.setAttribute("data-l10n-id",Zt.#le["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=this.#a._uiManager._signal;t.addEventListener("contextmenu",Pt,{signal:s}),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:s});const i=t=>{t.preventDefault(),this.#a._uiManager.editAltText(this.#a),this.#he&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#ce}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#ne=!0,i(e))},{signal:s}),await this.#de(),t}get#ce(){return(this.#h?"added":null===this.#h&&this.guessedText&&"review")||"missing"}finish(){this.#te&&(this.#te.focus({focusVisible:this.#ne}),this.#ne=!1)}isEmpty(){return this.#he?null===this.#h:!this.#h&&!this.#Zt}hasData(){return this.#he?null!==this.#h||!!this.#ae:this.isEmpty()}get guessedText(){return this.#ae}async setGuessedText(t){null===this.#h&&(this.#ae=t,this.#oe=await Zt._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#de())}toggleAltTextBadge(t=!1){if(this.#he&&!this.#h){if(!this.#re){const t=this.#re=document.createElement("div");t.className="noAltTextBadge",this.#a.div.append(t)}this.#re.classList.toggle("hidden",!t)}else this.#re?.remove(),this.#re=null}serialize(t){let e=this.#h;return t||this.#ae!==e||(e=this.#oe),{altText:e,decorative:this.#Zt,guessedText:this.#ae,textWithDisclaimer:this.#oe}}get data(){return{altText:this.#h,decorative:this.#Zt}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(this.#ae=s,this.#oe=i),this.#h===t&&this.#Zt===e||(n||(this.#h=t,this.#Zt=e),this.#de())}toggle(t=!1){this.#te&&(!t&&this.#ie&&(clearTimeout(this.#ie),this.#ie=null),this.#te.disabled=!t)}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#ce}})}destroy(){this.#te?.remove(),this.#te=null,this.#ee=null,this.#se=null,this.#re?.remove(),this.#re=null}async#de(){const t=this.#te;if(!t)return;if(this.#he){if(t.classList.toggle("done",!!this.#h),t.setAttribute("data-l10n-id",Zt.#le[this.#ce]),this.#ee?.setAttribute("data-l10n-id",Zt.#le[`${this.#ce}-label`]),!this.#h)return void this.#se?.remove()}else{if(!this.#h&&!this.#Zt)return t.classList.remove("done"),void this.#se?.remove();t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#se;if(!e){this.#se=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#a.id}`;const s=100,i=this.#a._uiManager._signal;i.addEventListener("abort",()=>{clearTimeout(this.#ie),this.#ie=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#ie=setTimeout(()=>{this.#ie=null,this.#se.classList.add("show"),this.#a._reportTelemetry({action:"alt_text_tooltip"})},s)},{signal:i}),t.addEventListener("mouseleave",()=>{this.#ie&&(clearTimeout(this.#ie),this.#ie=null),this.#se?.classList.remove("show")},{signal:i})}this.#Zt?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#h),e.parentNode||t.append(e);const s=this.#a.getElementForAltText();s?.setAttribute("aria-describedby",e.id)}}class te{#ue=null;#pe=null;#ge=!1;#a=null;#me=null;#fe=null;#be=null;#ye=null;#Ae=!1;#we=null;constructor(t){this.#a=t}renderForToolbar(){const t=this.#pe=document.createElement("button");return t.className="comment",this.#A(t,!1)}renderForStandalone(){const t=this.#ue=document.createElement("button");t.className="annotationCommentButton";const e=this.#a.commentButtonPosition;if(e){const{style:s}=t;s.insetInlineEnd=`calc(${100*("ltr"===this.#a._uiManager.direction?1-e[0]:e[0])}% - var(--comment-button-dim))`,s.top=`calc(${100*e[1]}% - var(--comment-button-dim))`;const i=this.#a.commentButtonColor;i&&(s.backgroundColor=i)}return this.#A(t,!0)}focusButton(){setTimeout(()=>{(this.#ue??this.#pe)?.focus()},0)}onUpdatedColor(){if(!this.#ue)return;const t=this.#a.commentButtonColor;t&&(this.#ue.style.backgroundColor=t),this.#a._uiManager.updatePopupColor(this.#a)}get commentButtonWidth(){return(this.#ue?.getBoundingClientRect().width??0)/this.#a.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#we)return this.#we;if(!this.#ue)return null;const{x:t,y:e,height:s}=this.#ue.getBoundingClientRect(),{x:i,y:n,width:r,height:a}=this.#a.parent.boundingClientRect;return[(t-i)/r,(e+s-n)/a]}set commentPopupPositionInLayer(t){this.#we=t}hasDefaultPopupPosition(){return null===this.#we}removeStandaloneCommentButton(){this.#ue?.remove(),this.#ue=null}removeToolbarCommentButton(){this.#pe?.remove(),this.#pe=null}setCommentButtonStates({selected:t,hasPopup:e}){this.#ue&&(this.#ue.classList.toggle("selected",t),this.#ue.ariaExpanded=e)}#A(t,e){if(!this.#a._uiManager.hasCommentManager())return null;t.tabIndex="0",t.ariaHasPopup="dialog",e?(t.ariaControls="commentPopup",t.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(t.ariaControlsElements=[this.#a._uiManager.getCommentDialogElement()],t.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button"));const s=this.#a._uiManager._signal;if(!(s instanceof AbortSignal)||s.aborted)return t;t.addEventListener("contextmenu",Pt,{signal:s}),e&&(t.addEventListener("focusin",t=>{this.#a._focusEventsAllowed=!1,Dt(t)},{capture:!0,signal:s}),t.addEventListener("focusout",t=>{this.#a._focusEventsAllowed=!0,Dt(t)},{capture:!0,signal:s})),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:s});const i=e=>{e.preventDefault(),t===this.#pe?this.edit():this.#a.toggleComment(!0)};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#ge=!0,i(e))},{signal:s}),t.addEventListener("pointerenter",()=>{this.#a.toggleComment(!1,!0)},{signal:s}),t.addEventListener("pointerleave",()=>{this.#a.toggleComment(!1,!1)},{signal:s}),t}edit(t){const e=this.commentPopupPositionInLayer;let s,i;if(e)[s,i]=e;else{[s,i]=this.#a.commentButtonPosition;const{width:t,height:e,x:n,y:r}=this.#a;s=n+s*t,i=r+i*e}const n=this.#a.parent.boundingClientRect,{x:r,y:a,width:o,height:h}=n;this.#a._uiManager.editComment(this.#a,r+s*o,a+i*h,{...t,parentDimensions:n})}finish(){this.#pe&&(this.#pe.focus({focusVisible:this.#ge}),this.#ge=!1)}isDeleted(){return this.#Ae||""===this.#be}isEmpty(){return null===this.#be}hasBeenEdited(){return this.isDeleted()||this.#be!==this.#me}serialize(){return this.data}get data(){return{text:this.#be,richText:this.#fe,date:this.#ye,deleted:this.isDeleted()}}set data(t){t!==this.#be&&(this.#fe=null),null!==t?(this.#be=t,this.#ye=new Date,this.#Ae=!1):(this.#be="",this.#Ae=!0)}restoreData({text:t,richText:e,date:s}){this.#be=t,this.#fe=e,this.#ye=s,this.#Ae=!1}setInitialText(t,e=null){this.#me=t,this.data=t,this.#ye=null,this.#fe=e}shown(){}destroy(){this.#pe?.remove(),this.#pe=null,this.#ue?.remove(),this.#ue=null,this.#be="",this.#fe=null,this.#ye=null,this.#a=null,this.#ge=!1,this.#Ae=!1}}class ee{#Tt;#ve=!1;#_e=null;#xe;#Se;#Ce;#ke;#Te=null;#Me;#Ee=null;#Pe;#De=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,signal:a}){this.#Tt=t,this.#_e=s,this.#xe=e,this.#Se=i,this.#Ce=n,this.#ke=r,this.#Pe=new AbortController,this.#Me=AbortSignal.any([a,this.#Pe.signal]),t.addEventListener("touchstart",this.#Ie.bind(this),{passive:!1,signal:this.#Me})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Lt.pixelRatio}#Ie(t){if(this.#xe?.())return;if(1===t.touches.length){if(this.#Te)return;const t=this.#Te=new AbortController,e=AbortSignal.any([this.#Me,t.signal]),s=this.#Tt,i={capture:!0,signal:e,passive:!1},n=t=>{"touch"===t.pointerType&&(this.#Te?.abort(),this.#Te=null)};return s.addEventListener("pointerdown",t=>{"touch"===t.pointerType&&(Dt(t),n(t))},i),s.addEventListener("pointerup",n,i),void s.addEventListener("pointercancel",n,i)}if(!this.#De){this.#De=new AbortController;const t=AbortSignal.any([this.#Me,this.#De.signal]),e=this.#Tt,s={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#Fe.bind(this),s);const i=this.#Ne.bind(this);e.addEventListener("touchend",i,s),e.addEventListener("touchcancel",i,s),s.capture=!0,e.addEventListener("pointerdown",Dt,s),e.addEventListener("pointermove",Dt,s),e.addEventListener("pointercancel",Dt,s),e.addEventListener("pointerup",Dt,s),this.#Se?.()}if(Dt(t),2!==t.touches.length||this.#_e?.())return void(this.#Ee=null);let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]),this.#Ee={touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY}}#Fe(t){if(!this.#Ee||2!==t.touches.length)return;Dt(t);let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e,{screenX:r,screenY:a}=s,o=this.#Ee,{touch0X:h,touch0Y:l,touch1X:c,touch1Y:d}=o,u=c-h,p=d-l,g=r-i,m=a-n,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#ve&&Math.abs(b-f)<=ee.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(o.touch0X=i,o.touch0Y=n,o.touch1X=r,o.touch1Y=a,!this.#ve)return void(this.#ve=!0);const y=[(i+r)/2,(n+a)/2];this.#Ce?.(y,b,f)}#Ne(t){t.touches.length>=2||(this.#De&&(this.#De.abort(),this.#De=null,this.#ke?.()),this.#Ee&&(Dt(t),this.#Ee=null,this.#ve=!1))}destroy(){this.#Pe?.abort(),this.#Pe=null,this.#Te?.abort(),this.#Te=null}}class se{#Re=null;#Oe=null;#h=null;#l=null;#ue=null;#Be=!1;#Le=null;#Ue="";#je=null;#He=null;#$e=null;#ze=null;#Ge=null;#We="";#Ve=!1;#Xe=null;#Ye=!1;#qe=!1;#Ke=!1;#Qe=null;#Je=0;#Ze=0;#ts=null;#es=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nAlert=null;static _l10nResizer=null;#ss=!1;#is=se._zIndex++;static _borderLineWidth=-1;static _colorManager=new Qt;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=se.prototype._resizeWithKeyboard,e=Jt.TRANSLATE_SMALL,s=Jt.TRANSLATE_BIG;return it(this,"_resizerKeyboardManager",new Kt([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],se.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null,this.annotationElementId=t.annotationElementId||null,this.creationDate=t.creationDate||new Date,this.modificationDate=t.modificationDate||null,this.canAddComment=!0;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[a,o]=this.parentDimensions;this.x=t.x/a,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}updatePageIndex(t){this.pageIndex=t}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return it(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new ie({id:t._uiManager.getId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){if(se._l10n??=t,se._l10nAlert??=Object.freeze({highlight:"pdfjs-editor-highlight-added-alert",freetext:"pdfjs-editor-freetext-added-alert",ink:"pdfjs-editor-ink-added-alert",stamp:"pdfjs-editor-stamp-added-alert",signature:"pdfjs-editor-signature-added-alert"}),se._l10nResizer??=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),-1!==se._borderLineWidth)return;const s=getComputedStyle(document.documentElement);se._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){Z("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#ss}set _isDraggable(t){this.#ss=t,this.div?.classList.toggle("draggable",t)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t),this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t),this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#is}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):(this.#ns(),this.#ze?.remove(),this.#ze=null),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#Ve?this.#Ve=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;e?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,r]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(t+s)/n,this.y=(e+i)/r,this.fixAndSetPosition()}_moveAfterPaste(t,e){if(this.isClone)return void delete this.isClone;const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i),this._onTranslated()}#rs([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#rs(this.parentDimensions,t,e)}translateInPage(t,e){this.#Xe||=[this.x,this.y,this.width,this.height],this.#rs(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#Xe||=[this.x,this.y,this.width,this.height];const{div:s,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=e/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,e)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:a}=this;const[o,h]=this.getBaseTranslation();r+=o,a+=h;const{style:l}=s;l.left=`${(100*r).toFixed(2)}%`,l.top=`${(100*a).toFixed(2)}%`,this._onTranslating(r,a),s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#Xe&&(this.#Xe[0]!==this.x||this.#Xe[1]!==this.y)}get _hasBeenResized(){return!!this.#Xe&&(this.#Xe[2]!==this.width||this.#Xe[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=se,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:a,height:o}=this;if(a*=s,o*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=yt(n,0,s-a),r=yt(r,0,i-o);break;case 90:n=yt(n,0,s-o),r=yt(r,a,i);break;case 180:n=yt(n,a,s),r=yt(r,o,i);break;case 270:n=yt(n,o,s),r=yt(r,0,i-a)}this.x=n/=s,this.y=r/=i;const[h,l]=this.getBaseTranslation();n+=h,r+=l,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#as(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return se.#as(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return se.#as(t,e,360-this.parentRotation)}#os(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(){const{div:{style:t},width:e,height:s}=this;t.width=`${(100*e).toFixed(2)}%`,t.height=`${(100*s).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#hs(){if(this.#je)return;this.#je=document.createElement("div"),this.#je.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const s of t){const t=document.createElement("div");this.#je.append(t),t.classList.add("resizer",s),t.setAttribute("data-resizer-name",s),t.addEventListener("pointerdown",this.#ls.bind(this,s),{signal:e}),t.addEventListener("contextmenu",Pt,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#je)}#ls(t,e){e.preventDefault();const{isMac:s}=ut.platform;if(0!==e.button||e.ctrlKey&&s)return;this.#h?.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,this.#He=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#cs.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",Dt,{passive:!1,signal:r}),window.addEventListener("contextmenu",Pt,{signal:r}),this.#$e={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const a=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const h=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#h?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=a,this.div.style.cursor=o,this.#ds()};window.addEventListener("pointerup",h,{signal:r}),window.addEventListener("blur",h,{signal:r})}#us(t,e,s,i){this.width=s,this.height=i,this.x=t,this.y=e,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#ds(){if(!this.#$e)return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#$e;this.#$e=null;const n=this.x,r=this.y,a=this.width,o=this.height;n===t&&r===e&&a===s&&o===i||this.addCommands({cmd:this.#us.bind(this,n,r,a,o),undo:this.#us.bind(this,t,e,s,i),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#cs(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,a=this.width,o=this.height,h=se.MIN_SIZE/s,l=se.MIN_SIZE/i,c=this.#os(this.rotation),d=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],u=this.#os(360-this.rotation);let p,g,m=!1,f=!1;switch(t){case"topLeft":m=!0,p=(t,e)=>[0,0],g=(t,e)=>[t,e];break;case"topMiddle":p=(t,e)=>[t/2,0],g=(t,e)=>[t/2,e];break;case"topRight":m=!0,p=(t,e)=>[t,0],g=(t,e)=>[0,e];break;case"middleRight":f=!0,p=(t,e)=>[t,e/2],g=(t,e)=>[0,e/2];break;case"bottomRight":m=!0,p=(t,e)=>[t,e],g=(t,e)=>[0,0];break;case"bottomMiddle":p=(t,e)=>[t/2,e],g=(t,e)=>[t/2,0];break;case"bottomLeft":m=!0,p=(t,e)=>[0,e],g=(t,e)=>[t,0];break;case"middleLeft":f=!0,p=(t,e)=>[0,e/2],g=(t,e)=>[t,e/2]}const b=p(a,o),y=g(a,o);let A=d(...y);const w=se._round(n+A[0]),v=se._round(r+A[1]);let _,x,S=1,C=1;if(e.fromKeyboard)({deltaX:_,deltaY:x}=e);else{const{screenX:t,screenY:s}=e,[i,n]=this.#He;[_,x]=this.screenToPageTranslation(t-i,s-n),this.#He[0]=t,this.#He[1]=s}var k,T;if([_,x]=(k=_/s,T=x/i,[u[0]*k+u[2]*T,u[1]*k+u[3]*T]),m){const t=Math.hypot(a,o);S=C=Math.max(Math.min(Math.hypot(y[0]-b[0]-_,y[1]-b[1]-x)/t,1/a,1/o),h/a,l/o)}else f?S=yt(Math.abs(y[0]-b[0]-_),h,1)/a:C=yt(Math.abs(y[1]-b[1]-x),l,1)/o;const M=se._round(a*S),E=se._round(o*C);A=d(...g(M,E));const P=w-A[0],D=v-A[1];this.#Xe||=[this.x,this.y,this.width,this.height],this.width=M,this.height=E,this.x=P,this.y=D,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#h?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#qe)return this._editToolbar;this._editToolbar=new zt(this),this.div.append(this._editToolbar.render());const{toolbarButtons:t}=this;if(t)for(const[e,s]of t)await this._editToolbar.addButton(e,s);return this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton()),this._editToolbar.addButton("delete"),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#h?.destroy()}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#h||(Zt.initialize(se._l10n),this.#h=new Zt(this),this.#Re&&(this.#h.data=this.#Re,this.#Re=null)),this.#h}get altTextData(){return this.#h?.data}set altTextData(t){this.#h&&(this.#h.data=t)}get guessedAltText(){return this.#h?.guessedText}async setGuessedAltText(t){await(this.#h?.setGuessedText(t))}serializeAltText(t){return this.#h?.serialize(t)}hasAltText(){return!!this.#h&&!this.#h.isEmpty()}hasAltTextData(){return this.#h?.hasData()??!1}focusCommentButton(){this.#l?.focusButton()}addCommentButton(){return this.canAddComment?this.#l||=new te(this):null}addStandaloneCommentButton(){this._uiManager.hasCommentManager()&&(this.#ue?this._uiManager.isEditingMode()&&this.#ue.classList.remove("hidden"):this.hasComment&&(this.#ue=this.#l.renderForStandalone(),this.div.append(this.#ue)))}removeStandaloneCommentButton(){this.#l.removeStandaloneCommentButton(),this.#ue=null}hideStandaloneCommentButton(){this.#ue?.classList.add("hidden")}get comment(){if(!this.#l)return null;const{data:{richText:t,text:e,date:s,deleted:i}}=this.#l;return{text:e,richText:t,date:s,deleted:i,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#l||=new te(this),"object"==typeof t&&null!==t?this.#l.restoreData(t):this.#l.data=t,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:t,popupRef:e,richText:s}){if(!e)return;if(this.#l||=new te(this),this.#l.setInitialText(t,s),!this.annotationElementId)return;const i=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);i&&this.updateFromAnnotationLayer(i)}get hasEditedComment(){return this.#l?.hasBeenEdited()}get hasDeletedComment(){return this.#l?.isDeleted()}get hasComment(){return!!this.#l&&!this.#l.isEmpty()&&!this.#l.isDeleted()}async editComment(t){this.#l||=new te(this),this.#l.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#l.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const e=180,s=100,[,,,i]=t.rect,[n]=this.pageDimensions,[r]=this.pageTranslation,a=r+n+1,o=i-s,h=a+e;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[a,o,h,i]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#l.data=e?null:t}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360),t.className=this.name,t.setAttribute("id",this.id),t.tabIndex=this.#Be?-1:0,t.setAttribute("role","application"),this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||t.classList.add("hidden"),this.setInForeground(),this.#ps();const[e,s]=this.parentDimensions;this.parentRotation%180!=0&&(t.style.maxWidth=`${(100*s/e).toFixed(2)}%`,t.style.maxHeight=`${(100*e/s).toFixed(2)}%`);const[i,n]=this.getInitialTranslation();return this.translate(i,n),Wt(this,t,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#es||=new ee({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#gs.bind(this),onPinching:this.#ms.bind(this),onPinchEnd:this.#fs.bind(this),signal:this._uiManager._signal})),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),t}#gs(){this.#$e={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#h?.toggle(!1),this.parent.togglePointerEvents(!1)}#ms(t,e,s){let i=s/e*.7+1-.7;if(1===i)return;const n=this.#os(this.rotation),r=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[a,o]=this.parentDimensions,h=this.x,l=this.y,c=this.width,d=this.height,u=se.MIN_SIZE/a,p=se.MIN_SIZE/o;i=Math.max(Math.min(i,1/c,1/d),u/c,p/d);const g=se._round(c*i),m=se._round(d*i);if(g===c&&m===d)return;this.#Xe||=[h,l,c,d];const f=r(c/2,d/2),b=se._round(h+f[0]),y=se._round(l+f[1]),A=r(g/2,m/2);this.x=b-A[0],this.y=y-A[1],this.width=g,this.height=m,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#fs(){this.#h?.toggle(!0),this.parent.togglePointerEvents(!0),this.#ds()}pointerdown(t){const{isMac:e}=ut.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#Ve=!0,this._isDraggable?this.#bs(t):this.#ys(t))}#ys(t){const{isMac:e}=ut.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#bs(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let s=!1;const i=new AbortController,n=this._uiManager.combinedSignal(i),r={capture:!0,passive:!1,signal:n},a=t=>{i.abort(),this.#Le=null,this.#Ve=!1,this._uiManager.endDragSession()||this.#ys(t),s&&this._onStopDragging()};e&&(this.#Je=t.clientX,this.#Ze=t.clientY,this.#Le=t.pointerId,this.#Ue=t.pointerType,window.addEventListener("pointermove",t=>{s||(s=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());const{clientX:e,clientY:i,pointerId:n}=t;if(n!==this.#Le)return void Dt(t);const[r,a]=this.screenToPageTranslation(e-this.#Je,i-this.#Ze);this.#Je=e,this.#Ze=i,this._uiManager.dragSelectedEditors(r,a)},r),window.addEventListener("touchmove",Dt,r),window.addEventListener("pointerdown",t=>{t.pointerType===this.#Ue&&(this.#es||t.isPrimary)&&a(t),Dt(t)},r));const o=t=>{this.#Le&&this.#Le!==t.pointerId?Dt(t):a(t)};window.addEventListener("pointerup",o,{signal:n}),window.addEventListener("blur",o,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Qe&&clearTimeout(this.#Qe),this.#Qe=setTimeout(()=>{this.#Qe=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[a,o]=this.pageTranslation,h=t/i,l=e/i,c=this.x*n,d=this.y*r,u=this.width*n,p=this.height*r;switch(s){case 0:return[c+h+a,r-d-l-p+o,c+h+u+a,r-d-l+o];case 90:return[c+l+a,r-d+h+o,c+l+p+a,r-d+h+u+o];case 180:return[c-h-u+a,r-d+l+o,c-h+a,r-d+l+p+o];case 270:return[c-l-p+a,r-d-h-u+o,c-l+a,r-d-h+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,a=n-s,o=r-i;switch(this.rotation){case 0:return[s,e-r,a,o];case 90:return[s,e-i,o,a];case 180:return[n,e-i,a,o];case 270:return[n,e-r,o,a];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&se._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#l?.onUpdatedColor()}getData(){const{comment:{text:t,color:e,date:s,opacity:i,deleted:n,richText:r},uid:a,pageIndex:o,creationDate:h,modificationDate:l}=this;return{id:a,pageIndex:o,rect:this.getPDFRect(),richText:r,contentsObj:{str:t},creationDate:h,modificationDate:s||l,popupRef:!n,color:e,opacity:i}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#qe=!0,!0)}disableEditMode(){return!!this.isInEditMode()&&(this.parent.setEditingState(!0),this.#qe=!1,!0)}isInEditMode(){return this.#qe}shouldGetKeyboardEvents(){return this.#Ke}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:s,right:i}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e<r&&i>0&&t<n&&s>0}#ps(){if(this.#Ge||!this.div)return;this.#Ge=new AbortController;const t=this._uiManager.combinedSignal(this.#Ge);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#ps()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:s.getId(),uiManager:s,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});i.rotation=t.rotation,i.#Re=t.accessibilityData,i._isCopy=t.isCopy||!1;const[n,r]=i.pageDimensions,[a,o,h,l]=i.getRectInCurrentCoords(t.rect,r);return i.x=a/n,i.y=o/r,i.width=h/n,i.height=l/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#Ge?.abort(),this.#Ge=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),this.#Qe&&(clearTimeout(this.#Qe),this.#Qe=null),this.#ns(),this.removeEditToolbar(),this.#ts){for(const t of this.#ts.values())clearTimeout(t);this.#ts=null}this.parent=null,this.#es?.destroy(),this.#es=null,this.#ze?.remove(),this.#ze=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#hs(),this.#je.classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return"ltr"===this._uiManager.direction?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[t,e]}=this,[s,i,n,r]=this.getPDFRect();return[se._round(s+(n-s)*t),se._round(i+(r-i)*(1-e))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#l.commentPopupPositionInLayer}set commentPopupPosition(t){this.#l.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#l.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#l.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#l?.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#$e={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#je.children;if(!this.#Oe){this.#Oe=Array.from(e);const t=this.#As.bind(this),s=this.#ws.bind(this),i=this._uiManager._signal;for(const e of this.#Oe){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:i}),e.addEventListener("blur",s,{signal:i}),e.addEventListener("focus",this.#vs.bind(this,n),{signal:i}),e.setAttribute("data-l10n-id",se._l10nResizer[n])}}const s=this.#Oe[0];let i=0;for(const r of e){if(r===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#Oe.length/4);if(n!==i){if(n<i)for(let e=0;e<i-n;e++)this.#je.append(this.#je.firstElementChild);else if(n>i)for(let e=0;e<n-i;e++)this.#je.firstElementChild.before(this.#je.lastElementChild);let t=0;for(const s of e){const e=this.#Oe[t++].getAttribute("data-resizer-name");s.setAttribute("data-l10n-id",se._l10nResizer[e])}}this.#_s(0),this.#Ke=!0,this.#je.firstElementChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#As(t){se._resizerKeyboardManager.exec(this,t)}#ws(t){this.#Ke&&t.relatedTarget?.parentNode!==this.#je&&this.#ns()}#vs(t){this.#We=this.#Ke?t:""}#_s(t){if(this.#Oe)for(const e of this.#Oe)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#Ke&&this.#cs(this.#We,{deltaX:t,deltaY:e,fromKeyboard:!0})}#ns(){this.#Ke=!1,this.#_s(-1),this.#ds()}_stopResizingWithKeyboard(){this.#ns(),this.div.focus()}select(){this.isSelected&&this._editToolbar?this._editToolbar.show():(this.isSelected=!0,this.makeResizable(),this.div?.classList.add("selectedEditor"),this._editToolbar?(this._editToolbar?.show(),this.#h?.toggleAltTextBadge(!1)):this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#je?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#h?.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(t){"BUTTON"!==t.target.nodeName&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#Ye}set isEditing(t){this.#Ye=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#ts||=new Map;const{action:e}=t;let s=this.#ts.get(e);return s&&clearTimeout(s),s=setTimeout(()=>{this._reportTelemetry(t),this.#ts.delete(e),0===this.#ts.size&&(this.#ts=null)},se._telemetryTimeout),void this.#ts.set(e,s)}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#Be=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#Be=!0}updateFakeAnnotationElement(t){this.#ze||this.deleted?this.deleted?(this.#ze.remove(),this.#ze=null):(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#ze.updateEdited({rect:this.getPDFRect(),popup:this.comment}):this.#ze=t.addFakeAnnotation(this)}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.before(e)}}else e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);return e}resetAnnotationElement(t){const{firstElementChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class ie extends se{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const ne=3285377520,re=4294901760,ae=65535;class oe{constructor(t){this.h1=t?4294967295&t:ne,this.h2=t?4294967295&t:ne}update(t){let e,s;if("string"==typeof t){e=new Uint8Array(2*t.length),s=0;for(let i=0,n=t.length;i<n;i++){const n=t.charCodeAt(i);n<=255?e[s++]=n:(e[s++]=n>>>8,e[s++]=255&n)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),s=e.byteLength}const i=s>>2,n=s-4*i,r=new Uint32Array(e.buffer,0,i);let a=0,o=0,h=this.h1,l=this.h2;const c=3432918353,d=461845907,u=11601,p=13715;for(let g=0;g<i;g++)1&g?(a=r[g],a=a*c&re|a*u&ae,a=a<<15|a>>>17,a=a*d&re|a*p&ae,h^=a,h=h<<13|h>>>19,h=5*h+3864292196):(o=r[g],o=o*c&re|o*u&ae,o=o<<15|o>>>17,o=o*d&re|o*p&ae,l^=o,l=l<<13|l>>>19,l=5*l+3864292196);switch(a=0,n){case 3:a^=e[4*i+2]<<16;case 2:a^=e[4*i+1]<<8;case 1:a^=e[4*i],a=a*c&re|a*u&ae,a=a<<15|a>>>17,a=a*d&re|a*p&ae,1&i?h^=a:l^=a}this.h1=h,this.h2=l}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&re|36045*t&ae,e=4283543511*e&re|(2950163797*(e<<16|t>>>16)&re)>>>16,t^=e>>>1,t=444984403*t&re|60499*t&ae,e=3301882366*e&re|(3120437893*(e<<16|t>>>16)&re)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const he=Object.freeze({map:null,hash:"",transfer:void 0});class le{#xs=!1;#Ss=null;#Cs=null;#ks=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(t,e){const s=this.#ks.get(t);return void 0===s?e:Object.assign(e,s)}getRawValue(t){return this.#ks.get(t)}remove(t){const e=this.#ks.get(t);void 0!==e&&(e instanceof se&&this.#Cs.delete(e.annotationElementId),this.#ks.delete(t),0===this.#ks.size&&this.resetModified(),this.#ks.values().some(t=>t instanceof se)||this.onAnnotationEditor?.(null))}setValue(t,e){const s=this.#ks.get(t);let i=!1;if(void 0!==s)for(const[n,r]of Object.entries(e))s[n]!==r&&(i=!0,s[n]=r);else i=!0,this.#ks.set(t,e);i&&this.#Ts(),e instanceof se&&((this.#Cs||=new Map).set(e.annotationElementId,e),this.onAnnotationEditor?.(e.constructor._type))}has(t){return this.#ks.has(t)}get size(){return this.#ks.size}#Ts(){this.#xs||(this.#xs=!0,this.onSetModified?.())}resetModified(){this.#xs&&(this.#xs=!1,this.onResetModified?.())}get print(){return new ce(this)}get serializable(){if(0===this.#ks.size)return he;const t=new Map,e=new oe,s=[],i=Object.create(null);let n=!1;for(const[r,a]of this.#ks){const s=a instanceof se?a.serialize(!1,i):a;a.page&&(a.pageIndex=a.page._pageIndex,delete a.page),s&&(t.set(r,s),e.update(`${r}:${JSON.stringify(s)}`),n||=!!s.bitmap)}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:he}get editorStats(){let t=null;const e=new Map;let s=0,i=0;for(const n of this.#ks.values()){if(!(n instanceof se)){n.popup&&(n.popup.deleted?i+=1:s+=1);continue}n.isCommentDeleted?i+=1:n.hasEditedComment&&(s+=1);const r=n.telemetryFinalData;if(!r)continue;const{type:a}=r;e.has(a)||e.set(a,Object.getPrototypeOf(n).constructor),t||=Object.create(null);const o=t[a]||=new Map;for(const[t,e]of Object.entries(r)){if("type"===t)continue;const s=o.getOrInsertComputed(t,ft);s.set(e,(s.get(e)??0)+1)}}if((i>0||s>0)&&(t||=Object.create(null),t.comments={deleted:i,edited:s}),!t)return null;for(const[n,r]of e)t[n]=r.computeTelemetryFinalData(t[n]);return t}resetModifiedIds(){this.#Ss=null}updateEditor(t,e){const s=this.#Cs?.get(t);return!!s&&(s.updateFromAnnotationLayer(e),!0)}getEditor(t){return this.#Cs?.get(t)||null}get modifiedIds(){if(this.#Ss)return this.#Ss;const t=[];if(this.#Cs)for(const s of this.#Cs.values())s.serialize()&&t.push(s.annotationElementId);let e="";if(t.length){const s=new oe;s.update(t.join(",")),e=s.hexdigest()}return this.#Ss={ids:new Set(t),hash:e}}[Symbol.iterator](){return this.#ks.entries()}}class ce extends le{#Ms=he;constructor(t){super();const{serializable:e}=t;if(e===he)return;const{map:s,hash:i,transfer:n}=e,r=structuredClone(s,n?{transfer:n}:null);this.#Ms={map:r,hash:i,transfer:[]}}get print(){Z("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#Ms}get modifiedIds(){return it(this,"modifiedIds",{ids:new Set,hash:""})}}const de="__forcedDependency",{floor:ue,ceil:pe}=Math;function ge(t,e,s,i,n,r){t[4*e+0]=Math.min(t[4*e+0],s),t[4*e+1]=Math.min(t[4*e+1],i),t[4*e+2]=Math.max(t[4*e+2],n),t[4*e+3]=Math.max(t[4*e+3],r)}const me=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class fe{#Es;#Ps;constructor(t,e){this.#Es=t,this.#Ps=e}get length(){return this.#Es.length}isEmpty(t){return this.#Es[t]===me}minX(t){return this.#Ps[4*t+0]/256}minY(t){return this.#Ps[4*t+1]/256}maxX(t){return(this.#Ps[4*t+2]+1)/256}maxY(t){return(this.#Ps[4*t+3]+1)/256}}const be=(t,e)=>t?.getOrInsertComputed(e,()=>({dependencies:new Set,isRenderingOperation:!1}));class ye{#Ds=[[1,0,0,1,0,0]];#Is=[-1/0,-1/0,1/0,1/0];#Fs=new Float64Array(u);_pendingBBoxIdx=-1;#Ns;#Rs;#Os;#Es;_savesStack=[];_markedContentStack=[];constructor(t,e){this.#Ns=t.width,this.#Rs=t.height,this.#Bs(e)}growOperationsCount(t){t>=this.#Es.length&&this.#Bs(t,this.#Es)}#Bs(t,e){const s=new ArrayBuffer(4*t);this.#Os=new Uint8ClampedArray(s),this.#Es=new Uint32Array(s),e&&e.length>0?(this.#Es.set(e),this.#Es.fill(me,e.length)):this.#Es.fill(me)}get clipBox(){return this.#Is}save(t){return this.#Is={__proto__:this.#Is},this._savesStack.push(t),this}restore(t,e){const s=Object.getPrototypeOf(this.#Is);if(null===s)return this;this.#Is=s;const i=this._savesStack.pop();return void 0!==i&&(e?.(i,t),this.#Es[t]=this.#Es[i]),this}recordOpenMarker(t){return this._savesStack.push(t),this}getOpenMarker(){return 0===this._savesStack.length?null:this._savesStack.at(-1)}recordCloseMarker(t,e){const s=this._savesStack.pop();return void 0!==s&&(e?.(s,t),this.#Es[t]=this.#Es[s]),this}beginMarkedContent(t){return this._markedContentStack.push(t),this}endMarkedContent(t,e){const s=this._markedContentStack.pop();return void 0!==s&&(e?.(s,t),this.#Es[t]=this.#Es[s]),this}pushBaseTransform(t){return this.#Ds.push(pt.multiplyByDOMMatrix(this.#Ds.at(-1),t.getTransform())),this}popBaseTransform(){return this.#Ds.length>1&&this.#Ds.pop(),this}resetBBox(t){return this._pendingBBoxIdx!==t&&(this._pendingBBoxIdx=t,this.#Fs.set(u,0)),this}recordClipBox(t,e,s,i,n,r){const a=pt.multiplyByDOMMatrix(this.#Ds.at(-1),e.getTransform()),o=u.slice();pt.axialAlignedBoundingBox([s,n,i,r],a,o);const h=pt.intersect(this.#Is,o);return h?(this.#Is[0]=h[0],this.#Is[1]=h[1],this.#Is[2]=h[2],this.#Is[3]=h[3]):(this.#Is[0]=this.#Is[1]=1/0,this.#Is[2]=this.#Is[3]=-1/0),this}recordBBox(t,e,s,i,n,r){const a=this.#Is;if(a[0]===1/0)return this;const o=pt.multiplyByDOMMatrix(this.#Ds.at(-1),e.getTransform());if(a[0]===-1/0)return pt.axialAlignedBoundingBox([s,n,i,r],o,this.#Fs),this;const h=u.slice();return pt.axialAlignedBoundingBox([s,n,i,r],o,h),this.#Fs[0]=yt(h[0],a[0],this.#Fs[0]),this.#Fs[1]=yt(h[1],a[1],this.#Fs[1]),this.#Fs[2]=yt(h[2],this.#Fs[2],a[2]),this.#Fs[3]=yt(h[3],this.#Fs[3],a[3]),this}recordFullPageBBox(t){return this.#Fs[0]=Math.max(0,this.#Is[0]),this.#Fs[1]=Math.max(0,this.#Is[1]),this.#Fs[2]=Math.min(this.#Ns,this.#Is[2]),this.#Fs[3]=Math.min(this.#Rs,this.#Is[3]),this}recordOperation(t,e=!1,s){if(this._pendingBBoxIdx!==t)return this;const i=ue(256*this.#Fs[0]/this.#Ns),n=ue(256*this.#Fs[1]/this.#Rs),r=pe(256*this.#Fs[2]/this.#Ns),a=pe(256*this.#Fs[3]/this.#Rs);if(ge(this.#Os,t,i,n,r,a),s)for(const o of s)for(const e of o)e!==t&&ge(this.#Os,e,i,n,r,a);return e||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(t){return this._pendingBBoxIdx===t&&(this._pendingBBoxIdx=-1,this.#Is[0]=Math.max(this.#Is[0],this.#Fs[0]),this.#Is[1]=Math.max(this.#Is[1],this.#Fs[1]),this.#Is[2]=Math.min(this.#Is[2],this.#Fs[2]),this.#Is[3]=Math.min(this.#Is[3],this.#Fs[3])),this}take(){return new fe(this.#Es,this.#Os)}takeDebugMetadata(){throw new Error("Unreachable")}recordSimpleData(t,e){return this}recordIncrementalData(t,e){return this}resetIncrementalData(t,e){return this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,s){return this}recordFutureForcedDependency(t,e){return this}inheritSimpleDataAsFutureForcedDependencies(t){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(t,e,s,i=1,n=0,r=0,a){return this}getSimpleIndex(t){}recordDependencies(t,e){return this}recordNamedDependency(t,e){return this}recordShowTextOperation(t,e=!1){return this}}class Ae{#Ls={__proto__:null};#Us={__proto__:null,transform:[],moveText:[],sameLineText:[],[de]:[]};#js=new Map;#Hs=new Set;#$s=new Map;#zs;#Gs;#Ws;constructor(t,e=!1){this.#Ws=t,e&&(this.#zs=new Map,this.#Gs=(t,e)=>{be(this.#zs,e).dependencies.add(t)})}get clipBox(){return this.#Ws.clipBox}growOperationsCount(t){this.#Ws.growOperationsCount(t)}save(t){return this.#Ls={__proto__:this.#Ls},this.#Us={__proto__:this.#Us,transform:{__proto__:this.#Us.transform},moveText:{__proto__:this.#Us.moveText},sameLineText:{__proto__:this.#Us.sameLineText},[de]:{__proto__:this.#Us[de]}},this.#Ws.save(t),this}restore(t){this.#Ws.restore(t,this.#Gs);const e=Object.getPrototypeOf(this.#Ls);return null===e||(this.#Ls=e,this.#Us=Object.getPrototypeOf(this.#Us)),this}recordOpenMarker(t){return this.#Ws.recordOpenMarker(t,this.#Gs),this}getOpenMarker(){return this.#Ws.getOpenMarker()}recordCloseMarker(t){return this.#Ws.recordCloseMarker(t,this.#Gs),this}beginMarkedContent(t){return this.#Ws.beginMarkedContent(t),this}endMarkedContent(t){return this.#Ws.endMarkedContent(t,this.#Gs),this}pushBaseTransform(t){return this.#Ws.pushBaseTransform(t),this}popBaseTransform(){return this.#Ws.popBaseTransform(),this}recordSimpleData(t,e){return this.#Ls[t]=e,this}recordIncrementalData(t,e){return this.#Us[t].push(e),this}resetIncrementalData(t,e){return this.#Us[t].length=0,this}recordNamedData(t,e){return this.#js.set(t,e),this}recordSimpleDataFromNamed(t,e,s){this.#Ls[t]=this.#js.get(e)??s}recordFutureForcedDependency(t,e){return this.recordIncrementalData(de,e),this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#Ls&&this.recordFutureForcedDependency(e,this.#Ls[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#Hs)this.recordFutureForcedDependency(de,t);return this}resetBBox(t){return this.#Ws.resetBBox(t),this}recordClipBox(t,e,s,i,n,r){return this.#Ws.recordClipBox(t,e,s,i,n,r),this}recordBBox(t,e,s,i,n,r){return this.#Ws.recordBBox(t,e,s,i,n,r),this}recordCharacterBBox(t,e,s,i=1,n=0,r=0,a){const o=s.bbox;let h,l;if(o&&(h=o[2]!==o[0]&&o[3]!==o[1]&&this.#$s.get(s),!1!==h&&(l=[0,0,0,0],pt.axialAlignedBoundingBox(o,s.fontMatrix,l),1===i&&0===n&&0===r||pt.scaleMinMax([i,0,0,-i,n,r],l),h)))return this.recordBBox(t,e,l[0],l[2],l[1],l[3]);if(!a)return this.recordFullPageBBox(t);const c=a();return o&&l&&void 0===h&&(h=l[0]<=n-c.actualBoundingBoxLeft&&l[2]>=n+c.actualBoundingBoxRight&&l[1]<=r-c.actualBoundingBoxAscent&&l[3]>=r+c.actualBoundingBoxDescent,this.#$s.set(s,h),h)?this.recordBBox(t,e,l[0],l[2],l[1],l[3]):this.recordBBox(t,e,n-c.actualBoundingBoxLeft,n+c.actualBoundingBoxRight,r-c.actualBoundingBoxAscent,r+c.actualBoundingBoxDescent)}recordFullPageBBox(t){return this.#Ws.recordFullPageBBox(t),this}getSimpleIndex(t){return this.#Ls[t]}recordDependencies(t,e){const s=this.#Hs,i=this.#Ls,n=this.#Us;for(const r of e)r in this.#Ls?s.add(i[r]):r in n&&n[r].forEach(s.add,s);return this}recordNamedDependency(t,e){return this.#js.has(e)&&this.#Hs.add(this.#js.get(e)),this}recordOperation(t,e=!1){if(this.recordDependencies(t,[de]),this.#zs){const e=be(this.#zs,t),{dependencies:s}=e;this.#Hs.forEach(s.add,s),this.#Ws._savesStack.forEach(s.add,s),this.#Ws._markedContentStack.forEach(s.add,s),s.delete(t),e.isRenderingOperation=!0}const s=!e&&t===this.#Ws._pendingBBoxIdx;return this.#Ws.recordOperation(t,e,[this.#Hs,this.#Ws._savesStack,this.#Ws._markedContentStack]),s&&this.#Hs.clear(),this}recordShowTextOperation(t,e=!1){const s=Array.from(this.#Hs);this.recordOperation(t,e),this.recordIncrementalData("sameLineText",t);for(const i of s)this.recordIncrementalData("sameLineText",i);return this}bboxToClipBoxDropOperation(t,e=!1){const s=!e&&t===this.#Ws._pendingBBoxIdx;return this.#Ws.bboxToClipBoxDropOperation(t),s&&this.#Hs.clear(),this}take(){return this.#$s.clear(),this.#Ws.take()}takeDebugMetadata(){return this.#zs}}class we{#Vs;#Xs;#Ys;#qs=0;#Ks=0;constructor(t,e,s){if(t instanceof we&&t.#Ys===!!s)return t;this.#Vs=t,this.#Xs=e,this.#Ys=!!s}get clipBox(){return this.#Vs.clipBox}growOperationsCount(){throw new Error("Unreachable")}save(t){return this.#Ks++,this.#Vs.save(this.#Xs),this}restore(t){return this.#Ks>0&&(this.#Vs.restore(this.#Xs),this.#Ks--),this}recordOpenMarker(t){return this.#qs++,this}getOpenMarker(){return this.#qs>0?this.#Xs:this.#Vs.getOpenMarker()}recordCloseMarker(t){return this.#qs--,this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){return this.#Vs.pushBaseTransform(t),this}popBaseTransform(){return this.#Vs.popBaseTransform(),this}recordSimpleData(t,e){return this.#Vs.recordSimpleData(t,this.#Xs),this}recordIncrementalData(t,e){return this.#Vs.recordIncrementalData(t,this.#Xs),this}resetIncrementalData(t,e){return this.#Vs.resetIncrementalData(t,this.#Xs),this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,s){return this.#Vs.recordSimpleDataFromNamed(t,e,this.#Xs),this}recordFutureForcedDependency(t,e){return this.#Vs.recordFutureForcedDependency(t,this.#Xs),this}inheritSimpleDataAsFutureForcedDependencies(t){return this.#Vs.inheritSimpleDataAsFutureForcedDependencies(t),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#Vs.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(t){return this.#Ys||this.#Vs.resetBBox(this.#Xs),this}recordClipBox(t,e,s,i,n,r){return this.#Ys||this.#Vs.recordClipBox(this.#Xs,e,s,i,n,r),this}recordBBox(t,e,s,i,n,r){return this.#Ys||this.#Vs.recordBBox(this.#Xs,e,s,i,n,r),this}recordCharacterBBox(t,e,s,i,n,r,a){return this.#Ys||this.#Vs.recordCharacterBBox(this.#Xs,e,s,i,n,r,a),this}recordFullPageBBox(t){return this.#Ys||this.#Vs.recordFullPageBBox(this.#Xs),this}getSimpleIndex(t){return this.#Vs.getSimpleIndex(t)}recordDependencies(t,e){return this.#Vs.recordDependencies(this.#Xs,e),this}recordNamedDependency(t,e){return this.#Vs.recordNamedDependency(this.#Xs,e),this}recordOperation(t){return this.#Vs.recordOperation(this.#Xs,!0),this}recordShowTextOperation(t){return this.#Vs.recordShowTextOperation(this.#Xs,!0),this}bboxToClipBoxDropOperation(t){return this.#Ys||this.#Vs.bboxToClipBoxDropOperation(this.#Xs,!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const ve=["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],_e=["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],xe=["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],Se=["filter","fillColor","fillAlpha"],Ce=["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],ke=["transform"],Te=["transform","fillColor"];class Me{#Ns;#Rs;#Qs=4;#Js=0;#Ps=new Me.#Zs(6*this.#Qs);static#Zs=ut.isFloat16ArraySupported?Float16Array:Float32Array;constructor(t){this.#Ns=t.width,this.#Rs=t.height}record(t,e,s,i){if(this.#Js===this.#Qs){this.#Qs*=2;const t=new Me.#Zs(6*this.#Qs);t.set(this.#Ps),this.#Ps=t}const n=pt.domMatrixToTransform(t.getTransform());let r;if(i[0]!==1/0){const t=u.slice();pt.axialAlignedBoundingBox([0,-s,e,0],n,t);const a=pt.intersect(i,t);if(!a)return;const[o,h,l,c]=a;if(o!==t[0]||h!==t[1]||l!==t[2]||c!==t[3]){const t=Math.atan2(n[1],n[0]),e=Math.abs(Math.sin(t)),s=Math.abs(Math.cos(t));if(e<1e-6||s<1e-6||Math.abs(e-s)<1e-6)r=[o,h,o,c,l,h];else{const t=l-o,i=c-h,n=e*e,a=s*s,d=s*e,u=a-n,p=(i*a-t*d)/u;r=[o+(i*d-t*n)/u,h,o,h+p,l,c-p]}}}r||(r=[0,-s,0,0,e,-s],pt.applyTransform(r,n,0),pt.applyTransform(r,n,2),pt.applyTransform(r,n,4)),r[0]/=this.#Ns,r[1]/=this.#Rs,r[2]/=this.#Ns,r[3]/=this.#Rs,r[4]/=this.#Ns,r[5]/=this.#Rs,this.#Ps.set(r,6*this.#Js),this.#Js++}take(){return this.#Ps.subarray(0,6*this.#Js)}}class Ee{#ti=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#ti.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:s}){if(t&&!this.#ti.has(t.loadedName)){if(tt(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:e,src:i,style:n}=t,r=new FontFace(e,i,n);this.addNativeFontFace(r);try{await r.load(),this.#ti.add(e),s?.(t)}catch{J(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}Z("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo)return void await this.loadSystemFont(t);if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(p){throw J(`Failed to load font '${e.family}': '${p}'.`),t.disableFontFace=!0,p}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(e=>{const s=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,s)})}}get isFontLoadingAPISupported(){return it(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return it(this,"isSyncFontLoadingSupported",d||ut.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:e}=this,s={done:!1,complete:function(){for(tt(!s.done,"completeRequest() cannot be called twice."),s.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(s),s}get _loadTestFont(){return it(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function s(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function i(t,e,s,i){return t.substring(0,e)+i+t.substring(e+s)}let n,r;const a=this._document.createElement("canvas");a.width=1,a.height=1;const o=a.getContext("2d");let h=0;const l=`lt${Date.now()}${this.loadTestFontId++}`;let c=this._loadTestFont;c=i(c,976,l.length,l);const d=1482184792;let u=s(c,16);for(n=0,r=l.length-3;n<r;n+=4)u=u-d+s(l,n)|0;n<l.length&&(u=u-d+s(l+"XXX",n)|0),c=i(c,16,4,function(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)}(u));const p=`@font-face {font-family:"${l}";src:url(data:font/opentype;base64,${btoa(c)});}`;this.insertRule(p);const g=this._document.createElement("div");g.style.visibility="hidden",g.style.width=g.style.height="10px",g.style.position="absolute",g.style.top=g.style.left="0px";for(const m of[t.loadedName,l]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=m,g.append(t)}this._document.body.append(g),function t(e,s){if(++h>30)return J("Load test font never loaded."),void s();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?s():setTimeout(t.bind(null,e,s))}(l,()=>{g.remove(),e.complete()})}}class Pe{compiledGlyphs=Object.create(null);#ei;constructor(t,e=null,s,i){this.#ei=t,this._inspectFont=e,s&&(this.charProcOperatorList=s),i&&Object.assign(this,i)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${this.data.toBase64()});`;let e;if(this.cssFontInfo){let s=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(s+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${s}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const s=this.loadedName+"_path_"+e;let i;try{i=t.get(s)}catch(t){J(`getPathGenerator - ignoring character: "${t}".`)}const n=$t(i?.path);return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}get black(){return this.#ei.black}get bold(){return this.#ei.bold}get disableFontFace(){return this.#ei.disableFontFace}set disableFontFace(t){it(this,"disableFontFace",!!t)}get fontExtraProperties(){return this.#ei.fontExtraProperties}get isInvalidPDFjsFont(){return this.#ei.isInvalidPDFjsFont}get isType3Font(){return this.#ei.isType3Font}get italic(){return this.#ei.italic}get missingFile(){return this.#ei.missingFile}get remeasure(){return this.#ei.remeasure}get vertical(){return this.#ei.vertical}get ascent(){return this.#ei.ascent}get defaultWidth(){return this.#ei.defaultWidth}get descent(){return this.#ei.descent}get bbox(){return this.#ei.bbox}get fontMatrix(){return this.#ei.fontMatrix}get fallbackName(){return this.#ei.fallbackName}get loadedName(){return this.#ei.loadedName}get mimetype(){return this.#ei.mimetype}get name(){return this.#ei.name}get data(){return this.#ei.data}clearData(){this.#ei.clearData()}get cssFontInfo(){return this.#ei.cssFontInfo}get systemFontInfo(){return this.#ei.systemFontInfo}get defaultVMetrics(){return this.#ei.defaultVMetrics}}class De{static strings=["fontFamily","fontWeight","italicAngle"]}class Ie{static strings=["css","loadedName","baseFontName","src"]}class Fe{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static OFFSET_NUMBERS=Math.ceil(2*this.bools.length/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+8*this.numbers.length;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6}class Ne{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16}class Re{#si;#ii=new TextDecoder;#ni;constructor(t){this.#si=t,this.#ni=new DataView(t)}#ri(t){tt(t<De.strings.length,"Invalid string index");let e=0;for(let i=0;i<t;i++)e+=this.#ni.getUint32(e)+4;const s=this.#ni.getUint32(e);return this.#ii.decode(new Uint8Array(this.#si,e+4,s))}get fontFamily(){return this.#ri(0)}get fontWeight(){return this.#ri(1)}get italicAngle(){return this.#ri(2)}}class Oe{#si;#ii=new TextDecoder;#ni;constructor(t){this.#si=t,this.#ni=new DataView(t)}get guessFallback(){return 0!==this.#ni.getUint8(0)}#ri(t){tt(t<Ie.strings.length,"Invalid string index");let e=5;for(let i=0;i<t;i++)e+=this.#ni.getUint32(e)+4;const s=this.#ni.getUint32(e);return this.#ii.decode(new Uint8Array(this.#si,e+4,s))}get css(){return this.#ri(0)}get loadedName(){return this.#ri(1)}get baseFontName(){return this.#ri(2)}get src(){return this.#ri(3)}get style(){let t=1;t+=4+this.#ni.getUint32(t);const e=this.#ni.getUint32(t),s=this.#ii.decode(new Uint8Array(this.#si,t+4,e));t+=4+e;const i=this.#ni.getUint32(t);return{style:s,weight:this.#ii.decode(new Uint8Array(this.#si,t+4,i))}}}class Be{#si;#ii=new TextDecoder;#ni;constructor({buffer:t,extra:e}){this.#si=t,this.#ni=new DataView(t),e&&Object.assign(this,e)}#ai(t){tt(t<Fe.bools.length,"Invalid boolean index");const e=Math.floor(t/4),s=2*t%8,i=this.#ni.getUint8(e)>>s&3;return 0===i?void 0:2===i}get black(){return this.#ai(0)}get bold(){return this.#ai(1)}get disableFontFace(){return this.#ai(2)}get fontExtraProperties(){return this.#ai(3)}get isInvalidPDFjsFont(){return this.#ai(4)}get isType3Font(){return this.#ai(5)}get italic(){return this.#ai(6)}get missingFile(){return this.#ai(7)}get remeasure(){return this.#ai(8)}get vertical(){return this.#ai(9)}#oi(t){return tt(t<Fe.numbers.length,"Invalid number index"),this.#ni.getFloat64(Fe.OFFSET_NUMBERS+8*t)}get ascent(){return this.#oi(0)}get defaultWidth(){return this.#oi(1)}get descent(){return this.#oi(2)}#hi(t,e,s,i){const n=this.#ni.getUint8(t);if(0===n)return;tt(n===e,"Invalid array length."),t+=1;const r=new Array(n);for(let a=0;a<n;a++)r[a]=this.#ni[s](t,!0),t+=i;return r}get bbox(){return this.#hi(Fe.OFFSET_BBOX,4,"getInt16",2)}get fontMatrix(){return this.#hi(Fe.OFFSET_FONT_MATRIX,6,"getFloat64",8)}get defaultVMetrics(){return this.#hi(Fe.OFFSET_DEFAULT_VMETRICS,3,"getInt16",2)}#ri(t){tt(t<Fe.strings.length,"Invalid string index");let e=Fe.OFFSET_STRINGS+4;for(let i=0;i<t;i++)e+=this.#ni.getUint32(e)+4;const s=this.#ni.getUint32(e);return this.#ii.decode(new Uint8Array(this.#si,e+4,s))}get fallbackName(){return this.#ri(0)}get loadedName(){return this.#ri(1)}get mimetype(){return this.#ri(2)}get name(){return this.#ri(3)}#li(){let t=Fe.OFFSET_STRINGS;return t+=4+this.#ni.getUint32(t),t+=4+this.#ni.getUint32(t),t+=4+this.#ni.getUint32(t),{offset:t,length:this.#ni.getUint32(t)}}get data(){const{offset:t,length:e}=this.#li();return 0===e?void 0:new Uint8Array(this.#si,t+4,e)}clearData(){const{offset:t,length:e}=this.#li();0!==e&&(this.#ni.setUint32(t,0),this.#si=new Uint8Array(this.#si,0,t+4).slice().buffer,this.#ni=new DataView(this.#si))}get cssFontInfo(){let t=Fe.OFFSET_STRINGS;t+=4+this.#ni.getUint32(t),t+=4+this.#ni.getUint32(t);const e=this.#ni.getUint32(t);if(0===e)return null;const s=new Uint8Array(e);return s.set(new Uint8Array(this.#si,t+4,e)),new Re(s.buffer)}get systemFontInfo(){let t=Fe.OFFSET_STRINGS;t+=4+this.#ni.getUint32(t);const e=this.#ni.getUint32(t);if(0===e)return null;const s=new Uint8Array(e);return s.set(new Uint8Array(this.#si,t+4,e)),new Oe(s.buffer)}}class Le{constructor(t){this.buffer=t,this.view=new DataView(t),this.data=new Uint8Array(t)}getIR(){const t=this.view,e=this.data[Ne.KIND],s=!!this.data[Ne.HAS_BBOX],i=!!this.data[Ne.HAS_BACKGROUND],n=t.getUint32(Ne.N_COORD,!0),r=t.getUint32(Ne.N_COLOR,!0),a=t.getUint32(Ne.N_STOP,!0);let o=20;const h=new Float32Array(this.buffer,o,2*n);o+=8*n;const l=new Uint8Array(this.buffer,o,4*r);o+=4*r;const c=[];for(let u=0;u<a;++u){const e=t.getFloat32(o,!0);o+=4;const s=t.getUint32(o,!0);o+=4,c.push([e,`#${s.toString(16).padStart(6,"0")}`])}let d=null;if(s){d=[];for(let e=0;e<4;++e)d.push(t.getFloat32(o,!0)),o+=4}let p=null;if(i&&(p=new Uint8Array(this.buffer,o,3),o+=3),1===e)return["RadialAxial","axial",d,c,Array.from(h.slice(0,2)),Array.from(h.slice(2,4)),null,null];if(2===e)return["RadialAxial","radial",d,c,[h[0],h[1]],[h[3],h[4]],h[2],h[5]];if(3===e){const t=this.data[Ne.SHADING_TYPE];let e=null;if(h.length>0){e=u.slice();for(let t=0,s=h.length;t<s;t+=2)pt.pointBoundingBox(h[t],h[t+1],e)}return["Mesh",t,h,l,n,e,d,p]}throw new Error(`Unsupported pattern kind: ${e}`)}}class Ue{#si;constructor(t){this.#si=t}get path(){return ut.isFloat16ArraySupported?new Float16Array(this.#si):new Float32Array(this.#si)}}function je(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const He=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0;(function(t,e,s){if(!Array.isArray(s)||s.length<2)return!1;const[i,n,...r]=s;if(!t(i)&&!Number.isInteger(i))return!1;if(!e(n))return!1;const a=r.length;let o=!0;switch(n.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return 0===a;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(4!==a)return!1;o=!1;break;default:return!1}for(const h of r)if(!("number"==typeof h||o&&null===h))return!1;return!0}).bind(null,He,t=>"object"==typeof t&&"string"==typeof t?.name);class $e{#ci=new Map;#di=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#di.then(()=>{for(const[t]of this.#ci)t.call(this,s)})}addEventListener(t,e,s=null){let i=null;if(s?.signal instanceof AbortSignal){const{signal:n}=s;if(n.aborted)return void J("LoopbackPort - cannot use an `aborted` signal.");const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}this.#ci.set(e,i)}removeEventListener(t,e){const s=this.#ci.get(e);s?.(),this.#ci.delete(e)}terminate(){for(const[,t]of this.#ci)t?.();this.#ci.clear()}}const ze=1,Ge=2,We=1,Ve=2,Xe=3,Ye=4,qe=5,Ke=6,Qe=7,Je=8;function Ze(){}function ts(t){if(t instanceof ct||t instanceof ot||t instanceof rt||t instanceof ht||t instanceof at)return t;switch(t instanceof Error||"object"==typeof t&&null!==t||Z('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new ct(t.message);case"InvalidPDFException":return new ot(t.message);case"PasswordException":return new rt(t.message,t.code);case"ResponseException":return new ht(t.message,t.status,t.missing);case"UnknownErrorException":return new at(t.message,t.details)}return new at(t.message,t.toString())}class es{#ui=new AbortController;constructor(t,e,s){this.sourceName=t,this.targetName=e,this.comObj=s,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),s.addEventListener("message",this.#pi.bind(this),{signal:this.#ui.signal})}#pi({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream)return void this.#gi(t);if(t.callback){const e=t.callbackId,s=this.callbackCapabilities[e];if(!s)throw new Error(`Cannot resolve callback ${e}`);if(delete this.callbackCapabilities[e],t.callback===ze)s.resolve(t.data);else{if(t.callback!==Ge)throw new Error("Unexpected callback case");s.reject(ts(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;return void Promise.try(e,t.data).then(function(e){n.postMessage({sourceName:s,targetName:i,callback:ze,callbackId:t.callbackId,data:e})},function(e){n.postMessage({sourceName:s,targetName:i,callback:Ge,callbackId:t.callbackId,reason:ts(e)})})}t.streamId?this.#mi(t):e(t.data)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,r=this.sourceName,a=this.targetName,o=this.comObj;return new ReadableStream({start:s=>{const h=Promise.withResolvers();return this.streamControllers[n]={controller:s,startCall:h,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:r,targetName:a,action:t,streamId:n,data:e,desiredSize:s.desiredSize},i),h.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[n].pullCall=e,o.postMessage({sourceName:r,targetName:a,stream:Ke,streamId:n,desiredSize:t.desiredSize}),e.promise},cancel:t=>{tt(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[n].cancelCall=e,this.streamControllers[n].isClosed=!0,o.postMessage({sourceName:r,targetName:a,stream:We,streamId:n,reason:ts(t)}),e.promise}},s)}#mi(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,a=this.actionHandler[t.action],o={enqueue(t,r=1,a){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=r,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:Ye,streamId:e,chunk:t},a)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Xe,streamId:e}),delete r.streamSinks[e])},error(t){tt(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:qe,streamId:e,reason:ts(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,Promise.try(a,t.data,o).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Je,streamId:e,success:!0})},function(t){n.postMessage({sourceName:s,targetName:i,stream:Je,streamId:e,reason:ts(t)})})}#gi(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case Je:t.success?r.startCall.resolve():r.startCall.reject(ts(t.reason));break;case Qe:t.success?r.pullCall.resolve():r.pullCall.reject(ts(t.reason));break;case Ke:if(!a){n.postMessage({sourceName:s,targetName:i,stream:Qe,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve(),a.desiredSize=t.desiredSize,Promise.try(a.onPull||Ze).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Qe,streamId:e,success:!0})},function(t){n.postMessage({sourceName:s,targetName:i,stream:Qe,streamId:e,reason:ts(t)})});break;case Ye:if(tt(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case Xe:if(tt(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#fi(r,e);break;case qe:tt(r,"error should have stream controller"),r.controller.error(ts(t.reason)),this.#fi(r,e);break;case Ve:t.success?r.cancelCall.resolve():r.cancelCall.reject(ts(t.reason)),this.#fi(r,e);break;case We:if(!a)break;const o=ts(t.reason);Promise.try(a.onCancel||Ze,o).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ve,streamId:e,success:!0})},function(t){n.postMessage({sourceName:s,targetName:i,stream:Ve,streamId:e,reason:ts(t)})}),a.sinkCapability.reject(o),a.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#fi(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#ui?.abort(),this.#ui=null}}class ss{#bi=Object.freeze({cMapUrl:"CMap",standardFontDataUrl:"font",wasmUrl:"wasm"});constructor({cMapUrl:t=null,standardFontDataUrl:e=null,wasmUrl:s=null}){this.cMapUrl=t,this.standardFontDataUrl=e,this.wasmUrl=s}async fetch({kind:t,filename:e}){switch(t){case"cMapUrl":case"standardFontDataUrl":case"wasmUrl":break;default:Z(`Not implemented: ${t}`)}const s=this[t];if(!s)throw new Error(`Ensure that the \`${t}\` API parameter is provided.`);const i=`${s}${e}`;return this._fetch(i,t).catch(e=>{throw new Error(`Unable to load ${this.#bi[t]} data at: ${i}`)})}async _fetch(t,e){Z("Abstract method `_fetch` called.")}}class is extends ss{async _fetch(t,e){const s="cMapUrl"!==e||t.endsWith(".bcmap")?"bytes":"text",i=await xt(t,s);return i instanceof Uint8Array?i:dt(i)}}class ns{#yi=!1;constructor({enableHWA:t=!1}){this.#yi=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!this.#yi})}}reset({canvas:t},e,s){if(!t)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.width=e,t.height=s}destroy(t){const{canvas:e}=t;if(!e)throw new Error("Canvas is not specified");e.width=e.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){Z("Abstract method `_createCanvas` called.")}}class rs extends ns{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}}class as{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addKnockoutFilter(t=0){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class os extends as{#Ai;#wi;#vi;#_i;#xi;#Si;#k=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#_i=t,this.#xi=e}get#M(){return this.#wi||=new Map}get#Ci(){return this.#Si||=new Map}get#ki(){if(!this.#vi){const t=this.#xi.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const s=this.#xi.createElementNS(vt,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#vi=this.#xi.createElementNS(vt,"defs"),t.append(s),s.append(this.#vi),this.#xi.body.append(t)}return this.#vi}#Ti(t){if(1===t.length){const e=t[0],s=new Array(256);for(let t=0;t<256;t++)s[t]=e[t]/255;const i=s.join(",");return[i,i,i]}const[e,s,i]=t,n=new Array(256),r=new Array(256),a=new Array(256);for(let o=0;o<256;o++)n[o]=e[o]/255,r[o]=s[o]/255,a[o]=i[o]/255;return[n.join(","),r.join(","),a.join(",")]}#Mi(t){if(void 0===this.#Ai){this.#Ai="";const t=this.#xi.URL;t!==this.#xi.baseURI&&(kt(t)?J('#createUrl: ignore "data:"-URL for performance reasons.'):this.#Ai=st(t,""))}return`url(${this.#Ai}#${t})`}addFilter(t){if(!t)return"none";let e=this.#M.get(t);if(e)return e;const[s,i,n]=this.#Ti(t),r=1===t.length?s:`${s}${i}${n}`;if(e=this.#M.get(r),e)return this.#M.set(t,e),e;const a=`g_${this.#_i}_transfer_map_${this.#k++}`,o=this.#Mi(a);this.#M.set(t,o),this.#M.set(r,o);const h=this.#Ei(a);return this.#Pi(s,i,n,h),o}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#Ci.get(i);if(n?.key===s)return n.url;if(n?(n.filter?.remove(),n.key=s,n.url="none",n.filter=null):(n={key:s,url:"none",filter:null},this.#Ci.set(i,n)),!t||!e)return n.url;const r=this.#Di(t);t=pt.makeHexColor(...r);const a=this.#Di(e);if(e=pt.makeHexColor(...a),this.#ki.style.color="","#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let u=0;u<=255;u++){const t=u/255;o[u]=t<=.03928?t/12.92:((t+.055)/1.055)**2.4}const h=o.join(","),l=`g_${this.#_i}_hcm_filter`,c=n.filter=this.#Ei(l);this.#Pi(h,h,h,c),this.#Ii(c);const d=(t,e)=>{const s=r[t]/255,i=a[t]/255,n=new Array(e+1);for(let r=0;r<=e;r++)n[r]=s+r/e*(i-s);return n.join(",")};return this.#Pi(d(0,5),d(1,5),d(2,5),c),n.url=this.#Mi(l),n.url}addAlphaFilter(t){let e=this.#M.get(t);if(e)return e;const[s]=this.#Ti([t]),i=`alpha_${s}`;if(e=this.#M.get(i),e)return this.#M.set(t,e),e;const n=`g_${this.#_i}_alpha_map_${this.#k++}`,r=this.#Mi(n);this.#M.set(t,r),this.#M.set(i,r);const a=this.#Ei(n);return this.#Fi(s,a),r}addLuminosityFilter(t){let e,s,i=this.#M.get(t||"luminosity");if(i)return i;if(t?([e]=this.#Ti([t]),s=`luminosity_${e}`):s="luminosity",i=this.#M.get(s),i)return this.#M.set(t,i),i;const n=`g_${this.#_i}_luminosity_map_${this.#k++}`,r=this.#Mi(n);this.#M.set(t,r),this.#M.set(s,r);const a=this.#Ei(n);return this.#Ni(a),t&&this.#Fi(e,a),r}addKnockoutFilter(t=0){const e=t>0?Math.min(1/t,1e6):1e6,s=`knockout_${e}`,i=this.#M.get(s);if(i)return i;const n=`g_${this.#_i}_knockout_filter_${this.#k++}`,r=this.#Mi(n);this.#M.set(s,r);const a=this.#Ei(n),o=this.#xi.createElementNS(vt,"feComponentTransfer");a.append(o);const h=this.#xi.createElementNS(vt,"feFuncA");return h.setAttribute("type","linear"),h.setAttribute("slope",`${e}`),h.setAttribute("intercept","0"),o.append(h),r}addHighlightHCMFilter(t,e,s,i,n){const r=`${e}-${s}-${i}-${n}`;let a=this.#Ci.get(t);if(a?.key===r)return a.url;if(a?(a.filter?.remove(),a.key=r,a.url="none",a.filter=null):(a={key:r,url:"none",filter:null},this.#Ci.set(t,a)),!e||!s)return a.url;const[o,h]=[e,s].map(this.#Di.bind(this));let l=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),c=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),[d,u]=[i,n].map(this.#Di.bind(this));c<l&&([l,c,d,u]=[c,l,u,d]),this.#ki.style.color="";const p=(t,e,s)=>{const i=new Array(256),n=(c-l)/s,r=t/255,a=(e-t)/(255*s);let o=0;for(let h=0;h<=s;h++){const t=Math.round(l+h*n),e=r+h*a;for(let s=o;s<=t;s++)i[s]=e;o=t+1}for(let h=o;h<256;h++)i[h]=i[o-1];return i.join(",")},g=`g_${this.#_i}_hcm_${t}_filter`,m=a.filter=this.#Ei(g);return this.#Ii(m),this.#Pi(p(d[0],u[0],5),p(d[1],u[1],5),p(d[2],u[2],5),m),a.url=this.#Mi(g),a.url}destroy(t=!1){t&&this.#Si?.size||(this.#vi?.parentNode.parentNode.remove(),this.#vi=null,this.#wi?.clear(),this.#wi=null,this.#Si?.clear(),this.#Si=null,this.#k=0)}#Ni(t){const e=this.#xi.createElementNS(vt,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#Ii(t){const e=this.#xi.createElementNS(vt,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#Ei(t){const e=this.#xi.createElementNS(vt,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#ki.append(e),e}#Ri(t,e,s){const i=this.#xi.createElementNS(vt,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#Pi(t,e,s,i){const n=this.#xi.createElementNS(vt,"feComponentTransfer");i.append(n),this.#Ri(n,"feFuncR",t),this.#Ri(n,"feFuncG",e),this.#Ri(n,"feFuncB",s)}#Fi(t,e){const s=this.#xi.createElementNS(vt,"feComponentTransfer");e.append(s),this.#Ri(s,"feFuncA",t)}#Di(t){return this.#ki.style.color=t,Nt(getComputedStyle(this.#ki).getPropertyValue("color"))}}d&&J("Please use the `legacy` build in Node.js environments.");class hs extends as{}class ls extends ns{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}class cs extends ss{async _fetch(t,e){return async function(t){const e=process.getBuiltinModule("fs/promises"),s=await e.readFile(t);return new Uint8Array(s)}(t)}}const ds=new class{#Oi=null;#Bi=null;#Li=null;#Ui=null;async#ji(){if(!globalThis.navigator?.gpu)return!1;try{const t=await navigator.gpu.requestAdapter();return!!t&&(this.#Ui=navigator.gpu.getPreferredCanvasFormat(),this.#Bi=await t.requestDevice(),!0)}catch{return!1}}init(){return this.#Oi||=this.#ji()}get isReady(){return null!==this.#Bi}loadMeshShader(){if(!this.#Bi||this.#Li)return;const t=this.#Bi.createShaderModule({code:"\nstruct Uniforms {\n offsetX : f32,\n offsetY : f32,\n scaleX : f32,\n scaleY : f32,\n paddedWidth : f32,\n paddedHeight : f32,\n borderSize : f32,\n _pad : f32,\n};\n\n@group(0) @binding(0) var<uniform> u : Uniforms;\n\nstruct VertexInput {\n @location(0) position : vec2<f32>,\n @location(1) color : vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position : vec4<f32>,\n @location(0) color : vec3<f32>,\n};\n\n@vertex\nfn vs_main(in : VertexInput) -> VertexOutput {\n var out : VertexOutput;\n let cx = (in.position.x + u.offsetX) * u.scaleX;\n let cy = (in.position.y + u.offsetY) * u.scaleY;\n out.position = vec4<f32>(\n ((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0,\n 1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0,\n 0.0,\n 1.0\n );\n out.color = in.color.rgb;\n return out;\n}\n\n@fragment\nfn fs_main(in : VertexOutput) -> @location(0) vec4<f32> {\n return vec4<f32>(in.color, 1.0);\n}\n"});this.#Li=this.#Bi.createRenderPipeline({layout:"auto",vertex:{module:t,entryPoint:"vs_main",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"unorm8x4"}]}]},fragment:{module:t,entryPoint:"fs_main",targets:[{format:this.#Ui}]},primitive:{topology:"triangle-list"}})}draw(t,e,s,i,n,r,a,o){this.loadMeshShader();const h=this.#Bi,{offsetX:l,offsetY:c,scaleX:d,scaleY:u}=i,p=h.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&h.queue.writeBuffer(p,0,t);const g=h.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&h.queue.writeBuffer(g,0,e);const m=h.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});h.queue.writeBuffer(m,0,new Float32Array([l,c,d,u,r,a,o,0]));const f=h.createBindGroup({layout:this.#Li.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:m}}]}),b=new OffscreenCanvas(r,a),y=b.getContext("webgpu");y.configure({device:h,format:this.#Ui,alphaMode:n?"opaque":"premultiplied"});const A=n?{r:n[0]/255,g:n[1]/255,b:n[2]/255,a:1}:{r:0,g:0,b:0,a:0},w=h.createCommandEncoder(),v=w.beginRenderPass({colorAttachments:[{view:y.getCurrentTexture().createView(),clearValue:A,loadOp:"clear",storeOp:"store"}]});return s>0&&(v.setPipeline(this.#Li),v.setBindGroup(0,f),v.setVertexBuffer(0,p),v.setVertexBuffer(1,g),v.draw(s)),v.end(),h.queue.submit([w.finish()]),p.destroy(),g.destroy(),m.destroy(),b.transferToImageBitmap()}},us="Fill",ps="Stroke",gs="Shading";function ms(t,e){if(!e)return;const s=e[2]-e[0],i=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],s,i),t.clip(n)}class fs{isModifyingCurrentTransform(){return!1}getPattern(){Z("Abstract method `getPattern` called.")}}class bs extends fs{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}isOriginBased(){return 0===this._p0[0]&&0===this._p0[1]&&(!this.isRadial()||0===this._p1[0]&&0===this._p1[1])}isRadial(){return"radial"===this._type}areConic(){if(!this.isRadial())return!1;const t=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return t+this._r1>this._r0&&t+this._r0>this._r1}_createGradient(t,e=null){let s,i=this._p0,n=this._p1;if(e&&(i=i.slice(),n=n.slice(),pt.applyTransform(i,e),pt.applyTransform(n,e)),"axial"===this._type)s=t.createLinearGradient(i[0],i[1],n[0],n[1]);else if("radial"===this._type){let r=this._r0,a=this._r1;if(e){const t=new Float32Array(2);pt.singularValueDecompose2dScale(e,t),r*=t[0],a*=t[0]}s=t.createRadialGradient(i[0],i[1],r,n[0],n[1],a)}for(const r of this._colorStops)s.addColorStop(r[0],r[1]);return s}_createReversedGradient(t,e=null){let s=this._p1,i=this._p0;e&&(s=s.slice(),i=i.slice(),pt.applyTransform(s,e),pt.applyTransform(i,e));let n=this._r1,r=this._r0;if(e){const t=new Float32Array(2);pt.singularValueDecompose2dScale(e,t),n*=t[0],r*=t[0]}const a=t.createRadialGradient(s[0],s[1],n,i[0],i[1],r),o=this._colorStops.map(([t,e])=>[1-t,e]).reverse();for(const[h,l]of o)a.addColorStop(h,l);return a}getPattern(t,e,s,i){let n;if(i===ps||i===us){if(this.isOriginBased()){let i=pt.transform(s,e.baseTransform);this.matrix&&(i=pt.transform(i,this.matrix));const n=.001,r=Math.hypot(i[0],i[1]),a=Math.hypot(i[2],i[3]),o=(i[0]*i[2]+i[1]*i[3])/(r*a);if(Math.abs(o)<n){if(!this.isRadial())return this._createGradient(t,i);if(Math.abs(r-a)<n)return this._createGradient(t,i)}}const r=e.current.getClippedPathBoundingBox(i,Rt(t))||[0,0,0,0],a=Math.ceil(r[2]-r[0])||1,o=Math.ceil(r[3]-r[1])||1,h=e.canvasFactory.create(a,o),l=h.context;l.clearRect(0,0,l.canvas.width,l.canvas.height),l.beginPath(),l.rect(0,0,l.canvas.width,l.canvas.height),l.translate(-r[0],-r[1]),s=pt.transform(s,[1,0,0,1,r[0],r[1]]),l.transform(...e.baseTransform),this.matrix&&l.transform(...this.matrix),ms(l,this._bbox),this.areConic()&&(l.fillStyle=this._createReversedGradient(l),l.fill()),l.fillStyle=this._createGradient(l),l.fill(),n=t.createPattern(h.canvas,"no-repeat"),e.canvasFactory.destroy(h);const c=new DOMMatrix(s);n.setTransform(c)}else this.areConic()&&(t.save(),ms(t,this._bbox),t.fillStyle=this._createReversedGradient(t),t.fillRect(-1e10,-1e10,2e10,2e10),t.restore()),ms(t,this._bbox),n=this._createGradient(t);return n}}function ys(t,e,s,i,n,r,a,o){const h=e.coords,l=e.colors,c=t.data,d=4*t.width;let u;h[2*s+1]>h[2*i+1]&&(u=s,s=i,i=u,u=r,r=a,a=u),h[2*i+1]>h[2*n+1]&&(u=i,i=n,n=u,u=a,a=o,o=u),h[2*s+1]>h[2*i+1]&&(u=s,s=i,i=u,u=r,r=a,a=u);const p=(h[2*s]+e.offsetX)*e.scaleX,g=(h[2*s+1]+e.offsetY)*e.scaleY,m=(h[2*i]+e.offsetX)*e.scaleX,f=(h[2*i+1]+e.offsetY)*e.scaleY,b=(h[2*n]+e.offsetX)*e.scaleX,y=(h[2*n+1]+e.offsetY)*e.scaleY;if(g>=y)return;const A=l[4*r],w=l[4*r+1],v=l[4*r+2],_=l[4*a],x=l[4*a+1],S=l[4*a+2],C=l[4*o],k=l[4*o+1],T=l[4*o+2],M=Math.round(g),E=Math.round(y);let P,D,I,F,N,R,O,B;for(let L=M;L<=E;L++){if(L<f){const t=L<g?0:(g-L)/(g-f);P=p-(p-m)*t,D=A-(A-_)*t,I=w-(w-x)*t,F=v-(v-S)*t}else{let t;t=L>y?1:f===y?0:(f-L)/(f-y),P=m-(m-b)*t,D=_-(_-C)*t,I=x-(x-k)*t,F=S-(S-T)*t}let t;t=L<g?0:L>y?1:(g-L)/(g-y),N=p-(p-b)*t,R=A-(A-C)*t,O=w-(w-k)*t,B=v-(v-T)*t;const e=Math.round(Math.min(P,N)),s=Math.round(Math.max(P,N));let i=d*L+4*e;for(let n=e;n<=s;n++)t=(P-n)/(P-N),t<0?t=0:t>1&&(t=1),c[i++]=D-(D-R)*t|0,c[i++]=I-(I-O)*t|0,c[i++]=F-(F-B)*t|0,c[i++]=255}}class As extends fs{constructor(t){super(),this._posData=t[2],this._colData=t[3],this._vertexCount=t[4],this._bounds=t[5],this._bbox=t[6],this._background=t[7],this.matrix=null,ds.loadMeshShader()}_createMeshCanvas(t,e,s){const i=Math.floor(this._bounds[0]),n=Math.floor(this._bounds[1]),r=Math.ceil(this._bounds[2])-i,a=Math.ceil(this._bounds[3])-n,o=Math.min(Math.ceil(Math.abs(r*t[0]*1.1)),3e3)||1,h=Math.min(Math.ceil(Math.abs(a*t[1]*1.1)),3e3)||1,l=r?r/o:1,c=a?a/h:1,d={coords:this._posData,colors:this._colData,offsetX:-i,offsetY:-n,scaleX:1/l,scaleY:1/c},u=o+4,p=h+4,g=s.create(u,p);if(ds.isReady&&this._vertexCount>48)g.context.drawImage(function(t,e,s,i,n,r,a,o){return ds.draw(t,e,s,i,n,r,a,o)}(this._posData,this._colData,this._vertexCount,d,e,u,p,2),0,0);else{const t=g.context.createImageData(o,h);if(e){const s=t.data;for(let t=0,i=s.length;t<i;t+=4)s[t]=e[0],s[t+1]=e[1],s[t+2]=e[2],s[t+3]=255}for(let e=0,s=this._vertexCount;e<s;e+=3)ys(t,d,e,e+1,e+2,e,e+1,e+2);g.context.putImageData(t,2,2)}return{canvas:g.canvas,offsetX:i-2*l,offsetY:n-2*c,scaleX:l,scaleY:c}}isModifyingCurrentTransform(){return!0}getPattern(t,e,s,i){ms(t,this._bbox);const n=new Float32Array(2);if(i===gs)pt.singularValueDecompose2dScale(Rt(t),n);else if(this.matrix){pt.singularValueDecompose2dScale(this.matrix,n);const[t,s]=n;pt.singularValueDecompose2dScale(e.baseTransform,n),n[0]*=t,n[1]*=s}else pt.singularValueDecompose2dScale(e.baseTransform,n);const r=this._createMeshCanvas(n,i===gs?null:this._background,e.canvasFactory);i!==gs&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY);const a=t.createPattern(r.canvas,"no-repeat");return e.canvasFactory.destroy(r),a}}class ws extends fs{getPattern(){return"hotpink"}}const vs=1,_s=2;class xs{static MAX_PATTERN_SIZE=3e3;constructor(t,e,s,i){this.color=t[1],this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.needsIsolation=t[9]??!0,this.ctx=e,this.canvasGraphicsFactory=s,this.baseTransform=i,this.patternBaseMatrix=this.matrix?pt.transform(i,this.matrix):i}canSkipPatternCanvas([t,e,s,i]){const[n,r,a,o]=this.bbox,h=Math.abs(this.xstep),l=Math.abs(this.ystep);if(t>h+1e-6||e>l+1e-6)return null;const c=Math.floor((s-a)/h)+1,d=Math.ceil((s+t-n)/h)-1,u=Math.floor((i-o)/l)+1,p=Math.ceil((i+e-r)/l)-1;return d<=c&&p<=u?[c,u]:null}updatePatternDims(t,e){const s=pt.inverseTransform(this.patternBaseMatrix),i=[t[0],t[1]],n=[t[2],t[3]];pt.applyTransform(i,s),pt.applyTransform(n,s),e[0]=Math.abs(n[0]-i[0]),e[1]=Math.abs(n[1]-i[1]),e[2]=Math.min(i[0],n[0]),e[3]=Math.min(i[1],n[1])}_renderTileCanvas(t,e,s,i){const[n,r,a,o]=this.bbox,h=t.canvasFactory.create(s.size,i.size),l=h.context,c=this.canvasGraphicsFactory.createCanvasGraphics(l,e);return c.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(c,this.paintType,this.color),l.translate(-s.scale*n,-i.scale*r),c.transform(0,s.scale,0,0,i.scale,0,0),l.save(),c.dependencyTracker?.save(),this.clipBbox(c,n,r,a,o),c.baseTransform=Rt(c.ctx),c.executeOperatorList(this.operatorList),c.endDrawing(),c.dependencyTracker?.restore(),l.restore(),h}_getCombinedScales(){const t=new Float32Array(2);pt.singularValueDecompose2dScale(this.matrix,t);const[e,s]=t;return pt.singularValueDecompose2dScale(this.baseTransform,t),[e*t[0],s*t[1]]}drawPattern(t,e,s=!1,[i,n],r){const[a,o,h,l]=this.bbox,c=t.dependencyTracker;if(c&&(t.dependencyTracker=new we(c,r)),t.save(),s?t.ctx.clip(e,"evenodd"):t.ctx.clip(e),t.ctx.setTransform(...this.patternBaseMatrix),t.ctx.translate(i*this.xstep,n*this.ystep),this.needsIsolation||1!==t.ctx.globalAlpha||"source-over"!==t.ctx.globalCompositeOperation||t.inSMaskMode){const e=h-a,s=l-o,[i,n]=this._getCombinedScales(),c=this.getSizeAndScale(e,this.ctx.canvas.width,i),d=this.getSizeAndScale(s,this.ctx.canvas.height,n),u=this._renderTileCanvas(t,r,c,d);t.ctx.drawImage(u.canvas,a,o,e,s),t.canvasFactory.destroy(u)}else this.setFillAndStrokeStyleToContext(t,this.paintType,this.color),this.clipBbox(t,a,o,h,l),t.baseTransformStack.push(t.baseTransform),t.baseTransform=Rt(t.ctx),t.executeOperatorList(this.operatorList),t.baseTransform=t.baseTransformStack.pop();t.restore(),c&&(t.dependencyTracker=c)}createPatternCanvas(t,e){const[s,i,n,r]=this.bbox,a=n-s,o=r-i;let{xstep:h,ystep:l}=this;h=Math.abs(h),l=Math.abs(l),Q("TilingType: "+this.tilingType);const[c,d]=this._getCombinedScales();let u=a,p=o,g=!1,m=!1;Math.ceil(h*c)>=Math.ceil(a*c)?u=h:g=!0,Math.ceil(l*d)>=Math.ceil(o*d)?p=l:m=!0;const f=this.getSizeAndScale(u,this.ctx.canvas.width,c),b=this.getSizeAndScale(p,this.ctx.canvas.height,d),y=this._renderTileCanvas(t,e,f,b);if(g||m){const e=y.canvas;g&&(u=h),m&&(p=l);const n=this.getSizeAndScale(u,this.ctx.canvas.width,c),r=this.getSizeAndScale(p,this.ctx.canvas.height,d),f=n.size,b=r.size,A=t.canvasFactory.create(f,b),w=A.context,v=g?Math.floor(a/h):0,_=m?Math.floor(o/l):0;for(let t=0;t<=v;t++)for(let s=0;s<=_;s++)w.drawImage(e,f*t,b*s,f,b,0,0,f,b);return t.canvasFactory.destroy(y),{canvas:A.canvas,canvasEntry:A,scaleX:n.scale,scaleY:r.scale,offsetX:s,offsetY:i}}return{canvas:y.canvas,canvasEntry:y,scaleX:f.scale,scaleY:b.scale,offsetX:s,offsetY:i}}getSizeAndScale(t,e,s){const i=Math.max(xs.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const r=i-e,a=n-s,o=new Path2D;o.rect(e,s,r,a),pt.axialAlignedBoundingBox([e,s,i,n],Rt(t.ctx),t.current.minMax),t.ctx.clip(o),t.current.updateClipFromPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(n.patternFill=n.patternStroke=!1,e){case vs:const{fillStyle:t,strokeStyle:r}=this.ctx;i.fillStyle=n.fillColor=t,i.strokeStyle=n.strokeColor=r;break;case _s:i.fillStyle=i.strokeStyle=s,n.fillColor=n.strokeColor=s;break;default:throw new lt(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,s,i,n){const r=i!==gs?pt.transform(s,this.patternBaseMatrix):s,a=this.createPatternCanvas(e,n);let o=new DOMMatrix(r);o=o.translate(a.offsetX,a.offsetY),o=o.scale(1/a.scaleX,1/a.scaleY);const h=t.createPattern(a.canvas,"repeat");return e.canvasFactory.destroy(a.canvasEntry),h.setTransform(o),h}}function Ss({src:t,srcPos:e=0,dest:s,width:i,height:n,nonBlackColor:r=4294967295,inverseDecode:a=!1}){const o=ut.isLittleEndian?4278190080:255,[h,l]=a?[r,o]:[o,r],c=i>>3,d=7&i,u=h^l,p=t.length;s=new Uint32Array(s.buffer);let g=0;for(let m=0;m<n;++m){for(const n=e+c;e<n;++e,g+=8){const i=t[e];s[g]=h^-(i>>7&1)&u,s[g+1]=h^-(i>>6&1)&u,s[g+2]=h^-(i>>5&1)&u,s[g+3]=h^-(i>>4&1)&u,s[g+4]=h^-(i>>3&1)&u,s[g+5]=h^-(i>>2&1)&u,s[g+6]=h^-(i>>1&1)&u,s[g+7]=h^-(1&i)&u}if(0===d)continue;const i=e<p?t[e++]:255;for(let t=0;t<d;++t,++g)s[g]=h^-(i>>7-t&1)&u}return{srcPos:e,destPos:g}}const Cs=16,ks=new DOMMatrix,Ts=new Float32Array(2);function Ms(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");const s=new Map;for(const i of["save","restore","rotate","scale","translate","transform","setTransform","resetTransform","clip","moveTo","lineTo","bezierCurveTo","quadraticCurveTo","arc","arcTo","ellipse","rect","roundRect","closePath","beginPath"]){const n=t[i];"function"==typeof n&&"function"==typeof e[i]&&(s.set(i,n),t[i]=function(...t){return e[i](...t),n.apply(this,t)})}t._removeMirroring=()=>{for(const[e,i]of s)t[e]=i;delete t._removeMirroring}}function Es(t,e,s,i,n,r,a,o,h,l){const[c,d,u,p,g,m]=Rt(t);if(0===d&&0===u){const f=a*c+g,b=Math.round(f),y=o*p+m,A=Math.round(y),w=(a+h)*c+g,v=Math.abs(Math.round(w)-b)||1,_=(o+l)*p+m,x=Math.abs(Math.round(_)-A)||1;return t.setTransform(Math.sign(c),0,0,Math.sign(p),b,A),t.drawImage(e,s,i,n,r,0,0,v,x),t.setTransform(c,d,u,p,g,m),[v,x]}if(0===c&&0===p){const f=o*u+g,b=Math.round(f),y=a*d+m,A=Math.round(y),w=(o+l)*u+g,v=Math.abs(Math.round(w)-b)||1,_=(a+h)*d+m,x=Math.abs(Math.round(_)-A)||1;return t.setTransform(0,Math.sign(d),Math.sign(u),0,b,A),t.drawImage(e,s,i,n,r,0,0,x,v),t.setTransform(c,d,u,p,g,m),[x,v]}return t.drawImage(e,s,i,n,r,a,o,h,l),[Math.hypot(c,d)*h,Math.hypot(u,p)*l]}class Ps{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=g;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=E;textRise=0;fillColor="#000000";strokeColor="#000000";tilingPatternDims=null;patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";minMax=p.slice();constructor(t,e){this.clipBox=new Float32Array([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t.minMax=this.minMax.slice(),t.tilingPatternDims=this.tilingPatternDims?.slice(),t}getPathBoundingBox(t=us,e=null){const s=this.minMax.slice();if(t===ps){e||Z("Stroke bounding box must include transform."),pt.singularValueDecompose2dScale(e,Ts);const t=Ts[0]*this.lineWidth/2,i=Ts[1]*this.lineWidth/2;s[0]-=t,s[1]-=i,s[2]+=t,s[3]+=i}return s}updateClipFromPath(){const t=pt.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0),this.minMax.set(p,0)}getClippedPathBoundingBox(t=us,e=null){return pt.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function Ds(t,e){if(e instanceof ImageData)return void t.putImageData(e,0,0);const s=e.height,i=e.width,n=s%Cs,r=(s-n)/Cs,a=0===n?r:r+1,o=t.createImageData(i,Cs);let h,l=0;const c=e.data,d=o.data;let u,p,g,m;if(e.kind===R.GRAYSCALE_1BPP){const e=c.byteLength,s=new Uint32Array(d.buffer,0,d.byteLength>>2),m=s.length,f=i+7>>3,b=4294967295,y=ut.isLittleEndian?4278190080:255;for(u=0;u<a;u++){for(g=u<r?Cs:n,h=0,p=0;p<g;p++){const t=e-l;let n=0;const r=t>f?i:8*t-7,a=-8&r;let o=0,d=0;for(;n<a;n+=8)d=c[l++],s[h++]=128&d?b:y,s[h++]=64&d?b:y,s[h++]=32&d?b:y,s[h++]=16&d?b:y,s[h++]=8&d?b:y,s[h++]=4&d?b:y,s[h++]=2&d?b:y,s[h++]=1&d?b:y;for(;n<r;n++)0===o&&(d=c[l++],o=128),s[h++]=d&o?b:y,o>>=1}for(;h<m;)s[h++]=0;t.putImageData(o,0,u*Cs)}}else if(e.kind===R.RGBA_32BPP){for(p=0,m=i*Cs*4,u=0;u<r;u++)d.set(c.subarray(l,l+m)),l+=m,t.putImageData(o,0,p),p+=Cs;u<a&&(m=i*n*4,d.set(c.subarray(l,l+m)),t.putImageData(o,0,p))}else{if(e.kind!==R.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);for(g=Cs,m=i*g,u=0;u<a;u++){for(u>=r&&(g=n,m=i*g),h=0,p=m;p--;)d[h++]=c[l++],d[h++]=c[l++],d[h++]=c[l++],d[h++]=255;t.putImageData(o,0,u*Cs)}}}function Is(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const s=e.height,i=e.width,n=s%Cs,r=(s-n)/Cs,a=0===n?r:r+1,o=t.createImageData(i,Cs);let h=0;const l=e.data,c=o.data;for(let d=0;d<a;d++){const e=d<r?Cs:n;({srcPos:h}=Ss({src:l,srcPos:h,dest:c,width:i,height:e,nonBlackColor:0})),t.putImageData(o,0,d*Cs)}}function Fs(t,e){const s=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const i of s)void 0!==t[i]&&(e[i]=t[i]);void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function Ns(t){t.strokeStyle=t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0);const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}function Rs(t,e){if(e)return!0;pt.singularValueDecompose2dScale(t,Ts);const s=Math.fround(Lt.pixelRatio*_t.PDF_TO_CSS_UNITS);return Ts[0]<=s&&Ts[1]<=s}const Os=["butt","round","square"],Bs=["miter","round","bevel"],Ls={},Us={};class js{#Hi=0;#$i=0;#zi=null;#Gi=null;#Wi=null;#Vi=null;#Xi=1;#Yi;#qi=null;#Ki=[];constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:a=null},o,h,l,c){this.ctx=t,this.current=new Ps(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.commonObjs=e,this.objs=s,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.tempSMask=null,this.smaskGroupCanvases=[],this.smaskPreparedEntry=null,this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=a||[],this.optionalContentConfig=r,this.cachedPatterns=new Map,this.annotationCanvasMap=o,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=h,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=l??null,this.imagesTracker=c??null}getObject(t,e,s=null){return"string"==typeof e?(this.dependencyTracker?.recordNamedDependency(t,e),e.startsWith("g_")?this.commonObjs.get(e):this.objs.get(e)):s}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,a=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=a,s){const t=this.transparentCanvasEntry=this.canvasFactory.create(n,r);this.compositeCtx=this.ctx,({canvas:this.transparentCanvas,context:this.ctx}=t),this.ctx.save(),this.ctx.transform(...Rt(this.compositeCtx))}this.ctx.save(),Ns(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[3]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=Rt(this.ctx)}executeOperatorList(t,e,s,i,n,r=null,a=null){const o=Number.isFinite(r?.executionTime)&&r.executionTime>0?r.executionTime:15,h=Number.isInteger(r?.executionSteps)&&r.executionSteps>0?r.executionSteps:10,l=t.argsArray,c=t.fnArray;let d=e||0;const u=l.length;if(u===d)return d;const p=u-d>h&&"function"==typeof s,g=p?performance.now()+o:0;let m=0;const f=this.commonObjs,b=this.objs;let y,A;for(;;){if(void 0!==i){if(d===i.nextBreakPoint)return i.breakIt(d,s),d;if(i.shouldSkip(d)){if(++d===u)return d;continue}}if(!n||n(d))if(y=c[d],A=l[d]??null,y!==$.dependency)null===A?this[y](d):this[y](d,...A);else for(const t of A){this.dependencyTracker?.recordNamedData(t,d);const e=t.startsWith("g_")?f:b;if(!e.has(t))return e.get(t,s),d}if(d++,d===u)return d;if(p&&++m>h){const t=performance.now()>g;if("function"==typeof a&&a()||t)return s(),d;m=0}}}#Qi(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(this.transparentCanvasEntry),this.transparentCanvas=null,this.transparentCanvasEntry=null)}endDrawing(){this.#Qi();for(const t of this.smaskGroupCanvases)this.canvasFactory.destroy(t);this.smaskGroupCanvases.length=0,this._clearPreparedSMask(),this.tempSMask=null,this.smaskStack.length=0;for(const t of this.#Ki)this.#Ji(t);this.#Ki.length=0,this.#zi=null,this.#Gi=null,this.#Wi=null,this.#Vi=null,this.#Xi=1,this.#qi=null,this.#$i=0,this.#Hi=0,this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#Zi()}#Zi(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const s=t.width??t.displayWidth,i=t.height??t.displayHeight,n=[];let r=Math.max(Math.hypot(e[0],e[1]),1),a=Math.max(Math.hypot(e[2],e[3]),1),o=s,h=i;for(;r>2&&o>1||a>2&&h>1;){let t=o,e=h;r>2&&o>1&&(t=Math.ceil(o/2),r/=o/t),a>2&&h>1&&(e=Math.ceil(h/2),a/=h/e),n.push({newWidth:t,newHeight:e}),o=t,h=e}if(0===n.length)return{img:t,paintWidth:s,paintHeight:i,tmpCanvas:null};if(1===n.length){const{newWidth:e,newHeight:r}=n[0],a=this.canvasFactory.create(e,r);return a.context.drawImage(t,0,0,s,i,0,0,e,r),{img:a.canvas,paintWidth:e,paintHeight:r,tmpCanvas:a}}let l=this.canvasFactory.create(1,1),c=this.canvasFactory.create(1,1),d=s,u=i,p=t;for(const{newWidth:g,newHeight:m}of n)this.canvasFactory.reset(c,g,m),c.context.drawImage(p,0,0,d,u,0,0,g,m),[l,c]=[c,l],p=l.canvas,d=g,u=m;return this.canvasFactory.destroy(c),{img:l.canvas,paintWidth:d,paintHeight:u,tmpCanvas:l}}_createMaskCanvas(t,e){const s=this.ctx,{width:i,height:n}=e,r=this.current.fillColor,a=this.current.patternFill,o=Rt(s);let h,l,c,d;if((e.bitmap||e.data)&&e.count>1){const s=e.bitmap||e.data.buffer;l=JSON.stringify(a?o:[o.slice(0,4),r]),h=this._cachedBitmapsMap.getOrInsertComputed(s,ft);const i=h.get(l);if(i&&!a){const e=Math.round(Math.min(o[0],o[2])+o[4]),s=Math.round(Math.min(o[1],o[3])+o[5]);return this.dependencyTracker?.recordDependencies(t,Te),{canvas:i,offsetX:e,offsetY:s}}c=i}c||(d=this.canvasFactory.create(i,n),Is(d.context,e));let u=pt.transform(o,[1/i,0,0,-1/n,0,0]);u=pt.transform(u,[1,0,0,1,0,-n]);const g=p.slice();pt.axialAlignedBoundingBox([0,0,i,n],u,g);const[m,f,b,y]=g,A=Math.round(b-m)||1,w=Math.round(y-f)||1,v=this.canvasFactory.create(A,w),_=v.context,x=m,S=f;_.translate(-x,-S),_.transform(...u);let C=null;if(!c){const t=this._scaleImage(d.canvas,Ot(_));c=t.img,C=t.tmpCanvas,c!==d.canvas&&(this.canvasFactory.destroy(d),d=null),h&&a&&(h.set(l,c),C=null,d=null)}_.imageSmoothingEnabled=Rs(Rt(_),e.interpolate),Es(_,c,0,0,c.width,c.height,0,0,i,n),C&&this.canvasFactory.destroy(C),d&&this.canvasFactory.destroy(d),_.globalCompositeOperation="source-in";const k=pt.transform(Ot(_),[1,0,0,1,-x,-S]);return _.fillStyle=a?r.getPattern(s,this,k,us,t):r,_.fillRect(0,0,i,n),h&&!a&&h.set(l,v.canvas),this.dependencyTracker?.recordDependencies(t,Te),{canvas:v.canvas,canvasEntry:h&&!a?null:v,offsetX:Math.round(x),offsetY:Math.round(S)}}setLineWidth(t,e){this.dependencyTracker?.recordSimpleData("lineWidth",t),e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(t,e){this.dependencyTracker?.recordSimpleData("lineCap",t),this.ctx.lineCap=Os[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t),this.ctx.lineJoin=Bs[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t),this.ctx.miterLimit=e}setDash(t,e,s){this.dependencyTracker?.recordSimpleData("dash",t);const i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(e),i.lineDashOffset=s)}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(const[s,i]of e)switch(s){case"LW":this.setLineWidth(t,i);break;case"LC":this.setLineCap(t,i);break;case"LJ":this.setLineJoin(t,i);break;case"ML":this.setMiterLimit(t,i);break;case"D":this.setDash(t,i[0],i[1]);break;case"RI":this.setRenderingIntent(t,i);break;case"FL":this.setFlatness(t,i);break;case"Font":this.setFont(t,i[0],i[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t),this.current.strokeAlpha=i;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t),this.ctx.globalAlpha=this.current.fillAlpha=i;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t),this.ctx.globalCompositeOperation=i;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t),this.current.activeSMask=i?this.tempSMask:null,this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation),this.tempSMask=null,this.checkSMaskState(t);break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){this.smaskPreparedEntry&&(this.canvasFactory.destroy(this.smaskPreparedEntry),this.smaskPreparedEntry=null),this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null}_ensurePreparedSMask(t){t!==this.smaskPreparedFor&&(this._clearPreparedSMask(),this._prepareSMaskCanvas(t))}checkSMaskState(t){const e=this.inSMaskMode;this.current.activeSMask&&!e?this.beginSMaskMode(t):!this.current.activeSMask&&e?this.endSMaskMode():this.current.activeSMask&&e&&this._ensurePreparedSMask(this.current.activeSMask)}_prepareSMaskCanvas(t){const{canvas:e,subtype:s,backdrop:i,transferMap:n}=t,r="Luminosity"===s||"Alpha"===s&&n;if(!(r||"Luminosity"===s&&i))return void(this.smaskPreparedFor=t);let a;if("Luminosity"===s&&i){const[t,e,s]=Ft(i),r=Math.round(.3*t+.59*e+.11*s);a=n?.[r]??r}else a=n?.[0]??0;const{width:o,height:h}=this.ctx.canvas,l=o*h<e.width*e.height*4,c=r?{url:"Alpha"===s?this.filterFactory.addAlphaFilter(n):this.filterFactory.addLuminosityFilter(n),subtype:s,transferMap:n}:null,d="Luminosity"===s?i:null;let u,p,g;l?(u=this._bakeSMaskCanvas(e,t.offsetX,t.offsetY,o,h,d,c),p=0,g=0):(u=this._bakeSMaskCanvas(e,0,0,e.width,e.height,d,c),p=t.offsetX,g=t.offsetY),this.smaskPreparedEntry=u,this.smaskPreparedFor=t,this.smaskPreparedOffsetX=p,this.smaskPreparedOffsetY=g,this.smaskPreparedOOBAlpha=l||0===a?null:a}_bakeSMaskCanvas(t,e,s,i,n,r,a){r||a||Z("_bakeSMaskCanvas with neither backdrop nor filter");const o=this.canvasFactory.create(i,n),h=o.context;if(h.drawImage(t,e,s),r&&(h.globalCompositeOperation="destination-atop",h.fillStyle=r,h.fillRect(0,0,i,n)),!a)return o;const l=this.canvasFactory.create(i,n),c=l.context;c.filter=a.url;const d=ut.isCanvasFilterSupported&&"none"!==c.filter&&""!==c.filter;if(c.drawImage(o.canvas,0,0),ut.isCanvasFilterSupported&&(c.filter="none"),!d){const t=c.getImageData(0,0,i,n),{data:e}=t,{transferMap:s}=a;if("Luminosity"===a.subtype)for(let i=0,n=e.length;i<n;i+=4){const t=.3*e[i]+.59*e[i+1]+.11*e[i+2]+.5|0;e[i]=e[i+1]=e[i+2]=0,e[i+3]=s?.[t]??t}else for(let i=3,n=e.length;i<n;i+=4)e[i]=s[e[i]];c.putImageData(t,0,0)}return this.canvasFactory.destroy(o),l}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const{width:e,height:s}=this.ctx.canvas,i=this.canvasFactory.create(e,s);this.smaskScratchCanvas=i,this.suspendedCtx=this.ctx;const n=this.ctx=i.context;n.setTransform(this.suspendedCtx.getTransform()),Fs(this.suspendedCtx,n),Ms(n,this.suspendedCtx),this._ensurePreparedSMask(this.current.activeSMask),this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),Fs(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null,this.canvasFactory.destroy(this.smaskScratchCanvas),this.smaskScratchCanvas=null,this._clearPreparedSMask()}#tn(t,e=null,s=1){const{width:i,height:n}=t,r=e??this.canvasFactory.create(i,n),a=r.context,o=(s=Math.round(255*s)/255)<1;o&&void 0===this.#Yi&&(this.#Yi=ut.isCanvasFilterSupported?new Map:"none");let h="none";if(o&&this.#Yi instanceof Map&&(h=this.#Yi.get(s),h||(h=this.filterFactory.addKnockoutFilter(s),this.#Yi.set(s,h))),!o||"none"!==h)return e&&(a.save(),a.setTransform(1,0,0,1,0,0),a.clearRect(0,0,i,n),a.restore()),a.filter=h,a.drawImage(t,0,0),a.filter="none",r;const l=t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,i,n),c=a.createImageData(i,n),d=l.data,u=c.data,p=s>0?1/s:1e6;for(let g=3,m=d.length;g<m;g+=4)u[g]=Math.min(Math.round(d[g]*p),255);return a.putImageData(c,0,0),r}#en(t,e,s,i){let n=t?.[e]??null;if(!n||n.canvas.width===s&&n.canvas.height===i||(this.canvasFactory.destroy(n),n=null),!n)return n=this.canvasFactory.create(s,i),t&&(t[e]=n),n;const r=n.context;return r.save(),r.setTransform(1,0,0,1,0,0),r.clearRect(0,0,s,i),r.restore(),n}#sn(t,e,s={}){const{backdropCanvas:i=null,destTransform:n=[1,0,0,1,0,0],backdropOffset:r=[0,0],reuseMaskEntry:a=null,poolMeta:o=null,sourceAlpha:h=1,sourceFilter:l="none",knockoutAlpha:c=1}=s,{width:d,height:u}=e,p=this.#tn(e,a,c),g=t.globalCompositeOperation;if(t.save(),t.setTransform(...n),t.globalAlpha=1,ut.isCanvasFilterSupported&&(t.filter="none"),t.globalCompositeOperation="destination-out",t.drawImage(p.canvas,0,0),i){const[e,s]=r,n=this.#en(o,"knockoutBackdropEntry",d,u),a=n.context;a.drawImage(i,e,s,d,u,0,0,d,u),a.globalCompositeOperation="destination-in",a.drawImage(p.canvas,0,0),a.globalCompositeOperation="source-over",t.globalCompositeOperation="destination-over",t.drawImage(n.canvas,0,0),o||this.canvasFactory.destroy(n)}t.globalCompositeOperation=g,t.globalAlpha=h,ut.isCanvasFilterSupported&&(t.filter=l??"none"),t.drawImage(e,0,0),t.restore(),a||this.canvasFactory.destroy(p)}#in(t=1){if(0===this.#Hi||this.#$i>0||!this.contentVisible)return!1;this.#$i++,this.#Xi=t;const e=this.#Ki.at(-1),{canvas:s}=this.ctx,i=this.#en(e,"knockoutTempEntry",s.width,s.height);this.#zi=i;const n=i.context;return n.save(),n.setTransform(this.ctx.getTransform()),Fs(this.ctx,n),this.#Vi=n.globalCompositeOperation,n.globalCompositeOperation="source-over",Ms(n,this.ctx),this.#qi=e,this.#Gi=this.ctx,this.#Wi=this.suspendedCtx,this.ctx=n,this.inSMaskMode&&(this.suspendedCtx=n),!0}#nn(t){if(!t)return;const e=this.#zi,s=this.#Gi,i=this.#Wi,n=e.context;this.#zi=null,this.#Gi=null,this.#Wi=null,this.inSMaskMode&&this.suspendedCtx===n&&this.ctx!==n&&this.endSMaskMode(),this.inSMaskMode&&(this.suspendedCtx=i),this.ctx._removeMirroring(),this.ctx.globalCompositeOperation=this.#Vi,this.#Vi=null,Fs(this.ctx,s),this.ctx=s;const r=this.#qi;this.#qi=null;const a=this.#Xi;this.#Xi=1;try{this.#sn(i??s,e.canvas,{backdropCanvas:r?.backdropCtx?.canvas??null,backdropOffset:r?.backdropCtx?[r.offsetX,r.offsetY]:[0,0],reuseMaskEntry:r?.knockoutMaskEntry??null,poolMeta:r,knockoutAlpha:a})}finally{n.restore(),this.#$i--,r||this.canvasFactory.destroy(e)}}compose(t){if(!this.current.activeSMask)return;t=t?[Math.floor(t[0]),Math.floor(t[1]),Math.ceil(t[2]),Math.ceil(t[3])]:[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx,i=this.#$i>0&&s===this.ctx;this.composeSMask(i?null:s,e,this.ctx,t),i||(this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(t[0],t[1],t[2]-t[0],t[3]-t[1]),this.ctx.restore())}composeSMask(t,e,s,i){const n=i[0],r=i[1],a=i[2]-n,o=i[3]-r;if(0===a||0===o)return;const h=this.smaskPreparedEntry;if(h){let t=n,i=r,l=a,c=o;const d=this.smaskPreparedOOBAlpha,u=null!==d;if(u&&(t=Math.max(n,e.offsetX),i=Math.max(r,e.offsetY),l=Math.min(n+a,e.offsetX+e.canvas.width)-t,c=Math.min(r+o,e.offsetY+e.canvas.height)-i),l>0&&c>0){const e=t-this.smaskPreparedOffsetX,n=i-this.smaskPreparedOffsetY;s.save(),s.globalAlpha=1,s.setTransform(1,0,0,1,0,0);const r=new Path2D;r.rect(t,i,l,c),s.clip(r),s.globalCompositeOperation="destination-in",s.drawImage(h.canvas,e,n,l,c,t,i,l,c),s.restore()}u&&d<255&&this._applySMaskOOBAlpha(s,n,r,a,o,t,i,t+l,i+c,d)}else this.genericComposeSMask(e,s,a,o,n,r);t&&(t.save(),t.globalAlpha=1,t.globalCompositeOperation=e.blendMode||"source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(s.canvas,n,r,a,o,n,r,a,o),t.restore())}_applySMaskOOBAlpha(t,e,s,i,n,r,a,o,h,l){const c=r<o&&a<h;if(c&&r===e&&a===s&&o===e+i&&h===s+n)return;const d=new Path2D;d.rect(e,s,i,n),c&&d.rect(r,a,o-r,h-a),t.save(),t.globalAlpha=l/255,t.setTransform(1,0,0,1,0,0),t.clip(d,"evenodd"),t.globalCompositeOperation="destination-in",t.fillStyle="#000000",t.fillRect(e,s,i,n),t.restore()}genericComposeSMask(t,e,s,i,n,r){const{context:a,offsetX:o,offsetY:h}=t;e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0);const l=new Path2D;l.rect(n,r,s,i),e.clip(l),e.globalCompositeOperation="destination-in",e.drawImage(a.canvas,n-o,r-h,s,i,n,r,s,i),e.restore()}save(t){this.inSMaskMode&&Fs(this.ctx,this.suspendedCtx),this.ctx.save();const e=this.current;this.stateStack.push(e),this.current=e.clone(),this.dependencyTracker?.save(t)}restore(t){this.dependencyTracker?.restore(t),0!==this.stateStack.length?(this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&(Fs(this.suspendedCtx,this.ctx),this.ctx.setTransform(this.suspendedCtx.getTransform())),this.checkSMaskState(t),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null):this.inSMaskMode&&this.endSMaskMode()}transform(t,e,s,i,n,r,a){this.dependencyTracker?.recordIncrementalData("transform",t),this.ctx.transform(e,s,i,n,r,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s,i){let[n]=s;if(!i)return n||=s[0]=new Path2D,e!==$.stroke&&e!==$.closeStroke&&(this.current.tilingPatternDims=null),void this[e](t,n);if(null!==this.dependencyTracker){const s=e===$.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,i[0]-s,i[2]+s,i[1]-s,i[3]+s).recordDependencies(t,["transform"])}n instanceof Path2D||(n=s[0]=$t(n)),pt.axialAlignedBoundingBox(i,Rt(this.ctx),this.current.minMax);const r=this.current.tilingPatternDims;if(r&&e!==$.stroke&&e!==$.closeStroke&&this.current.fillColor instanceof xs){const t=pt.intersect(this.current.clipBox,this.current.minMax);t?this.current.fillColor.updatePatternDims(t,r):this.current.tilingPatternDims=null}this[e](t,n),this._pathStartIdx=t}closePath(t){this.ctx.closePath()}stroke(t,e,s=!0){const i=s&&this.#in(this.current.strokeAlpha),n=this.ctx,r=this.current.strokeColor;if(n.globalAlpha=this.current.strokeAlpha,this.contentVisible)if("object"==typeof r&&r?.getPattern){const s=r.isModifyingCurrentTransform()?n.getTransform():null;if(n.save(),n.strokeStyle=r.getPattern(n,this,Ot(n),ps,t),s){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(s)),e=t}this.rescaleAndStroke(e,!1),n.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,ve),s&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(ps,Rt(this.ctx))),n.globalAlpha=this.current.fillAlpha,this.#nn(i)}closeStroke(t,e){this.stroke(t,e)}fill(t,e,s=!0){const i=s&&this.#in(this.current.fillAlpha),n=this.ctx,r=this.current.fillColor,a=this.current.patternFill;let o=!1;const h=this.current.getClippedPathBoundingBox();if(this.dependencyTracker?.recordDependencies(t,_e),a){const a=this.current.tilingPatternDims,l=a&&r.canSkipPatternCanvas(a);if(l)return r.drawPattern(this,e,this.pendingEOFill,l,t),this.pendingEOFill=!1,s&&this.consumePath(t,e,h),this.current.tilingPatternDims=null,void this.#nn(i);const c=r.isModifyingCurrentTransform()?n.getTransform():null;if(this.dependencyTracker?.save(t),n.save(),n.fillStyle=r.getPattern(n,this,Ot(n),us,t),c){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(c)),e=t}o=!0}this.contentVisible&&null!==h&&(this.pendingEOFill?(n.fill(e,"evenodd"),this.pendingEOFill=!1):n.fill(e)),o&&(n.restore(),this.dependencyTracker?.restore(t)),s&&this.consumePath(t,e,h),this.#nn(i)}eoFill(t,e){this.pendingEOFill=!0,this.fill(t,e)}fillStroke(t,e){const s=this.#in(Math.min(this.current.fillAlpha,this.current.strokeAlpha));this.fill(t,e,!1),this.stroke(t,e,!1),this.consumePath(t,e),this.#nn(s)}eoFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}closeFillStroke(t,e){this.fillStroke(t,e)}closeEOFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}endPath(t,e){this.consumePath(t,e)}rawFillPath(t,e){const s=this.#in(this.current.fillAlpha);this.ctx.fill(e),this.dependencyTracker?.recordDependencies(t,Se).recordOperation(t),this.#nn(s)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Ls}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Us}beginText(t){this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.dependencyTracker?.recordOpenMarker(t).resetIncrementalData("sameLineText").resetIncrementalData("moveText",t)}endText(t){const e=this.pendingTextPaths,s=this.ctx;if(this.dependencyTracker){const{dependencyTracker:s}=this;void 0!==e&&s.recordFutureForcedDependency("textClip",s.getOpenMarker()).recordFutureForcedDependency("textClip",t),s.recordCloseMarker(t)}if(void 0!==e){const t=new Path2D,i=s.getTransform().invertSelf();for(const{transform:s,x:n,y:r,fontSize:a,path:o}of e)o&&t.addPath(o,new DOMMatrix(s).preMultiplySelf(i).translate(n,r).scale(a,-a));s.clip(t)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t),this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t),this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t),this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t),this.current.leading=-e}setFont(t,e,s){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",e,t);const i=this.commonObjs.get(e),n=this.current;if(!i)throw new Error(`Can't find font for ${e}`);if(n.fontMatrix=i.fontMatrix||g,0!==n.fontMatrix[0]&&0!==n.fontMatrix[3]||J("Invalid font matrix for font "+e),s<0?(s=-s,n.fontDirection=-1):n.fontDirection=1,this.current.font=i,this.current.fontSize=s,i.isType3Font)return;const r=i.loadedName||"sans-serif",a=i.systemFontInfo?.css||`"${r}", ${i.fallbackName}`;let o="normal";i.black?o="900":i.bold&&(o="bold");const h=i.italic?"italic":"normal";let l=s;s<16?l=16:s>100&&(l=100),this.current.fontSizeScale=s/l,this.ctx.font=`${h} ${o} ${l}px ${a}`}setTextRenderingMode(t,e){this.dependencyTracker?.recordSimpleData("textRenderingMode",t),this.current.textRenderingMode=e}setTextRise(t,e){this.dependencyTracker?.recordSimpleData("textRise",t),this.current.textRise=e}moveText(t,e,s){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t),this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=s}setLeadingMoveText(t,e,s){this.setLeading(t,-s),this.moveText(t,e,s)}setTextMatrix(t,e){this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",t);const{current:s}=this;s.textMatrix=e,s.textMatrixScale=Math.hypot(e[0],e[1]),s.x=s.lineX=0,s.y=s.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading),this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#rn(t,e,s){const i=new Path2D;return i.addPath(t,new DOMMatrix(s).invertSelf().multiplySelf(e)),i}paintChar(t,e,s,i,n,r){const a=this.ctx,o=this.current,h=o.font,l=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,d=l&F,u=!!(l&N),p=o.patternFill&&!h.missingFile,g=o.patternStroke&&!h.missingFile;let m;if((h.disableFontFace||u||p||g)&&!h.missingFile&&(m=h.getPathGenerator(this.commonObjs,e)),m&&(h.disableFontFace||p||g)){let e;if(a.save(),a.translate(s,i),a.scale(c,-c),this.dependencyTracker?.recordCharacterBBox(t,a,h),d===E||d===D)if(n){e=a.getTransform(),a.setTransform(...n);const t=this.#rn(m,e,n);a.fill(t)}else a.fill(m);if(d===P||d===D)if(r){e||=a.getTransform(),a.setTransform(...r);const{a:t,b:s,c:i,d:n}=e,o=pt.inverseTransform(r),h=pt.transform([t,s,i,n,0,0],o);pt.singularValueDecompose2dScale(h,Ts),a.lineWidth*=Math.max(Ts[0],Ts[1])/c,a.stroke(this.#rn(m,e,r))}else a.lineWidth/=c,a.stroke(m);a.restore()}else d!==E&&d!==D||(a.fillText(e,s,i),this.dependencyTracker?.recordCharacterBBox(t,a,h,c,s,i,()=>a.measureText(e))),d!==P&&d!==D||(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,a,h,c,s,i,()=>a.measureText(e)).recordDependencies(t,ve),a.strokeText(e,s,i));u&&((this.pendingTextPaths||=[]).push({transform:Rt(a),x:s,y:i,fontSize:c,path:m}),this.dependencyTracker?.recordCharacterBBox(t,a,h,c,s,i))}get isFontSubpixelAAEnabled(){const t=this.canvasFactory.create(10,10),e=t.context;e.scale(1.5,1),e.fillText("I",0,10);const s=e.getImageData(0,0,10,10).data;this.canvasFactory.destroy(t);let i=!1;for(let n=3;n<s.length;n+=4)if(s[n]>0&&s[n]<255){i=!0;break}return it(this,"isFontSubpixelAAEnabled",i)}showText(t,e){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(t,Ce).resetBBox(t),this.current.textRenderingMode&N&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies());const s=this.current,i=s.font;if(i.isType3Font){const i=this.#in(s.fillAlpha);return this.showType3Text(t,e),this.dependencyTracker?.recordShowTextOperation(t),void this.#nn(i)}const n=s.fontSize;if(0===n)return void this.dependencyTracker?.recordOperation(t);const r=this.#in(s.fillAlpha),a=this.ctx,o=s.fontSizeScale,h=s.charSpacing,l=s.wordSpacing,c=s.fontDirection,d=s.textHScale*c,u=e.length,p=i.vertical,g=p?1:-1,m=i.defaultVMetrics,f=n*s.fontMatrix[0],b=s.textRenderingMode===E&&!i.disableFontFace&&!s.patternFill;let y,A;a.save(),s.textMatrix&&a.transform(...s.textMatrix),a.translate(s.x,s.y+s.textRise),c>0?a.scale(d,-1):a.scale(d,1);const w=s.textRenderingMode&F,v=w===E||w===D,_=w===P||w===D;let x=s.lineWidth;const S=s.textMatrixScale;if(0===S||0===x?_&&(x=this.getSinglePixelWidth()):x/=S,1!==o&&(a.scale(o,o),x/=o),a.lineWidth=x,v&&s.patternFill){a.save();const e=s.fillColor.getPattern(a,this,Ot(a),us,t);y=Rt(a),a.restore(),a.fillStyle=e}if(_&&s.patternStroke){a.save();const e=s.strokeColor.getPattern(a,this,Ot(a),ps,t);A=Rt(a),a.restore(),a.strokeStyle=e}if(i.isInvalidPDFjsFont){const i=[];let n=0;for(const t of e)i.push(t.unicode),n+=t.width;const o=i.join("");if(a.fillText(o,0,0),null!==this.dependencyTracker){const e=a.measureText(o);this.dependencyTracker.recordBBox(t,this.ctx,-e.actualBoundingBoxLeft,e.actualBoundingBoxRight,-e.actualBoundingBoxAscent,e.actualBoundingBoxDescent).recordShowTextOperation(t)}return s.x+=n*f*d,a.restore(),this.compose(),void this.#nn(r)}let C,k=0;for(C=0;C<u;++C){const s=e[C];if("number"==typeof s){k+=g*s*n/1e3;continue}let r=!1;const d=(s.isSpace?l:0)+h,u=s.fontChar,w=s.accent;let v,_,x,S=s.width;if(p){const t=s.vmetric||m,e=-(s.vmetric?t[1]:.5*S)*f,i=t[2]*f;S=t?-t[0]:S,v=e/o,_=(k+i)/o}else v=k/o,_=0;if(i.remeasure&&S>0){x=a.measureText(u);const t=1e3*x.width/n*o;if(S<t&&this.isFontSubpixelAAEnabled){const e=S/t;r=!0,a.save(),a.scale(e,1),v/=e}else S!==t&&(v+=(S-t)/2e3*n/o)}if(this.contentVisible&&(s.isInFont||i.missingFile))if(b&&!w)a.fillText(u,v,_),this.dependencyTracker?.recordCharacterBBox(t,a,x?{bbox:null}:i,n/o,v,_,()=>x??a.measureText(u));else if(this.paintChar(t,u,v,_,y,A),w){const e=v+n*w.offset.x/o,s=_-n*w.offset.y/o;this.paintChar(t,w.fontChar,e,s,y,A)}k+=p?S*f-d*c:S*f+d*c,r&&a.restore()}p?s.y-=k:s.x+=k*d,a.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(t),this.#nn(r)}showType3Text(t,e){const s=this.ctx,i=this.current,n=i.font,r=i.fontSize,a=i.fontDirection,o=n.vertical?1:-1,h=i.charSpacing,l=i.wordSpacing,c=i.textHScale*a,d=i.fontMatrix||g,u=e.length;let p,m,f,b;if(i.textRenderingMode===I||0===r)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,s.save(),i.textMatrix&&s.transform(...i.textMatrix),s.translate(i.x,i.y+i.textRise),s.scale(c,a);const y=this.dependencyTracker;for(this.dependencyTracker=y?new we(y,t):null,p=0;p<u;++p){if(m=e[p],"number"==typeof m){b=o*m*r/1e3,this.ctx.translate(b,0),i.x+=b*c;continue}const t=(m.isSpace?l:0)+h,a=n.charProcOperatorList[m.operatorListId];a?this.contentVisible&&(this.save(),s.scale(r,r),s.transform(...d),this.executeOperatorList(a),this.restore()):J(`Type3 character "${m.operatorListId}" is not available.`);const u=[m.width,0];pt.applyTransform(u,d),f=u[0]*r+t,s.translate(f,0),i.x+=f*c}s.restore(),y&&(this.dependencyTracker=y)}setCharWidth(t,e,s){}setCharWidthAndBounds(t,e,s,i,n,r,a){const o=new Path2D;o.rect(i,n,r-i,a-n),this.ctx.clip(o),this.dependencyTracker?.recordBBox(t,this.ctx,i,r,n,a).recordClipBox(t,this.ctx,i,r,n,a),this.endPath(t)}getColorN_Pattern(t,e){let s;if("TilingPattern"===e[0]){const t=this.baseTransform||Rt(this.ctx),i={createCanvasGraphics:(t,e)=>new js(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new we(this.dependencyTracker,e,!0):null)};s=new xs(e,this.ctx,i,t)}else s=this._getPattern(t,e[1],e[2]);return s}setStrokeColorN(t,...e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.current.strokeColor=this.getColorN_Pattern(t,e),this.current.patternStroke=!0}setFillColorN(t,...e){this.dependencyTracker?.recordSimpleData("fillColor",t);const s=this.current.fillColor=this.getColorN_Pattern(t,e);this.current.patternFill=!0,this.current.tilingPatternDims=s instanceof xs?[0,0,0,0]:null}setStrokeRGBColor(t,e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor=e,this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor=e,this.current.patternFill=!1,this.current.tilingPatternDims=null}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1,this.current.tilingPatternDims=null}_getPattern(t,e,s=null){let i;return this.cachedPatterns.has(e)?i=this.cachedPatterns.get(e):(i=function(t){switch(t[0]){case"RadialAxial":return new bs(t);case"Mesh":return new As(t);case"Dummy":return new ws}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t,e)),this.cachedPatterns.set(e,i)),s&&(i.matrix=s),i}shadingFill(t,e){if(!this.contentVisible)return;const s=this.#in(this.current.fillAlpha),i=this.ctx;this.save(t);const n=this._getPattern(t,e);i.fillStyle=n.getPattern(i,this,Ot(i),gs,t);const r=Ot(i);if(r){const{width:t,height:e}=i.canvas,s=p.slice();pt.axialAlignedBoundingBox([0,0,t,e],r,s);const[n,a,o,h]=s;this.ctx.fillRect(n,a,o-n,h-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,ke).recordDependencies(t,_e).recordOperation(t),this.compose(this.current.getClippedPathBoundingBox()),this.restore(t),this.#nn(s)}beginInlineImage(){Z("Should not call beginInlineImage")}beginImageData(){Z("Should not call beginImageData")}paintFormXObjectBegin(t,e,s){if(this.contentVisible&&(this.save(t),this.baseTransformStack.push(this.baseTransform),e&&this.transform(t,...e),this.baseTransform=Rt(this.ctx),s)){pt.axialAlignedBoundingBox(s,this.baseTransform,this.current.minMax);const[e,i,n,r]=s,a=new Path2D;a.rect(e,i,n-e,r-i),this.ctx.clip(a),this.dependencyTracker?.recordClipBox(t,this.ctx,e,n,i,r),this.endPath(t)}}paintFormXObjectEnd(t){this.contentVisible&&(this.restore(t),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t,e){if(!this.contentVisible)return;this.save(t);const{inSMaskMode:s}=this;s&&(this.endSMaskMode(),this.current.activeSMask=null);const i=this.ctx;if(e.isolated||e.knockout||0!==this.#Hi||Q("TODO: Fully support non-isolated non-knockout groups."),!e.needsIsolation&&!e.knockout&&0===this.#Hi&&1===i.globalAlpha&&"source-over"===i.globalCompositeOperation&&!s){if(e.bbox){let t=new Path2D;const[s,n,r,a]=e.bbox;if(t.rect(s,n,r-s,a-n),e.matrix){const s=new Path2D;s.addPath(t,new DOMMatrix(e.matrix)),t=s}i.clip(t)}return this.groupStack.push(null),this.#Ki.push(null),void this.groupLevel++}const n=Rt(i);e.matrix&&i.transform(...e.matrix);const r=[0,0,i.canvas.width,i.canvas.height];let a;e.bbox?(a=p.slice(),pt.axialAlignedBoundingBox(e.bbox,Rt(i),a),a=pt.intersect(a,r)||[0,0,0,0]):a=r;const o=Math.floor(a[0]),h=Math.floor(a[1]),l=Math.max(Math.ceil(a[2])-o,1),c=Math.max(Math.ceil(a[3])-h,1);this.current.startNewPathAndClipBox([0,0,l,c]);const d=this.canvasFactory.create(l,c);e.smask&&this.smaskGroupCanvases.push(d);const u=d.context,g=e.knockout&&!e.isolated?i:null,m=!e.isolated&&!e.knockout&&!e.smask&&e.needsIsolation&&this.#Hi>0,f=e.knockout?this.canvasFactory.create(l,c):null,b=this.#Hi;if(e.knockout?this.#Hi++:this.#Hi=0,u.translate(-o,-h),u.transform(...n),!e.isolated&&!e.smask&&s&&e.needsIsolation&&(u.save(),u.setTransform(1,0,0,1,0,0),u.drawImage(i.canvas,-o,-h),u.restore()),e.bbox){let t=new Path2D;const[s,i,n,r]=e.bbox;if(t.rect(s,i,n-s,r-i),e.matrix){const s=new Path2D;s.addPath(t,new DOMMatrix(e.matrix)),t=s}u.clip(t)}e.smask&&this.smaskStack.push({canvas:d.canvas,context:u,offsetX:o,offsetY:h,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null}),e.smask&&!this.dependencyTracker||(i.setTransform(1,0,0,1,0,0),i.translate(o,h),i.save()),Fs(i,u),this.ctx=u,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i),this.setGState(t,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]),this.groupStack.push(i),this.#Ki.push({backdropCtx:g,savedKnockoutLevel:b,offsetX:o,offsetY:h,hasInnerBackdrop:m,knockoutMaskEntry:f,knockoutTempEntry:null,knockoutBackdropEntry:null}),this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const s=this.ctx,i=this.groupStack.pop(),n=this.#Ki.pop();if(n&&(this.#Hi=n.savedKnockoutLevel),null!==i)if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),e.smask)this.tempSMask=this.smaskStack.pop(),this.restore(t),this.dependencyTracker&&(this.ctx.restore(),this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform())),this.#Ji(n);else{this.ctx.restore();const e=Rt(this.ctx);this.restore(t),this.ctx.save(),this.ctx.setTransform(...e);const r=p.slice();pt.axialAlignedBoundingBox([0,0,s.canvas.width,s.canvas.height],e,r);const a=this.#Ki.at(-1);if(this.#Hi>0)if(n.hasInnerBackdrop){const{width:t,height:r}=s.canvas,a=this.canvasFactory.create(t,r),o=a.context;o.drawImage(i.canvas,n.offsetX,n.offsetY,t,r,0,0,t,r),o.globalCompositeOperation="source-over",o.drawImage(s.canvas,0,0);const h=this.#tn(s.canvas);o.globalCompositeOperation="destination-in",o.drawImage(h.canvas,0,0);const l=this.ctx.globalCompositeOperation,c=this.ctx.globalAlpha,d=this.ctx.filter;this.ctx.save(),this.ctx.setTransform(...e),this.ctx.globalAlpha=1,ut.isCanvasFilterSupported&&(this.ctx.filter="none"),this.ctx.globalCompositeOperation="destination-out",this.ctx.drawImage(h.canvas,0,0),this.ctx.globalCompositeOperation=l,this.ctx.globalAlpha=c,ut.isCanvasFilterSupported&&(this.ctx.filter=d??"none"),this.ctx.drawImage(a.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(h),this.canvasFactory.destroy(a)}else{const t=a?.backdropCtx??null;this.#sn(this.ctx,s.canvas,{backdropCanvas:t?.canvas??null,destTransform:e,backdropOffset:t?[a.offsetX+n.offsetX,a.offsetY+n.offsetY]:[0,0],sourceAlpha:this.ctx.globalAlpha,sourceFilter:this.ctx.filter})}else this.ctx.drawImage(s.canvas,0,0);this.ctx.restore(),this.canvasFactory.destroy({canvas:s.canvas,context:s}),this.#Ji(n),this.compose(r)}else this.restore(t)}#Ji(t){t&&(t.knockoutMaskEntry&&(this.canvasFactory.destroy(t.knockoutMaskEntry),t.knockoutMaskEntry=null),t.knockoutTempEntry&&(this.canvasFactory.destroy(t.knockoutTempEntry),t.knockoutTempEntry=null),t.knockoutBackdropEntry&&(this.canvasFactory.destroy(t.knockoutBackdropEntry),t.knockoutBackdropEntry=null))}beginAnnotation(t,e,s,i,n,r){if(this.#Qi(),Ns(this.ctx),this.ctx.save(),this.save(t),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),s){const n=s[2]-s[0],a=s[3]-s[1];if(r&&this.annotationCanvasMap){(i=i.slice())[4]-=s[0],i[5]-=s[1],(s=s.slice())[0]=s[1]=0,s[2]=n,s[3]=a,pt.singularValueDecompose2dScale(Rt(this.ctx),Ts);const{viewportScale:t}=this,r=Math.ceil(n*this.outputScaleX*t),o=Math.ceil(a*this.outputScaleY*t);this.annotationCanvas=this.canvasFactory.create(r,o);const{canvas:h,context:l}=this.annotationCanvas;this.annotationCanvasMap.set(e,h),this.annotationCanvas.savedCtx=this.ctx,this.ctx=l,this.ctx.save(),this.ctx.setTransform(Ts[0],0,0,-Ts[1],0,a*Ts[1]),Ns(this.ctx)}else{Ns(this.ctx),this.endPath(t);const e=new Path2D;e.rect(s[0],s[1],n,a),this.ctx.clip(e)}}this.current=new Ps(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(t,...i),this.transform(t,...n),this.baseTransform=Rt(this.ctx)}endAnnotation(t){this.annotationCanvas&&(this.ctx.restore(),this.#Zi(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const s=e.count;(e=this.getObject(t,e.data,e)).count=s;const i=this.#in(this.current.fillAlpha),n=this.ctx,r=this._createMaskCanvas(t,e),a=r.canvas;n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage(a,r.offsetX,r.offsetY),this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,r.offsetX,r.offsetX+a.width,r.offsetY,r.offsetY+a.height).recordOperation(t),n.restore(),r.canvasEntry&&this.canvasFactory.destroy(r.canvasEntry),this.compose(),this.#nn(i)}paintImageMaskXObjectRepeat(t,e,s,i=0,n=0,r,a){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);const o=this.#in(this.current.fillAlpha),h=this.ctx;h.save();const l=Rt(h);h.transform(s,i,n,r,0,0);const c=this._createMaskCanvas(t,e);h.setTransform(1,0,0,1,c.offsetX-l[4],c.offsetY-l[5]),this.dependencyTracker?.resetBBox(t);for(let d=0,u=a.length;d<u;d+=2){const e=pt.transform(l,[s,i,n,r,a[d],a[d+1]]);h.drawImage(c.canvas,e[4],e[5]),this.dependencyTracker?.recordBBox(t,this.ctx,e[4],e[4]+c.canvas.width,e[5],e[5]+c.canvas.height)}h.restore(),c.canvasEntry&&this.canvasFactory.destroy(c.canvasEntry),this.compose(),this.dependencyTracker?.recordOperation(t),this.#nn(o)}paintImageMaskXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.#in(this.current.fillAlpha),i=this.ctx,n=this.current.fillColor,r=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,Te);for(const a of e){const{data:e,width:s,height:o,transform:h}=a,l=this.canvasFactory.create(s,o),c=l.context;c.save(),Is(c,this.getObject(t,e,a)),c.globalCompositeOperation="source-in",c.fillStyle=r?n.getPattern(c,this,Ot(i),us,t):n,c.fillRect(0,0,s,o),c.restore(),i.save(),i.transform(...h),i.scale(1,-1),Es(i,l.canvas,0,0,s,o,0,-1,1,1),this.canvasFactory.destroy(l),this.dependencyTracker?.recordBBox(t,i,0,s,0,o),i.restore()}this.compose(),this.dependencyTracker?.recordOperation(t),this.#nn(s)}paintImageXObject(t,e){if(!this.contentVisible)return;const s=this.getObject(t,e);s?this.paintInlineImageXObject(t,s):J("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,s,i,n){if(!this.contentVisible)return;const r=this.getObject(t,e);if(!r)return void J("Dependent image isn't ready yet");const a=r.width,o=r.height,h=[];for(let l=0,c=n.length;l<c;l+=2)h.push({transform:[s,0,0,i,n[l],n[l+1]],x:0,y:0,w:a,h:o});this.paintInlineImageXObjectGroup(t,r,h)}applyTransferMapsToCanvas(t){return"none"!==this.current.transferMaps&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if("none"===this.current.transferMaps)return{img:t.bitmap,canvasEntry:null};const{bitmap:e,width:s,height:i}=t,n=this.canvasFactory.create(s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",{img:n.canvas,canvasEntry:n}}paintInlineImageXObject(t,e){if(!this.contentVisible)return;const s=e.width,i=e.height,n=this.#in(this.current.fillAlpha),r=this.ctx;this.save(t);const{filter:a}=r;"none"!==a&&""!==a&&(r.filter="none"),r.scale(1/s,-1/i);let o,h=null;if(e.bitmap){const t=this.applyTransferMapsToBitmap(e);o=t.img,h=t.canvasEntry}else if("function"==typeof HTMLElement&&e instanceof HTMLElement||!e.data)o=e;else{const t=this.canvasFactory.create(s,i);Ds(t.context,e),o=this.applyTransferMapsToCanvas(t.context),h=t}const l=this._scaleImage(o,Ot(r));r.imageSmoothingEnabled=Rs(Rt(r),e.interpolate),this.dependencyTracker&&(this.dependencyTracker.resetBBox(t).recordBBox(t,r,0,s,-i,0).recordDependencies(t,xe).recordOperation(t),this.imagesTracker?.record(r,s,i,this.dependencyTracker.clipBox)),Es(r,l.img,0,0,l.paintWidth,l.paintHeight,0,-i,s,i),l.tmpCanvas&&this.canvasFactory.destroy(l.tmpCanvas),h&&this.canvasFactory.destroy(h),this.compose(),this.restore(t),this.#nn(n)}paintInlineImageXObjectGroup(t,e,s){if(!this.contentVisible)return;const i=this.#in(this.current.fillAlpha),n=this.ctx;let r,a=null;if(e.bitmap)r=e.bitmap;else{const t=e.width,s=e.height,i=this.canvasFactory.create(t,s);Ds(i.context,e),r=this.applyTransferMapsToCanvas(i.context),a=i}this.dependencyTracker?.resetBBox(t);for(const o of s)n.save(),n.transform(...o.transform),n.scale(1,-1),Es(n,r,o.x,o.y,o.w,o.h,0,-1,1,1),this.dependencyTracker?.recordBBox(t,n,0,1,-1,0),n.restore();a&&this.canvasFactory.destroy(a),this.dependencyTracker?.recordOperation(t),this.compose(),this.#nn(i)}paintSolidColorImageMask(t){if(!this.contentVisible)return;const e=this.#in(this.current.fillAlpha);this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,_e).recordOperation(t),this.ctx.fillRect(0,0,1,1),this.compose(),this.#nn(e)}markPoint(t,e){}markPointProps(t,e,s){}beginMarkedContent(t,e){this.dependencyTracker?.beginMarkedContent(t),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e,s){this.dependencyTracker?.beginMarkedContent(t),"OC"===e?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(s)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(t){this.dependencyTracker?.endMarkedContent(t),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(t){}endCompat(t){}consumePath(t,e,s){const i=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(s);const n=this.ctx;this.pendingClip?(i||(this.pendingClip===Us?n.clip(e,"evenodd"):n.clip(e)),this.pendingClip=null,this.dependencyTracker?.bboxToClipBoxDropOperation(t).recordFutureForcedDependency("clipPath",t)):this.dependencyTracker?.recordOperation(t),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=Rt(this.ctx);if(0===t[1]&&0===t[2])this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,a;if(0===s&&0===i){const s=Math.abs(e),i=Math.abs(n);if(s===i)if(0===t)r=a=1/s;else{const e=s*t;r=a=e<1?1/e:1}else if(0===t)r=1/s,a=1/i;else{const e=s*t,n=i*t;r=e<1?1/e:1,a=n<1?1/n:1}}else{const o=Math.abs(e*n-s*i),h=Math.hypot(e,s),l=Math.hypot(i,n);if(0===t)r=l/o,a=h/o;else{const e=t*o;r=l>e?l/e:1,a=h>e?h/e:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:s,current:{lineWidth:i}}=this,[n,r]=this.getScaleForStroking();if(n===r)return s.lineWidth=(i||1)*n,void s.stroke(t);const a=s.getLineDash();e&&s.save(),s.scale(n,r),ks.a=1/n,ks.d=1/r;const o=new Path2D;if(o.addPath(t,ks),a.length>0){const t=Math.max(n,r);s.setLineDash(a.map(e=>e/t)),s.lineDashOffset/=t}s.lineWidth=i||1,s.stroke(o),e&&s.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const vn in $)void 0!==js.prototype[vn]&&(js.prototype[$[vn]]=js.prototype[vn]);class Hs{#an=null;#on=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(t,e,s){this._source=t,this.#an=e,this.#on=s}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){return tt(!this._fullReader,"BasePDFStream.getFullReader can only be called once."),this._fullReader=new this.#an(this)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new this.#on(this,t,e);return this._rangeReaders.add(s),s}cancelAllRequests(t){this._fullReader?.cancel(t);for(const e of new Set(this._rangeReaders))e.cancel(t)}}class $s{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(t){this._stream=t}_callOnProgress(){this.onProgress?.({loaded:this._loaded,total:this._contentLength})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){Z("Abstract method `read` called")}cancel(t){Z("Abstract method `cancel` called")}}class zs{_stream=null;constructor(t,e,s){this._stream=t}async read(){Z("Abstract method `read` called")}cancel(t){Z("Abstract method `cancel` called")}}function Gs(t,e){const s=new Headers;if(!t||!e||"object"!=typeof e)return s;for(const i in e){const t=e[i];void 0!==t&&s.append(i,t)}return s}function Ws(t){return URL.parse(t)?.origin??null}function Vs({responseHeaders:t,isHttp:e,rangeChunkSize:s,disableRange:i}){const n={contentLength:0,isRangeSupported:!1},r=parseInt(t.get("Content-Length"),10);return Number.isInteger(r)?(n.contentLength=r,r<=2*s||i||!e||"bytes"!==t.get("Accept-Ranges")||"identity"===(t.get("Content-Encoding")||"identity")&&(n.isRangeSupported=!0),n):n}function Xs(t){const e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,s=i("filename\\*","i").exec(t);if(s){s=s[1];let t=a(s);return t=unescape(t),t=o(t),t=h(t),r(t)}if(s=function(t){const e=[];let s;const n=i("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(s=n.exec(t));){let[,t,i,n]=s;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[i,n]}const r=[];for(let i=0;i<e.length&&i in e;++i){let[t,s]=e[i];s=a(s),t&&(s=unescape(s),0===i&&(s=o(s))),r.push(s)}return r.join("")}(t),s)return r(h(s));if(s=i("filename","i").exec(t),s){s=s[1];let t=a(s);return t=h(t),r(t)}function i(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function n(t,s){if(t){if(!/^[\x00-\xFF]+$/.test(s))return s;try{const i=new TextDecoder(t,{fatal:!0}),n=dt(s);s=i.decode(n),e=!1}catch{}}return s}function r(t){return e&&/[\x80-\xff]/.test(t)&&(t=n("utf-8",t),e&&(t=n("iso-8859-1",t))),t}function a(t){if(t.startsWith('"')){const e=t.slice(1).split('\\"');for(let t=0;t<e.length;++t){const s=e[t].indexOf('"');-1!==s&&(e[t]=e[t].slice(0,s),e.length=t+1),e[t]=e[t].replaceAll(/\\(.)/g,"$1")}t=e.join('"')}return t}function o(t){const e=t.indexOf("'");return-1===e?t:n(t.slice(0,e),t.slice(e+1).replace(/^[^']*'/,""))}function h(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(t,e,s,i){if("q"===s||"Q"===s)return n(e,i=(i=i.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}));try{i=atob(i)}catch{}return n(e,i)})}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(Tt(t))return t}return null}function Ys(t,e){return new ht(`Unexpected server response (${t}) while retrieving PDF "${e.href}".`,t,404===t||0===t&&"file:"===e.protocol)}function qs(t,e){if(t!==e)throw new Error(`Expected range response-origin "${t}" to match "${e}".`)}function Ks(t,e,s,i){return fetch(t,{method:"GET",headers:e,signal:i.signal,mode:"cors",credentials:s?"include":"same-origin",redirect:"follow"})}function Qs(t,e){if(200!==t&&206!==t)throw Ys(t,e)}function Js(t){if(t instanceof Uint8Array)return t.buffer;if(t instanceof ArrayBuffer)return t;throw new Error(`getArrayBuffer - unexpected data: ${t}`)}class Zs extends Hs{_responseOrigin=null;constructor(t){super(t,ti,ei);const{httpHeaders:e,url:s}=t;tt(/https?:/.test(s.protocol),"PDFFetchStream only supports http(s):// URLs."),this.headers=Gs(!0,e)}}class ti extends $s{_abortController=new AbortController;_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:s,rangeChunkSize:i,url:n,withCredentials:r}=t._source;this._isStreamingSupported=!s;const a=new Headers(t.headers);Ks(n,a,r,this._abortController).then(s=>{t._responseOrigin=Ws(s.url),Qs(s.status,n),this._reader=s.body.getReader();const r=s.headers,{contentLength:a,isRangeSupported:o}=Vs({responseHeaders:r,isHttp:!0,rangeChunkSize:i,disableRange:e});this._contentLength=a,this._isRangeSupported=o,this._filename=Xs(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new ct("Streaming is disabled.")),this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:Js(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class ei extends zs{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,s){super(t,e,s);const{url:i,withCredentials:n}=t._source,r=new Headers(t.headers);r.append("Range",`bytes=${e}-${s-1}`),Ks(i,r,n,this._abortController).then(e=>{qs(Ws(e.url),t._responseOrigin),Qs(e.status,i),this._reader=e.body.getReader(),this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:Js(t),done:!1}}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}function si(t){return t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function ii(){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}class ni extends Hs{_progressiveDone=!1;_queuedChunks=[];constructor(t){super(t,ri,ai);const{pdfDataRangeTransport:e}=t,{initialData:s,progressiveDone:i}=e;if(s?.length>0){const t=si(s);this._queuedChunks.push(t)}this._progressiveDone=i,e.transportReady(t=>{switch(t.type){case"range":case"progressiveRead":this.#hn(t.begin,t.chunk);break;case"progressiveDone":this._fullReader?.progressiveDone(),this._progressiveDone=!0}})}#hn(t,e){const s=si(e);if(void 0===t)this._fullReader?this._fullReader._enqueue(s):this._queuedChunks.push(s);else{const e=this._rangeReaders.keys().find(e=>e._begin===t);tt(e,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),e._enqueue(s)}}getFullReader(){const t=super.getFullReader();return this._queuedChunks=null,t}getRangeReader(t,e){const s=super.getRangeReader(t,e);return s&&(s.onDone=()=>this._rangeReaders.delete(s),this._source.pdfDataRangeTransport.requestDataRange(t,e)),s}cancelAllRequests(t){super.cancelAllRequests(t),this._source.pdfDataRangeTransport.abort()}}class ri extends $s{#ln=ii.bind(this);_done=!1;_queuedChunks=null;_requests=[];constructor(t){super(t);const{pdfDataRangeTransport:e,disableRange:s,disableStream:i}=t._source,{length:n,contentDispositionFilename:r}=e;this._queuedChunks=t._queuedChunks||[];for(const o of this._queuedChunks)this._loaded+=o.byteLength;this._done=t._progressiveDone,this._contentLength=n,this._isStreamingSupported=!i,this._isRangeSupported=!s,Tt(r)&&(this._filename=r),this._headersCapability.resolve();const a=this._loaded;Promise.resolve().then(()=>{a>0&&this._loaded===a&&this._callOnProgress()})}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength,this._callOnProgress())}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this.#ln()}progressiveDone(){this._done||=!0,0===this._queuedChunks.length&&this.#ln()}}class ai extends zs{#ln=ii.bind(this);onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(t,e,s){super(t,e,s),this._begin=e}_enqueue(t){this._done||(0===this._requests.length?this._queuedChunk=t:(this._requests.shift().resolve({value:t,done:!1}),this.#ln()),this._done=!0,this.onDone?.())}async read(){if(this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this.#ln(),this.onDone?.()}}class oi extends Hs{#cn=new WeakMap;_responseOrigin=null;constructor(t){super(t,hi,li);const{httpHeaders:e,url:s}=t;this.url=s,this.isHttp=/https?:/.test(s.protocol),this.headers=Gs(this.isHttp,e)}_request(t){const e=new XMLHttpRequest,s={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};this.#cn.set(e,s),e.open("GET",this.url),e.withCredentials=this._source.withCredentials;for(const[i,n]of this.headers)e.setRequestHeader(i,n);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),s.validateStatus=t=>206===t||200===t):s.validateStatus=t=>200===t,e.responseType="arraybuffer",tt(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>t.onError(e.status),e.onreadystatechange=this.#dn.bind(this,e),e.onprogress=this.#un.bind(this,e),e.send(null),e}#un(t,e){const s=this.#cn.get(t);s?.onProgress?.(e)}#dn(t,e){const s=this.#cn.get(t);if(!s)return;if(t.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),4!==t.readyState)return;if(!this.#cn.has(t))return;if(this.#cn.delete(t),0===t.status&&this.isHttp)return void s.onError(t.status);const i=t.status||200;if(!s.validateStatus(i))return void s.onError(t.status);const n=function(t){return"string"!=typeof t?t:dt(t).buffer}(t.response);if(206===i){const e=t.getResponseHeader("Content-Range");/bytes (\d+)-(\d+)\/(\d+)/.test(e)?s.onDone(n):(J('Missing or invalid "Content-Range" header.'),s.onError(0))}else n?s.onDone(n):s.onError(t.status)}_abortRequest(t){this.#cn.has(t)&&(this.#cn.delete(t),t.abort())}getRangeReader(t,e){const s=super.getRangeReader(t,e);return s&&(s.onClosed=()=>this._rangeReaders.delete(s)),s}}class hi extends $s{#ln=ii.bind(this);_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(t){super(t),this._fullRequestXhr=t._request({onHeadersReceived:this.#pn.bind(this),onDone:this.#gn.bind(this),onError:this.#mn.bind(this),onProgress:this.#un.bind(this)})}#pn(){const t=this._stream,{disableRange:e,rangeChunkSize:s}=t._source,i=this._fullRequestXhr;t._responseOrigin=Ws(i.responseURL);const n=i.getAllResponseHeaders(),r=new Headers(n?n.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(t=>{const[e,...s]=t.split(": ");return[e,s.join(": ")]}):[]),{contentLength:a,isRangeSupported:o}=Vs({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:s,disableRange:e});this._contentLength=a,this._isRangeSupported=o,this._filename=Xs(r),this._isRangeSupported&&t._abortRequest(i),this._headersCapability.resolve()}#gn(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._cachedChunks.push(t),this._done=!0,0===this._cachedChunks.length&&this.#ln()}#mn(t){this._storedError=Ys(t,this._stream.url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}#un(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t),this.#ln(),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}}class li extends zs{#ln=ii.bind(this);onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(t,e,s){super(t,e,s),this._requestXhr=t._request({begin:e,end:s,onHeadersReceived:this.#pn.bind(this),onDone:this.#gn.bind(this),onError:this.#mn.bind(this),onProgress:null})}#pn(){const t=Ws(this._requestXhr?.responseURL);try{qs(t,this._stream._responseOrigin)}catch(t){this._storedError=t,this.#mn(0)}}#gn(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0,this.#ln(),this.onClosed?.()}#mn(t){this._storedError??=Ys(t,this._stream.url);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this.#ln(),this._stream._abortRequest(this._requestXhr),this.onClosed?.()}}function ci(t,e=null){const s=process.getBuiltinModule("fs"),{Readable:i}=process.getBuiltinModule("stream"),n=s.createReadStream(t,e);return i.toWeb(n)}class di extends Hs{constructor(t){super(t,ui,pi);const{url:e}=t;tt("file:"===e.protocol,"PDFNodeStream only supports file:// URLs.")}}class ui extends $s{_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:s,rangeChunkSize:i,url:n}=t._source;this._isStreamingSupported=!s,process.getBuiltinModule("fs/promises").lstat(n).then(t=>{const s=ci(n);this._reader=s.getReader();const{size:r}=t;this._contentLength=r,this._isRangeSupported=!e&&r>2*i,!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new ct("Streaming is disabled.")),this._headersCapability.resolve()}).catch(t=>{"ENOENT"===t.code&&(t=Ys(0,n)),this._headersCapability.reject(t)})}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:Js(t),done:!1})}cancel(t){this._reader?.cancel(t)}}class pi extends zs{_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,s){super(t,e,s);const{url:i}=t._source;try{const t=ci(i,{start:e,end:s-1});this._reader=t.getReader(),this._readCapability.resolve()}catch(t){this._readCapability.reject(t)}}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:Js(t),done:!1}}cancel(t){this._reader?.cancel(t)}}class gi{static#fn=null;static#bn="";static get workerPort(){return this.#fn}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#fn=t}static get workerSrc(){return this.#bn}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#bn=t}}class mi{#yn;#An;constructor({parsedData:t,rawData:e}){this.#yn=t,this.#An=e}getRaw(){return this.#An}get(t){return this.#yn.get(t)??null}[Symbol.iterator](){return this.#yn.entries()}}const fi=Symbol("INTERNAL");class bi{#wn=!1;#vn=!1;#_n=!1;#xn=!0;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#wn=!!(t&b),this.#vn=!!(t&y),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(this.#_n)return this.#xn;if(!this.#xn)return!1;const{print:t,view:e}=this.usage;return this.#wn?"OFF"!==e?.viewState:!this.#vn||"OFF"!==t?.printState}_setVisible(t,e,s=!1){t!==fi&&Z("Internal method `_setVisible` called."),this.#_n=s,this.#xn=e}}class yi{#Sn=null;#Cn=new Map;#kn=null;#Tn=null;constructor(t,e=b){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#Tn=t.order;for(const s of t.groups)this.#Cn.set(s.id,new bi(e,s));if("OFF"===t.baseState)for(const t of this.#Cn.values())t._setVisible(fi,!1);for(const e of t.on)this.#Cn.get(e)._setVisible(fi,!0);for(const e of t.off)this.#Cn.get(e)._setVisible(fi,!1);this.#kn=this.getHash()}}#Mn(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const e=t[i];let n;if(Array.isArray(e))n=this.#Mn(e);else{if(!this.#Cn.has(e))return J(`Optional content group not found: ${e}`),!0;n=this.#Cn.get(e).visible}switch(s){case"And":if(!n)return!1;break;case"Or":if(n)return!0;break;case"Not":return!n;default:return!0}}return"And"===s}isVisible(t){if(0===this.#Cn.size)return!0;if(!t)return Q("Optional content group not defined."),!0;if("OCG"===t.type)return this.#Cn.has(t.id)?this.#Cn.get(t.id).visible:(J(`Optional content group not found: ${t.id}`),!0);if("OCMD"===t.type){if(t.expression)return this.#Mn(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#Cn.has(e))return J(`Optional content group not found: ${e}`),!0;if(this.#Cn.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#Cn.has(e))return J(`Optional content group not found: ${e}`),!0;if(!this.#Cn.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#Cn.has(e))return J(`Optional content group not found: ${e}`),!0;if(!this.#Cn.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#Cn.has(e))return J(`Optional content group not found: ${e}`),!0;if(this.#Cn.get(e).visible)return!1}return!0}return J(`Unknown optional content policy ${t.policy}.`),!0}return J(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){const i=this.#Cn.get(t);if(i){if(s&&e&&i.rbGroups.length)for(const e of i.rbGroups)for(const s of e)s!==t&&this.#Cn.get(s)?._setVisible(fi,!1,!0);i._setVisible(fi,!!e,!0),this.#Sn=null}else J(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let s;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const t=this.#Cn.get(i);if(t)switch(s){case"ON":this.setVisibility(i,!0,e);break;case"OFF":this.setVisibility(i,!1,e);break;case"Toggle":this.setVisibility(i,!t.visible,e)}}this.#Sn=null}get hasInitialVisibility(){return null===this.#kn||this.getHash()===this.#kn}getOrder(){return this.#Cn.size?this.#Tn?this.#Tn.slice():[...this.#Cn.keys()]:null}getGroup(t){return this.#Cn.get(t)||null}getHash(){if(null!==this.#Sn)return this.#Sn;const t=new oe;for(const[e,s]of this.#Cn)t.update(`${e}:${s.visible}`);return this.#Sn=t.hexdigest()}[Symbol.iterator](){return this.#Cn.entries()}}class Ai{#En=null;#Pn=null;#Dn=0;#In=null;#Fn=null;get pagesNumber(){return this.#Dn}set pagesNumber(t){this.#Dn!==t&&(this.#Dn=t,this.#En=null,this.#Pn=null)}#Nn(){if(this.#En)return;const t=this.#Dn,e=this.#En=new Uint32Array(t);for(let s=0;s<t;s++)e[s]=s+1;this.#Pn=new Int32Array(e)}#Rn(){const t=new Map,e=this.#En;for(let s=0,i=this.#Dn;s<i;s++){const i=e[s],n=t.get(i);n?n.push(s+1):t.set(i,[s+1])}return t}movePages(t,e,s){this.#Nn();const i=this.#En,n=this.#Rn(),r=e.length,a=new Uint32Array(r);let o=0;for(let d=0;d<r;d++){const t=e[d]-1;a[d]=i[t],t<s&&o++}const h=this.#Dn,l=h-r,c=yt(s-o,0,l);for(let d=0,u=0;d<h;d++)t.has(d+1)||(i[u++]=i[d]);i.copyWithin(c+r,c,l),i.set(a,c),this.#On(n),i.every((t,e)=>t===e+1)&&(this.#En=null)}deletePages(t){this.#Nn();const e=this.#En,s=this.#Rn();this.#Fn={pageNumberToId:e.slice(),pagesNumber:this.#Dn,prevPageNumbers:this.#Pn.slice()};const i=this.#Dn-t.length;this.#Dn=i;const n=this.#En=new Uint32Array(i);this.#Pn=new Int32Array(i);let r=0,a=0;for(const o of t){const t=o-1;t!==r&&(n.set(e.subarray(r,t),a),a+=t-r),r=t+1}r<e.length&&n.set(e.subarray(r),a),this.#On(s,new Set(t))}cancelDelete(){this.#Fn&&(this.#En=this.#Fn.pageNumberToId,this.#Dn=this.#Fn.pagesNumber,this.#Pn=this.#Fn.prevPageNumbers,this.#Fn=null)}cleanSavedData(){this.#Fn=null}copyPages(t){this.#Nn(),this.#In={pageNumbers:t,pageIds:t.map(t=>this.#En[t-1])}}cancelCopy(){this.#In=null}pastePages(t){this.#Nn();const e=this.#En,s=this.#Rn(),{pageNumbers:i,pageIds:n}=this.#In,r=this.#Dn+i.length;this.#Dn=r;const a=this.#En=new Uint32Array(r);this.#Pn=new Int32Array(r),a.set(e.subarray(0,t),0),a.set(n,t),a.set(e.subarray(t),t+i.length),this.#On(s,null,t,i),this.#In=null}#On(t,e=null,s=-1,i=null){const n=this.#Pn,r=this.#En,a=s+(i?.length??0),o=new Map;for(let h=0,l=this.#Dn;h<l;h++){if(h>=s&&h<a){n[h]=-i[h-s];continue}const l=r[h],c=t.get(l);let d=o.get(l)||0;if(e&&c)for(;d<c.length&&e.has(c[d]);)d++;n[h]=c?.[d],o.set(l,d+1)}}hasBeenAltered(){return null!==this.#En}getPageMappingForSaving(t=null){t??=this.#Rn();let e=0;for(const i of t.values())e=Math.max(e,i.length);const s=new Array(e);for(let i=0;i<e;i++)s[i]={document:null,pageIndices:[],includePages:[]};for(const[i,n]of t)for(let t=0,e=n.length;t<e;t++)s[t].includePages.push([i-1,n[t]-1]);for(const{includePages:i,pageIndices:n}of s){i.sort((t,e)=>t[0]-e[0]);for(let t=0,e=i.length;t<e;t++)n.push(i[t][1]),i[t]=i[t][0]}return s}extractPages(t){t=Array.from(t).sort((t,e)=>t-e);const e=new Map;for(let s=0,i=t.length;s<i;s++){const i=this.getPageId(t[s]);e.getOrInsertComputed(i,mt).push(s+1)}return this.getPageMappingForSaving(e)}getPrevPageNumber(t){return this.#Pn?.[t-1]??0}getPageNumber(t){if(!this.#En)return t;const e=this.#En;for(let s=0,i=this.#Dn;s<i;s++)if(e[s]===t)return s+1;return 0}getPageId(t){return this.#En?.[t-1]??t}getMapping(){return this.#En?.subarray(0,this.pagesNumber)}}const wi=Symbol("INITIAL_DATA"),vi=()=>({...Promise.withResolvers(),data:wi});class _i{#Bn=new Map;get(t,e=null){if(e){const s=this.#Bn.getOrInsertComputed(t,vi);return s.promise.then(()=>e(s.data)),null}const s=this.#Bn.get(t);if(!s||s.data===wi)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#Bn.get(t);return!!e&&e.data!==wi}delete(t){const e=this.#Bn.get(t);return!(!e||e.data===wi)&&(this.#Bn.delete(t),!0)}resolve(t,e=null){const s=this.#Bn.getOrInsertComputed(t,vi);if(s.data!==wi)throw new Error(`Object already resolved ${t}.`);s.data=e,s.resolve()}clear(){for(const{data:t}of this.#Bn.values())t?.bitmap?.close();this.#Bn.clear()}*[Symbol.iterator](){for(const[t,{data:e}]of this.#Bn)e!==wi&&(yield[t,e])}}class xi{#Ln=Promise.withResolvers();#Tt=null;#Un=!1;#jn=!!globalThis.FontInspector?.enabled;#Hn=null;#$n=null;#zn=null;#Gn=0;#Wn=0;#Vn=null;#Xn=null;#Yn=0;#qn=0;#Kn=Object.create(null);#Qn=[];#Jn=null;#Zn=[];#tr=new WeakMap;#er=null;static#sr=new Map;static#ir=new Map;static#nr=new WeakMap;static#rr=null;static#ar=new Set;constructor({textContentSource:t,images:e,container:s,viewport:i}){if(t instanceof ReadableStream)this.#Jn=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#Jn=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#Tt=this.#Xn=s,this.#Hn=e,this.#qn=i.scale*Lt.pixelRatio,this.#Yn=i.rotation,this.#zn={div:null,properties:null,ctx:null};const{pageWidth:n,pageHeight:r,pageX:a,pageY:o}=i.rawDims;this.#er=[1,0,0,-1,-a,o+r],this.#Wn=n,this.#Gn=r,xi.#or(),s.style.setProperty("--min-font-size",xi.#rr),Bt(s,i),this.#Ln.promise.finally(()=>{xi.#ar.delete(this),this.#zn=null,this.#Kn=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=ut.platform;return it(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){this.#Hn&&this.#Tt.append(this.#Hn.render());const t=()=>{this.#Vn.read().then(({value:e,done:s})=>{s?this.#Ln.resolve():(this.#$n??=e.lang,Object.assign(this.#Kn,e.styles),this.#hr(e.items),t())},this.#Ln.reject)};return this.#Vn=this.#Jn.getReader(),xi.#ar.add(this),t(),this.#Ln.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*Lt.pixelRatio,i=t.rotation;if(i!==this.#Yn&&(e?.(),this.#Yn=i,Bt(this.#Xn,{rotation:i})),s!==this.#qn){e?.(),this.#qn=s;const t={div:null,properties:null,ctx:xi.#lr(this.#$n)};for(const e of this.#Zn)t.properties=this.#tr.get(e),t.div=e,this.#cr(t)}}cancel(){const t=new ct("TextLayer task cancelled.");this.#Vn?.cancel(t).catch(()=>{}),this.#Vn=null,this.#Ln.reject(t)}get textDivs(){return this.#Zn}get textContentItemsStr(){return this.#Qn}#hr(t){if(this.#Un)return;this.#zn.ctx??=xi.#lr(this.#$n);const e=this.#Zn,s=this.#Qn;for(const i of t){if(e.length>1e5)return J("Ignoring additional textDivs for performance reasons."),void(this.#Un=!0);if(void 0!==i.str)s.push(i.str),this.#dr(i);else if("beginMarkedContentProps"===i.type||"beginMarkedContent"===i.type){const t=this.#Tt;this.#Tt=document.createElement("span"),this.#Tt.classList.add("markedContent"),i.id&&this.#Tt.setAttribute("id",`${i.id}`),"Artifact"===i.tag&&(this.#Tt.ariaHidden=!0),t.append(this.#Tt)}else"endMarkedContent"===i.type&&(this.#Tt=this.#Tt.parentNode)}}#dr(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Zn.push(e);const i=pt.transform(this.#er,t.transform);let n=Math.atan2(i[1],i[0]);const r=this.#Kn[t.fontName];r.vertical&&(n+=Math.PI/2);let a=this.#jn&&r.fontSubstitution||r.fontFamily;a=xi.fontFamilyMap.get(a)||a;const o=Math.hypot(i[2],i[3]),h=o*xi.#ur(a,r,this.#$n);let l,c;0===n?(l=i[4],c=i[5]-h):(l=i[4]+h*Math.sin(n),c=i[5]-h*Math.cos(n));const d=e.style;d.left=`${(100*l/this.#Wn).toFixed(2)}%`,d.top=`${(100*c/this.#Gn).toFixed(2)}%`,d.setProperty("--font-height",`${o.toFixed(2)}px`),d.fontFamily=a,s.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#jn&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),0!==n&&(s.angle=n*(180/Math.PI));let u=!1;if(t.str.length>1)u=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),s=Math.abs(t.transform[3]);e!==s&&Math.max(e,s)/Math.min(e,s)>1.5&&(u=!0)}if(u&&(s.canvasWidth=r.vertical?t.height:t.width),this.#tr.set(e,s),this.#zn.div=e,this.#zn.properties=s,this.#cr(this.#zn),s.hasText&&this.#Tt.append(e),s.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#Tt.append(t)}}#cr(t){const{div:e,properties:s,ctx:i}=t,{style:n}=e;if(0!==s.canvasWidth&&s.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:a}=s;xi.#pr(i,a*this.#qn,t);const{width:o}=i.measureText(e.textContent);o>0&&n.setProperty("--scale-x",r*this.#qn/o)}0!==s.angle&&n.setProperty("--rotate",`${s.angle}deg`)}static cleanup(){if(!(this.#ar.size>0)){this.#sr.clear();for(const{canvas:t}of this.#ir.values())t.remove();this.#ir.clear()}}static#lr(t=null){let e=this.#ir.get(t||="");if(!e){const s=document.createElement("canvas");s.className="hiddenCanvasElement",s.lang=t,document.body.append(s),e=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#ir.set(t,e),this.#nr.set(e,{size:0,family:""})}return e}static#pr(t,e,s){const i=this.#nr.get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)}static#or(){if(null!==this.#rr)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#rr=t.getBoundingClientRect().height,t.remove()}static#ur(t,e,s){const i=this.#sr.get(t);if(i)return i;const n=this.#lr(s);n.canvas.width=n.canvas.height=30,this.#pr(n,30,t);const r=n.measureText(""),a=r.fontBoundingBoxAscent,o=Math.abs(r.fontBoundingBoxDescent);n.canvas.width=n.canvas.height=0;let h=.8;return a?h=a/(a+o):(ut.platform.isFirefox&&J("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),e.ascent?h=e.ascent:e.descent&&(h=1+e.descent)),this.#sr.set(t,h),h}}function Si(t={}){const e=new Ci,{docId:s}=e,i=t.url?function(t){if(t instanceof URL)return t;if("string"==typeof t){if(d){if(/^[a-z][a-z0-9\-+.]+:/i.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}const e=URL.parse(t,window.location);if(e)return e}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,n=t.data?function(t){if(d&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return dt(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,a=!0===t.withCredentials,o=t.password??null,h=t.range instanceof ki?t.range:null,l=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:65536;let c=t.worker instanceof Ei?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||kt(t.docBaseUrl)?null:t.docBaseUrl,g=je(t.cMapUrl),m=!1!==t.cMapPacked,f=je(t.iccUrl),b=je(t.standardFontDataUrl),y=je(t.wasmUrl),A=!0!==t.stopAtErrors,w=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,v="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!d,_="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!d,x=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,S="boolean"==typeof t.disableFontFace?t.disableFontFace:d,C=!0===t.fontExtraProperties,k=!0===t.enableXfa,T=t.ownerDocument||globalThis.document,M=!0===t.disableRange,E=!0===t.disableStream,P=!0===t.disableAutoFetch,D=!0===t.pdfBug,I=t.CanvasFactory||(d?ls:rs),F=t.FilterFactory||(d?hs:os),N=t.BinaryDataFactory||(d?cs:is),R=!0===t.enableHWA,O=!0===t.enableWebGPU?ds.init():Promise.resolve(!1),B=!1!==t.useWasm,L=t.pagesMapper||new Ai,U="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!d&&!S,j="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:!!(N===is&&g&&m&&b&&y&&Et(g,document.baseURI)&&Et(b,document.baseURI)&&Et(y,document.baseURI));q(u);const H={canvasFactory:new I({ownerDocument:T,enableHWA:R}),filterFactory:new F({docId:s,ownerDocument:T}),binaryDataFactory:j?null:new N({cMapUrl:g,standardFontDataUrl:b,wasmUrl:y})};c||(c=Ei.create({verbosity:u,port:gi.workerPort}),e._worker=c);const $={docId:s,apiVersion:"6.0.92",data:n,password:o,disableAutoFetch:P,rangeChunkSize:l,docBaseUrl:p,enableXfa:k,evaluatorOptions:{maxImageSize:w,disableFontFace:S,ignoreErrors:A,isOffscreenCanvasSupported:v,isImageDecoderSupported:_,canvasMaxAreaInBytes:x,fontExtraProperties:C,useSystemFonts:U,useWasm:B,useWorkerFetch:j,cMapUrl:g,cMapPacked:m,iccUrl:f,standardFontDataUrl:b,wasmUrl:y,hasGPU:!1}},z={ownerDocument:T,pdfBug:D,styleElement:null,enableHWA:R,loadingParams:{disableAutoFetch:P,enableXfa:k}};return Promise.all([c.promise,O]).then(function([,t]){if(c.destroyed)throw new Error("Worker was destroyed");$.evaluatorOptions.hasGPU=t;const o=c.messageHandler.sendWithPromise("GetDocRequest",$,n?[n.buffer]:null);let u;if(n);else if(h)u=new ni({pdfDataRangeTransport:h,disableRange:M,disableStream:E});else{if(!i)throw new Error("getDocument - expected either `data`, `range`, or `url` parameter.");{const t=function(t){return Et(t)?Zs:d?di:oi}(i);u=new t({url:i,httpHeaders:r,withCredentials:a,rangeChunkSize:l,disableRange:M,disableStream:E})}}return o.then(t=>{if(c.destroyed)throw new Error("Worker was destroyed");const i=new es(s,t,c.port),n=new Pi(i,e,u,z,H,L);if(e._transport=n,e.destroyed)throw new Error("Loading aborted");i.send("Ready",null)})}).catch(e._capability.reject).finally(e._setupCapability.resolve),e}class Ci{static#_i=0;_capability=Promise.withResolvers();_setupCapability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+Ci.#_i++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0,this._capability.promise.catch(()=>{});try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._setupCapability.promise,await(this._transport?.destroy())}catch(d){throw this._worker?.port&&delete this._worker._pendingDestroy,d}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}}class ki{#Ln=Promise.withResolvers();#gr=null;constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i}onDataRange(t,e){this.#gr({type:"range",begin:t,chunk:e})}onDataProgressiveRead(t){this.#Ln.promise.then(()=>{this.#gr({type:"progressiveRead",chunk:t})})}onDataProgressiveDone(){this.#Ln.promise.then(()=>{this.#gr({type:"progressiveDone"})})}transportReady(t){this.#gr=t,this.#Ln.resolve()}requestDataRange(t,e){Z("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Ti{constructor(t,e){this._pdfInfo=t,this._transport=e}get pagesMapper(){return this._transport.pagesMapper}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return it(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAnnotationsByType(t,e){return this._transport.getAnnotationsByType(t,e)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(t){return this._transport.extractPages(t)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}getRawData(t){return this._transport.getRawData(t)}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class Mi{#mr=!1;#fr=null;constructor(t,e,s,i,n=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=n?new Mt:null,this._pdfBug=n,this.commonObjs=s.commonObjs,this.objs=new _i,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,this.#fr=i,this.imageCoordinates=null}clone(t){const e=new Mi(t,this._pageInfo,this._transport,this.#fr,this._pdfBug);return e.clonedFromIndex=this.clonedFromIndex??this._pageIndex,this._transport.updatePage(e),e}get pageNumber(){return this._pageIndex+1}set pageNumber(t){this._pageIndex=t-1,this._transport.updatePage(this)}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new St({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return it(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:e=t.canvas,viewport:s,intent:i="display",annotationMode:n=S.ENABLE,transform:r=null,background:a=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:l=null,printAnnotationStorage:c=null,isEditing:d=!1,recordImages:u=!1,recordOperations:p=!1,operationsFilter:g=null,renderingBudget:m=null,renderingScheduler:f=null}){this._stats?.time("Overall");const b=this._transport.getRenderingIntent(i,n,c,d),{renderingIntent:A,cacheKey:w}=b;this.#mr=!1,o||=this._transport.getOptionalContentConfig(A);const v=this._intentStates.getOrInsertComputed(w,bt);v.streamReaderCancelTimeout&&(clearTimeout(v.streamReaderCancelTimeout),v.streamReaderCancelTimeout=null);const _=!!(A&y);v.displayReadyCapability||(v.displayReadyCapability=Promise.withResolvers(),v.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(b));const x=!(!this._pdfBug||!globalThis.StepperManager?.enabled),C=!!e&&!this.recordedBBoxes&&(p||x),k=!!e&&!this.imageCoordinates&&u,T=t=>{if(v.renderTasks.delete(P),C){const t=P.gfx?.dependencyTracker.take();t&&(P.stepper?.setOperatorBBoxes(t,P.gfx.dependencyTracker.takeDebugMetadata()),p&&(this.recordedBBoxes=t))}k&&!t&&(this.imageCoordinates=P.gfx?.imagesTracker.take()),_&&(this.#mr=!0),this.#br(),t?(P.capability.reject(t),this._abortOperatorList({intentState:v,reason:t instanceof Error?t:new Error(t)})):P.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))};let M=null,E=null;(C||k)&&(E=new ye(e,v.operatorList.length)),C&&(M=new Ae(E,x));const P=new Ii({callback:T,params:{canvas:e,canvasContext:t,dependencyTracker:M??E,imagesTracker:k?new Me(e):null,viewport:s,transform:r,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:v.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!_,pdfBug:this._pdfBug,pageColors:l,enableHWA:this._transport.enableHWA,operationsFilter:g,renderingBudget:m,renderingScheduler:f});(v.renderTasks||=new Set).add(P);const D=P.task;return Promise.all([v.displayReadyCapability.promise,o]).then(([t,e])=>{if(this.destroyed)T();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&A))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");P.initializeGraphics({transparency:t,optionalContentConfig:e}),P.operatorListChanged()}}).catch(T),D}getOperatorList({intent:t="display",annotationMode:e=S.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){const n=this._transport.getRenderingIntent(t,e,s,i,!0),r=this._intentStates.getOrInsertComputed(n.cacheKey,bt);let a;return r.opListReadCapability||(a=Object.create(null),a.operatorListChanged=function(){r.operatorList.lastChunk&&(r.opListReadCapability.resolve(r.operatorList),r.renderTasks.delete(a))},r.opListReadCapability=Promise.withResolvers(),(r.renderTasks||=new Set).add(a),r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(n)),r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:this.#fr.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}async getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>At.textContent(t));const e=this.streamTextContent(t),s={items:[],styles:Object.create(null),lang:null};for await(const i of e)s.lang??=i.lang,Object.assign(s.styles,i.styles),s.items.push(...i.items);return s}getStructTree(){return this._transport.getStructTree(this._pageIndex)}getGeoPDFMetadata(){return this._transport.getGeoPDFMetadata(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),this.#mr=!1,Promise.all(t)}cleanup(t=!1){this.#mr=!0;const e=this.#br();return t&&e&&(this._stats&&=new Mt),e}#br(){if(!this.#mr||this.destroyed)return!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#mr=!1,!0}_startRenderPage(t,e){const s=this._intentStates.get(e);s&&(this._stats?.timeEnd("Page Request"),s.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++)e.operatorList.fnArray.push(t.fnArray[s]),e.operatorList.argsArray.push(t.argsArray[s]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const s of e.renderTasks)s.operatorListChanged();t.lastChunk&&this.#br()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:r}=s,a=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageId:this.#fr.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},void 0,r).getReader(),o=this._intentStates.get(e);o.streamReader=a;const h=()=>{a.read().then(({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),h())},t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#br()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}})};h()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!s){if(t.renderTasks.size>0)return;if(e instanceof Ct){let s=100;return e.extraDelay>0&&e.extraDelay<1e3&&(s+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},s))}}if(t.streamReader.cancel(new ct(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[e,s]of this._intentStates)if(s===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class Ei{#Ln=Promise.withResolvers();#yr=null;#fn=null;#Ar=null;static#wr=0;static#vr=!1;static#_r=new WeakMap;static{d&&(this.#vr=!0,gi.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{const s=URL.parse(t);if(!s?.origin||"null"===s.origin)return!1;const i=new URL(e,s);return s.origin===i.origin},this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:s=K()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=s,e){if(Ei.#_r.has(e))throw new Error("Cannot use more than one PDFWorker per port.");Ei.#_r.set(e,this),this.#xr(e)}else this.#Sr()}get promise(){return this.#Ln.promise}#Cr(){this.#Ln.resolve(),this.#yr.send("configure",{verbosity:this.verbosity})}get port(){return this.#fn}get messageHandler(){return this.#yr}#xr(t){this.#fn=t,this.#yr=new es("main","worker",t),this.#yr.on("ready",()=>{}),this.#Cr()}#Sr(){if(Ei.#vr||Ei.#kr)return void this.#Tr();let{workerSrc:t}=Ei;try{Ei._isSameOrigin(window.location,t)||(t=Ei._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new es("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?this.#Ln.reject(new Error("Worker was destroyed")):this.#Tr()},n=new AbortController;e.addEventListener("error",()=>{this.#Ar||i()},{signal:n.signal}),s.on("test",t=>{n.abort(),!this.destroyed&&t?(this.#yr=s,this.#fn=e,this.#Ar=e,this.#Cr()):i()}),s.on("ready",t=>{if(n.abort(),this.destroyed)i();else try{r()}catch{this.#Tr()}});const r=()=>{const t=new Uint8Array;s.send("test",t,[t.buffer])};return void r()}catch{Q("The worker has been disabled.")}this.#Tr()}#Tr(){Ei.#vr||(J("Setting up fake worker."),Ei.#vr=!0),Ei._setupFakeWorkerGlobal.then(t=>{if(this.destroyed)return void this.#Ln.reject(new Error("Worker was destroyed"));const e=new $e;this.#fn=e;const s="fake"+Ei.#wr++,i=new es(s+"_worker",s,e);t.setup(i,e),this.#yr=new es(s,s+"_worker",e),this.#Cr()}).catch(t=>{this.#Ln.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this.#Ar?.terminate(),this.#Ar=null,Ei.#_r.delete(this.#fn),this.#fn=null,this.#yr?.destroy(),this.#yr=null}static create(t){const e=this.#_r.get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new Ei(t)}static get workerSrc(){if(gi.workerSrc)return gi.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#kr(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return it(this,"_setupFakeWorkerGlobal",(async()=>this.#kr?this.#kr:(await(import(
2
+ import{getAssetUrl as t}from"../../assets.js";import e from"../../request.js";import s from"../../core/Error.js";import{throwIfAborted as i}from"../../core/promiseUtils.js";import{create as n,fromValues as r}from"../../core/libs/gl-matrix-2/factories/mat2df64.js";import{invert as a}from"../../core/libs/gl-matrix-2/math/mat2d.js";import o from"../../geometry/Extent.js";import{projectIsLoaded as h,projectLoad as l}from"../../geometry/operators/projectOperator.js";import{renderBitmap as c}from"./renderExtentUtils.js";const d=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),u=[1/0,1/0,-1/0,-1/0],p=new Float32Array(u),g=[.001,0,0,.001,0,0],m=1.35,f=1,b=2,y=4,A=16,w=32,v=64,_=128,x=256,S={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},C="pdfjs_internal_id_",k="pdfjs_internal_editor_",T={NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101},M={CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},E=0,P=1,D=2,I=3,F=3,N=4,R={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},O=1,B=2,L=3,U=4,j=5,H={WARNINGS:1,INFOS:5},$={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},z=0,G=1,W=2,V=3,X=4;let Y=H.WARNINGS;function q(t){Number.isInteger(t)&&(Y=t)}function K(){return Y}function Q(t){Y>=H.INFOS&&console.info(`Info: ${t}`)}function J(t){Y>=H.WARNINGS&&console.warn(`Warning: ${t}`)}function Z(t){throw new Error(t)}function tt(t,e){t||Z(e)}function et(t,e=null,s=null){if(!t)return null;if(s&&"string"==typeof t){if(s.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(s.tryConvertEncoding)try{t=function(t){return decodeURIComponent(escape(t))}(t)}catch{}}const i=e?URL.parse(t,e):URL.parse(t);return function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(i)?i:null}function st(t,e,s=!1){const i=URL.parse(t);return i?(i.hash=e,i.href):s&&et(t,"http://example.com")?t.split("#",1)[0]+"":""}function it(t,e,s,i=!1){return Object.defineProperty(t,e,{value:s,enumerable:!i,configurable:!0,writable:!1}),s}const nt=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}();class rt extends nt{constructor(t,e){super(t,"PasswordException"),this.code=e}}class at extends nt{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class ot extends nt{constructor(t){super(t,"InvalidPDFException")}}class ht extends nt{constructor(t,e,s){super(t,"ResponseException"),this.status=e,this.missing=s}}class lt extends nt{constructor(t){super(t,"FormatError")}}class ct extends nt{constructor(t){super(t,"AbortException")}}function dt(t){"string"!=typeof t&&Z("Invalid argument for stringToBytes");const e=t.length,s=new Uint8Array(e);for(let i=0;i<e;++i)s[i]=255&t.charCodeAt(i);return s}class ut{static get isLittleEndian(){const t=new Uint8Array(4);return t[0]=1,it(this,"isLittleEndian",1===new Uint32Array(t.buffer,0,1)[0])}static get isOffscreenCanvasSupported(){return it(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return it(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get isFloat16ArraySupported(){return it(this,"isFloat16ArraySupported","undefined"!=typeof Float16Array)}static get isSanitizerSupported(){return it(this,"isSanitizerSupported","undefined"!=typeof Sanitizer)}static get platform(){const{platform:t,userAgent:e}=navigator;return it(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCanvasFilterSupported(){let t;return this.isOffscreenCanvasSupported?t=new OffscreenCanvas(1,1).getContext("2d"):"undefined"!=typeof document&&(t=document.createElement("canvas").getContext("2d")),it(this,"isCanvasFilterSupported",void 0!==t?.filter)}static get isAlphaColorInputSupported(){return it(this,"isAlphaColorInputSupported",(()=>{if("undefined"==typeof document)return!1;const t=document.createElement("input");return t.type="color",t.setAttribute("alpha",""),t.value="#ff000080","#ff0000"!==t.value})())}}class pt{static get hexNums(){return it(this,"hexNums",Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0")))}static makeHexColor(t,e,s){return`#${this.hexNums[t]}${this.hexNums[e]}${this.hexNums[s]}`}static domMatrixToTransform(t){return[t.a,t.b,t.c,t.d,t.e,t.f]}static scaleMinMax(t,e){let s;t[0]?(t[0]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[3],e[3]*=t[3]):(s=e[0],e[0]=e[1],e[1]=s,s=e[2],e[2]=e[3],e[3]=s,t[1]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static multiplyByDOMMatrix(t,e){return[t[0]*e.a+t[2]*e.b,t[1]*e.a+t[3]*e.b,t[0]*e.c+t[2]*e.d,t[1]*e.c+t[3]*e.d,t[0]*e.e+t[2]*e.f+t[4],t[1]*e.e+t[3]*e.f+t[5]]}static applyTransform(t,e,s=0){const i=t[s],n=t[s+1];t[s]=i*e[0]+n*e[2]+e[4],t[s+1]=i*e[1]+n*e[3]+e[5]}static applyTransformToBezier(t,e,s=0){const i=e[0],n=e[1],r=e[2],a=e[3],o=e[4],h=e[5];for(let l=0;l<6;l+=2){const e=t[s+l],c=t[s+l+1];t[s+l]=e*i+c*r+o,t[s+l+1]=e*n+c*a+h}}static applyInverseTransform(t,e){const s=t[0],i=t[1],n=e[0]*e[3]-e[1]*e[2];t[0]=(s*e[3]-i*e[2]+e[2]*e[5]-e[4]*e[3])/n,t[1]=(-s*e[1]+i*e[0]+e[4]*e[1]-e[5]*e[0])/n}static axialAlignedBoundingBox(t,e,s){const i=e[0],n=e[1],r=e[2],a=e[3],o=e[4],h=e[5],l=t[0],c=t[1],d=t[2],u=t[3];let p=i*l+o,g=p,m=i*d+o,f=m,b=a*c+h,y=b,A=a*u+h,w=A;if(0!==n||0!==r){const t=n*l,e=n*d,s=r*c,i=r*u;p+=s,f+=s,m+=i,g+=i,b+=t,w+=t,A+=e,y+=e}s[0]=Math.min(s[0],p,m,g,f),s[1]=Math.min(s[1],b,A,y,w),s[2]=Math.max(s[2],p,m,g,f),s[3]=Math.max(s[3],b,A,y,w)}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t,e){const s=t[0],i=t[1],n=t[2],r=t[3],a=s**2+i**2,o=s*n+i*r,h=n**2+r**2,l=(a+h)/2,c=Math.sqrt(l**2-(a*h-o**2));e[0]=Math.sqrt(l+c||1),e[1]=Math.sqrt(l-c||1)}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>r?null:[s,n,i,r]}static pointBoundingBox(t,e,s){s[0]=Math.min(s[0],t),s[1]=Math.min(s[1],e),s[2]=Math.max(s[2],t),s[3]=Math.max(s[3],e)}static rectBoundingBox(t,e,s,i,n){n[0]=Math.min(n[0],t,s),n[1]=Math.min(n[1],e,i),n[2]=Math.max(n[2],t,s),n[3]=Math.max(n[3],e,i)}static#t(t,e,s,i,n,r,a,o,h,l){if(h<=0||h>=1)return;const c=1-h,d=h*h,u=d*h,p=c*(c*(c*t+3*h*e)+3*d*s)+u*i,g=c*(c*(c*n+3*h*r)+3*d*a)+u*o;l[0]=Math.min(l[0],p),l[1]=Math.min(l[1],g),l[2]=Math.max(l[2],p),l[3]=Math.max(l[3],g)}static#e(t,e,s,i,n,r,a,o,h,l,c,d){if(Math.abs(h)<1e-12)return void(Math.abs(l)>=1e-12&&this.#t(t,e,s,i,n,r,a,o,-c/l,d));const u=l**2-4*c*h;if(u<0)return;const p=Math.sqrt(u),g=2*h;this.#t(t,e,s,i,n,r,a,o,(-l+p)/g,d),this.#t(t,e,s,i,n,r,a,o,(-l-p)/g,d)}static bezierBoundingBox(t,e,s,i,n,r,a,o,h){h[0]=Math.min(h[0],t,a),h[1]=Math.min(h[1],e,o),h[2]=Math.max(h[2],t,a),h[3]=Math.max(h[3],e,o),this.#e(t,s,n,a,e,i,r,o,3*(3*(s-n)-t+a),6*(t-2*s+n),3*(s-t),h),this.#e(t,s,n,a,e,i,r,o,3*(3*(i-r)-e+o),6*(e-2*i+r),3*(i-e),h)}}function gt(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);return crypto.getRandomValues(t),function(t){"object"==typeof t&&void 0!==t?.length||Z("Invalid argument for bytesToString");const e=t.length,s=8192;if(e<s)return String.fromCharCode.apply(null,t);const i=[];for(let n=0;n<e;n+=s){const r=Math.min(n+s,e),a=t.subarray(n,r);i.push(String.fromCharCode.apply(null,a))}return i.join("")}(t)}const mt=()=>[],ft=()=>new Map,bt=()=>Object.create(null);function yt(t,e,s){return Math.min(Math.max(t,e),s)}class At{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};return function t(s){if(!s)return;let i=null;const n=s.name;if("#text"===n)i=s.value;else{if(!At.shouldBuildText(n))return;s?.attributes?.textContent?i=s.attributes.textContent:s.value&&(i=s.value)}if(null!==i&&e.push({str:i}),s.children)for(const e of s.children)t(e)}(t),s}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}class wt{static setupStorage(t,e,s,i,n){const r=i.getValue(e,{value:null});switch(s.name){case"textarea":if(null!==r.value&&(t.textContent=r.value),"print"===n)break;t.addEventListener("input",t=>{i.setValue(e,{value:t.target.value})});break;case"input":if("radio"===s.attributes.type||"checkbox"===s.attributes.type){if(r.value===s.attributes.xfaOn?t.setAttribute("checked",!0):r.value===s.attributes.xfaOff&&t.removeAttribute("checked"),"print"===n)break;t.addEventListener("change",t=>{i.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})})}else{if(null!==r.value&&t.setAttribute("value",r.value),"print"===n)break;t.addEventListener("input",t=>{i.setValue(e,{value:t.target.value})})}break;case"select":if(null!==r.value){t.setAttribute("value",r.value);for(const t of s.children)t.attributes.value===r.value?t.attributes.selected=!0:Object.hasOwn(t.attributes,"selected")&&delete t.attributes.selected}t.addEventListener("input",t=>{const s=t.target.options,n=-1===s.selectedIndex?"":s[s.selectedIndex].value;i.setValue(e,{value:n})})}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,a=t instanceof HTMLAnchorElement;"radio"===r.type&&(r.name=`${r.name}-${i}`);for(const[o,h]of Object.entries(r))if(null!=h)switch(o){case"class":h.length&&t.setAttribute(o,h.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",h);break;case"style":Object.assign(t.style,h);break;case"textContent":t.textContent=h;break;default:(!a||"href"!==o&&"newWindow"!==o)&&t.setAttribute(o,h)}a&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:s});const a="richText"!==n,o=t.div;if(o.append(r),t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}a&&o.setAttribute("class","xfaLayer xfaFont");const h=[];if(0===i.children.length){if(i.value){const t=document.createTextNode(i.value);r.append(t),a&&At.shouldBuildText(i.name)&&h.push(t)}return{textDivs:h}}const l=[[i,-1,r]];for(;l.length>0;){const[t,i,r]=l.at(-1);if(i+1===t.children.length){l.pop();continue}const o=t.children[++l.at(-1)[1]];if(null===o)continue;const{name:c}=o;if("#text"===c){const t=document.createTextNode(o.value);h.push(t),r.append(t);continue}const d=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,c):document.createElement(c);if(r.append(d),o.attributes&&this.setAttributes({html:d,element:o,storage:e,intent:n,linkService:s}),o.children?.length>0)l.push([o,-1,d]);else if(o.value){const t=document.createTextNode(o.value);a&&At.shouldBuildText(c)&&h.push(t),d.append(t)}}for(const c of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))c.setAttribute("readOnly",!0);return{textDivs:h}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const vt="http://www.w3.org/2000/svg";class _t{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function xt(t,e="text"){if(Et(t,document.baseURI)){const s=await fetch(t);if(!s.ok)throw new Error(s.statusText);switch(e){case"blob":return s.blob();case"bytes":return s.bytes();case"json":return s.json()}return s.text()}return new Promise((s,i)=>{const n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType="bytes"===e?"arraybuffer":e,n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)i(new Error(n.statusText));else{switch(e){case"bytes":return void s(new Uint8Array(n.response));case"blob":case"json":return void s(n.response)}s(n.responseText)}},n.send(null)})}class St{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t,this.userUnit=e,this.scale=s,this.rotation=i,this.offsetX=n,this.offsetY=r,s*=e;const o=(t[2]+t[0])/2,h=(t[3]+t[1])/2;let l,c,d,u,p,g,m,f;switch((i%=360)<0&&(i+=360),i){case 180:l=-1,c=0,d=0,u=1;break;case 90:l=0,c=1,d=1,u=0;break;case 270:l=0,c=-1,d=-1,u=0;break;case 0:l=1,c=0,d=0,u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,u=-u),0===l?(p=Math.abs(h-t[1])*s+n,g=Math.abs(o-t[0])*s+r,m=(t[3]-t[1])*s,f=(t[2]-t[0])*s):(p=Math.abs(o-t[0])*s+n,g=Math.abs(h-t[1])*s+r,m=(t[2]-t[0])*s,f=(t[3]-t[1])*s),this.transform=[l*s,c*s,d*s,u*s,p-l*s*o-d*s*h,g-c*s*o-u*s*h],this.width=m,this.height=f}get rawDims(){const t=this.viewBox;return it(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new St({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){const s=[t,e];return pt.applyTransform(s,this.transform),s}convertToViewportRectangle(t){const e=[t[0],t[1]];pt.applyTransform(e,this.transform);const s=[t[2],t[3]];return pt.applyTransform(s,this.transform),[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){const s=[t,e];return pt.applyInverseTransform(s,this.transform),s}}class Ct extends nt{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function kt(t){const e=t.length;let s=0;for(;s<e&&""===t[s].trim();)s++;return"data:"===t.substring(s,s+5).toLowerCase()}function Tt(t){return"string"==typeof t&&/\.pdf$/i.test(t)}class Mt{#s=new Map;times=[];time(t){this.#s.has(t)&&J(`Timer is already running for ${t}`),this.#s.set(t,Date.now())}timeEnd(t){this.#s.has(t)||J(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.#s.get(t),end:Date.now()}),this.#s.delete(t)}toString(){const t=Math.max(...this.times.map(t=>t.name.length));return this.times.map(e=>`${e.name.padEnd(t)} ${e.end-e.start}ms\n`).join("")}}function Et(t,e){const s=e?URL.parse(t,e):URL.parse(t);return/https?:/.test(s?.protocol??"")}function Pt(t){t.preventDefault()}function Dt(t){t.preventDefault(),t.stopPropagation()}class It{static#i;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#i||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#i.exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let a=parseInt(e[5],10);a=a>=0&&a<=59?a:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const h=e[7]||"Z";let l=parseInt(e[8],10);l=l>=0&&l<=23?l:0;let c=parseInt(e[9],10)||0;return c=c>=0&&c<=59?c:0,"-"===h?(r+=l,a+=c):"+"===h&&(r-=l,a-=c),new Date(Date.UTC(s,i,n,r,a,o))}}function Ft(t){if(t.startsWith("#")){const e=t.slice(1);return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16),e.length>=8?parseInt(e.slice(6,8),16)/255:1]}if(t.startsWith("rgb(")){const[e,s,i]=t.slice(4,-1).split(",").map(t=>parseInt(t,10));return[e,s,i,1]}if(t.startsWith("rgba(")){const e=t.slice(5,-1).split(",");return[parseInt(e[0],10),parseInt(e[1],10),parseInt(e[2],10),parseFloat(e[3])]}const e=t.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return e?[Math.round(255*parseFloat(e[1])),Math.round(255*parseFloat(e[2])),Math.round(255*parseFloat(e[3])),void 0!==e[4]&&"none"!==e[4]?parseFloat(e[4]):1]:null}function Nt(t){const e=Ft(t);return e?e.slice(0,3):(J(`Not a valid color format: "${t}"`),[0,0,0])}function Rt(t){const{a:e,b:s,c:i,d:n,e:r,f:a}=t.getTransform();return[e,s,i,n,r,a]}function Ot(t){const{a:e,b:s,c:i,d:n,e:r,f:a}=t.getTransform().invertSelf();return[e,s,i,n,r,a]}function Bt(t,e,s=!1,i=!0){if(e instanceof St){const{pageWidth:i,pageHeight:n}=e.rawDims,{style:r}=t,a=`round(down, var(--total-scale-factor) * ${i}px, var(--scale-round-x))`,o=`round(down, var(--total-scale-factor) * ${n}px, var(--scale-round-y))`;s&&e.rotation%180!=0?(r.width=o,r.height=a):(r.width=a,r.height=o)}i&&t.setAttribute("data-main-rotation",e.rotation)}class Lt{constructor(){const{pixelRatio:t}=Lt;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,s,i,n=-1){let r=1/0,a=1/0,o=1/0;(s=Lt.capPixels(s,n))>0&&(r=Math.sqrt(s/(t*e))),-1!==i&&(a=i/t,o=i/e);const h=Math.min(r,a,o);return(this.sx>h||this.sy>h)&&(this.sx=h,this.sy=h,!0)}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const s=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,s):s}return t}}const Ut=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class jt{static get isDarkMode(){return it(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}function Ht({html:t,dir:e,className:s},i){const n=document.createDocumentFragment();if("string"==typeof t){const s=document.createElement("p");s.dir=e||"auto";const i=t.split(/(?:\r\n?|\n)/);for(let t=0,e=i.length;t<e;++t){const n=i[t];s.append(document.createTextNode(n)),t<e-1&&s.append(document.createElement("br"))}n.append(s)}else wt.render({xfaHtml:t,div:n,intent:"richText"});n.firstElementChild.classList.add("richText",s),i.append(n)}function $t(t){const e=new Path2D;if(!t)return e;for(let s=0,i=t.length;s<i;)switch(t[s++]){case z:e.moveTo(t[s++],t[s++]);break;case G:e.lineTo(t[s++],t[s++]);break;case W:e.bezierCurveTo(t[s++],t[s++],t[s++],t[s++],t[s++],t[s++]);break;case V:e.quadraticCurveTo(t[s++],t[s++],t[s++],t[s++]);break;case X:e.closePath();break;default:J(`Unrecognized drawing path operator: ${t[s-1]}`)}return e}class zt{#n=null;#r=null;#a;#o=null;#h=null;#l=null;#c=null;#d=null;static#u=null;constructor(t){this.#a=t,zt.#u||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"})}render(){const t=this.#n=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("contextmenu",Pt,{signal:e}),t.addEventListener("pointerdown",zt.#p,{signal:e}));const s=this.#o=document.createElement("div");s.className="buttons",t.append(s);const i=this.#a.toolbarPosition;if(i){const{style:e}=t,s="ltr"===this.#a._uiManager.direction?1-i[0]:i[0];e.insetInlineEnd=100*s+"%",e.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return t}get div(){return this.#n}static#p(t){t.stopPropagation()}#g(t){this.#a._focusEventsAllowed=!1,Dt(t)}#m(t){this.#a._focusEventsAllowed=!0,Dt(t)}#f(t){const e=this.#a._uiManager._signal;return e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("focusin",this.#g.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#m.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",Pt,{signal:e}),!0)}hide(){this.#n.classList.add("hidden"),this.#r?.hideDropdown()}show(){this.#n.classList.remove("hidden"),this.#h?.shown(),this.#l?.shown()}addDeleteButton(){const{editorType:t,_uiManager:e}=this.#a,s=document.createElement("button");s.classList.add("basic","deleteButton"),s.tabIndex=0,s.setAttribute("data-l10n-id",zt.#u[t]),this.#f(s)&&s.addEventListener("click",t=>{e.delete()},{signal:e._signal}),this.#o.append(s)}get#b(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#f(e),this.#o.append(e,this.#b),this.#h=t}addComment(t,e=null){if(this.#l)return;const s=t.renderForToolbar();if(!s)return;this.#f(s);const i=this.#c=this.#b;e?(this.#o.insertBefore(s,e),this.#o.insertBefore(i,e)):this.#o.append(s,i),this.#l=t,t.toolbar=this}addColorPicker(t){if(this.#r)return;this.#r=t;const e=t.renderButton();this.#f(e),this.#o.append(e,this.#b)}async addEditSignatureButton(t){const e=this.#d=await t.renderEditButton(this.#a);this.#f(e),this.#o.append(e,this.#b)}removeButton(t){"comment"===t&&(this.#l?.removeToolbarCommentButton(),this.#l=null,this.#c?.remove(),this.#c=null)}async addButton(t,e){switch(t){case"colorPicker":e&&this.addColorPicker(e);break;case"altText":e&&await this.addAltText(e);break;case"editSignature":e&&await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":e&&this.addComment(e)}}async addButtonBefore(t,e,s){if(!e&&"comment"===t)return;const i=this.#o.querySelector(s);i&&"comment"===t&&this.addComment(e,i)}updateEditSignatureButton(t){this.#d&&(this.#d.title=t)}remove(){this.#n.remove(),this.#r?.destroy(),this.#r=null}}class Gt{#o=null;#n=null;#y;constructor(t){this.#y=t}#A(){const t=this.#n=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar");const e=this.#y._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",Pt,{signal:e});const s=this.#o=document.createElement("div");return s.className="buttons",t.append(s),this.#y.hasCommentManager()&&this.#w("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#y.commentSelection("floating_button")}),this.#w("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#y.highlightSelection("floating_button")}),t}#v(t,e){let s=0,i=0;for(const n of t){const t=n.y+n.height;if(t<s)continue;const r=n.x+(e?n.width:0);t>s?(i=r,s=t):e?r>i&&(i=r):r<i&&(i=r)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#v(e,s),{style:r}=this.#n||=this.#A();t.append(this.#n),r.insetInlineEnd=100*i+"%",r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#n.remove()}#w(t,e,s,i){const n=document.createElement("button");n.classList.add("basic",t),n.tabIndex=0,n.setAttribute("data-l10n-id",e);const r=document.createElement("span");n.append(r),r.className="visuallyHidden",r.setAttribute("data-l10n-id",s);const a=this.#y._signal;a instanceof AbortSignal&&!a.aborted&&(n.addEventListener("contextmenu",Pt,{signal:a}),n.addEventListener("click",i,{signal:a})),this.#o.append(n)}}function Wt(t,e,s){for(const i of s)e.addEventListener(i,t[i].bind(t))}class Vt{static#_=NaN;static#x=null;static#S=NaN;static#C=null;static initializeAndAddPointerId(t){(Vt.#x||=new Set).add(t)}static setPointer(t,e){Vt.#_||=e,Vt.#C??=t}static setTimeStamp(t){Vt.#S=t}static isSamePointerId(t){return Vt.#_===t}static isSamePointerIdOrRemove(t){return Vt.#_===t||(Vt.#x?.delete(t),!1)}static isSamePointerType(t){return Vt.#C===t}static isInitializedAndDifferentPointerType(t){return null!==Vt.#C&&!Vt.isSamePointerType(t)}static isSameTimeStamp(t){return Vt.#S===t}static isUsingMultiplePointers(){return Vt.#x?.size>=1}static clearPointerType(){Vt.#C=null}static clearPointerIds(){Vt.#_=NaN,Vt.#x=null}static clearTimeStamp(){Vt.#S=NaN}}class Xt{#k=0;get id(){return`${k}${this.#k++}`}}class Yt{#T=gt();#k=0;#M=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;return e.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>',it(this,"_isSVGFittingCanvas",e.decode().then(()=>(t.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0])))}async#E(t,e){this.#M||=new Map;let s=this.#M.get(t);if(null===s)return null;if(s?.bitmap)return s.refCounter+=1,s;try{let t;if(s||={bitmap:null,id:`image_${this.#T}_${this.#k++}`,refCounter:0,isSvg:!1},"string"==typeof e?(s.url=e,t=await xt(e,"blob")):e instanceof File?t=s.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){const e=Yt._isSVGFittingCanvas,i=new FileReader,n=new Image,r=new Promise((t,r)=>{n.onload=()=>{s.bitmap=n,s.isSvg=!0,t()},i.onload=async()=>{const t=s.svgUrl=i.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=i.onerror=r});i.readAsDataURL(t),await r}else s.bitmap=await createImageBitmap(t);s.refCounter=1}catch(t){J(t),s=null}return this.#M.set(t,s),s&&this.#M.set(s.id,s),s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#E(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#E(t,t)}async getFromBlob(t,e){const s=await e;return this.#E(t,s)}async getFromId(t){this.#M||=new Map;const e=this.#M.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#M||=new Map;let s=this.#M.get(t);if(s?.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${this.#T}_${this.#k++}`,refCounter:1,isSvg:!1},this.#M.set(t,s),this.#M.set(s.id,s),s}getSvgUrl(t){const e=this.#M.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#M||=new Map;const e=this.#M.get(t);if(!e)return;if(e.refCounter-=1,0!==e.refCounter)return;const{bitmap:s}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(s.width,s.height);t.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=t.convertToBlob()}s.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#T}_`)}}class qt{#P=[];#D=!1;#I;#F=-1;constructor(t=128){this.#I=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){if(i&&t(),this.#D)return;const o={cmd:t,undo:e,post:s,type:n};if(-1===this.#F)return this.#P.length>0&&(this.#P.length=0),this.#F=0,void this.#P.push(o);if(r&&this.#P[this.#F].type===n)return a&&(o.undo=this.#P[this.#F].undo),void(this.#P[this.#F]=o);const h=this.#F+1;h===this.#I?this.#P.splice(0,1):(this.#F=h,h<this.#P.length&&this.#P.splice(h)),this.#P.push(o)}undo(){if(-1===this.#F)return;this.#D=!0;const{undo:t,post:e}=this.#P[this.#F];t(),e?.(),this.#D=!1,this.#F-=1}redo(){if(this.#F<this.#P.length-1){this.#F+=1,this.#D=!0;const{cmd:t,post:e}=this.#P[this.#F];t(),e?.(),this.#D=!1}}hasSomethingToUndo(){return-1!==this.#F}hasSomethingToRedo(){return this.#F<this.#P.length-1}cleanType(t){if(-1!==this.#F){for(let e=this.#F;e>=0;e--)if(this.#P[e].type!==t)return this.#P.splice(e+1,this.#F-e),void(this.#F=e);this.#P.length=0,this.#F=-1}}destroy(){this.#P=null}}class Kt{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=ut.platform;for(const[s,i,n={}]of t)for(const t of s){const s=t.startsWith("mac+");e&&s?(this.callbacks.set(t.slice(4),{callback:i,options:n}),this.allKeys.add(t.split("+").at(-1))):e||s||(this.callbacks.set(t,{callback:i,options:n}),this.allKeys.add(t.split("+").at(-1)))}}#N(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(this.#N(e));if(!s)return;const{callback:i,options:{bubbles:n=!1,args:r=[],checker:a=null}}=s;a&&!a(t,e)||(i.bind(t,...r,e)(),n||Dt(e))}}class Qt{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return function(t){const e=document.createElement("span");e.style.visibility="hidden",e.style.colorScheme="only light",document.body.append(e);for(const s of t.keys()){e.style.color=s;const i=window.getComputedStyle(e).color;t.set(s,Nt(i))}e.remove()}(t),it(this,"_colors",t)}convert(t){const e=Nt(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[s,i]of this._colors)if(i.every((t,s)=>t===e[s]))return Qt._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?pt.makeHexColor(...e):t}}class Jt{#R=new AbortController;#O=null;#B=null;#L=new Map;#U=new Map;#j=null;#H=null;#$=null;#z=null;#G=new qt;#W=null;#V=null;#X=null;#Y=0;#q=new Set;#K=null;#Q=null;#J=new Set;_editorUndoBar=null;#Z=!1;#tt=!1;#et=!1;#st=null;#it=null;#nt=null;#rt=null;#at=!1;#ot=null;#ht=new Xt;#lt=!1;#ct=!1;#dt=!1;#ut=null;#pt=null;#gt=null;#mt=null;#ft=null;#bt=T.NONE;#yt=new Set;#At=null;#wt=null;#vt=null;#_t=null;#xt=null;#St={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#Ct=[0,0];#kt=null;#Tt=null;#Mt=null;#Et=null;#Pt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=Jt.prototype,e=t=>t.#Tt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),s=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return it(this,"_keyboardManager",new Kt([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],t.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:s}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#Tt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#Tt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,s,i,n,r,a,o,h,l,c,d,u,p,g,m){const f=this._signal=this.#R.signal;this.#Tt=t,this.#Mt=e,this.#Et=s,this.#H=i,this.#W=n,this.#wt=r,this.#xt=o,this._eventBus=a,a._on("editingaction",this.onEditingAction.bind(this),{signal:f}),a._on("pagechanging",this.onPageChanging.bind(this),{signal:f}),a._on("scalechanging",this.onScaleChanging.bind(this),{signal:f}),a._on("rotationchanging",this.onRotationChanging.bind(this),{signal:f}),a._on("setpreference",this.onSetPreference.bind(this),{signal:f}),a._on("switchannotationeditorparams",t=>this.updateParams(t.type,t.value),{signal:f}),window.addEventListener("pointerdown",()=>{this.#ct=!0},{capture:!0,signal:f}),window.addEventListener("pointerup",()=>{this.#ct=!1},{capture:!0,signal:f}),window.addEventListener("beforeunload",this.#Dt.bind(this),{capture:!0,signal:f}),this.#It(),this.#Ft(),this.#Nt(),this.#$=o.annotationStorage,this.#st=o.filterFactory,this.#vt=h,this.#rt=l||null,this.#Z=c,this.#tt=d,this.#et=u,this.#ft=p||null,this.viewParameters={realScale:_t.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=g||null,this._supportsPinchToZoom=!1!==m,n?.setSidebarUiManager(this)}destroy(){this.#Pt?.resolve(),this.#Pt=null,this.#R?.abort(),this.#R=null,this._signal=null;for(const t of this.#U.values())t.destroy();this.#U.clear(),this.#L.clear(),this.#J.clear(),this.#mt?.clear(),this.#O=null,this.#yt.clear(),this.#G.destroy(),this.#H?.destroy(),this.#W?.destroy(),this.#wt?.destroy(),this.#ot?.hide(),this.#ot=null,this.#gt?.destroy(),this.#gt=null,this.#B=null,this.#it&&(clearTimeout(this.#it),this.#it=null),this.#kt&&(clearTimeout(this.#kt),this.#kt=null),this._editorUndoBar?.destroy(),this.#xt=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#ft}get useNewAltTextFlow(){return this.#tt}get useNewAltTextWhenAddingImage(){return this.#et}get hcmFilter(){return it(this,"hcmFilter",this.#vt?this.#st.addHCMFilter(this.#vt.foreground,this.#vt.background):"none")}get direction(){return it(this,"direction",getComputedStyle(this.#Tt).direction)}get _highlightColors(){return it(this,"_highlightColors",this.#rt?new Map(this.#rt.split(",").map(t=>((t=t.split("=").map(t=>t.trim()))[1]=t[1].toUpperCase(),t))):null)}get highlightColors(){const{_highlightColors:t}=this;if(!t)return it(this,"highlightColors",null);const e=new Map,s=!!this.#vt;for(const[i,n]of t){const t=i.endsWith("_HCM");s&&t?e.set(i.replace("_HCM",""),n):s||t||e.set(i,n)}return it(this,"highlightColors",e)}get highlightColorNames(){return it(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}getNonHCMColor(t){if(!this._highlightColors)return t;const e=this.highlightColorNames.get(t);return this._highlightColors.get(e)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#X=t}setMainHighlightColorPicker(t){this.#gt=t}editAltText(t,e=!1){this.#H?.editAltText(this,t,e)}hasCommentManager(){return!!this.#W}editComment(t,e,s,i){this.#W?.showDialog(this,t,e,s,i)}selectComment(t,e){const s=this.#U.get(t),i=s?.getEditorByUID(e);i?.toggleComment(!0,!0)}updateComment(t){this.#W?.updateComment(t.getData())}updatePopupColor(t){this.#W?.updatePopupColor(t)}removeComment(t){this.#W?.removeComments([t.uid])}deleteComment(t,e){const s=()=>{t.comment=e};this.addCommands({cmd:()=>{this._editorUndoBar?.show(s,"comment"),this.toggleComment(null),t.comment=null},undo:s,mustExec:!0})}toggleComment(t,e,s=void 0){this.#W?.toggleCommentPopup(t,e,s)}makeCommentColor(t,e){return t&&this.#W?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#W?.dialogElement||null}async waitForEditorsRendered(t){if(this.#U.has(t-1))return;const{resolve:e,promise:s}=Promise.withResolvers(),i=s=>{s.pageNumber===t&&(this._eventBus._off("editorsrendered",i),e())};this._eventBus.on("editorsrendered",i),await s}getSignature(t){this.#wt?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#wt}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){"enableNewAltTextWhenAddingImage"===t&&(this.#et=e)}onPageChanging({pageNumber:t}){this.#Y=t-1}deletePage(t){for(const e of this.getEditors(t))e.remove();this.#U.delete(t),this.#Y===t&&(this.#Y=0)}focusMainContainer(){this.#Tt.focus()}findParent(t,e){for(const s of this.#U.values()){const{x:i,y:n,width:r,height:a}=s.div.getBoundingClientRect();if(t>=i&&t<=i+r&&e>=n&&e<=n+a)return s}return null}disableUserSelect(t=!1){this.#Mt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#J.add(t)}removeShouldRescale(t){this.#J.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*_t.PDF_TO_CSS_UNITS;for(const e of this.#J)e.onScaleChanging();this.#X?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#Rt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Ot(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of this.#U.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t="",e=!1){const s=document.getSelection();if(!s||s.isCollapsed)return;const{anchorNode:i,anchorOffset:n,focusNode:r,focusOffset:a}=s,o=s.toString(),h=this.#Rt(s).closest(".textLayer"),l=this.getSelectionBoxes(h);if(!l)return;s.empty();const c=this.#Ot(h),d=this.#bt===T.NONE,u=()=>{const s=c?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:n,focusNode:r,focusOffset:a,text:o});d&&this.showAllEditors("highlight",!0,!0),e&&s?.editComment()};d?this.switchToMode(T.HIGHLIGHT,u):u()}commentSelection(t=""){this.highlightSelection(t,!0)}#Dt(t){this.commitOrRemove(),this.currentLayer?.endDrawingSession(!1)}#Bt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#Rt(t).closest(".textLayer"),s=this.getSelectionBoxes(e);s&&(this.#ot||=new Gt(this),this.#ot.show(e,s,"ltr"===this.direction))}getAndRemoveDataFromAnnotationStorage(t){if(!this.#$)return null;const e=`${k}${t}`,s=this.#$.getRawValue(e);return s&&this.#$.remove(e),s}addToAnnotationStorage(t){t.isEmpty()||!this.#$||this.#$.has(t.id)||this.#$.setValue(t.id,t)}a11yAlert(t,e=null){const s=this.#Et;s&&(s.setAttribute("data-l10n-id",t),e?s.setAttribute("data-l10n-args",JSON.stringify(e)):s.removeAttribute("data-l10n-args"))}#Lt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#At&&(this.#ot?.hide(),this.#At=null,this.#Ut({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#At)return;const s=this.#Rt(t).closest(".textLayer");if(s){if(this.#ot?.hide(),this.#At=e,this.#Ut({hasSelectedText:!0}),(this.#bt===T.HIGHLIGHT||this.#bt===T.NONE)&&(this.#bt===T.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#at=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#bt===T.HIGHLIGHT?this.#Ot(s):null;if(t?.toggleDrawing(),this.#ct){const e=new AbortController,s=this.combinedSignal(e),i=s=>{"pointerup"===s.type&&0!==s.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===s.type&&this.#jt("main_toolbar"))};window.addEventListener("pointerup",i,{signal:s}),window.addEventListener("blur",i,{signal:s})}else t?.toggleDrawing(!0),this.#jt("main_toolbar")}}else this.#At&&(this.#ot?.hide(),this.#At=null,this.#Ut({hasSelectedText:!1}))}#jt(t=""){this.#bt===T.HIGHLIGHT?this.highlightSelection(t):this.#Z&&this.#Bt()}#It(){document.addEventListener("selectionchange",this.#Lt.bind(this),{signal:this._signal})}#Ht(){if(this.#nt)return;this.#nt=new AbortController;const t=this.combinedSignal(this.#nt);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#$t(){this.#nt?.abort(),this.#nt=null}blur(){if(this.isShiftKeyDown=!1,this.#at&&(this.#at=!1,this.#jt("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#yt)if(e.div.contains(t)){this.#pt=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#pt)return;const[t,e]=this.#pt;this.#pt=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#Nt(){if(this.#ut)return;this.#ut=new AbortController;const t=this.combinedSignal(this.#ut);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#zt(){this.#ut?.abort(),this.#ut=null}#Gt(){if(this.#V)return;this.#V=new AbortController;const t=this.combinedSignal(this.#V);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Wt(){this.#V?.abort(),this.#V=null}#Ft(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Nt(),this.setEditingState(!0)}removeEditListeners(){this.#zt(),this.setEditingState(!1)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#Q)if(s.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const s of this.#Q)if(s.isHandlingMimeForPasting(e.type))return s.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#O?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const s of this.#yt){const t=s.serialize(!0);t&&e.push(t)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const n of e.items)for(const t of this.#Q)if(t.isHandlingMimeForPasting(n.type))return void t.paste(n,this.currentLayer);let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(t){return void J(`paste: "${t.message}".`)}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const t=[];for(const r of s){const e=await i.deserialize(r);if(!e)return;t.push(e)}const e=()=>{for(const e of t)this.#Vt(e);this.#Xt(t)},n=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:n,mustExec:!0})}catch(t){J(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#bt===T.NONE||this.isEditorHandlingKeyboard||Jt._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#at&&(this.#at=!1,this.#jt("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu")}}updatePageIndex(t,e){for(const i of this.getEditors(t))i.pageIndex=e;const s=this.#j.get(t);s&&(s.pageIndex=e,this.#U.set(e,s),this.#lt?s.enable():s.disable())}startUpdatePages(){this.#j=new Map(this.#U),this.#U.clear()}endUpdatePages(){this.#j=null}clonePage(t,e){for(const s of this.getEditors(t)){const t=s.serialize(s.mode!==T.HIGHLIGHT);t&&(t.pageIndex=e,t.id=this.getId(),t.isClone=!0,delete t.popupRef,this.#$.setValue(t.id,t))}}findClonesForPage(t){const e=[],{pageIndex:s}=t;for(const[i,n]of this.#$)n.pageIndex===s&&n.isClone&&(this.#$.remove(i),e.push(t.deserialize(n).then(e=>{e&&(e.isClone=!0,t.addOrRebuild(e))})));return Promise.all(e)}#Ut(t){Object.entries(t).some(([t,e])=>this.#St[t]!==e)&&(this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(this.#St,t)}),this.#bt===T.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Yt([[M.HIGHLIGHT_FREE,!0]]))}#Yt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#Ht(),this.#Gt(),this.#Ut({isEditing:this.#bt!==T.NONE,isEmpty:this.#qt(),hasSomethingToUndo:this.#G.hasSomethingToUndo(),hasSomethingToRedo:this.#G.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#$t(),this.#Wt(),this.#Ut({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#Q){this.#Q=t;for(const t of this.#Q)this.#Yt(t.defaultPropertiesToUpdate)}}getId(){return this.#ht.id}get currentLayer(){return this.#U.get(this.#Y)}getLayer(t){return this.#U.get(t)}get currentPageIndex(){return this.#Y}addLayer(t){this.#U.set(t.pageIndex,t),this.#lt?t.enable():t.disable()}removeLayer(t){this.#U.delete(t.pageIndex)}async updateMode(t,e=null,s=!1,i=!1,n=!1,r=!1){if(this.#bt!==t){if(this.#Pt&&(await this.#Pt.promise,!this.#Pt))return;if(this.#Pt=Promise.withResolvers(),this.#X?.commitOrRemove(),this.#bt===T.POPUP&&this.#W?.hideSidebar(),this.#W?.destroyPopup(),this.#bt=t,t!==T.NONE){for(const t of this.#L.values())t.addStandaloneCommentButton();t===T.SIGNATURE&&await(this.#wt?.loadSignatures()),s&&Vt.clearPointerType(),this.setEditingState(!0),await this.#Kt(),this.unselectAll();for(const e of this.#U.values())e.updateMode(t);if(t===T.POPUP){this.#B||=await this.#xt.getAnnotationsByType(new Set(this.#Q.map(t=>t._editorType)));const t=new Set,e=[];for(const s of this.#L.values()){const{annotationElementId:i,hasComment:n,deleted:r}=s;i&&t.add(i),n&&!r&&e.push(s.getData())}for(const s of this.#B){const{id:i,popupRef:n,contentsObj:r}=s;n&&r?.str&&!t.has(i)&&!this.#q.has(i)&&e.push(s)}this.#W?.showSidebar(e)}if(e){for(const t of this.#L.values())t.uid===e?(this.setSelected(t),r?t.editComment():n?t.enterInEditMode():t.focus()):t.unselect();this.#Pt.resolve()}else i&&this.addNewEditorFromKeyboard(),this.#Pt.resolve()}else{this.setEditingState(!1),this.#Qt();for(const t of this.#L.values())t.hideStandaloneCommentButton();this._editorUndoBar?.hide(),this.toggleComment(null),this.#Pt.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#bt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#Q){switch(t){case M.CREATE:return void this.currentLayer.addNewEditor(e);case M.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#_t||=new Map).set(t,e),this.showAllEditors("highlight",e)}if(this.hasSelection)for(const s of this.#yt)s.updateParams(t,e);else for(const s of this.#Q)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const i of this.#L.values())i.editorType===t&&i.show(e);(this.#_t?.get(M.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Yt([[M.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#dt!==t){this.#dt=t;for(const e of this.#U.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#Kt(){if(!this.#lt){this.#lt=!0;const t=[];for(const e of this.#U.values())t.push(e.enable());await Promise.all(t);for(const e of this.#L.values())e.enable()}}#Qt(){if(this.unselectAll(),this.#lt){this.#lt=!1;for(const t of this.#U.values())t.disable();for(const t of this.#L.values())t.disable()}}*getEditors(t){for(const e of this.#L.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#L.get(t)}addEditor(t){this.#L.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#it&&clearTimeout(this.#it),this.#it=setTimeout(()=>{this.focusMainContainer(),this.#it=null},0)),this.#L.delete(t.id),t.annotationElementId&&this.#mt?.delete(t.annotationElementId),this.unselect(t),t.annotationElementId&&this.#q.has(t.annotationElementId)||this.#$?.remove(t.id)}addDeletedAnnotationElement(t){this.#q.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#q.has(t)}removeDeletedAnnotationElement(t){this.#q.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#Vt(t){const e=this.#U.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#O!==t&&(this.#O=t,t&&this.#Yt(t.propertiesToUpdate))}get#Jt(){let t=null;for(t of this.#yt);return t}updateUI(t){this.#Jt===t&&this.#Yt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Yt(t.defaultPropertiesToUpdate)}toggleSelected(t){this.#yt.has(t)?(this.#yt.delete(t),t.unselect(),this.#Ut({hasSelectedEditor:this.hasSelection})):(this.#yt.add(t),t.select(),this.#Yt(t.propertiesToUpdate),this.#Ut({hasSelectedEditor:!0}))}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.uid}),this.#X?.commitOrRemove();for(const e of this.#yt)e!==t&&e.unselect();this.#W?.destroyPopup(),this.#yt.clear(),this.#yt.add(t),t.select(),this.#Yt(t.propertiesToUpdate),this.#Ut({hasSelectedEditor:!0})}isSelected(t){return this.#yt.has(t)}get firstSelectedEditor(){return this.#yt.values().next().value}unselect(t){t.unselect(),this.#yt.delete(t),this.#Ut({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#yt.size}get isEnterHandled(){return 1===this.#yt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#G.undo(),this.#Ut({hasSomethingToUndo:this.#G.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#qt()}),this._editorUndoBar?.hide()}redo(){this.#G.redo(),this.#Ut({hasSomethingToUndo:!0,hasSomethingToRedo:this.#G.hasSomethingToRedo(),isEmpty:this.#qt()})}addCommands(t){this.#G.add(t),this.#Ut({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#qt()})}cleanUndoStack(t){this.#G.cleanType(t)}#qt(){if(0===this.#L.size)return!0;if(1===this.#L.size)for(const t of this.#L.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#yt],s=()=>{for(const t of e)this.#Vt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(s,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo:s,mustExec:!0})}commitOrRemove(){this.#O?.commitOrRemove()}hasSomethingToControl(){return this.#O||this.hasSelection}#Xt(t){for(const e of this.#yt)e.unselect();this.#yt.clear();for(const e of t)e.isEmpty()||(this.#yt.add(e),e.select());this.#Ut({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#yt)t.commit();this.#Xt(this.#L.values())}unselectAll(){if((!this.#O||(this.#O.commitOrRemove(),this.#bt===T.NONE))&&!this.#X?.commitOrRemove()&&(this.#W?.destroyPopup(),this.hasSelection)){for(const t of this.#yt)t.unselect();this.#yt.clear(),this.#Ut({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#Ct[0]+=t,this.#Ct[1]+=e;const[i,n]=this.#Ct,r=[...this.#yt];this.#kt&&clearTimeout(this.#kt),this.#kt=setTimeout(()=>{this.#kt=null,this.#Ct[0]=this.#Ct[1]=0,this.addCommands({cmd:()=>{for(const t of r)this.#L.has(t.id)&&(t.translateInPage(i,n),t.translationDone())},undo:()=>{for(const t of r)this.#L.has(t.id)&&(t.translateInPage(-i,-n),t.translationDone())},mustExec:!1})},1e3);for(const a of r)a.translateInPage(t,e),a.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#K=new Map;for(const t of this.#yt)this.#K.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#K)return!1;this.disableUserSelect(!1);const t=this.#K;this.#K=null;let e=!1;for(const[{x:i,y:n,pageIndex:r},a]of t)a.newX=i,a.newY=n,a.newPageIndex=r,e||=i!==a.savedX||n!==a.savedY||r!==a.savedPageIndex;if(!e)return!1;const s=(t,e,s,i)=>{if(this.#L.has(t.id)){const n=this.#U.get(i);n?t._setParentAndPosition(n,e,s):(t.pageIndex=i,t.x=e,t.y=s)}};return this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:n,newPageIndex:r}]of t)s(e,i,n,r)},undo:()=>{for(const[e,{savedX:i,savedY:n,savedPageIndex:r}]of t)s(e,i,n,r)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#K)for(const s of this.#K.keys())s.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#yt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#O===t}getActive(){return this.#O}getMode(){return this.#bt}isEditingMode(){return this.#bt!==T.NONE}get imageManager(){return it(this,"imageManager",new Yt)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let h=0,l=e.rangeCount;h<l;h++)if(!t.contains(e.getRangeAt(h).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let a;switch(t.getAttribute("data-main-rotation")){case"90":a=(t,e,a,o)=>({x:(e-i)/r,y:1-(t+a-s)/n,width:o/r,height:a/n});break;case"180":a=(t,e,a,o)=>({x:1-(t+a-s)/n,y:1-(e+o-i)/r,width:a/n,height:o/r});break;case"270":a=(t,e,a,o)=>({x:1-(e+o-i)/r,y:(t-s)/n,width:o/r,height:a/n});break;default:a=(t,e,a,o)=>({x:(t-s)/n,y:(e-i)/r,width:a/n,height:o/r})}const o=[];for(let h=0,l=e.rangeCount;h<l;h++){const t=e.getRangeAt(h);if(!t.collapsed)for(const{x:e,y:s,width:i,height:n}of t.getClientRects())0!==i&&0!==n&&o.push(a(e,s,i,n))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#z||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#z?.delete(t)}renderAnnotationElement(t){const e=this.#z?.get(t.data.id);if(!e)return;const s=this.#$.getRawValue(e);s&&(this.#bt!==T.NONE||s.hasBeenModified)&&s.renderAnnotationElement(t)}setMissingCanvas(t,e,s){const i=this.#mt?.get(t);i&&(i.setCanvas(e,s),this.#mt.delete(t))}addMissingCanvas(t,e){(this.#mt||=new Map).set(t,e)}}class Zt{#h=null;#Zt=!1;#te=null;#ee=null;#se=null;#ie=null;#ne=!1;#re=null;#a=null;#ae=null;#oe=null;#he=!1;static#le=null;static _l10n=null;constructor(t){this.#a=t,this.#he=t._uiManager.useNewAltTextFlow,Zt.#le||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){Zt._l10n??=t}async render(){const t=this.#te=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#ee=document.createElement("span");t.append(e),this.#he?(t.classList.add("new"),t.setAttribute("data-l10n-id",Zt.#le.missing),e.setAttribute("data-l10n-id",Zt.#le["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=this.#a._uiManager._signal;t.addEventListener("contextmenu",Pt,{signal:s}),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:s});const i=t=>{t.preventDefault(),this.#a._uiManager.editAltText(this.#a),this.#he&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#ce}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#ne=!0,i(e))},{signal:s}),await this.#de(),t}get#ce(){return(this.#h?"added":null===this.#h&&this.guessedText&&"review")||"missing"}finish(){this.#te&&(this.#te.focus({focusVisible:this.#ne}),this.#ne=!1)}isEmpty(){return this.#he?null===this.#h:!this.#h&&!this.#Zt}hasData(){return this.#he?null!==this.#h||!!this.#ae:this.isEmpty()}get guessedText(){return this.#ae}async setGuessedText(t){null===this.#h&&(this.#ae=t,this.#oe=await Zt._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#de())}toggleAltTextBadge(t=!1){if(this.#he&&!this.#h){if(!this.#re){const t=this.#re=document.createElement("div");t.className="noAltTextBadge",this.#a.div.append(t)}this.#re.classList.toggle("hidden",!t)}else this.#re?.remove(),this.#re=null}serialize(t){let e=this.#h;return t||this.#ae!==e||(e=this.#oe),{altText:e,decorative:this.#Zt,guessedText:this.#ae,textWithDisclaimer:this.#oe}}get data(){return{altText:this.#h,decorative:this.#Zt}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(this.#ae=s,this.#oe=i),this.#h===t&&this.#Zt===e||(n||(this.#h=t,this.#Zt=e),this.#de())}toggle(t=!1){this.#te&&(!t&&this.#ie&&(clearTimeout(this.#ie),this.#ie=null),this.#te.disabled=!t)}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#ce}})}destroy(){this.#te?.remove(),this.#te=null,this.#ee=null,this.#se=null,this.#re?.remove(),this.#re=null}async#de(){const t=this.#te;if(!t)return;if(this.#he){if(t.classList.toggle("done",!!this.#h),t.setAttribute("data-l10n-id",Zt.#le[this.#ce]),this.#ee?.setAttribute("data-l10n-id",Zt.#le[`${this.#ce}-label`]),!this.#h)return void this.#se?.remove()}else{if(!this.#h&&!this.#Zt)return t.classList.remove("done"),void this.#se?.remove();t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#se;if(!e){this.#se=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#a.id}`;const s=100,i=this.#a._uiManager._signal;i.addEventListener("abort",()=>{clearTimeout(this.#ie),this.#ie=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#ie=setTimeout(()=>{this.#ie=null,this.#se.classList.add("show"),this.#a._reportTelemetry({action:"alt_text_tooltip"})},s)},{signal:i}),t.addEventListener("mouseleave",()=>{this.#ie&&(clearTimeout(this.#ie),this.#ie=null),this.#se?.classList.remove("show")},{signal:i})}this.#Zt?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#h),e.parentNode||t.append(e);const s=this.#a.getElementForAltText();s?.setAttribute("aria-describedby",e.id)}}class te{#ue=null;#pe=null;#ge=!1;#a=null;#me=null;#fe=null;#be=null;#ye=null;#Ae=!1;#we=null;constructor(t){this.#a=t}renderForToolbar(){const t=this.#pe=document.createElement("button");return t.className="comment",this.#A(t,!1)}renderForStandalone(){const t=this.#ue=document.createElement("button");t.className="annotationCommentButton";const e=this.#a.commentButtonPosition;if(e){const{style:s}=t;s.insetInlineEnd=`calc(${100*("ltr"===this.#a._uiManager.direction?1-e[0]:e[0])}% - var(--comment-button-dim))`,s.top=`calc(${100*e[1]}% - var(--comment-button-dim))`;const i=this.#a.commentButtonColor;i&&(s.backgroundColor=i)}return this.#A(t,!0)}focusButton(){setTimeout(()=>{(this.#ue??this.#pe)?.focus()},0)}onUpdatedColor(){if(!this.#ue)return;const t=this.#a.commentButtonColor;t&&(this.#ue.style.backgroundColor=t),this.#a._uiManager.updatePopupColor(this.#a)}get commentButtonWidth(){return(this.#ue?.getBoundingClientRect().width??0)/this.#a.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#we)return this.#we;if(!this.#ue)return null;const{x:t,y:e,height:s}=this.#ue.getBoundingClientRect(),{x:i,y:n,width:r,height:a}=this.#a.parent.boundingClientRect;return[(t-i)/r,(e+s-n)/a]}set commentPopupPositionInLayer(t){this.#we=t}hasDefaultPopupPosition(){return null===this.#we}removeStandaloneCommentButton(){this.#ue?.remove(),this.#ue=null}removeToolbarCommentButton(){this.#pe?.remove(),this.#pe=null}setCommentButtonStates({selected:t,hasPopup:e}){this.#ue&&(this.#ue.classList.toggle("selected",t),this.#ue.ariaExpanded=e)}#A(t,e){if(!this.#a._uiManager.hasCommentManager())return null;t.tabIndex="0",t.ariaHasPopup="dialog",e?(t.ariaControls="commentPopup",t.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(t.ariaControlsElements=[this.#a._uiManager.getCommentDialogElement()],t.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button"));const s=this.#a._uiManager._signal;if(!(s instanceof AbortSignal)||s.aborted)return t;t.addEventListener("contextmenu",Pt,{signal:s}),e&&(t.addEventListener("focusin",t=>{this.#a._focusEventsAllowed=!1,Dt(t)},{capture:!0,signal:s}),t.addEventListener("focusout",t=>{this.#a._focusEventsAllowed=!0,Dt(t)},{capture:!0,signal:s})),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:s});const i=e=>{e.preventDefault(),t===this.#pe?this.edit():this.#a.toggleComment(!0)};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#ge=!0,i(e))},{signal:s}),t.addEventListener("pointerenter",()=>{this.#a.toggleComment(!1,!0)},{signal:s}),t.addEventListener("pointerleave",()=>{this.#a.toggleComment(!1,!1)},{signal:s}),t}edit(t){const e=this.commentPopupPositionInLayer;let s,i;if(e)[s,i]=e;else{[s,i]=this.#a.commentButtonPosition;const{width:t,height:e,x:n,y:r}=this.#a;s=n+s*t,i=r+i*e}const n=this.#a.parent.boundingClientRect,{x:r,y:a,width:o,height:h}=n;this.#a._uiManager.editComment(this.#a,r+s*o,a+i*h,{...t,parentDimensions:n})}finish(){this.#pe&&(this.#pe.focus({focusVisible:this.#ge}),this.#ge=!1)}isDeleted(){return this.#Ae||""===this.#be}isEmpty(){return null===this.#be}hasBeenEdited(){return this.isDeleted()||this.#be!==this.#me}serialize(){return this.data}get data(){return{text:this.#be,richText:this.#fe,date:this.#ye,deleted:this.isDeleted()}}set data(t){t!==this.#be&&(this.#fe=null),null!==t?(this.#be=t,this.#ye=new Date,this.#Ae=!1):(this.#be="",this.#Ae=!0)}restoreData({text:t,richText:e,date:s}){this.#be=t,this.#fe=e,this.#ye=s,this.#Ae=!1}setInitialText(t,e=null){this.#me=t,this.data=t,this.#ye=null,this.#fe=e}shown(){}destroy(){this.#pe?.remove(),this.#pe=null,this.#ue?.remove(),this.#ue=null,this.#be="",this.#fe=null,this.#ye=null,this.#a=null,this.#ge=!1,this.#Ae=!1}}class ee{#Tt;#ve=!1;#_e=null;#xe;#Se;#Ce;#ke;#Te=null;#Me;#Ee=null;#Pe;#De=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,signal:a}){this.#Tt=t,this.#_e=s,this.#xe=e,this.#Se=i,this.#Ce=n,this.#ke=r,this.#Pe=new AbortController,this.#Me=AbortSignal.any([a,this.#Pe.signal]),t.addEventListener("touchstart",this.#Ie.bind(this),{passive:!1,signal:this.#Me})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Lt.pixelRatio}#Ie(t){if(this.#xe?.())return;if(1===t.touches.length){if(this.#Te)return;const t=this.#Te=new AbortController,e=AbortSignal.any([this.#Me,t.signal]),s=this.#Tt,i={capture:!0,signal:e,passive:!1},n=t=>{"touch"===t.pointerType&&(this.#Te?.abort(),this.#Te=null)};return s.addEventListener("pointerdown",t=>{"touch"===t.pointerType&&(Dt(t),n(t))},i),s.addEventListener("pointerup",n,i),void s.addEventListener("pointercancel",n,i)}if(!this.#De){this.#De=new AbortController;const t=AbortSignal.any([this.#Me,this.#De.signal]),e=this.#Tt,s={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#Fe.bind(this),s);const i=this.#Ne.bind(this);e.addEventListener("touchend",i,s),e.addEventListener("touchcancel",i,s),s.capture=!0,e.addEventListener("pointerdown",Dt,s),e.addEventListener("pointermove",Dt,s),e.addEventListener("pointercancel",Dt,s),e.addEventListener("pointerup",Dt,s),this.#Se?.()}if(Dt(t),2!==t.touches.length||this.#_e?.())return void(this.#Ee=null);let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]),this.#Ee={touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY}}#Fe(t){if(!this.#Ee||2!==t.touches.length)return;Dt(t);let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e,{screenX:r,screenY:a}=s,o=this.#Ee,{touch0X:h,touch0Y:l,touch1X:c,touch1Y:d}=o,u=c-h,p=d-l,g=r-i,m=a-n,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#ve&&Math.abs(b-f)<=ee.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(o.touch0X=i,o.touch0Y=n,o.touch1X=r,o.touch1Y=a,!this.#ve)return void(this.#ve=!0);const y=[(i+r)/2,(n+a)/2];this.#Ce?.(y,b,f)}#Ne(t){t.touches.length>=2||(this.#De&&(this.#De.abort(),this.#De=null,this.#ke?.()),this.#Ee&&(Dt(t),this.#Ee=null,this.#ve=!1))}destroy(){this.#Pe?.abort(),this.#Pe=null,this.#Te?.abort(),this.#Te=null}}class se{#Re=null;#Oe=null;#h=null;#l=null;#ue=null;#Be=!1;#Le=null;#Ue="";#je=null;#He=null;#$e=null;#ze=null;#Ge=null;#We="";#Ve=!1;#Xe=null;#Ye=!1;#qe=!1;#Ke=!1;#Qe=null;#Je=0;#Ze=0;#ts=null;#es=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nAlert=null;static _l10nResizer=null;#ss=!1;#is=se._zIndex++;static _borderLineWidth=-1;static _colorManager=new Qt;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=se.prototype._resizeWithKeyboard,e=Jt.TRANSLATE_SMALL,s=Jt.TRANSLATE_BIG;return it(this,"_resizerKeyboardManager",new Kt([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],se.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null,this.annotationElementId=t.annotationElementId||null,this.creationDate=t.creationDate||new Date,this.modificationDate=t.modificationDate||null,this.canAddComment=!0;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[a,o]=this.parentDimensions;this.x=t.x/a,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}updatePageIndex(t){this.pageIndex=t}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return it(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new ie({id:t._uiManager.getId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){if(se._l10n??=t,se._l10nAlert??=Object.freeze({highlight:"pdfjs-editor-highlight-added-alert",freetext:"pdfjs-editor-freetext-added-alert",ink:"pdfjs-editor-ink-added-alert",stamp:"pdfjs-editor-stamp-added-alert",signature:"pdfjs-editor-signature-added-alert"}),se._l10nResizer??=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),-1!==se._borderLineWidth)return;const s=getComputedStyle(document.documentElement);se._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){Z("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#ss}set _isDraggable(t){this.#ss=t,this.div?.classList.toggle("draggable",t)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t),this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t),this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#is}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):(this.#ns(),this.#ze?.remove(),this.#ze=null),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#Ve?this.#Ve=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;e?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,r]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(t+s)/n,this.y=(e+i)/r,this.fixAndSetPosition()}_moveAfterPaste(t,e){if(this.isClone)return void delete this.isClone;const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i),this._onTranslated()}#rs([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#rs(this.parentDimensions,t,e)}translateInPage(t,e){this.#Xe||=[this.x,this.y,this.width,this.height],this.#rs(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#Xe||=[this.x,this.y,this.width,this.height];const{div:s,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=e/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,e)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:a}=this;const[o,h]=this.getBaseTranslation();r+=o,a+=h;const{style:l}=s;l.left=`${(100*r).toFixed(2)}%`,l.top=`${(100*a).toFixed(2)}%`,this._onTranslating(r,a),s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#Xe&&(this.#Xe[0]!==this.x||this.#Xe[1]!==this.y)}get _hasBeenResized(){return!!this.#Xe&&(this.#Xe[2]!==this.width||this.#Xe[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=se,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:a,height:o}=this;if(a*=s,o*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=yt(n,0,s-a),r=yt(r,0,i-o);break;case 90:n=yt(n,0,s-o),r=yt(r,a,i);break;case 180:n=yt(n,a,s),r=yt(r,o,i);break;case 270:n=yt(n,o,s),r=yt(r,0,i-a)}this.x=n/=s,this.y=r/=i;const[h,l]=this.getBaseTranslation();n+=h,r+=l,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#as(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return se.#as(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return se.#as(t,e,360-this.parentRotation)}#os(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(){const{div:{style:t},width:e,height:s}=this;t.width=`${(100*e).toFixed(2)}%`,t.height=`${(100*s).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#hs(){if(this.#je)return;this.#je=document.createElement("div"),this.#je.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const s of t){const t=document.createElement("div");this.#je.append(t),t.classList.add("resizer",s),t.setAttribute("data-resizer-name",s),t.addEventListener("pointerdown",this.#ls.bind(this,s),{signal:e}),t.addEventListener("contextmenu",Pt,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#je)}#ls(t,e){e.preventDefault();const{isMac:s}=ut.platform;if(0!==e.button||e.ctrlKey&&s)return;this.#h?.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,this.#He=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#cs.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",Dt,{passive:!1,signal:r}),window.addEventListener("contextmenu",Pt,{signal:r}),this.#$e={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const a=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const h=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#h?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=a,this.div.style.cursor=o,this.#ds()};window.addEventListener("pointerup",h,{signal:r}),window.addEventListener("blur",h,{signal:r})}#us(t,e,s,i){this.width=s,this.height=i,this.x=t,this.y=e,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#ds(){if(!this.#$e)return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#$e;this.#$e=null;const n=this.x,r=this.y,a=this.width,o=this.height;n===t&&r===e&&a===s&&o===i||this.addCommands({cmd:this.#us.bind(this,n,r,a,o),undo:this.#us.bind(this,t,e,s,i),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#cs(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,a=this.width,o=this.height,h=se.MIN_SIZE/s,l=se.MIN_SIZE/i,c=this.#os(this.rotation),d=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],u=this.#os(360-this.rotation);let p,g,m=!1,f=!1;switch(t){case"topLeft":m=!0,p=(t,e)=>[0,0],g=(t,e)=>[t,e];break;case"topMiddle":p=(t,e)=>[t/2,0],g=(t,e)=>[t/2,e];break;case"topRight":m=!0,p=(t,e)=>[t,0],g=(t,e)=>[0,e];break;case"middleRight":f=!0,p=(t,e)=>[t,e/2],g=(t,e)=>[0,e/2];break;case"bottomRight":m=!0,p=(t,e)=>[t,e],g=(t,e)=>[0,0];break;case"bottomMiddle":p=(t,e)=>[t/2,e],g=(t,e)=>[t/2,0];break;case"bottomLeft":m=!0,p=(t,e)=>[0,e],g=(t,e)=>[t,0];break;case"middleLeft":f=!0,p=(t,e)=>[0,e/2],g=(t,e)=>[t,e/2]}const b=p(a,o),y=g(a,o);let A=d(...y);const w=se._round(n+A[0]),v=se._round(r+A[1]);let _,x,S=1,C=1;if(e.fromKeyboard)({deltaX:_,deltaY:x}=e);else{const{screenX:t,screenY:s}=e,[i,n]=this.#He;[_,x]=this.screenToPageTranslation(t-i,s-n),this.#He[0]=t,this.#He[1]=s}var k,T;if([_,x]=(k=_/s,T=x/i,[u[0]*k+u[2]*T,u[1]*k+u[3]*T]),m){const t=Math.hypot(a,o);S=C=Math.max(Math.min(Math.hypot(y[0]-b[0]-_,y[1]-b[1]-x)/t,1/a,1/o),h/a,l/o)}else f?S=yt(Math.abs(y[0]-b[0]-_),h,1)/a:C=yt(Math.abs(y[1]-b[1]-x),l,1)/o;const M=se._round(a*S),E=se._round(o*C);A=d(...g(M,E));const P=w-A[0],D=v-A[1];this.#Xe||=[this.x,this.y,this.width,this.height],this.width=M,this.height=E,this.x=P,this.y=D,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#h?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#qe)return this._editToolbar;this._editToolbar=new zt(this),this.div.append(this._editToolbar.render());const{toolbarButtons:t}=this;if(t)for(const[e,s]of t)await this._editToolbar.addButton(e,s);return this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton()),this._editToolbar.addButton("delete"),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#h?.destroy()}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#h||(Zt.initialize(se._l10n),this.#h=new Zt(this),this.#Re&&(this.#h.data=this.#Re,this.#Re=null)),this.#h}get altTextData(){return this.#h?.data}set altTextData(t){this.#h&&(this.#h.data=t)}get guessedAltText(){return this.#h?.guessedText}async setGuessedAltText(t){await(this.#h?.setGuessedText(t))}serializeAltText(t){return this.#h?.serialize(t)}hasAltText(){return!!this.#h&&!this.#h.isEmpty()}hasAltTextData(){return this.#h?.hasData()??!1}focusCommentButton(){this.#l?.focusButton()}addCommentButton(){return this.canAddComment?this.#l||=new te(this):null}addStandaloneCommentButton(){this._uiManager.hasCommentManager()&&(this.#ue?this._uiManager.isEditingMode()&&this.#ue.classList.remove("hidden"):this.hasComment&&(this.#ue=this.#l.renderForStandalone(),this.div.append(this.#ue)))}removeStandaloneCommentButton(){this.#l.removeStandaloneCommentButton(),this.#ue=null}hideStandaloneCommentButton(){this.#ue?.classList.add("hidden")}get comment(){if(!this.#l)return null;const{data:{richText:t,text:e,date:s,deleted:i}}=this.#l;return{text:e,richText:t,date:s,deleted:i,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#l||=new te(this),"object"==typeof t&&null!==t?this.#l.restoreData(t):this.#l.data=t,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:t,popupRef:e,richText:s}){if(!e)return;if(this.#l||=new te(this),this.#l.setInitialText(t,s),!this.annotationElementId)return;const i=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);i&&this.updateFromAnnotationLayer(i)}get hasEditedComment(){return this.#l?.hasBeenEdited()}get hasDeletedComment(){return this.#l?.isDeleted()}get hasComment(){return!!this.#l&&!this.#l.isEmpty()&&!this.#l.isDeleted()}async editComment(t){this.#l||=new te(this),this.#l.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#l.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const e=180,s=100,[,,,i]=t.rect,[n]=this.pageDimensions,[r]=this.pageTranslation,a=r+n+1,o=i-s,h=a+e;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[a,o,h,i]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#l.data=e?null:t}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360),t.className=this.name,t.setAttribute("id",this.id),t.tabIndex=this.#Be?-1:0,t.setAttribute("role","application"),this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||t.classList.add("hidden"),this.setInForeground(),this.#ps();const[e,s]=this.parentDimensions;this.parentRotation%180!=0&&(t.style.maxWidth=`${(100*s/e).toFixed(2)}%`,t.style.maxHeight=`${(100*e/s).toFixed(2)}%`);const[i,n]=this.getInitialTranslation();return this.translate(i,n),Wt(this,t,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#es||=new ee({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#gs.bind(this),onPinching:this.#ms.bind(this),onPinchEnd:this.#fs.bind(this),signal:this._uiManager._signal})),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),t}#gs(){this.#$e={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#h?.toggle(!1),this.parent.togglePointerEvents(!1)}#ms(t,e,s){let i=s/e*.7+1-.7;if(1===i)return;const n=this.#os(this.rotation),r=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[a,o]=this.parentDimensions,h=this.x,l=this.y,c=this.width,d=this.height,u=se.MIN_SIZE/a,p=se.MIN_SIZE/o;i=Math.max(Math.min(i,1/c,1/d),u/c,p/d);const g=se._round(c*i),m=se._round(d*i);if(g===c&&m===d)return;this.#Xe||=[h,l,c,d];const f=r(c/2,d/2),b=se._round(h+f[0]),y=se._round(l+f[1]),A=r(g/2,m/2);this.x=b-A[0],this.y=y-A[1],this.width=g,this.height=m,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#fs(){this.#h?.toggle(!0),this.parent.togglePointerEvents(!0),this.#ds()}pointerdown(t){const{isMac:e}=ut.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#Ve=!0,this._isDraggable?this.#bs(t):this.#ys(t))}#ys(t){const{isMac:e}=ut.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#bs(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let s=!1;const i=new AbortController,n=this._uiManager.combinedSignal(i),r={capture:!0,passive:!1,signal:n},a=t=>{i.abort(),this.#Le=null,this.#Ve=!1,this._uiManager.endDragSession()||this.#ys(t),s&&this._onStopDragging()};e&&(this.#Je=t.clientX,this.#Ze=t.clientY,this.#Le=t.pointerId,this.#Ue=t.pointerType,window.addEventListener("pointermove",t=>{s||(s=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());const{clientX:e,clientY:i,pointerId:n}=t;if(n!==this.#Le)return void Dt(t);const[r,a]=this.screenToPageTranslation(e-this.#Je,i-this.#Ze);this.#Je=e,this.#Ze=i,this._uiManager.dragSelectedEditors(r,a)},r),window.addEventListener("touchmove",Dt,r),window.addEventListener("pointerdown",t=>{t.pointerType===this.#Ue&&(this.#es||t.isPrimary)&&a(t),Dt(t)},r));const o=t=>{this.#Le&&this.#Le!==t.pointerId?Dt(t):a(t)};window.addEventListener("pointerup",o,{signal:n}),window.addEventListener("blur",o,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Qe&&clearTimeout(this.#Qe),this.#Qe=setTimeout(()=>{this.#Qe=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[a,o]=this.pageTranslation,h=t/i,l=e/i,c=this.x*n,d=this.y*r,u=this.width*n,p=this.height*r;switch(s){case 0:return[c+h+a,r-d-l-p+o,c+h+u+a,r-d-l+o];case 90:return[c+l+a,r-d+h+o,c+l+p+a,r-d+h+u+o];case 180:return[c-h-u+a,r-d+l+o,c-h+a,r-d+l+p+o];case 270:return[c-l-p+a,r-d-h-u+o,c-l+a,r-d-h+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,a=n-s,o=r-i;switch(this.rotation){case 0:return[s,e-r,a,o];case 90:return[s,e-i,o,a];case 180:return[n,e-i,a,o];case 270:return[n,e-r,o,a];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&se._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#l?.onUpdatedColor()}getData(){const{comment:{text:t,color:e,date:s,opacity:i,deleted:n,richText:r},uid:a,pageIndex:o,creationDate:h,modificationDate:l}=this;return{id:a,pageIndex:o,rect:this.getPDFRect(),richText:r,contentsObj:{str:t},creationDate:h,modificationDate:s||l,popupRef:!n,color:e,opacity:i}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#qe=!0,!0)}disableEditMode(){return!!this.isInEditMode()&&(this.parent.setEditingState(!0),this.#qe=!1,!0)}isInEditMode(){return this.#qe}shouldGetKeyboardEvents(){return this.#Ke}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:s,right:i}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e<r&&i>0&&t<n&&s>0}#ps(){if(this.#Ge||!this.div)return;this.#Ge=new AbortController;const t=this._uiManager.combinedSignal(this.#Ge);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#ps()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:s.getId(),uiManager:s,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});i.rotation=t.rotation,i.#Re=t.accessibilityData,i._isCopy=t.isCopy||!1;const[n,r]=i.pageDimensions,[a,o,h,l]=i.getRectInCurrentCoords(t.rect,r);return i.x=a/n,i.y=o/r,i.width=h/n,i.height=l/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#Ge?.abort(),this.#Ge=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),this.#Qe&&(clearTimeout(this.#Qe),this.#Qe=null),this.#ns(),this.removeEditToolbar(),this.#ts){for(const t of this.#ts.values())clearTimeout(t);this.#ts=null}this.parent=null,this.#es?.destroy(),this.#es=null,this.#ze?.remove(),this.#ze=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#hs(),this.#je.classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return"ltr"===this._uiManager.direction?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[t,e]}=this,[s,i,n,r]=this.getPDFRect();return[se._round(s+(n-s)*t),se._round(i+(r-i)*(1-e))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#l.commentPopupPositionInLayer}set commentPopupPosition(t){this.#l.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#l.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#l.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#l?.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#$e={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#je.children;if(!this.#Oe){this.#Oe=Array.from(e);const t=this.#As.bind(this),s=this.#ws.bind(this),i=this._uiManager._signal;for(const e of this.#Oe){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:i}),e.addEventListener("blur",s,{signal:i}),e.addEventListener("focus",this.#vs.bind(this,n),{signal:i}),e.setAttribute("data-l10n-id",se._l10nResizer[n])}}const s=this.#Oe[0];let i=0;for(const r of e){if(r===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#Oe.length/4);if(n!==i){if(n<i)for(let e=0;e<i-n;e++)this.#je.append(this.#je.firstElementChild);else if(n>i)for(let e=0;e<n-i;e++)this.#je.firstElementChild.before(this.#je.lastElementChild);let t=0;for(const s of e){const e=this.#Oe[t++].getAttribute("data-resizer-name");s.setAttribute("data-l10n-id",se._l10nResizer[e])}}this.#_s(0),this.#Ke=!0,this.#je.firstElementChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#As(t){se._resizerKeyboardManager.exec(this,t)}#ws(t){this.#Ke&&t.relatedTarget?.parentNode!==this.#je&&this.#ns()}#vs(t){this.#We=this.#Ke?t:""}#_s(t){if(this.#Oe)for(const e of this.#Oe)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#Ke&&this.#cs(this.#We,{deltaX:t,deltaY:e,fromKeyboard:!0})}#ns(){this.#Ke=!1,this.#_s(-1),this.#ds()}_stopResizingWithKeyboard(){this.#ns(),this.div.focus()}select(){this.isSelected&&this._editToolbar?this._editToolbar.show():(this.isSelected=!0,this.makeResizable(),this.div?.classList.add("selectedEditor"),this._editToolbar?(this._editToolbar?.show(),this.#h?.toggleAltTextBadge(!1)):this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#je?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#h?.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(t){"BUTTON"!==t.target.nodeName&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#Ye}set isEditing(t){this.#Ye=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#ts||=new Map;const{action:e}=t;let s=this.#ts.get(e);return s&&clearTimeout(s),s=setTimeout(()=>{this._reportTelemetry(t),this.#ts.delete(e),0===this.#ts.size&&(this.#ts=null)},se._telemetryTimeout),void this.#ts.set(e,s)}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#Be=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#Be=!0}updateFakeAnnotationElement(t){this.#ze||this.deleted?this.deleted?(this.#ze.remove(),this.#ze=null):(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#ze.updateEdited({rect:this.getPDFRect(),popup:this.comment}):this.#ze=t.addFakeAnnotation(this)}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.before(e)}}else e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);return e}resetAnnotationElement(t){const{firstElementChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class ie extends se{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const ne=3285377520,re=4294901760,ae=65535;class oe{constructor(t){this.h1=t?4294967295&t:ne,this.h2=t?4294967295&t:ne}update(t){let e,s;if("string"==typeof t){e=new Uint8Array(2*t.length),s=0;for(let i=0,n=t.length;i<n;i++){const n=t.charCodeAt(i);n<=255?e[s++]=n:(e[s++]=n>>>8,e[s++]=255&n)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),s=e.byteLength}const i=s>>2,n=s-4*i,r=new Uint32Array(e.buffer,0,i);let a=0,o=0,h=this.h1,l=this.h2;const c=3432918353,d=461845907,u=11601,p=13715;for(let g=0;g<i;g++)1&g?(a=r[g],a=a*c&re|a*u&ae,a=a<<15|a>>>17,a=a*d&re|a*p&ae,h^=a,h=h<<13|h>>>19,h=5*h+3864292196):(o=r[g],o=o*c&re|o*u&ae,o=o<<15|o>>>17,o=o*d&re|o*p&ae,l^=o,l=l<<13|l>>>19,l=5*l+3864292196);switch(a=0,n){case 3:a^=e[4*i+2]<<16;case 2:a^=e[4*i+1]<<8;case 1:a^=e[4*i],a=a*c&re|a*u&ae,a=a<<15|a>>>17,a=a*d&re|a*p&ae,1&i?h^=a:l^=a}this.h1=h,this.h2=l}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&re|36045*t&ae,e=4283543511*e&re|(2950163797*(e<<16|t>>>16)&re)>>>16,t^=e>>>1,t=444984403*t&re|60499*t&ae,e=3301882366*e&re|(3120437893*(e<<16|t>>>16)&re)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const he=Object.freeze({map:null,hash:"",transfer:void 0});class le{#xs=!1;#Ss=null;#Cs=null;#ks=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(t,e){const s=this.#ks.get(t);return void 0===s?e:Object.assign(e,s)}getRawValue(t){return this.#ks.get(t)}remove(t){const e=this.#ks.get(t);void 0!==e&&(e instanceof se&&this.#Cs.delete(e.annotationElementId),this.#ks.delete(t),0===this.#ks.size&&this.resetModified(),this.#ks.values().some(t=>t instanceof se)||this.onAnnotationEditor?.(null))}setValue(t,e){const s=this.#ks.get(t);let i=!1;if(void 0!==s)for(const[n,r]of Object.entries(e))s[n]!==r&&(i=!0,s[n]=r);else i=!0,this.#ks.set(t,e);i&&this.#Ts(),e instanceof se&&((this.#Cs||=new Map).set(e.annotationElementId,e),this.onAnnotationEditor?.(e.constructor._type))}has(t){return this.#ks.has(t)}get size(){return this.#ks.size}#Ts(){this.#xs||(this.#xs=!0,this.onSetModified?.())}resetModified(){this.#xs&&(this.#xs=!1,this.onResetModified?.())}get print(){return new ce(this)}get serializable(){if(0===this.#ks.size)return he;const t=new Map,e=new oe,s=[],i=Object.create(null);let n=!1;for(const[r,a]of this.#ks){const s=a instanceof se?a.serialize(!1,i):a;a.page&&(a.pageIndex=a.page._pageIndex,delete a.page),s&&(t.set(r,s),e.update(`${r}:${JSON.stringify(s)}`),n||=!!s.bitmap)}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:he}get editorStats(){let t=null;const e=new Map;let s=0,i=0;for(const n of this.#ks.values()){if(!(n instanceof se)){n.popup&&(n.popup.deleted?i+=1:s+=1);continue}n.isCommentDeleted?i+=1:n.hasEditedComment&&(s+=1);const r=n.telemetryFinalData;if(!r)continue;const{type:a}=r;e.has(a)||e.set(a,Object.getPrototypeOf(n).constructor),t||=Object.create(null);const o=t[a]||=new Map;for(const[t,e]of Object.entries(r)){if("type"===t)continue;const s=o.getOrInsertComputed(t,ft);s.set(e,(s.get(e)??0)+1)}}if((i>0||s>0)&&(t||=Object.create(null),t.comments={deleted:i,edited:s}),!t)return null;for(const[n,r]of e)t[n]=r.computeTelemetryFinalData(t[n]);return t}resetModifiedIds(){this.#Ss=null}updateEditor(t,e){const s=this.#Cs?.get(t);return!!s&&(s.updateFromAnnotationLayer(e),!0)}getEditor(t){return this.#Cs?.get(t)||null}get modifiedIds(){if(this.#Ss)return this.#Ss;const t=[];if(this.#Cs)for(const s of this.#Cs.values())s.serialize()&&t.push(s.annotationElementId);let e="";if(t.length){const s=new oe;s.update(t.join(",")),e=s.hexdigest()}return this.#Ss={ids:new Set(t),hash:e}}[Symbol.iterator](){return this.#ks.entries()}}class ce extends le{#Ms=he;constructor(t){super();const{serializable:e}=t;if(e===he)return;const{map:s,hash:i,transfer:n}=e,r=structuredClone(s,n?{transfer:n}:null);this.#Ms={map:r,hash:i,transfer:[]}}get print(){Z("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#Ms}get modifiedIds(){return it(this,"modifiedIds",{ids:new Set,hash:""})}}const de="__forcedDependency",{floor:ue,ceil:pe}=Math;function ge(t,e,s,i,n,r){t[4*e+0]=Math.min(t[4*e+0],s),t[4*e+1]=Math.min(t[4*e+1],i),t[4*e+2]=Math.max(t[4*e+2],n),t[4*e+3]=Math.max(t[4*e+3],r)}const me=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class fe{#Es;#Ps;constructor(t,e){this.#Es=t,this.#Ps=e}get length(){return this.#Es.length}isEmpty(t){return this.#Es[t]===me}minX(t){return this.#Ps[4*t+0]/256}minY(t){return this.#Ps[4*t+1]/256}maxX(t){return(this.#Ps[4*t+2]+1)/256}maxY(t){return(this.#Ps[4*t+3]+1)/256}}const be=(t,e)=>t?.getOrInsertComputed(e,()=>({dependencies:new Set,isRenderingOperation:!1}));class ye{#Ds=[[1,0,0,1,0,0]];#Is=[-1/0,-1/0,1/0,1/0];#Fs=new Float64Array(u);_pendingBBoxIdx=-1;#Ns;#Rs;#Os;#Es;_savesStack=[];_markedContentStack=[];constructor(t,e){this.#Ns=t.width,this.#Rs=t.height,this.#Bs(e)}growOperationsCount(t){t>=this.#Es.length&&this.#Bs(t,this.#Es)}#Bs(t,e){const s=new ArrayBuffer(4*t);this.#Os=new Uint8ClampedArray(s),this.#Es=new Uint32Array(s),e&&e.length>0?(this.#Es.set(e),this.#Es.fill(me,e.length)):this.#Es.fill(me)}get clipBox(){return this.#Is}save(t){return this.#Is={__proto__:this.#Is},this._savesStack.push(t),this}restore(t,e){const s=Object.getPrototypeOf(this.#Is);if(null===s)return this;this.#Is=s;const i=this._savesStack.pop();return void 0!==i&&(e?.(i,t),this.#Es[t]=this.#Es[i]),this}recordOpenMarker(t){return this._savesStack.push(t),this}getOpenMarker(){return 0===this._savesStack.length?null:this._savesStack.at(-1)}recordCloseMarker(t,e){const s=this._savesStack.pop();return void 0!==s&&(e?.(s,t),this.#Es[t]=this.#Es[s]),this}beginMarkedContent(t){return this._markedContentStack.push(t),this}endMarkedContent(t,e){const s=this._markedContentStack.pop();return void 0!==s&&(e?.(s,t),this.#Es[t]=this.#Es[s]),this}pushBaseTransform(t){return this.#Ds.push(pt.multiplyByDOMMatrix(this.#Ds.at(-1),t.getTransform())),this}popBaseTransform(){return this.#Ds.length>1&&this.#Ds.pop(),this}resetBBox(t){return this._pendingBBoxIdx!==t&&(this._pendingBBoxIdx=t,this.#Fs.set(u,0)),this}recordClipBox(t,e,s,i,n,r){const a=pt.multiplyByDOMMatrix(this.#Ds.at(-1),e.getTransform()),o=u.slice();pt.axialAlignedBoundingBox([s,n,i,r],a,o);const h=pt.intersect(this.#Is,o);return h?(this.#Is[0]=h[0],this.#Is[1]=h[1],this.#Is[2]=h[2],this.#Is[3]=h[3]):(this.#Is[0]=this.#Is[1]=1/0,this.#Is[2]=this.#Is[3]=-1/0),this}recordBBox(t,e,s,i,n,r){const a=this.#Is;if(a[0]===1/0)return this;const o=pt.multiplyByDOMMatrix(this.#Ds.at(-1),e.getTransform());if(a[0]===-1/0)return pt.axialAlignedBoundingBox([s,n,i,r],o,this.#Fs),this;const h=u.slice();return pt.axialAlignedBoundingBox([s,n,i,r],o,h),this.#Fs[0]=yt(h[0],a[0],this.#Fs[0]),this.#Fs[1]=yt(h[1],a[1],this.#Fs[1]),this.#Fs[2]=yt(h[2],this.#Fs[2],a[2]),this.#Fs[3]=yt(h[3],this.#Fs[3],a[3]),this}recordFullPageBBox(t){return this.#Fs[0]=Math.max(0,this.#Is[0]),this.#Fs[1]=Math.max(0,this.#Is[1]),this.#Fs[2]=Math.min(this.#Ns,this.#Is[2]),this.#Fs[3]=Math.min(this.#Rs,this.#Is[3]),this}recordOperation(t,e=!1,s){if(this._pendingBBoxIdx!==t)return this;const i=ue(256*this.#Fs[0]/this.#Ns),n=ue(256*this.#Fs[1]/this.#Rs),r=pe(256*this.#Fs[2]/this.#Ns),a=pe(256*this.#Fs[3]/this.#Rs);if(ge(this.#Os,t,i,n,r,a),s)for(const o of s)for(const e of o)e!==t&&ge(this.#Os,e,i,n,r,a);return e||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(t){return this._pendingBBoxIdx===t&&(this._pendingBBoxIdx=-1,this.#Is[0]=Math.max(this.#Is[0],this.#Fs[0]),this.#Is[1]=Math.max(this.#Is[1],this.#Fs[1]),this.#Is[2]=Math.min(this.#Is[2],this.#Fs[2]),this.#Is[3]=Math.min(this.#Is[3],this.#Fs[3])),this}take(){return new fe(this.#Es,this.#Os)}takeDebugMetadata(){throw new Error("Unreachable")}recordSimpleData(t,e){return this}recordIncrementalData(t,e){return this}resetIncrementalData(t,e){return this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,s){return this}recordFutureForcedDependency(t,e){return this}inheritSimpleDataAsFutureForcedDependencies(t){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(t,e,s,i=1,n=0,r=0,a){return this}getSimpleIndex(t){}recordDependencies(t,e){return this}recordNamedDependency(t,e){return this}recordShowTextOperation(t,e=!1){return this}}class Ae{#Ls={__proto__:null};#Us={__proto__:null,transform:[],moveText:[],sameLineText:[],[de]:[]};#js=new Map;#Hs=new Set;#$s=new Map;#zs;#Gs;#Ws;constructor(t,e=!1){this.#Ws=t,e&&(this.#zs=new Map,this.#Gs=(t,e)=>{be(this.#zs,e).dependencies.add(t)})}get clipBox(){return this.#Ws.clipBox}growOperationsCount(t){this.#Ws.growOperationsCount(t)}save(t){return this.#Ls={__proto__:this.#Ls},this.#Us={__proto__:this.#Us,transform:{__proto__:this.#Us.transform},moveText:{__proto__:this.#Us.moveText},sameLineText:{__proto__:this.#Us.sameLineText},[de]:{__proto__:this.#Us[de]}},this.#Ws.save(t),this}restore(t){this.#Ws.restore(t,this.#Gs);const e=Object.getPrototypeOf(this.#Ls);return null===e||(this.#Ls=e,this.#Us=Object.getPrototypeOf(this.#Us)),this}recordOpenMarker(t){return this.#Ws.recordOpenMarker(t,this.#Gs),this}getOpenMarker(){return this.#Ws.getOpenMarker()}recordCloseMarker(t){return this.#Ws.recordCloseMarker(t,this.#Gs),this}beginMarkedContent(t){return this.#Ws.beginMarkedContent(t),this}endMarkedContent(t){return this.#Ws.endMarkedContent(t,this.#Gs),this}pushBaseTransform(t){return this.#Ws.pushBaseTransform(t),this}popBaseTransform(){return this.#Ws.popBaseTransform(),this}recordSimpleData(t,e){return this.#Ls[t]=e,this}recordIncrementalData(t,e){return this.#Us[t].push(e),this}resetIncrementalData(t,e){return this.#Us[t].length=0,this}recordNamedData(t,e){return this.#js.set(t,e),this}recordSimpleDataFromNamed(t,e,s){this.#Ls[t]=this.#js.get(e)??s}recordFutureForcedDependency(t,e){return this.recordIncrementalData(de,e),this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#Ls&&this.recordFutureForcedDependency(e,this.#Ls[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#Hs)this.recordFutureForcedDependency(de,t);return this}resetBBox(t){return this.#Ws.resetBBox(t),this}recordClipBox(t,e,s,i,n,r){return this.#Ws.recordClipBox(t,e,s,i,n,r),this}recordBBox(t,e,s,i,n,r){return this.#Ws.recordBBox(t,e,s,i,n,r),this}recordCharacterBBox(t,e,s,i=1,n=0,r=0,a){const o=s.bbox;let h,l;if(o&&(h=o[2]!==o[0]&&o[3]!==o[1]&&this.#$s.get(s),!1!==h&&(l=[0,0,0,0],pt.axialAlignedBoundingBox(o,s.fontMatrix,l),1===i&&0===n&&0===r||pt.scaleMinMax([i,0,0,-i,n,r],l),h)))return this.recordBBox(t,e,l[0],l[2],l[1],l[3]);if(!a)return this.recordFullPageBBox(t);const c=a();return o&&l&&void 0===h&&(h=l[0]<=n-c.actualBoundingBoxLeft&&l[2]>=n+c.actualBoundingBoxRight&&l[1]<=r-c.actualBoundingBoxAscent&&l[3]>=r+c.actualBoundingBoxDescent,this.#$s.set(s,h),h)?this.recordBBox(t,e,l[0],l[2],l[1],l[3]):this.recordBBox(t,e,n-c.actualBoundingBoxLeft,n+c.actualBoundingBoxRight,r-c.actualBoundingBoxAscent,r+c.actualBoundingBoxDescent)}recordFullPageBBox(t){return this.#Ws.recordFullPageBBox(t),this}getSimpleIndex(t){return this.#Ls[t]}recordDependencies(t,e){const s=this.#Hs,i=this.#Ls,n=this.#Us;for(const r of e)r in this.#Ls?s.add(i[r]):r in n&&n[r].forEach(s.add,s);return this}recordNamedDependency(t,e){return this.#js.has(e)&&this.#Hs.add(this.#js.get(e)),this}recordOperation(t,e=!1){if(this.recordDependencies(t,[de]),this.#zs){const e=be(this.#zs,t),{dependencies:s}=e;this.#Hs.forEach(s.add,s),this.#Ws._savesStack.forEach(s.add,s),this.#Ws._markedContentStack.forEach(s.add,s),s.delete(t),e.isRenderingOperation=!0}const s=!e&&t===this.#Ws._pendingBBoxIdx;return this.#Ws.recordOperation(t,e,[this.#Hs,this.#Ws._savesStack,this.#Ws._markedContentStack]),s&&this.#Hs.clear(),this}recordShowTextOperation(t,e=!1){const s=Array.from(this.#Hs);this.recordOperation(t,e),this.recordIncrementalData("sameLineText",t);for(const i of s)this.recordIncrementalData("sameLineText",i);return this}bboxToClipBoxDropOperation(t,e=!1){const s=!e&&t===this.#Ws._pendingBBoxIdx;return this.#Ws.bboxToClipBoxDropOperation(t),s&&this.#Hs.clear(),this}take(){return this.#$s.clear(),this.#Ws.take()}takeDebugMetadata(){return this.#zs}}class we{#Vs;#Xs;#Ys;#qs=0;#Ks=0;constructor(t,e,s){if(t instanceof we&&t.#Ys===!!s)return t;this.#Vs=t,this.#Xs=e,this.#Ys=!!s}get clipBox(){return this.#Vs.clipBox}growOperationsCount(){throw new Error("Unreachable")}save(t){return this.#Ks++,this.#Vs.save(this.#Xs),this}restore(t){return this.#Ks>0&&(this.#Vs.restore(this.#Xs),this.#Ks--),this}recordOpenMarker(t){return this.#qs++,this}getOpenMarker(){return this.#qs>0?this.#Xs:this.#Vs.getOpenMarker()}recordCloseMarker(t){return this.#qs--,this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){return this.#Vs.pushBaseTransform(t),this}popBaseTransform(){return this.#Vs.popBaseTransform(),this}recordSimpleData(t,e){return this.#Vs.recordSimpleData(t,this.#Xs),this}recordIncrementalData(t,e){return this.#Vs.recordIncrementalData(t,this.#Xs),this}resetIncrementalData(t,e){return this.#Vs.resetIncrementalData(t,this.#Xs),this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,s){return this.#Vs.recordSimpleDataFromNamed(t,e,this.#Xs),this}recordFutureForcedDependency(t,e){return this.#Vs.recordFutureForcedDependency(t,this.#Xs),this}inheritSimpleDataAsFutureForcedDependencies(t){return this.#Vs.inheritSimpleDataAsFutureForcedDependencies(t),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#Vs.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(t){return this.#Ys||this.#Vs.resetBBox(this.#Xs),this}recordClipBox(t,e,s,i,n,r){return this.#Ys||this.#Vs.recordClipBox(this.#Xs,e,s,i,n,r),this}recordBBox(t,e,s,i,n,r){return this.#Ys||this.#Vs.recordBBox(this.#Xs,e,s,i,n,r),this}recordCharacterBBox(t,e,s,i,n,r,a){return this.#Ys||this.#Vs.recordCharacterBBox(this.#Xs,e,s,i,n,r,a),this}recordFullPageBBox(t){return this.#Ys||this.#Vs.recordFullPageBBox(this.#Xs),this}getSimpleIndex(t){return this.#Vs.getSimpleIndex(t)}recordDependencies(t,e){return this.#Vs.recordDependencies(this.#Xs,e),this}recordNamedDependency(t,e){return this.#Vs.recordNamedDependency(this.#Xs,e),this}recordOperation(t){return this.#Vs.recordOperation(this.#Xs,!0),this}recordShowTextOperation(t){return this.#Vs.recordShowTextOperation(this.#Xs,!0),this}bboxToClipBoxDropOperation(t){return this.#Ys||this.#Vs.bboxToClipBoxDropOperation(this.#Xs,!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const ve=["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],_e=["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],xe=["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],Se=["filter","fillColor","fillAlpha"],Ce=["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],ke=["transform"],Te=["transform","fillColor"];class Me{#Ns;#Rs;#Qs=4;#Js=0;#Ps=new Me.#Zs(6*this.#Qs);static#Zs=ut.isFloat16ArraySupported?Float16Array:Float32Array;constructor(t){this.#Ns=t.width,this.#Rs=t.height}record(t,e,s,i){if(this.#Js===this.#Qs){this.#Qs*=2;const t=new Me.#Zs(6*this.#Qs);t.set(this.#Ps),this.#Ps=t}const n=pt.domMatrixToTransform(t.getTransform());let r;if(i[0]!==1/0){const t=u.slice();pt.axialAlignedBoundingBox([0,-s,e,0],n,t);const a=pt.intersect(i,t);if(!a)return;const[o,h,l,c]=a;if(o!==t[0]||h!==t[1]||l!==t[2]||c!==t[3]){const t=Math.atan2(n[1],n[0]),e=Math.abs(Math.sin(t)),s=Math.abs(Math.cos(t));if(e<1e-6||s<1e-6||Math.abs(e-s)<1e-6)r=[o,h,o,c,l,h];else{const t=l-o,i=c-h,n=e*e,a=s*s,d=s*e,u=a-n,p=(i*a-t*d)/u;r=[o+(i*d-t*n)/u,h,o,h+p,l,c-p]}}}r||(r=[0,-s,0,0,e,-s],pt.applyTransform(r,n,0),pt.applyTransform(r,n,2),pt.applyTransform(r,n,4)),r[0]/=this.#Ns,r[1]/=this.#Rs,r[2]/=this.#Ns,r[3]/=this.#Rs,r[4]/=this.#Ns,r[5]/=this.#Rs,this.#Ps.set(r,6*this.#Js),this.#Js++}take(){return this.#Ps.subarray(0,6*this.#Js)}}class Ee{#ti=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#ti.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:s}){if(t&&!this.#ti.has(t.loadedName)){if(tt(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:e,src:i,style:n}=t,r=new FontFace(e,i,n);this.addNativeFontFace(r);try{await r.load(),this.#ti.add(e),s?.(t)}catch{J(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}Z("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo)return void await this.loadSystemFont(t);if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(p){throw J(`Failed to load font '${e.family}': '${p}'.`),t.disableFontFace=!0,p}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(e=>{const s=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,s)})}}get isFontLoadingAPISupported(){return it(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return it(this,"isSyncFontLoadingSupported",d||ut.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:e}=this,s={done:!1,complete:function(){for(tt(!s.done,"completeRequest() cannot be called twice."),s.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(s),s}get _loadTestFont(){return it(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function s(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function i(t,e,s,i){return t.substring(0,e)+i+t.substring(e+s)}let n,r;const a=this._document.createElement("canvas");a.width=1,a.height=1;const o=a.getContext("2d");let h=0;const l=`lt${Date.now()}${this.loadTestFontId++}`;let c=this._loadTestFont;c=i(c,976,l.length,l);const d=1482184792;let u=s(c,16);for(n=0,r=l.length-3;n<r;n+=4)u=u-d+s(l,n)|0;n<l.length&&(u=u-d+s(l+"XXX",n)|0),c=i(c,16,4,function(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)}(u));const p=`@font-face {font-family:"${l}";src:url(data:font/opentype;base64,${btoa(c)});}`;this.insertRule(p);const g=this._document.createElement("div");g.style.visibility="hidden",g.style.width=g.style.height="10px",g.style.position="absolute",g.style.top=g.style.left="0px";for(const m of[t.loadedName,l]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=m,g.append(t)}this._document.body.append(g),function t(e,s){if(++h>30)return J("Load test font never loaded."),void s();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?s():setTimeout(t.bind(null,e,s))}(l,()=>{g.remove(),e.complete()})}}class Pe{compiledGlyphs=Object.create(null);#ei;constructor(t,e=null,s,i){this.#ei=t,this._inspectFont=e,s&&(this.charProcOperatorList=s),i&&Object.assign(this,i)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${this.data.toBase64()});`;let e;if(this.cssFontInfo){let s=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(s+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${s}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const s=this.loadedName+"_path_"+e;let i;try{i=t.get(s)}catch(t){J(`getPathGenerator - ignoring character: "${t}".`)}const n=$t(i?.path);return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}get black(){return this.#ei.black}get bold(){return this.#ei.bold}get disableFontFace(){return this.#ei.disableFontFace}set disableFontFace(t){it(this,"disableFontFace",!!t)}get fontExtraProperties(){return this.#ei.fontExtraProperties}get isInvalidPDFjsFont(){return this.#ei.isInvalidPDFjsFont}get isType3Font(){return this.#ei.isType3Font}get italic(){return this.#ei.italic}get missingFile(){return this.#ei.missingFile}get remeasure(){return this.#ei.remeasure}get vertical(){return this.#ei.vertical}get ascent(){return this.#ei.ascent}get defaultWidth(){return this.#ei.defaultWidth}get descent(){return this.#ei.descent}get bbox(){return this.#ei.bbox}get fontMatrix(){return this.#ei.fontMatrix}get fallbackName(){return this.#ei.fallbackName}get loadedName(){return this.#ei.loadedName}get mimetype(){return this.#ei.mimetype}get name(){return this.#ei.name}get data(){return this.#ei.data}clearData(){this.#ei.clearData()}get cssFontInfo(){return this.#ei.cssFontInfo}get systemFontInfo(){return this.#ei.systemFontInfo}get defaultVMetrics(){return this.#ei.defaultVMetrics}}class De{static strings=["fontFamily","fontWeight","italicAngle"]}class Ie{static strings=["css","loadedName","baseFontName","src"]}class Fe{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static OFFSET_NUMBERS=Math.ceil(2*this.bools.length/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+8*this.numbers.length;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6}class Ne{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16}class Re{#si;#ii=new TextDecoder;#ni;constructor(t){this.#si=t,this.#ni=new DataView(t)}#ri(t){tt(t<De.strings.length,"Invalid string index");let e=0;for(let i=0;i<t;i++)e+=this.#ni.getUint32(e)+4;const s=this.#ni.getUint32(e);return this.#ii.decode(new Uint8Array(this.#si,e+4,s))}get fontFamily(){return this.#ri(0)}get fontWeight(){return this.#ri(1)}get italicAngle(){return this.#ri(2)}}class Oe{#si;#ii=new TextDecoder;#ni;constructor(t){this.#si=t,this.#ni=new DataView(t)}get guessFallback(){return 0!==this.#ni.getUint8(0)}#ri(t){tt(t<Ie.strings.length,"Invalid string index");let e=5;for(let i=0;i<t;i++)e+=this.#ni.getUint32(e)+4;const s=this.#ni.getUint32(e);return this.#ii.decode(new Uint8Array(this.#si,e+4,s))}get css(){return this.#ri(0)}get loadedName(){return this.#ri(1)}get baseFontName(){return this.#ri(2)}get src(){return this.#ri(3)}get style(){let t=1;t+=4+this.#ni.getUint32(t);const e=this.#ni.getUint32(t),s=this.#ii.decode(new Uint8Array(this.#si,t+4,e));t+=4+e;const i=this.#ni.getUint32(t);return{style:s,weight:this.#ii.decode(new Uint8Array(this.#si,t+4,i))}}}class Be{#si;#ii=new TextDecoder;#ni;constructor({buffer:t,extra:e}){this.#si=t,this.#ni=new DataView(t),e&&Object.assign(this,e)}#ai(t){tt(t<Fe.bools.length,"Invalid boolean index");const e=Math.floor(t/4),s=2*t%8,i=this.#ni.getUint8(e)>>s&3;return 0===i?void 0:2===i}get black(){return this.#ai(0)}get bold(){return this.#ai(1)}get disableFontFace(){return this.#ai(2)}get fontExtraProperties(){return this.#ai(3)}get isInvalidPDFjsFont(){return this.#ai(4)}get isType3Font(){return this.#ai(5)}get italic(){return this.#ai(6)}get missingFile(){return this.#ai(7)}get remeasure(){return this.#ai(8)}get vertical(){return this.#ai(9)}#oi(t){return tt(t<Fe.numbers.length,"Invalid number index"),this.#ni.getFloat64(Fe.OFFSET_NUMBERS+8*t)}get ascent(){return this.#oi(0)}get defaultWidth(){return this.#oi(1)}get descent(){return this.#oi(2)}#hi(t,e,s,i){const n=this.#ni.getUint8(t);if(0===n)return;tt(n===e,"Invalid array length."),t+=1;const r=new Array(n);for(let a=0;a<n;a++)r[a]=this.#ni[s](t,!0),t+=i;return r}get bbox(){return this.#hi(Fe.OFFSET_BBOX,4,"getInt16",2)}get fontMatrix(){return this.#hi(Fe.OFFSET_FONT_MATRIX,6,"getFloat64",8)}get defaultVMetrics(){return this.#hi(Fe.OFFSET_DEFAULT_VMETRICS,3,"getInt16",2)}#ri(t){tt(t<Fe.strings.length,"Invalid string index");let e=Fe.OFFSET_STRINGS+4;for(let i=0;i<t;i++)e+=this.#ni.getUint32(e)+4;const s=this.#ni.getUint32(e);return this.#ii.decode(new Uint8Array(this.#si,e+4,s))}get fallbackName(){return this.#ri(0)}get loadedName(){return this.#ri(1)}get mimetype(){return this.#ri(2)}get name(){return this.#ri(3)}#li(){let t=Fe.OFFSET_STRINGS;return t+=4+this.#ni.getUint32(t),t+=4+this.#ni.getUint32(t),t+=4+this.#ni.getUint32(t),{offset:t,length:this.#ni.getUint32(t)}}get data(){const{offset:t,length:e}=this.#li();return 0===e?void 0:new Uint8Array(this.#si,t+4,e)}clearData(){const{offset:t,length:e}=this.#li();0!==e&&(this.#ni.setUint32(t,0),this.#si=new Uint8Array(this.#si,0,t+4).slice().buffer,this.#ni=new DataView(this.#si))}get cssFontInfo(){let t=Fe.OFFSET_STRINGS;t+=4+this.#ni.getUint32(t),t+=4+this.#ni.getUint32(t);const e=this.#ni.getUint32(t);if(0===e)return null;const s=new Uint8Array(e);return s.set(new Uint8Array(this.#si,t+4,e)),new Re(s.buffer)}get systemFontInfo(){let t=Fe.OFFSET_STRINGS;t+=4+this.#ni.getUint32(t);const e=this.#ni.getUint32(t);if(0===e)return null;const s=new Uint8Array(e);return s.set(new Uint8Array(this.#si,t+4,e)),new Oe(s.buffer)}}class Le{constructor(t){this.buffer=t,this.view=new DataView(t),this.data=new Uint8Array(t)}getIR(){const t=this.view,e=this.data[Ne.KIND],s=!!this.data[Ne.HAS_BBOX],i=!!this.data[Ne.HAS_BACKGROUND],n=t.getUint32(Ne.N_COORD,!0),r=t.getUint32(Ne.N_COLOR,!0),a=t.getUint32(Ne.N_STOP,!0);let o=20;const h=new Float32Array(this.buffer,o,2*n);o+=8*n;const l=new Uint8Array(this.buffer,o,4*r);o+=4*r;const c=[];for(let u=0;u<a;++u){const e=t.getFloat32(o,!0);o+=4;const s=t.getUint32(o,!0);o+=4,c.push([e,`#${s.toString(16).padStart(6,"0")}`])}let d=null;if(s){d=[];for(let e=0;e<4;++e)d.push(t.getFloat32(o,!0)),o+=4}let p=null;if(i&&(p=new Uint8Array(this.buffer,o,3),o+=3),1===e)return["RadialAxial","axial",d,c,Array.from(h.slice(0,2)),Array.from(h.slice(2,4)),null,null];if(2===e)return["RadialAxial","radial",d,c,[h[0],h[1]],[h[3],h[4]],h[2],h[5]];if(3===e){const t=this.data[Ne.SHADING_TYPE];let e=null;if(h.length>0){e=u.slice();for(let t=0,s=h.length;t<s;t+=2)pt.pointBoundingBox(h[t],h[t+1],e)}return["Mesh",t,h,l,n,e,d,p]}throw new Error(`Unsupported pattern kind: ${e}`)}}class Ue{#si;constructor(t){this.#si=t}get path(){return ut.isFloat16ArraySupported?new Float16Array(this.#si):new Float32Array(this.#si)}}function je(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const He=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0;(function(t,e,s){if(!Array.isArray(s)||s.length<2)return!1;const[i,n,...r]=s;if(!t(i)&&!Number.isInteger(i))return!1;if(!e(n))return!1;const a=r.length;let o=!0;switch(n.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return 0===a;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(4!==a)return!1;o=!1;break;default:return!1}for(const h of r)if(!("number"==typeof h||o&&null===h))return!1;return!0}).bind(null,He,t=>"object"==typeof t&&"string"==typeof t?.name);class $e{#ci=new Map;#di=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#di.then(()=>{for(const[t]of this.#ci)t.call(this,s)})}addEventListener(t,e,s=null){let i=null;if(s?.signal instanceof AbortSignal){const{signal:n}=s;if(n.aborted)return void J("LoopbackPort - cannot use an `aborted` signal.");const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}this.#ci.set(e,i)}removeEventListener(t,e){const s=this.#ci.get(e);s?.(),this.#ci.delete(e)}terminate(){for(const[,t]of this.#ci)t?.();this.#ci.clear()}}const ze=1,Ge=2,We=1,Ve=2,Xe=3,Ye=4,qe=5,Ke=6,Qe=7,Je=8;function Ze(){}function ts(t){if(t instanceof ct||t instanceof ot||t instanceof rt||t instanceof ht||t instanceof at)return t;switch(t instanceof Error||"object"==typeof t&&null!==t||Z('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new ct(t.message);case"InvalidPDFException":return new ot(t.message);case"PasswordException":return new rt(t.message,t.code);case"ResponseException":return new ht(t.message,t.status,t.missing);case"UnknownErrorException":return new at(t.message,t.details)}return new at(t.message,t.toString())}class es{#ui=new AbortController;constructor(t,e,s){this.sourceName=t,this.targetName=e,this.comObj=s,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),s.addEventListener("message",this.#pi.bind(this),{signal:this.#ui.signal})}#pi({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream)return void this.#gi(t);if(t.callback){const e=t.callbackId,s=this.callbackCapabilities[e];if(!s)throw new Error(`Cannot resolve callback ${e}`);if(delete this.callbackCapabilities[e],t.callback===ze)s.resolve(t.data);else{if(t.callback!==Ge)throw new Error("Unexpected callback case");s.reject(ts(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;return void Promise.try(e,t.data).then(function(e){n.postMessage({sourceName:s,targetName:i,callback:ze,callbackId:t.callbackId,data:e})},function(e){n.postMessage({sourceName:s,targetName:i,callback:Ge,callbackId:t.callbackId,reason:ts(e)})})}t.streamId?this.#mi(t):e(t.data)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,r=this.sourceName,a=this.targetName,o=this.comObj;return new ReadableStream({start:s=>{const h=Promise.withResolvers();return this.streamControllers[n]={controller:s,startCall:h,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:r,targetName:a,action:t,streamId:n,data:e,desiredSize:s.desiredSize},i),h.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[n].pullCall=e,o.postMessage({sourceName:r,targetName:a,stream:Ke,streamId:n,desiredSize:t.desiredSize}),e.promise},cancel:t=>{tt(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[n].cancelCall=e,this.streamControllers[n].isClosed=!0,o.postMessage({sourceName:r,targetName:a,stream:We,streamId:n,reason:ts(t)}),e.promise}},s)}#mi(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,a=this.actionHandler[t.action],o={enqueue(t,r=1,a){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=r,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:Ye,streamId:e,chunk:t},a)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Xe,streamId:e}),delete r.streamSinks[e])},error(t){tt(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:qe,streamId:e,reason:ts(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,Promise.try(a,t.data,o).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Je,streamId:e,success:!0})},function(t){n.postMessage({sourceName:s,targetName:i,stream:Je,streamId:e,reason:ts(t)})})}#gi(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case Je:t.success?r.startCall.resolve():r.startCall.reject(ts(t.reason));break;case Qe:t.success?r.pullCall.resolve():r.pullCall.reject(ts(t.reason));break;case Ke:if(!a){n.postMessage({sourceName:s,targetName:i,stream:Qe,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve(),a.desiredSize=t.desiredSize,Promise.try(a.onPull||Ze).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Qe,streamId:e,success:!0})},function(t){n.postMessage({sourceName:s,targetName:i,stream:Qe,streamId:e,reason:ts(t)})});break;case Ye:if(tt(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case Xe:if(tt(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#fi(r,e);break;case qe:tt(r,"error should have stream controller"),r.controller.error(ts(t.reason)),this.#fi(r,e);break;case Ve:t.success?r.cancelCall.resolve():r.cancelCall.reject(ts(t.reason)),this.#fi(r,e);break;case We:if(!a)break;const o=ts(t.reason);Promise.try(a.onCancel||Ze,o).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ve,streamId:e,success:!0})},function(t){n.postMessage({sourceName:s,targetName:i,stream:Ve,streamId:e,reason:ts(t)})}),a.sinkCapability.reject(o),a.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#fi(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#ui?.abort(),this.#ui=null}}class ss{#bi=Object.freeze({cMapUrl:"CMap",standardFontDataUrl:"font",wasmUrl:"wasm"});constructor({cMapUrl:t=null,standardFontDataUrl:e=null,wasmUrl:s=null}){this.cMapUrl=t,this.standardFontDataUrl=e,this.wasmUrl=s}async fetch({kind:t,filename:e}){switch(t){case"cMapUrl":case"standardFontDataUrl":case"wasmUrl":break;default:Z(`Not implemented: ${t}`)}const s=this[t];if(!s)throw new Error(`Ensure that the \`${t}\` API parameter is provided.`);const i=`${s}${e}`;return this._fetch(i,t).catch(e=>{throw new Error(`Unable to load ${this.#bi[t]} data at: ${i}`)})}async _fetch(t,e){Z("Abstract method `_fetch` called.")}}class is extends ss{async _fetch(t,e){const s="cMapUrl"!==e||t.endsWith(".bcmap")?"bytes":"text",i=await xt(t,s);return i instanceof Uint8Array?i:dt(i)}}class ns{#yi=!1;constructor({enableHWA:t=!1}){this.#yi=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!this.#yi})}}reset({canvas:t},e,s){if(!t)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.width=e,t.height=s}destroy(t){const{canvas:e}=t;if(!e)throw new Error("Canvas is not specified");e.width=e.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){Z("Abstract method `_createCanvas` called.")}}class rs extends ns{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}}class as{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addKnockoutFilter(t=0){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class os extends as{#Ai;#wi;#vi;#_i;#xi;#Si;#k=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#_i=t,this.#xi=e}get#M(){return this.#wi||=new Map}get#Ci(){return this.#Si||=new Map}get#ki(){if(!this.#vi){const t=this.#xi.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const s=this.#xi.createElementNS(vt,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#vi=this.#xi.createElementNS(vt,"defs"),t.append(s),s.append(this.#vi),this.#xi.body.append(t)}return this.#vi}#Ti(t){if(1===t.length){const e=t[0],s=new Array(256);for(let t=0;t<256;t++)s[t]=e[t]/255;const i=s.join(",");return[i,i,i]}const[e,s,i]=t,n=new Array(256),r=new Array(256),a=new Array(256);for(let o=0;o<256;o++)n[o]=e[o]/255,r[o]=s[o]/255,a[o]=i[o]/255;return[n.join(","),r.join(","),a.join(",")]}#Mi(t){if(void 0===this.#Ai){this.#Ai="";const t=this.#xi.URL;t!==this.#xi.baseURI&&(kt(t)?J('#createUrl: ignore "data:"-URL for performance reasons.'):this.#Ai=st(t,""))}return`url(${this.#Ai}#${t})`}addFilter(t){if(!t)return"none";let e=this.#M.get(t);if(e)return e;const[s,i,n]=this.#Ti(t),r=1===t.length?s:`${s}${i}${n}`;if(e=this.#M.get(r),e)return this.#M.set(t,e),e;const a=`g_${this.#_i}_transfer_map_${this.#k++}`,o=this.#Mi(a);this.#M.set(t,o),this.#M.set(r,o);const h=this.#Ei(a);return this.#Pi(s,i,n,h),o}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#Ci.get(i);if(n?.key===s)return n.url;if(n?(n.filter?.remove(),n.key=s,n.url="none",n.filter=null):(n={key:s,url:"none",filter:null},this.#Ci.set(i,n)),!t||!e)return n.url;const r=this.#Di(t);t=pt.makeHexColor(...r);const a=this.#Di(e);if(e=pt.makeHexColor(...a),this.#ki.style.color="","#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let u=0;u<=255;u++){const t=u/255;o[u]=t<=.03928?t/12.92:((t+.055)/1.055)**2.4}const h=o.join(","),l=`g_${this.#_i}_hcm_filter`,c=n.filter=this.#Ei(l);this.#Pi(h,h,h,c),this.#Ii(c);const d=(t,e)=>{const s=r[t]/255,i=a[t]/255,n=new Array(e+1);for(let r=0;r<=e;r++)n[r]=s+r/e*(i-s);return n.join(",")};return this.#Pi(d(0,5),d(1,5),d(2,5),c),n.url=this.#Mi(l),n.url}addAlphaFilter(t){let e=this.#M.get(t);if(e)return e;const[s]=this.#Ti([t]),i=`alpha_${s}`;if(e=this.#M.get(i),e)return this.#M.set(t,e),e;const n=`g_${this.#_i}_alpha_map_${this.#k++}`,r=this.#Mi(n);this.#M.set(t,r),this.#M.set(i,r);const a=this.#Ei(n);return this.#Fi(s,a),r}addLuminosityFilter(t){let e,s,i=this.#M.get(t||"luminosity");if(i)return i;if(t?([e]=this.#Ti([t]),s=`luminosity_${e}`):s="luminosity",i=this.#M.get(s),i)return this.#M.set(t,i),i;const n=`g_${this.#_i}_luminosity_map_${this.#k++}`,r=this.#Mi(n);this.#M.set(t,r),this.#M.set(s,r);const a=this.#Ei(n);return this.#Ni(a),t&&this.#Fi(e,a),r}addKnockoutFilter(t=0){const e=t>0?Math.min(1/t,1e6):1e6,s=`knockout_${e}`,i=this.#M.get(s);if(i)return i;const n=`g_${this.#_i}_knockout_filter_${this.#k++}`,r=this.#Mi(n);this.#M.set(s,r);const a=this.#Ei(n),o=this.#xi.createElementNS(vt,"feComponentTransfer");a.append(o);const h=this.#xi.createElementNS(vt,"feFuncA");return h.setAttribute("type","linear"),h.setAttribute("slope",`${e}`),h.setAttribute("intercept","0"),o.append(h),r}addHighlightHCMFilter(t,e,s,i,n){const r=`${e}-${s}-${i}-${n}`;let a=this.#Ci.get(t);if(a?.key===r)return a.url;if(a?(a.filter?.remove(),a.key=r,a.url="none",a.filter=null):(a={key:r,url:"none",filter:null},this.#Ci.set(t,a)),!e||!s)return a.url;const[o,h]=[e,s].map(this.#Di.bind(this));let l=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),c=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),[d,u]=[i,n].map(this.#Di.bind(this));c<l&&([l,c,d,u]=[c,l,u,d]),this.#ki.style.color="";const p=(t,e,s)=>{const i=new Array(256),n=(c-l)/s,r=t/255,a=(e-t)/(255*s);let o=0;for(let h=0;h<=s;h++){const t=Math.round(l+h*n),e=r+h*a;for(let s=o;s<=t;s++)i[s]=e;o=t+1}for(let h=o;h<256;h++)i[h]=i[o-1];return i.join(",")},g=`g_${this.#_i}_hcm_${t}_filter`,m=a.filter=this.#Ei(g);return this.#Ii(m),this.#Pi(p(d[0],u[0],5),p(d[1],u[1],5),p(d[2],u[2],5),m),a.url=this.#Mi(g),a.url}destroy(t=!1){t&&this.#Si?.size||(this.#vi?.parentNode.parentNode.remove(),this.#vi=null,this.#wi?.clear(),this.#wi=null,this.#Si?.clear(),this.#Si=null,this.#k=0)}#Ni(t){const e=this.#xi.createElementNS(vt,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#Ii(t){const e=this.#xi.createElementNS(vt,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#Ei(t){const e=this.#xi.createElementNS(vt,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#ki.append(e),e}#Ri(t,e,s){const i=this.#xi.createElementNS(vt,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#Pi(t,e,s,i){const n=this.#xi.createElementNS(vt,"feComponentTransfer");i.append(n),this.#Ri(n,"feFuncR",t),this.#Ri(n,"feFuncG",e),this.#Ri(n,"feFuncB",s)}#Fi(t,e){const s=this.#xi.createElementNS(vt,"feComponentTransfer");e.append(s),this.#Ri(s,"feFuncA",t)}#Di(t){return this.#ki.style.color=t,Nt(getComputedStyle(this.#ki).getPropertyValue("color"))}}d&&J("Please use the `legacy` build in Node.js environments.");class hs extends as{}class ls extends ns{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}class cs extends ss{async _fetch(t,e){return async function(t){const e=process.getBuiltinModule("fs/promises"),s=await e.readFile(t);return new Uint8Array(s)}(t)}}const ds=new class{#Oi=null;#Bi=null;#Li=null;#Ui=null;async#ji(){if(!globalThis.navigator?.gpu)return!1;try{const t=await navigator.gpu.requestAdapter();return!!t&&(this.#Ui=navigator.gpu.getPreferredCanvasFormat(),this.#Bi=await t.requestDevice(),!0)}catch{return!1}}init(){return this.#Oi||=this.#ji()}get isReady(){return null!==this.#Bi}loadMeshShader(){if(!this.#Bi||this.#Li)return;const t=this.#Bi.createShaderModule({code:"\nstruct Uniforms {\n offsetX : f32,\n offsetY : f32,\n scaleX : f32,\n scaleY : f32,\n paddedWidth : f32,\n paddedHeight : f32,\n borderSize : f32,\n _pad : f32,\n};\n\n@group(0) @binding(0) var<uniform> u : Uniforms;\n\nstruct VertexInput {\n @location(0) position : vec2<f32>,\n @location(1) color : vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position : vec4<f32>,\n @location(0) color : vec3<f32>,\n};\n\n@vertex\nfn vs_main(in : VertexInput) -> VertexOutput {\n var out : VertexOutput;\n let cx = (in.position.x + u.offsetX) * u.scaleX;\n let cy = (in.position.y + u.offsetY) * u.scaleY;\n out.position = vec4<f32>(\n ((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0,\n 1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0,\n 0.0,\n 1.0\n );\n out.color = in.color.rgb;\n return out;\n}\n\n@fragment\nfn fs_main(in : VertexOutput) -> @location(0) vec4<f32> {\n return vec4<f32>(in.color, 1.0);\n}\n"});this.#Li=this.#Bi.createRenderPipeline({layout:"auto",vertex:{module:t,entryPoint:"vs_main",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"unorm8x4"}]}]},fragment:{module:t,entryPoint:"fs_main",targets:[{format:this.#Ui}]},primitive:{topology:"triangle-list"}})}draw(t,e,s,i,n,r,a,o){this.loadMeshShader();const h=this.#Bi,{offsetX:l,offsetY:c,scaleX:d,scaleY:u}=i,p=h.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&h.queue.writeBuffer(p,0,t);const g=h.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&h.queue.writeBuffer(g,0,e);const m=h.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});h.queue.writeBuffer(m,0,new Float32Array([l,c,d,u,r,a,o,0]));const f=h.createBindGroup({layout:this.#Li.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:m}}]}),b=new OffscreenCanvas(r,a),y=b.getContext("webgpu");y.configure({device:h,format:this.#Ui,alphaMode:n?"opaque":"premultiplied"});const A=n?{r:n[0]/255,g:n[1]/255,b:n[2]/255,a:1}:{r:0,g:0,b:0,a:0},w=h.createCommandEncoder(),v=w.beginRenderPass({colorAttachments:[{view:y.getCurrentTexture().createView(),clearValue:A,loadOp:"clear",storeOp:"store"}]});return s>0&&(v.setPipeline(this.#Li),v.setBindGroup(0,f),v.setVertexBuffer(0,p),v.setVertexBuffer(1,g),v.draw(s)),v.end(),h.queue.submit([w.finish()]),p.destroy(),g.destroy(),m.destroy(),b.transferToImageBitmap()}},us="Fill",ps="Stroke",gs="Shading";function ms(t,e){if(!e)return;const s=e[2]-e[0],i=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],s,i),t.clip(n)}class fs{isModifyingCurrentTransform(){return!1}getPattern(){Z("Abstract method `getPattern` called.")}}class bs extends fs{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}isOriginBased(){return 0===this._p0[0]&&0===this._p0[1]&&(!this.isRadial()||0===this._p1[0]&&0===this._p1[1])}isRadial(){return"radial"===this._type}areConic(){if(!this.isRadial())return!1;const t=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return t+this._r1>this._r0&&t+this._r0>this._r1}_createGradient(t,e=null){let s,i=this._p0,n=this._p1;if(e&&(i=i.slice(),n=n.slice(),pt.applyTransform(i,e),pt.applyTransform(n,e)),"axial"===this._type)s=t.createLinearGradient(i[0],i[1],n[0],n[1]);else if("radial"===this._type){let r=this._r0,a=this._r1;if(e){const t=new Float32Array(2);pt.singularValueDecompose2dScale(e,t),r*=t[0],a*=t[0]}s=t.createRadialGradient(i[0],i[1],r,n[0],n[1],a)}for(const r of this._colorStops)s.addColorStop(r[0],r[1]);return s}_createReversedGradient(t,e=null){let s=this._p1,i=this._p0;e&&(s=s.slice(),i=i.slice(),pt.applyTransform(s,e),pt.applyTransform(i,e));let n=this._r1,r=this._r0;if(e){const t=new Float32Array(2);pt.singularValueDecompose2dScale(e,t),n*=t[0],r*=t[0]}const a=t.createRadialGradient(s[0],s[1],n,i[0],i[1],r),o=this._colorStops.map(([t,e])=>[1-t,e]).reverse();for(const[h,l]of o)a.addColorStop(h,l);return a}getPattern(t,e,s,i){let n;if(i===ps||i===us){if(this.isOriginBased()){let i=pt.transform(s,e.baseTransform);this.matrix&&(i=pt.transform(i,this.matrix));const n=.001,r=Math.hypot(i[0],i[1]),a=Math.hypot(i[2],i[3]),o=(i[0]*i[2]+i[1]*i[3])/(r*a);if(Math.abs(o)<n){if(!this.isRadial())return this._createGradient(t,i);if(Math.abs(r-a)<n)return this._createGradient(t,i)}}const r=e.current.getClippedPathBoundingBox(i,Rt(t))||[0,0,0,0],a=Math.ceil(r[2]-r[0])||1,o=Math.ceil(r[3]-r[1])||1,h=e.canvasFactory.create(a,o),l=h.context;l.clearRect(0,0,l.canvas.width,l.canvas.height),l.beginPath(),l.rect(0,0,l.canvas.width,l.canvas.height),l.translate(-r[0],-r[1]),s=pt.transform(s,[1,0,0,1,r[0],r[1]]),l.transform(...e.baseTransform),this.matrix&&l.transform(...this.matrix),ms(l,this._bbox),this.areConic()&&(l.fillStyle=this._createReversedGradient(l),l.fill()),l.fillStyle=this._createGradient(l),l.fill(),n=t.createPattern(h.canvas,"no-repeat"),e.canvasFactory.destroy(h);const c=new DOMMatrix(s);n.setTransform(c)}else this.areConic()&&(t.save(),ms(t,this._bbox),t.fillStyle=this._createReversedGradient(t),t.fillRect(-1e10,-1e10,2e10,2e10),t.restore()),ms(t,this._bbox),n=this._createGradient(t);return n}}function ys(t,e,s,i,n,r,a,o){const h=e.coords,l=e.colors,c=t.data,d=4*t.width;let u;h[2*s+1]>h[2*i+1]&&(u=s,s=i,i=u,u=r,r=a,a=u),h[2*i+1]>h[2*n+1]&&(u=i,i=n,n=u,u=a,a=o,o=u),h[2*s+1]>h[2*i+1]&&(u=s,s=i,i=u,u=r,r=a,a=u);const p=(h[2*s]+e.offsetX)*e.scaleX,g=(h[2*s+1]+e.offsetY)*e.scaleY,m=(h[2*i]+e.offsetX)*e.scaleX,f=(h[2*i+1]+e.offsetY)*e.scaleY,b=(h[2*n]+e.offsetX)*e.scaleX,y=(h[2*n+1]+e.offsetY)*e.scaleY;if(g>=y)return;const A=l[4*r],w=l[4*r+1],v=l[4*r+2],_=l[4*a],x=l[4*a+1],S=l[4*a+2],C=l[4*o],k=l[4*o+1],T=l[4*o+2],M=Math.round(g),E=Math.round(y);let P,D,I,F,N,R,O,B;for(let L=M;L<=E;L++){if(L<f){const t=L<g?0:(g-L)/(g-f);P=p-(p-m)*t,D=A-(A-_)*t,I=w-(w-x)*t,F=v-(v-S)*t}else{let t;t=L>y?1:f===y?0:(f-L)/(f-y),P=m-(m-b)*t,D=_-(_-C)*t,I=x-(x-k)*t,F=S-(S-T)*t}let t;t=L<g?0:L>y?1:(g-L)/(g-y),N=p-(p-b)*t,R=A-(A-C)*t,O=w-(w-k)*t,B=v-(v-T)*t;const e=Math.round(Math.min(P,N)),s=Math.round(Math.max(P,N));let i=d*L+4*e;for(let n=e;n<=s;n++)t=(P-n)/(P-N),t<0?t=0:t>1&&(t=1),c[i++]=D-(D-R)*t|0,c[i++]=I-(I-O)*t|0,c[i++]=F-(F-B)*t|0,c[i++]=255}}class As extends fs{constructor(t){super(),this._posData=t[2],this._colData=t[3],this._vertexCount=t[4],this._bounds=t[5],this._bbox=t[6],this._background=t[7],this.matrix=null,ds.loadMeshShader()}_createMeshCanvas(t,e,s){const i=Math.floor(this._bounds[0]),n=Math.floor(this._bounds[1]),r=Math.ceil(this._bounds[2])-i,a=Math.ceil(this._bounds[3])-n,o=Math.min(Math.ceil(Math.abs(r*t[0]*1.1)),3e3)||1,h=Math.min(Math.ceil(Math.abs(a*t[1]*1.1)),3e3)||1,l=r?r/o:1,c=a?a/h:1,d={coords:this._posData,colors:this._colData,offsetX:-i,offsetY:-n,scaleX:1/l,scaleY:1/c},u=o+4,p=h+4,g=s.create(u,p);if(ds.isReady&&this._vertexCount>48)g.context.drawImage(function(t,e,s,i,n,r,a,o){return ds.draw(t,e,s,i,n,r,a,o)}(this._posData,this._colData,this._vertexCount,d,e,u,p,2),0,0);else{const t=g.context.createImageData(o,h);if(e){const s=t.data;for(let t=0,i=s.length;t<i;t+=4)s[t]=e[0],s[t+1]=e[1],s[t+2]=e[2],s[t+3]=255}for(let e=0,s=this._vertexCount;e<s;e+=3)ys(t,d,e,e+1,e+2,e,e+1,e+2);g.context.putImageData(t,2,2)}return{canvas:g.canvas,offsetX:i-2*l,offsetY:n-2*c,scaleX:l,scaleY:c}}isModifyingCurrentTransform(){return!0}getPattern(t,e,s,i){ms(t,this._bbox);const n=new Float32Array(2);if(i===gs)pt.singularValueDecompose2dScale(Rt(t),n);else if(this.matrix){pt.singularValueDecompose2dScale(this.matrix,n);const[t,s]=n;pt.singularValueDecompose2dScale(e.baseTransform,n),n[0]*=t,n[1]*=s}else pt.singularValueDecompose2dScale(e.baseTransform,n);const r=this._createMeshCanvas(n,i===gs?null:this._background,e.canvasFactory);i!==gs&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY);const a=t.createPattern(r.canvas,"no-repeat");return e.canvasFactory.destroy(r),a}}class ws extends fs{getPattern(){return"hotpink"}}const vs=1,_s=2;class xs{static MAX_PATTERN_SIZE=3e3;constructor(t,e,s,i){this.color=t[1],this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.needsIsolation=t[9]??!0,this.ctx=e,this.canvasGraphicsFactory=s,this.baseTransform=i,this.patternBaseMatrix=this.matrix?pt.transform(i,this.matrix):i}canSkipPatternCanvas([t,e,s,i]){const[n,r,a,o]=this.bbox,h=Math.abs(this.xstep),l=Math.abs(this.ystep);if(t>h+1e-6||e>l+1e-6)return null;const c=Math.floor((s-a)/h)+1,d=Math.ceil((s+t-n)/h)-1,u=Math.floor((i-o)/l)+1,p=Math.ceil((i+e-r)/l)-1;return d<=c&&p<=u?[c,u]:null}updatePatternDims(t,e){const s=pt.inverseTransform(this.patternBaseMatrix),i=[t[0],t[1]],n=[t[2],t[3]];pt.applyTransform(i,s),pt.applyTransform(n,s),e[0]=Math.abs(n[0]-i[0]),e[1]=Math.abs(n[1]-i[1]),e[2]=Math.min(i[0],n[0]),e[3]=Math.min(i[1],n[1])}_renderTileCanvas(t,e,s,i){const[n,r,a,o]=this.bbox,h=t.canvasFactory.create(s.size,i.size),l=h.context,c=this.canvasGraphicsFactory.createCanvasGraphics(l,e);return c.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(c,this.paintType,this.color),l.translate(-s.scale*n,-i.scale*r),c.transform(0,s.scale,0,0,i.scale,0,0),l.save(),c.dependencyTracker?.save(),this.clipBbox(c,n,r,a,o),c.baseTransform=Rt(c.ctx),c.executeOperatorList(this.operatorList),c.endDrawing(),c.dependencyTracker?.restore(),l.restore(),h}_getCombinedScales(){const t=new Float32Array(2);pt.singularValueDecompose2dScale(this.matrix,t);const[e,s]=t;return pt.singularValueDecompose2dScale(this.baseTransform,t),[e*t[0],s*t[1]]}drawPattern(t,e,s=!1,[i,n],r){const[a,o,h,l]=this.bbox,c=t.dependencyTracker;if(c&&(t.dependencyTracker=new we(c,r)),t.save(),s?t.ctx.clip(e,"evenodd"):t.ctx.clip(e),t.ctx.setTransform(...this.patternBaseMatrix),t.ctx.translate(i*this.xstep,n*this.ystep),this.needsIsolation||1!==t.ctx.globalAlpha||"source-over"!==t.ctx.globalCompositeOperation||t.inSMaskMode){const e=h-a,s=l-o,[i,n]=this._getCombinedScales(),c=this.getSizeAndScale(e,this.ctx.canvas.width,i),d=this.getSizeAndScale(s,this.ctx.canvas.height,n),u=this._renderTileCanvas(t,r,c,d);t.ctx.drawImage(u.canvas,a,o,e,s),t.canvasFactory.destroy(u)}else this.setFillAndStrokeStyleToContext(t,this.paintType,this.color),this.clipBbox(t,a,o,h,l),t.baseTransformStack.push(t.baseTransform),t.baseTransform=Rt(t.ctx),t.executeOperatorList(this.operatorList),t.baseTransform=t.baseTransformStack.pop();t.restore(),c&&(t.dependencyTracker=c)}createPatternCanvas(t,e){const[s,i,n,r]=this.bbox,a=n-s,o=r-i;let{xstep:h,ystep:l}=this;h=Math.abs(h),l=Math.abs(l),Q("TilingType: "+this.tilingType);const[c,d]=this._getCombinedScales();let u=a,p=o,g=!1,m=!1;Math.ceil(h*c)>=Math.ceil(a*c)?u=h:g=!0,Math.ceil(l*d)>=Math.ceil(o*d)?p=l:m=!0;const f=this.getSizeAndScale(u,this.ctx.canvas.width,c),b=this.getSizeAndScale(p,this.ctx.canvas.height,d),y=this._renderTileCanvas(t,e,f,b);if(g||m){const e=y.canvas;g&&(u=h),m&&(p=l);const n=this.getSizeAndScale(u,this.ctx.canvas.width,c),r=this.getSizeAndScale(p,this.ctx.canvas.height,d),f=n.size,b=r.size,A=t.canvasFactory.create(f,b),w=A.context,v=g?Math.floor(a/h):0,_=m?Math.floor(o/l):0;for(let t=0;t<=v;t++)for(let s=0;s<=_;s++)w.drawImage(e,f*t,b*s,f,b,0,0,f,b);return t.canvasFactory.destroy(y),{canvas:A.canvas,canvasEntry:A,scaleX:n.scale,scaleY:r.scale,offsetX:s,offsetY:i}}return{canvas:y.canvas,canvasEntry:y,scaleX:f.scale,scaleY:b.scale,offsetX:s,offsetY:i}}getSizeAndScale(t,e,s){const i=Math.max(xs.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const r=i-e,a=n-s,o=new Path2D;o.rect(e,s,r,a),pt.axialAlignedBoundingBox([e,s,i,n],Rt(t.ctx),t.current.minMax),t.ctx.clip(o),t.current.updateClipFromPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(n.patternFill=n.patternStroke=!1,e){case vs:const{fillStyle:t,strokeStyle:r}=this.ctx;i.fillStyle=n.fillColor=t,i.strokeStyle=n.strokeColor=r;break;case _s:i.fillStyle=i.strokeStyle=s,n.fillColor=n.strokeColor=s;break;default:throw new lt(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,s,i,n){const r=i!==gs?pt.transform(s,this.patternBaseMatrix):s,a=this.createPatternCanvas(e,n);let o=new DOMMatrix(r);o=o.translate(a.offsetX,a.offsetY),o=o.scale(1/a.scaleX,1/a.scaleY);const h=t.createPattern(a.canvas,"repeat");return e.canvasFactory.destroy(a.canvasEntry),h.setTransform(o),h}}function Ss({src:t,srcPos:e=0,dest:s,width:i,height:n,nonBlackColor:r=4294967295,inverseDecode:a=!1}){const o=ut.isLittleEndian?4278190080:255,[h,l]=a?[r,o]:[o,r],c=i>>3,d=7&i,u=h^l,p=t.length;s=new Uint32Array(s.buffer);let g=0;for(let m=0;m<n;++m){for(const n=e+c;e<n;++e,g+=8){const i=t[e];s[g]=h^-(i>>7&1)&u,s[g+1]=h^-(i>>6&1)&u,s[g+2]=h^-(i>>5&1)&u,s[g+3]=h^-(i>>4&1)&u,s[g+4]=h^-(i>>3&1)&u,s[g+5]=h^-(i>>2&1)&u,s[g+6]=h^-(i>>1&1)&u,s[g+7]=h^-(1&i)&u}if(0===d)continue;const i=e<p?t[e++]:255;for(let t=0;t<d;++t,++g)s[g]=h^-(i>>7-t&1)&u}return{srcPos:e,destPos:g}}const Cs=16,ks=new DOMMatrix,Ts=new Float32Array(2);function Ms(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");const s=new Map;for(const i of["save","restore","rotate","scale","translate","transform","setTransform","resetTransform","clip","moveTo","lineTo","bezierCurveTo","quadraticCurveTo","arc","arcTo","ellipse","rect","roundRect","closePath","beginPath"]){const n=t[i];"function"==typeof n&&"function"==typeof e[i]&&(s.set(i,n),t[i]=function(...t){return e[i](...t),n.apply(this,t)})}t._removeMirroring=()=>{for(const[e,i]of s)t[e]=i;delete t._removeMirroring}}function Es(t,e,s,i,n,r,a,o,h,l){const[c,d,u,p,g,m]=Rt(t);if(0===d&&0===u){const f=a*c+g,b=Math.round(f),y=o*p+m,A=Math.round(y),w=(a+h)*c+g,v=Math.abs(Math.round(w)-b)||1,_=(o+l)*p+m,x=Math.abs(Math.round(_)-A)||1;return t.setTransform(Math.sign(c),0,0,Math.sign(p),b,A),t.drawImage(e,s,i,n,r,0,0,v,x),t.setTransform(c,d,u,p,g,m),[v,x]}if(0===c&&0===p){const f=o*u+g,b=Math.round(f),y=a*d+m,A=Math.round(y),w=(o+l)*u+g,v=Math.abs(Math.round(w)-b)||1,_=(a+h)*d+m,x=Math.abs(Math.round(_)-A)||1;return t.setTransform(0,Math.sign(d),Math.sign(u),0,b,A),t.drawImage(e,s,i,n,r,0,0,x,v),t.setTransform(c,d,u,p,g,m),[x,v]}return t.drawImage(e,s,i,n,r,a,o,h,l),[Math.hypot(c,d)*h,Math.hypot(u,p)*l]}class Ps{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=g;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=E;textRise=0;fillColor="#000000";strokeColor="#000000";tilingPatternDims=null;patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";minMax=p.slice();constructor(t,e){this.clipBox=new Float32Array([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t.minMax=this.minMax.slice(),t.tilingPatternDims=this.tilingPatternDims?.slice(),t}getPathBoundingBox(t=us,e=null){const s=this.minMax.slice();if(t===ps){e||Z("Stroke bounding box must include transform."),pt.singularValueDecompose2dScale(e,Ts);const t=Ts[0]*this.lineWidth/2,i=Ts[1]*this.lineWidth/2;s[0]-=t,s[1]-=i,s[2]+=t,s[3]+=i}return s}updateClipFromPath(){const t=pt.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0),this.minMax.set(p,0)}getClippedPathBoundingBox(t=us,e=null){return pt.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function Ds(t,e){if(e instanceof ImageData)return void t.putImageData(e,0,0);const s=e.height,i=e.width,n=s%Cs,r=(s-n)/Cs,a=0===n?r:r+1,o=t.createImageData(i,Cs);let h,l=0;const c=e.data,d=o.data;let u,p,g,m;if(e.kind===R.GRAYSCALE_1BPP){const e=c.byteLength,s=new Uint32Array(d.buffer,0,d.byteLength>>2),m=s.length,f=i+7>>3,b=4294967295,y=ut.isLittleEndian?4278190080:255;for(u=0;u<a;u++){for(g=u<r?Cs:n,h=0,p=0;p<g;p++){const t=e-l;let n=0;const r=t>f?i:8*t-7,a=-8&r;let o=0,d=0;for(;n<a;n+=8)d=c[l++],s[h++]=128&d?b:y,s[h++]=64&d?b:y,s[h++]=32&d?b:y,s[h++]=16&d?b:y,s[h++]=8&d?b:y,s[h++]=4&d?b:y,s[h++]=2&d?b:y,s[h++]=1&d?b:y;for(;n<r;n++)0===o&&(d=c[l++],o=128),s[h++]=d&o?b:y,o>>=1}for(;h<m;)s[h++]=0;t.putImageData(o,0,u*Cs)}}else if(e.kind===R.RGBA_32BPP){for(p=0,m=i*Cs*4,u=0;u<r;u++)d.set(c.subarray(l,l+m)),l+=m,t.putImageData(o,0,p),p+=Cs;u<a&&(m=i*n*4,d.set(c.subarray(l,l+m)),t.putImageData(o,0,p))}else{if(e.kind!==R.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);for(g=Cs,m=i*g,u=0;u<a;u++){for(u>=r&&(g=n,m=i*g),h=0,p=m;p--;)d[h++]=c[l++],d[h++]=c[l++],d[h++]=c[l++],d[h++]=255;t.putImageData(o,0,u*Cs)}}}function Is(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const s=e.height,i=e.width,n=s%Cs,r=(s-n)/Cs,a=0===n?r:r+1,o=t.createImageData(i,Cs);let h=0;const l=e.data,c=o.data;for(let d=0;d<a;d++){const e=d<r?Cs:n;({srcPos:h}=Ss({src:l,srcPos:h,dest:c,width:i,height:e,nonBlackColor:0})),t.putImageData(o,0,d*Cs)}}function Fs(t,e){const s=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const i of s)void 0!==t[i]&&(e[i]=t[i]);void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function Ns(t){t.strokeStyle=t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0);const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}function Rs(t,e){if(e)return!0;pt.singularValueDecompose2dScale(t,Ts);const s=Math.fround(Lt.pixelRatio*_t.PDF_TO_CSS_UNITS);return Ts[0]<=s&&Ts[1]<=s}const Os=["butt","round","square"],Bs=["miter","round","bevel"],Ls={},Us={};class js{#Hi=0;#$i=0;#zi=null;#Gi=null;#Wi=null;#Vi=null;#Xi=1;#Yi;#qi=null;#Ki=[];constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:a=null},o,h,l,c){this.ctx=t,this.current=new Ps(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.commonObjs=e,this.objs=s,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.tempSMask=null,this.smaskGroupCanvases=[],this.smaskPreparedEntry=null,this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=a||[],this.optionalContentConfig=r,this.cachedPatterns=new Map,this.annotationCanvasMap=o,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=h,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=l??null,this.imagesTracker=c??null}getObject(t,e,s=null){return"string"==typeof e?(this.dependencyTracker?.recordNamedDependency(t,e),e.startsWith("g_")?this.commonObjs.get(e):this.objs.get(e)):s}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,a=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=a,s){const t=this.transparentCanvasEntry=this.canvasFactory.create(n,r);this.compositeCtx=this.ctx,({canvas:this.transparentCanvas,context:this.ctx}=t),this.ctx.save(),this.ctx.transform(...Rt(this.compositeCtx))}this.ctx.save(),Ns(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[3]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=Rt(this.ctx)}executeOperatorList(t,e,s,i,n,r=null,a=null){const o=Number.isFinite(r?.executionTime)&&r.executionTime>0?r.executionTime:15,h=Number.isInteger(r?.executionSteps)&&r.executionSteps>0?r.executionSteps:10,l=t.argsArray,c=t.fnArray;let d=e||0;const u=l.length;if(u===d)return d;const p=u-d>h&&"function"==typeof s,g=p?performance.now()+o:0;let m=0;const f=this.commonObjs,b=this.objs;let y,A;for(;;){if(void 0!==i){if(d===i.nextBreakPoint)return i.breakIt(d,s),d;if(i.shouldSkip(d)){if(++d===u)return d;continue}}if(!n||n(d))if(y=c[d],A=l[d]??null,y!==$.dependency)null===A?this[y](d):this[y](d,...A);else for(const t of A){this.dependencyTracker?.recordNamedData(t,d);const e=t.startsWith("g_")?f:b;if(!e.has(t))return e.get(t,s),d}if(d++,d===u)return d;if(p&&++m>h){const t=performance.now()>g;if("function"==typeof a&&a()||t)return s(),d;m=0}}}#Qi(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(this.transparentCanvasEntry),this.transparentCanvas=null,this.transparentCanvasEntry=null)}endDrawing(){this.#Qi();for(const t of this.smaskGroupCanvases)this.canvasFactory.destroy(t);this.smaskGroupCanvases.length=0,this._clearPreparedSMask(),this.tempSMask=null,this.smaskStack.length=0;for(const t of this.#Ki)this.#Ji(t);this.#Ki.length=0,this.#zi=null,this.#Gi=null,this.#Wi=null,this.#Vi=null,this.#Xi=1,this.#qi=null,this.#$i=0,this.#Hi=0,this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#Zi()}#Zi(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const s=t.width??t.displayWidth,i=t.height??t.displayHeight,n=[];let r=Math.max(Math.hypot(e[0],e[1]),1),a=Math.max(Math.hypot(e[2],e[3]),1),o=s,h=i;for(;r>2&&o>1||a>2&&h>1;){let t=o,e=h;r>2&&o>1&&(t=Math.ceil(o/2),r/=o/t),a>2&&h>1&&(e=Math.ceil(h/2),a/=h/e),n.push({newWidth:t,newHeight:e}),o=t,h=e}if(0===n.length)return{img:t,paintWidth:s,paintHeight:i,tmpCanvas:null};if(1===n.length){const{newWidth:e,newHeight:r}=n[0],a=this.canvasFactory.create(e,r);return a.context.drawImage(t,0,0,s,i,0,0,e,r),{img:a.canvas,paintWidth:e,paintHeight:r,tmpCanvas:a}}let l=this.canvasFactory.create(1,1),c=this.canvasFactory.create(1,1),d=s,u=i,p=t;for(const{newWidth:g,newHeight:m}of n)this.canvasFactory.reset(c,g,m),c.context.drawImage(p,0,0,d,u,0,0,g,m),[l,c]=[c,l],p=l.canvas,d=g,u=m;return this.canvasFactory.destroy(c),{img:l.canvas,paintWidth:d,paintHeight:u,tmpCanvas:l}}_createMaskCanvas(t,e){const s=this.ctx,{width:i,height:n}=e,r=this.current.fillColor,a=this.current.patternFill,o=Rt(s);let h,l,c,d;if((e.bitmap||e.data)&&e.count>1){const s=e.bitmap||e.data.buffer;l=JSON.stringify(a?o:[o.slice(0,4),r]),h=this._cachedBitmapsMap.getOrInsertComputed(s,ft);const i=h.get(l);if(i&&!a){const e=Math.round(Math.min(o[0],o[2])+o[4]),s=Math.round(Math.min(o[1],o[3])+o[5]);return this.dependencyTracker?.recordDependencies(t,Te),{canvas:i,offsetX:e,offsetY:s}}c=i}c||(d=this.canvasFactory.create(i,n),Is(d.context,e));let u=pt.transform(o,[1/i,0,0,-1/n,0,0]);u=pt.transform(u,[1,0,0,1,0,-n]);const g=p.slice();pt.axialAlignedBoundingBox([0,0,i,n],u,g);const[m,f,b,y]=g,A=Math.round(b-m)||1,w=Math.round(y-f)||1,v=this.canvasFactory.create(A,w),_=v.context,x=m,S=f;_.translate(-x,-S),_.transform(...u);let C=null;if(!c){const t=this._scaleImage(d.canvas,Ot(_));c=t.img,C=t.tmpCanvas,c!==d.canvas&&(this.canvasFactory.destroy(d),d=null),h&&a&&(h.set(l,c),C=null,d=null)}_.imageSmoothingEnabled=Rs(Rt(_),e.interpolate),Es(_,c,0,0,c.width,c.height,0,0,i,n),C&&this.canvasFactory.destroy(C),d&&this.canvasFactory.destroy(d),_.globalCompositeOperation="source-in";const k=pt.transform(Ot(_),[1,0,0,1,-x,-S]);return _.fillStyle=a?r.getPattern(s,this,k,us,t):r,_.fillRect(0,0,i,n),h&&!a&&h.set(l,v.canvas),this.dependencyTracker?.recordDependencies(t,Te),{canvas:v.canvas,canvasEntry:h&&!a?null:v,offsetX:Math.round(x),offsetY:Math.round(S)}}setLineWidth(t,e){this.dependencyTracker?.recordSimpleData("lineWidth",t),e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(t,e){this.dependencyTracker?.recordSimpleData("lineCap",t),this.ctx.lineCap=Os[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t),this.ctx.lineJoin=Bs[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t),this.ctx.miterLimit=e}setDash(t,e,s){this.dependencyTracker?.recordSimpleData("dash",t);const i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(e),i.lineDashOffset=s)}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(const[s,i]of e)switch(s){case"LW":this.setLineWidth(t,i);break;case"LC":this.setLineCap(t,i);break;case"LJ":this.setLineJoin(t,i);break;case"ML":this.setMiterLimit(t,i);break;case"D":this.setDash(t,i[0],i[1]);break;case"RI":this.setRenderingIntent(t,i);break;case"FL":this.setFlatness(t,i);break;case"Font":this.setFont(t,i[0],i[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t),this.current.strokeAlpha=i;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t),this.ctx.globalAlpha=this.current.fillAlpha=i;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t),this.ctx.globalCompositeOperation=i;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t),this.current.activeSMask=i?this.tempSMask:null,this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation),this.tempSMask=null,this.checkSMaskState(t);break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){this.smaskPreparedEntry&&(this.canvasFactory.destroy(this.smaskPreparedEntry),this.smaskPreparedEntry=null),this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null}_ensurePreparedSMask(t){t!==this.smaskPreparedFor&&(this._clearPreparedSMask(),this._prepareSMaskCanvas(t))}checkSMaskState(t){const e=this.inSMaskMode;this.current.activeSMask&&!e?this.beginSMaskMode(t):!this.current.activeSMask&&e?this.endSMaskMode():this.current.activeSMask&&e&&this._ensurePreparedSMask(this.current.activeSMask)}_prepareSMaskCanvas(t){const{canvas:e,subtype:s,backdrop:i,transferMap:n}=t,r="Luminosity"===s||"Alpha"===s&&n;if(!(r||"Luminosity"===s&&i))return void(this.smaskPreparedFor=t);let a;if("Luminosity"===s&&i){const[t,e,s]=Ft(i),r=Math.round(.3*t+.59*e+.11*s);a=n?.[r]??r}else a=n?.[0]??0;const{width:o,height:h}=this.ctx.canvas,l=o*h<e.width*e.height*4,c=r?{url:"Alpha"===s?this.filterFactory.addAlphaFilter(n):this.filterFactory.addLuminosityFilter(n),subtype:s,transferMap:n}:null,d="Luminosity"===s?i:null;let u,p,g;l?(u=this._bakeSMaskCanvas(e,t.offsetX,t.offsetY,o,h,d,c),p=0,g=0):(u=this._bakeSMaskCanvas(e,0,0,e.width,e.height,d,c),p=t.offsetX,g=t.offsetY),this.smaskPreparedEntry=u,this.smaskPreparedFor=t,this.smaskPreparedOffsetX=p,this.smaskPreparedOffsetY=g,this.smaskPreparedOOBAlpha=l||0===a?null:a}_bakeSMaskCanvas(t,e,s,i,n,r,a){r||a||Z("_bakeSMaskCanvas with neither backdrop nor filter");const o=this.canvasFactory.create(i,n),h=o.context;if(h.drawImage(t,e,s),r&&(h.globalCompositeOperation="destination-atop",h.fillStyle=r,h.fillRect(0,0,i,n)),!a)return o;const l=this.canvasFactory.create(i,n),c=l.context;c.filter=a.url;const d=ut.isCanvasFilterSupported&&"none"!==c.filter&&""!==c.filter;if(c.drawImage(o.canvas,0,0),ut.isCanvasFilterSupported&&(c.filter="none"),!d){const t=c.getImageData(0,0,i,n),{data:e}=t,{transferMap:s}=a;if("Luminosity"===a.subtype)for(let i=0,n=e.length;i<n;i+=4){const t=.3*e[i]+.59*e[i+1]+.11*e[i+2]+.5|0;e[i]=e[i+1]=e[i+2]=0,e[i+3]=s?.[t]??t}else for(let i=3,n=e.length;i<n;i+=4)e[i]=s[e[i]];c.putImageData(t,0,0)}return this.canvasFactory.destroy(o),l}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const{width:e,height:s}=this.ctx.canvas,i=this.canvasFactory.create(e,s);this.smaskScratchCanvas=i,this.suspendedCtx=this.ctx;const n=this.ctx=i.context;n.setTransform(this.suspendedCtx.getTransform()),Fs(this.suspendedCtx,n),Ms(n,this.suspendedCtx),this._ensurePreparedSMask(this.current.activeSMask),this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),Fs(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null,this.canvasFactory.destroy(this.smaskScratchCanvas),this.smaskScratchCanvas=null,this._clearPreparedSMask()}#tn(t,e=null,s=1){const{width:i,height:n}=t,r=e??this.canvasFactory.create(i,n),a=r.context,o=(s=Math.round(255*s)/255)<1;o&&void 0===this.#Yi&&(this.#Yi=ut.isCanvasFilterSupported?new Map:"none");let h="none";if(o&&this.#Yi instanceof Map&&(h=this.#Yi.get(s),h||(h=this.filterFactory.addKnockoutFilter(s),this.#Yi.set(s,h))),!o||"none"!==h)return e&&(a.save(),a.setTransform(1,0,0,1,0,0),a.clearRect(0,0,i,n),a.restore()),a.filter=h,a.drawImage(t,0,0),a.filter="none",r;const l=t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,i,n),c=a.createImageData(i,n),d=l.data,u=c.data,p=s>0?1/s:1e6;for(let g=3,m=d.length;g<m;g+=4)u[g]=Math.min(Math.round(d[g]*p),255);return a.putImageData(c,0,0),r}#en(t,e,s,i){let n=t?.[e]??null;if(!n||n.canvas.width===s&&n.canvas.height===i||(this.canvasFactory.destroy(n),n=null),!n)return n=this.canvasFactory.create(s,i),t&&(t[e]=n),n;const r=n.context;return r.save(),r.setTransform(1,0,0,1,0,0),r.clearRect(0,0,s,i),r.restore(),n}#sn(t,e,s={}){const{backdropCanvas:i=null,destTransform:n=[1,0,0,1,0,0],backdropOffset:r=[0,0],reuseMaskEntry:a=null,poolMeta:o=null,sourceAlpha:h=1,sourceFilter:l="none",knockoutAlpha:c=1}=s,{width:d,height:u}=e,p=this.#tn(e,a,c),g=t.globalCompositeOperation;if(t.save(),t.setTransform(...n),t.globalAlpha=1,ut.isCanvasFilterSupported&&(t.filter="none"),t.globalCompositeOperation="destination-out",t.drawImage(p.canvas,0,0),i){const[e,s]=r,n=this.#en(o,"knockoutBackdropEntry",d,u),a=n.context;a.drawImage(i,e,s,d,u,0,0,d,u),a.globalCompositeOperation="destination-in",a.drawImage(p.canvas,0,0),a.globalCompositeOperation="source-over",t.globalCompositeOperation="destination-over",t.drawImage(n.canvas,0,0),o||this.canvasFactory.destroy(n)}t.globalCompositeOperation=g,t.globalAlpha=h,ut.isCanvasFilterSupported&&(t.filter=l??"none"),t.drawImage(e,0,0),t.restore(),a||this.canvasFactory.destroy(p)}#in(t=1){if(0===this.#Hi||this.#$i>0||!this.contentVisible)return!1;this.#$i++,this.#Xi=t;const e=this.#Ki.at(-1),{canvas:s}=this.ctx,i=this.#en(e,"knockoutTempEntry",s.width,s.height);this.#zi=i;const n=i.context;return n.save(),n.setTransform(this.ctx.getTransform()),Fs(this.ctx,n),this.#Vi=n.globalCompositeOperation,n.globalCompositeOperation="source-over",Ms(n,this.ctx),this.#qi=e,this.#Gi=this.ctx,this.#Wi=this.suspendedCtx,this.ctx=n,this.inSMaskMode&&(this.suspendedCtx=n),!0}#nn(t){if(!t)return;const e=this.#zi,s=this.#Gi,i=this.#Wi,n=e.context;this.#zi=null,this.#Gi=null,this.#Wi=null,this.inSMaskMode&&this.suspendedCtx===n&&this.ctx!==n&&this.endSMaskMode(),this.inSMaskMode&&(this.suspendedCtx=i),this.ctx._removeMirroring(),this.ctx.globalCompositeOperation=this.#Vi,this.#Vi=null,Fs(this.ctx,s),this.ctx=s;const r=this.#qi;this.#qi=null;const a=this.#Xi;this.#Xi=1;try{this.#sn(i??s,e.canvas,{backdropCanvas:r?.backdropCtx?.canvas??null,backdropOffset:r?.backdropCtx?[r.offsetX,r.offsetY]:[0,0],reuseMaskEntry:r?.knockoutMaskEntry??null,poolMeta:r,knockoutAlpha:a})}finally{n.restore(),this.#$i--,r||this.canvasFactory.destroy(e)}}compose(t){if(!this.current.activeSMask)return;t=t?[Math.floor(t[0]),Math.floor(t[1]),Math.ceil(t[2]),Math.ceil(t[3])]:[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx,i=this.#$i>0&&s===this.ctx;this.composeSMask(i?null:s,e,this.ctx,t),i||(this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(t[0],t[1],t[2]-t[0],t[3]-t[1]),this.ctx.restore())}composeSMask(t,e,s,i){const n=i[0],r=i[1],a=i[2]-n,o=i[3]-r;if(0===a||0===o)return;const h=this.smaskPreparedEntry;if(h){let t=n,i=r,l=a,c=o;const d=this.smaskPreparedOOBAlpha,u=null!==d;if(u&&(t=Math.max(n,e.offsetX),i=Math.max(r,e.offsetY),l=Math.min(n+a,e.offsetX+e.canvas.width)-t,c=Math.min(r+o,e.offsetY+e.canvas.height)-i),l>0&&c>0){const e=t-this.smaskPreparedOffsetX,n=i-this.smaskPreparedOffsetY;s.save(),s.globalAlpha=1,s.setTransform(1,0,0,1,0,0);const r=new Path2D;r.rect(t,i,l,c),s.clip(r),s.globalCompositeOperation="destination-in",s.drawImage(h.canvas,e,n,l,c,t,i,l,c),s.restore()}u&&d<255&&this._applySMaskOOBAlpha(s,n,r,a,o,t,i,t+l,i+c,d)}else this.genericComposeSMask(e,s,a,o,n,r);t&&(t.save(),t.globalAlpha=1,t.globalCompositeOperation=e.blendMode||"source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(s.canvas,n,r,a,o,n,r,a,o),t.restore())}_applySMaskOOBAlpha(t,e,s,i,n,r,a,o,h,l){const c=r<o&&a<h;if(c&&r===e&&a===s&&o===e+i&&h===s+n)return;const d=new Path2D;d.rect(e,s,i,n),c&&d.rect(r,a,o-r,h-a),t.save(),t.globalAlpha=l/255,t.setTransform(1,0,0,1,0,0),t.clip(d,"evenodd"),t.globalCompositeOperation="destination-in",t.fillStyle="#000000",t.fillRect(e,s,i,n),t.restore()}genericComposeSMask(t,e,s,i,n,r){const{context:a,offsetX:o,offsetY:h}=t;e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0);const l=new Path2D;l.rect(n,r,s,i),e.clip(l),e.globalCompositeOperation="destination-in",e.drawImage(a.canvas,n-o,r-h,s,i,n,r,s,i),e.restore()}save(t){this.inSMaskMode&&Fs(this.ctx,this.suspendedCtx),this.ctx.save();const e=this.current;this.stateStack.push(e),this.current=e.clone(),this.dependencyTracker?.save(t)}restore(t){this.dependencyTracker?.restore(t),0!==this.stateStack.length?(this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&(Fs(this.suspendedCtx,this.ctx),this.ctx.setTransform(this.suspendedCtx.getTransform())),this.checkSMaskState(t),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null):this.inSMaskMode&&this.endSMaskMode()}transform(t,e,s,i,n,r,a){this.dependencyTracker?.recordIncrementalData("transform",t),this.ctx.transform(e,s,i,n,r,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s,i){let[n]=s;if(!i)return n||=s[0]=new Path2D,e!==$.stroke&&e!==$.closeStroke&&(this.current.tilingPatternDims=null),void this[e](t,n);if(null!==this.dependencyTracker){const s=e===$.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,i[0]-s,i[2]+s,i[1]-s,i[3]+s).recordDependencies(t,["transform"])}n instanceof Path2D||(n=s[0]=$t(n)),pt.axialAlignedBoundingBox(i,Rt(this.ctx),this.current.minMax);const r=this.current.tilingPatternDims;if(r&&e!==$.stroke&&e!==$.closeStroke&&this.current.fillColor instanceof xs){const t=pt.intersect(this.current.clipBox,this.current.minMax);t?this.current.fillColor.updatePatternDims(t,r):this.current.tilingPatternDims=null}this[e](t,n),this._pathStartIdx=t}closePath(t){this.ctx.closePath()}stroke(t,e,s=!0){const i=s&&this.#in(this.current.strokeAlpha),n=this.ctx,r=this.current.strokeColor;if(n.globalAlpha=this.current.strokeAlpha,this.contentVisible)if("object"==typeof r&&r?.getPattern){const s=r.isModifyingCurrentTransform()?n.getTransform():null;if(n.save(),n.strokeStyle=r.getPattern(n,this,Ot(n),ps,t),s){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(s)),e=t}this.rescaleAndStroke(e,!1),n.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,ve),s&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(ps,Rt(this.ctx))),n.globalAlpha=this.current.fillAlpha,this.#nn(i)}closeStroke(t,e){this.stroke(t,e)}fill(t,e,s=!0){const i=s&&this.#in(this.current.fillAlpha),n=this.ctx,r=this.current.fillColor,a=this.current.patternFill;let o=!1;const h=this.current.getClippedPathBoundingBox();if(this.dependencyTracker?.recordDependencies(t,_e),a){const a=this.current.tilingPatternDims,l=a&&r.canSkipPatternCanvas(a);if(l)return r.drawPattern(this,e,this.pendingEOFill,l,t),this.pendingEOFill=!1,s&&this.consumePath(t,e,h),this.current.tilingPatternDims=null,void this.#nn(i);const c=r.isModifyingCurrentTransform()?n.getTransform():null;if(this.dependencyTracker?.save(t),n.save(),n.fillStyle=r.getPattern(n,this,Ot(n),us,t),c){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(c)),e=t}o=!0}this.contentVisible&&null!==h&&(this.pendingEOFill?(n.fill(e,"evenodd"),this.pendingEOFill=!1):n.fill(e)),o&&(n.restore(),this.dependencyTracker?.restore(t)),s&&this.consumePath(t,e,h),this.#nn(i)}eoFill(t,e){this.pendingEOFill=!0,this.fill(t,e)}fillStroke(t,e){const s=this.#in(Math.min(this.current.fillAlpha,this.current.strokeAlpha));this.fill(t,e,!1),this.stroke(t,e,!1),this.consumePath(t,e),this.#nn(s)}eoFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}closeFillStroke(t,e){this.fillStroke(t,e)}closeEOFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}endPath(t,e){this.consumePath(t,e)}rawFillPath(t,e){const s=this.#in(this.current.fillAlpha);this.ctx.fill(e),this.dependencyTracker?.recordDependencies(t,Se).recordOperation(t),this.#nn(s)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Ls}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Us}beginText(t){this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.dependencyTracker?.recordOpenMarker(t).resetIncrementalData("sameLineText").resetIncrementalData("moveText",t)}endText(t){const e=this.pendingTextPaths,s=this.ctx;if(this.dependencyTracker){const{dependencyTracker:s}=this;void 0!==e&&s.recordFutureForcedDependency("textClip",s.getOpenMarker()).recordFutureForcedDependency("textClip",t),s.recordCloseMarker(t)}if(void 0!==e){const t=new Path2D,i=s.getTransform().invertSelf();for(const{transform:s,x:n,y:r,fontSize:a,path:o}of e)o&&t.addPath(o,new DOMMatrix(s).preMultiplySelf(i).translate(n,r).scale(a,-a));s.clip(t)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t),this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t),this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t),this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t),this.current.leading=-e}setFont(t,e,s){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",e,t);const i=this.commonObjs.get(e),n=this.current;if(!i)throw new Error(`Can't find font for ${e}`);if(n.fontMatrix=i.fontMatrix||g,0!==n.fontMatrix[0]&&0!==n.fontMatrix[3]||J("Invalid font matrix for font "+e),s<0?(s=-s,n.fontDirection=-1):n.fontDirection=1,this.current.font=i,this.current.fontSize=s,i.isType3Font)return;const r=i.loadedName||"sans-serif",a=i.systemFontInfo?.css||`"${r}", ${i.fallbackName}`;let o="normal";i.black?o="900":i.bold&&(o="bold");const h=i.italic?"italic":"normal";let l=s;s<16?l=16:s>100&&(l=100),this.current.fontSizeScale=s/l,this.ctx.font=`${h} ${o} ${l}px ${a}`}setTextRenderingMode(t,e){this.dependencyTracker?.recordSimpleData("textRenderingMode",t),this.current.textRenderingMode=e}setTextRise(t,e){this.dependencyTracker?.recordSimpleData("textRise",t),this.current.textRise=e}moveText(t,e,s){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t),this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=s}setLeadingMoveText(t,e,s){this.setLeading(t,-s),this.moveText(t,e,s)}setTextMatrix(t,e){this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",t);const{current:s}=this;s.textMatrix=e,s.textMatrixScale=Math.hypot(e[0],e[1]),s.x=s.lineX=0,s.y=s.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading),this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#rn(t,e,s){const i=new Path2D;return i.addPath(t,new DOMMatrix(s).invertSelf().multiplySelf(e)),i}paintChar(t,e,s,i,n,r){const a=this.ctx,o=this.current,h=o.font,l=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,d=l&F,u=!!(l&N),p=o.patternFill&&!h.missingFile,g=o.patternStroke&&!h.missingFile;let m;if((h.disableFontFace||u||p||g)&&!h.missingFile&&(m=h.getPathGenerator(this.commonObjs,e)),m&&(h.disableFontFace||p||g)){let e;if(a.save(),a.translate(s,i),a.scale(c,-c),this.dependencyTracker?.recordCharacterBBox(t,a,h),d===E||d===D)if(n){e=a.getTransform(),a.setTransform(...n);const t=this.#rn(m,e,n);a.fill(t)}else a.fill(m);if(d===P||d===D)if(r){e||=a.getTransform(),a.setTransform(...r);const{a:t,b:s,c:i,d:n}=e,o=pt.inverseTransform(r),h=pt.transform([t,s,i,n,0,0],o);pt.singularValueDecompose2dScale(h,Ts),a.lineWidth*=Math.max(Ts[0],Ts[1])/c,a.stroke(this.#rn(m,e,r))}else a.lineWidth/=c,a.stroke(m);a.restore()}else d!==E&&d!==D||(a.fillText(e,s,i),this.dependencyTracker?.recordCharacterBBox(t,a,h,c,s,i,()=>a.measureText(e))),d!==P&&d!==D||(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,a,h,c,s,i,()=>a.measureText(e)).recordDependencies(t,ve),a.strokeText(e,s,i));u&&((this.pendingTextPaths||=[]).push({transform:Rt(a),x:s,y:i,fontSize:c,path:m}),this.dependencyTracker?.recordCharacterBBox(t,a,h,c,s,i))}get isFontSubpixelAAEnabled(){const t=this.canvasFactory.create(10,10),e=t.context;e.scale(1.5,1),e.fillText("I",0,10);const s=e.getImageData(0,0,10,10).data;this.canvasFactory.destroy(t);let i=!1;for(let n=3;n<s.length;n+=4)if(s[n]>0&&s[n]<255){i=!0;break}return it(this,"isFontSubpixelAAEnabled",i)}showText(t,e){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(t,Ce).resetBBox(t),this.current.textRenderingMode&N&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies());const s=this.current,i=s.font;if(i.isType3Font){const i=this.#in(s.fillAlpha);return this.showType3Text(t,e),this.dependencyTracker?.recordShowTextOperation(t),void this.#nn(i)}const n=s.fontSize;if(0===n)return void this.dependencyTracker?.recordOperation(t);const r=this.#in(s.fillAlpha),a=this.ctx,o=s.fontSizeScale,h=s.charSpacing,l=s.wordSpacing,c=s.fontDirection,d=s.textHScale*c,u=e.length,p=i.vertical,g=p?1:-1,m=i.defaultVMetrics,f=n*s.fontMatrix[0],b=s.textRenderingMode===E&&!i.disableFontFace&&!s.patternFill;let y,A;a.save(),s.textMatrix&&a.transform(...s.textMatrix),a.translate(s.x,s.y+s.textRise),c>0?a.scale(d,-1):a.scale(d,1);const w=s.textRenderingMode&F,v=w===E||w===D,_=w===P||w===D;let x=s.lineWidth;const S=s.textMatrixScale;if(0===S||0===x?_&&(x=this.getSinglePixelWidth()):x/=S,1!==o&&(a.scale(o,o),x/=o),a.lineWidth=x,v&&s.patternFill){a.save();const e=s.fillColor.getPattern(a,this,Ot(a),us,t);y=Rt(a),a.restore(),a.fillStyle=e}if(_&&s.patternStroke){a.save();const e=s.strokeColor.getPattern(a,this,Ot(a),ps,t);A=Rt(a),a.restore(),a.strokeStyle=e}if(i.isInvalidPDFjsFont){const i=[];let n=0;for(const t of e)i.push(t.unicode),n+=t.width;const o=i.join("");if(a.fillText(o,0,0),null!==this.dependencyTracker){const e=a.measureText(o);this.dependencyTracker.recordBBox(t,this.ctx,-e.actualBoundingBoxLeft,e.actualBoundingBoxRight,-e.actualBoundingBoxAscent,e.actualBoundingBoxDescent).recordShowTextOperation(t)}return s.x+=n*f*d,a.restore(),this.compose(),void this.#nn(r)}let C,k=0;for(C=0;C<u;++C){const s=e[C];if("number"==typeof s){k+=g*s*n/1e3;continue}let r=!1;const d=(s.isSpace?l:0)+h,u=s.fontChar,w=s.accent;let v,_,x,S=s.width;if(p){const t=s.vmetric||m,e=-(s.vmetric?t[1]:.5*S)*f,i=t[2]*f;S=t?-t[0]:S,v=e/o,_=(k+i)/o}else v=k/o,_=0;if(i.remeasure&&S>0){x=a.measureText(u);const t=1e3*x.width/n*o;if(S<t&&this.isFontSubpixelAAEnabled){const e=S/t;r=!0,a.save(),a.scale(e,1),v/=e}else S!==t&&(v+=(S-t)/2e3*n/o)}if(this.contentVisible&&(s.isInFont||i.missingFile))if(b&&!w)a.fillText(u,v,_),this.dependencyTracker?.recordCharacterBBox(t,a,x?{bbox:null}:i,n/o,v,_,()=>x??a.measureText(u));else if(this.paintChar(t,u,v,_,y,A),w){const e=v+n*w.offset.x/o,s=_-n*w.offset.y/o;this.paintChar(t,w.fontChar,e,s,y,A)}k+=p?S*f-d*c:S*f+d*c,r&&a.restore()}p?s.y-=k:s.x+=k*d,a.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(t),this.#nn(r)}showType3Text(t,e){const s=this.ctx,i=this.current,n=i.font,r=i.fontSize,a=i.fontDirection,o=n.vertical?1:-1,h=i.charSpacing,l=i.wordSpacing,c=i.textHScale*a,d=i.fontMatrix||g,u=e.length;let p,m,f,b;if(i.textRenderingMode===I||0===r)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,s.save(),i.textMatrix&&s.transform(...i.textMatrix),s.translate(i.x,i.y+i.textRise),s.scale(c,a);const y=this.dependencyTracker;for(this.dependencyTracker=y?new we(y,t):null,p=0;p<u;++p){if(m=e[p],"number"==typeof m){b=o*m*r/1e3,this.ctx.translate(b,0),i.x+=b*c;continue}const t=(m.isSpace?l:0)+h,a=n.charProcOperatorList[m.operatorListId];a?this.contentVisible&&(this.save(),s.scale(r,r),s.transform(...d),this.executeOperatorList(a),this.restore()):J(`Type3 character "${m.operatorListId}" is not available.`);const u=[m.width,0];pt.applyTransform(u,d),f=u[0]*r+t,s.translate(f,0),i.x+=f*c}s.restore(),y&&(this.dependencyTracker=y)}setCharWidth(t,e,s){}setCharWidthAndBounds(t,e,s,i,n,r,a){const o=new Path2D;o.rect(i,n,r-i,a-n),this.ctx.clip(o),this.dependencyTracker?.recordBBox(t,this.ctx,i,r,n,a).recordClipBox(t,this.ctx,i,r,n,a),this.endPath(t)}getColorN_Pattern(t,e){let s;if("TilingPattern"===e[0]){const t=this.baseTransform||Rt(this.ctx),i={createCanvasGraphics:(t,e)=>new js(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new we(this.dependencyTracker,e,!0):null)};s=new xs(e,this.ctx,i,t)}else s=this._getPattern(t,e[1],e[2]);return s}setStrokeColorN(t,...e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.current.strokeColor=this.getColorN_Pattern(t,e),this.current.patternStroke=!0}setFillColorN(t,...e){this.dependencyTracker?.recordSimpleData("fillColor",t);const s=this.current.fillColor=this.getColorN_Pattern(t,e);this.current.patternFill=!0,this.current.tilingPatternDims=s instanceof xs?[0,0,0,0]:null}setStrokeRGBColor(t,e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor=e,this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor=e,this.current.patternFill=!1,this.current.tilingPatternDims=null}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1,this.current.tilingPatternDims=null}_getPattern(t,e,s=null){let i;return this.cachedPatterns.has(e)?i=this.cachedPatterns.get(e):(i=function(t){switch(t[0]){case"RadialAxial":return new bs(t);case"Mesh":return new As(t);case"Dummy":return new ws}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t,e)),this.cachedPatterns.set(e,i)),s&&(i.matrix=s),i}shadingFill(t,e){if(!this.contentVisible)return;const s=this.#in(this.current.fillAlpha),i=this.ctx;this.save(t);const n=this._getPattern(t,e);i.fillStyle=n.getPattern(i,this,Ot(i),gs,t);const r=Ot(i);if(r){const{width:t,height:e}=i.canvas,s=p.slice();pt.axialAlignedBoundingBox([0,0,t,e],r,s);const[n,a,o,h]=s;this.ctx.fillRect(n,a,o-n,h-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,ke).recordDependencies(t,_e).recordOperation(t),this.compose(this.current.getClippedPathBoundingBox()),this.restore(t),this.#nn(s)}beginInlineImage(){Z("Should not call beginInlineImage")}beginImageData(){Z("Should not call beginImageData")}paintFormXObjectBegin(t,e,s){if(this.contentVisible&&(this.save(t),this.baseTransformStack.push(this.baseTransform),e&&this.transform(t,...e),this.baseTransform=Rt(this.ctx),s)){pt.axialAlignedBoundingBox(s,this.baseTransform,this.current.minMax);const[e,i,n,r]=s,a=new Path2D;a.rect(e,i,n-e,r-i),this.ctx.clip(a),this.dependencyTracker?.recordClipBox(t,this.ctx,e,n,i,r),this.endPath(t)}}paintFormXObjectEnd(t){this.contentVisible&&(this.restore(t),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t,e){if(!this.contentVisible)return;this.save(t);const{inSMaskMode:s}=this;s&&(this.endSMaskMode(),this.current.activeSMask=null);const i=this.ctx;if(e.isolated||e.knockout||0!==this.#Hi||Q("TODO: Fully support non-isolated non-knockout groups."),!e.needsIsolation&&!e.knockout&&0===this.#Hi&&1===i.globalAlpha&&"source-over"===i.globalCompositeOperation&&!s){if(e.bbox){let t=new Path2D;const[s,n,r,a]=e.bbox;if(t.rect(s,n,r-s,a-n),e.matrix){const s=new Path2D;s.addPath(t,new DOMMatrix(e.matrix)),t=s}i.clip(t)}return this.groupStack.push(null),this.#Ki.push(null),void this.groupLevel++}const n=Rt(i);e.matrix&&i.transform(...e.matrix);const r=[0,0,i.canvas.width,i.canvas.height];let a;e.bbox?(a=p.slice(),pt.axialAlignedBoundingBox(e.bbox,Rt(i),a),a=pt.intersect(a,r)||[0,0,0,0]):a=r;const o=Math.floor(a[0]),h=Math.floor(a[1]),l=Math.max(Math.ceil(a[2])-o,1),c=Math.max(Math.ceil(a[3])-h,1);this.current.startNewPathAndClipBox([0,0,l,c]);const d=this.canvasFactory.create(l,c);e.smask&&this.smaskGroupCanvases.push(d);const u=d.context,g=e.knockout&&!e.isolated?i:null,m=!e.isolated&&!e.knockout&&!e.smask&&e.needsIsolation&&this.#Hi>0,f=e.knockout?this.canvasFactory.create(l,c):null,b=this.#Hi;if(e.knockout?this.#Hi++:this.#Hi=0,u.translate(-o,-h),u.transform(...n),!e.isolated&&!e.smask&&s&&e.needsIsolation&&(u.save(),u.setTransform(1,0,0,1,0,0),u.drawImage(i.canvas,-o,-h),u.restore()),e.bbox){let t=new Path2D;const[s,i,n,r]=e.bbox;if(t.rect(s,i,n-s,r-i),e.matrix){const s=new Path2D;s.addPath(t,new DOMMatrix(e.matrix)),t=s}u.clip(t)}e.smask&&this.smaskStack.push({canvas:d.canvas,context:u,offsetX:o,offsetY:h,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null}),e.smask&&!this.dependencyTracker||(i.setTransform(1,0,0,1,0,0),i.translate(o,h),i.save()),Fs(i,u),this.ctx=u,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i),this.setGState(t,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]),this.groupStack.push(i),this.#Ki.push({backdropCtx:g,savedKnockoutLevel:b,offsetX:o,offsetY:h,hasInnerBackdrop:m,knockoutMaskEntry:f,knockoutTempEntry:null,knockoutBackdropEntry:null}),this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const s=this.ctx,i=this.groupStack.pop(),n=this.#Ki.pop();if(n&&(this.#Hi=n.savedKnockoutLevel),null!==i)if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),e.smask)this.tempSMask=this.smaskStack.pop(),this.restore(t),this.dependencyTracker&&(this.ctx.restore(),this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform())),this.#Ji(n);else{this.ctx.restore();const e=Rt(this.ctx);this.restore(t),this.ctx.save(),this.ctx.setTransform(...e);const r=p.slice();pt.axialAlignedBoundingBox([0,0,s.canvas.width,s.canvas.height],e,r);const a=this.#Ki.at(-1);if(this.#Hi>0)if(n.hasInnerBackdrop){const{width:t,height:r}=s.canvas,a=this.canvasFactory.create(t,r),o=a.context;o.drawImage(i.canvas,n.offsetX,n.offsetY,t,r,0,0,t,r),o.globalCompositeOperation="source-over",o.drawImage(s.canvas,0,0);const h=this.#tn(s.canvas);o.globalCompositeOperation="destination-in",o.drawImage(h.canvas,0,0);const l=this.ctx.globalCompositeOperation,c=this.ctx.globalAlpha,d=this.ctx.filter;this.ctx.save(),this.ctx.setTransform(...e),this.ctx.globalAlpha=1,ut.isCanvasFilterSupported&&(this.ctx.filter="none"),this.ctx.globalCompositeOperation="destination-out",this.ctx.drawImage(h.canvas,0,0),this.ctx.globalCompositeOperation=l,this.ctx.globalAlpha=c,ut.isCanvasFilterSupported&&(this.ctx.filter=d??"none"),this.ctx.drawImage(a.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(h),this.canvasFactory.destroy(a)}else{const t=a?.backdropCtx??null;this.#sn(this.ctx,s.canvas,{backdropCanvas:t?.canvas??null,destTransform:e,backdropOffset:t?[a.offsetX+n.offsetX,a.offsetY+n.offsetY]:[0,0],sourceAlpha:this.ctx.globalAlpha,sourceFilter:this.ctx.filter})}else this.ctx.drawImage(s.canvas,0,0);this.ctx.restore(),this.canvasFactory.destroy({canvas:s.canvas,context:s}),this.#Ji(n),this.compose(r)}else this.restore(t)}#Ji(t){t&&(t.knockoutMaskEntry&&(this.canvasFactory.destroy(t.knockoutMaskEntry),t.knockoutMaskEntry=null),t.knockoutTempEntry&&(this.canvasFactory.destroy(t.knockoutTempEntry),t.knockoutTempEntry=null),t.knockoutBackdropEntry&&(this.canvasFactory.destroy(t.knockoutBackdropEntry),t.knockoutBackdropEntry=null))}beginAnnotation(t,e,s,i,n,r){if(this.#Qi(),Ns(this.ctx),this.ctx.save(),this.save(t),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),s){const n=s[2]-s[0],a=s[3]-s[1];if(r&&this.annotationCanvasMap){(i=i.slice())[4]-=s[0],i[5]-=s[1],(s=s.slice())[0]=s[1]=0,s[2]=n,s[3]=a,pt.singularValueDecompose2dScale(Rt(this.ctx),Ts);const{viewportScale:t}=this,r=Math.ceil(n*this.outputScaleX*t),o=Math.ceil(a*this.outputScaleY*t);this.annotationCanvas=this.canvasFactory.create(r,o);const{canvas:h,context:l}=this.annotationCanvas;this.annotationCanvasMap.set(e,h),this.annotationCanvas.savedCtx=this.ctx,this.ctx=l,this.ctx.save(),this.ctx.setTransform(Ts[0],0,0,-Ts[1],0,a*Ts[1]),Ns(this.ctx)}else{Ns(this.ctx),this.endPath(t);const e=new Path2D;e.rect(s[0],s[1],n,a),this.ctx.clip(e)}}this.current=new Ps(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(t,...i),this.transform(t,...n),this.baseTransform=Rt(this.ctx)}endAnnotation(t){this.annotationCanvas&&(this.ctx.restore(),this.#Zi(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const s=e.count;(e=this.getObject(t,e.data,e)).count=s;const i=this.#in(this.current.fillAlpha),n=this.ctx,r=this._createMaskCanvas(t,e),a=r.canvas;n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage(a,r.offsetX,r.offsetY),this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,r.offsetX,r.offsetX+a.width,r.offsetY,r.offsetY+a.height).recordOperation(t),n.restore(),r.canvasEntry&&this.canvasFactory.destroy(r.canvasEntry),this.compose(),this.#nn(i)}paintImageMaskXObjectRepeat(t,e,s,i=0,n=0,r,a){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);const o=this.#in(this.current.fillAlpha),h=this.ctx;h.save();const l=Rt(h);h.transform(s,i,n,r,0,0);const c=this._createMaskCanvas(t,e);h.setTransform(1,0,0,1,c.offsetX-l[4],c.offsetY-l[5]),this.dependencyTracker?.resetBBox(t);for(let d=0,u=a.length;d<u;d+=2){const e=pt.transform(l,[s,i,n,r,a[d],a[d+1]]);h.drawImage(c.canvas,e[4],e[5]),this.dependencyTracker?.recordBBox(t,this.ctx,e[4],e[4]+c.canvas.width,e[5],e[5]+c.canvas.height)}h.restore(),c.canvasEntry&&this.canvasFactory.destroy(c.canvasEntry),this.compose(),this.dependencyTracker?.recordOperation(t),this.#nn(o)}paintImageMaskXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.#in(this.current.fillAlpha),i=this.ctx,n=this.current.fillColor,r=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,Te);for(const a of e){const{data:e,width:s,height:o,transform:h}=a,l=this.canvasFactory.create(s,o),c=l.context;c.save(),Is(c,this.getObject(t,e,a)),c.globalCompositeOperation="source-in",c.fillStyle=r?n.getPattern(c,this,Ot(i),us,t):n,c.fillRect(0,0,s,o),c.restore(),i.save(),i.transform(...h),i.scale(1,-1),Es(i,l.canvas,0,0,s,o,0,-1,1,1),this.canvasFactory.destroy(l),this.dependencyTracker?.recordBBox(t,i,0,s,0,o),i.restore()}this.compose(),this.dependencyTracker?.recordOperation(t),this.#nn(s)}paintImageXObject(t,e){if(!this.contentVisible)return;const s=this.getObject(t,e);s?this.paintInlineImageXObject(t,s):J("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,s,i,n){if(!this.contentVisible)return;const r=this.getObject(t,e);if(!r)return void J("Dependent image isn't ready yet");const a=r.width,o=r.height,h=[];for(let l=0,c=n.length;l<c;l+=2)h.push({transform:[s,0,0,i,n[l],n[l+1]],x:0,y:0,w:a,h:o});this.paintInlineImageXObjectGroup(t,r,h)}applyTransferMapsToCanvas(t){return"none"!==this.current.transferMaps&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if("none"===this.current.transferMaps)return{img:t.bitmap,canvasEntry:null};const{bitmap:e,width:s,height:i}=t,n=this.canvasFactory.create(s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",{img:n.canvas,canvasEntry:n}}paintInlineImageXObject(t,e){if(!this.contentVisible)return;const s=e.width,i=e.height,n=this.#in(this.current.fillAlpha),r=this.ctx;this.save(t);const{filter:a}=r;"none"!==a&&""!==a&&(r.filter="none"),r.scale(1/s,-1/i);let o,h=null;if(e.bitmap){const t=this.applyTransferMapsToBitmap(e);o=t.img,h=t.canvasEntry}else if("function"==typeof HTMLElement&&e instanceof HTMLElement||!e.data)o=e;else{const t=this.canvasFactory.create(s,i);Ds(t.context,e),o=this.applyTransferMapsToCanvas(t.context),h=t}const l=this._scaleImage(o,Ot(r));r.imageSmoothingEnabled=Rs(Rt(r),e.interpolate),this.dependencyTracker&&(this.dependencyTracker.resetBBox(t).recordBBox(t,r,0,s,-i,0).recordDependencies(t,xe).recordOperation(t),this.imagesTracker?.record(r,s,i,this.dependencyTracker.clipBox)),Es(r,l.img,0,0,l.paintWidth,l.paintHeight,0,-i,s,i),l.tmpCanvas&&this.canvasFactory.destroy(l.tmpCanvas),h&&this.canvasFactory.destroy(h),this.compose(),this.restore(t),this.#nn(n)}paintInlineImageXObjectGroup(t,e,s){if(!this.contentVisible)return;const i=this.#in(this.current.fillAlpha),n=this.ctx;let r,a=null;if(e.bitmap)r=e.bitmap;else{const t=e.width,s=e.height,i=this.canvasFactory.create(t,s);Ds(i.context,e),r=this.applyTransferMapsToCanvas(i.context),a=i}this.dependencyTracker?.resetBBox(t);for(const o of s)n.save(),n.transform(...o.transform),n.scale(1,-1),Es(n,r,o.x,o.y,o.w,o.h,0,-1,1,1),this.dependencyTracker?.recordBBox(t,n,0,1,-1,0),n.restore();a&&this.canvasFactory.destroy(a),this.dependencyTracker?.recordOperation(t),this.compose(),this.#nn(i)}paintSolidColorImageMask(t){if(!this.contentVisible)return;const e=this.#in(this.current.fillAlpha);this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,_e).recordOperation(t),this.ctx.fillRect(0,0,1,1),this.compose(),this.#nn(e)}markPoint(t,e){}markPointProps(t,e,s){}beginMarkedContent(t,e){this.dependencyTracker?.beginMarkedContent(t),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e,s){this.dependencyTracker?.beginMarkedContent(t),"OC"===e?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(s)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(t){this.dependencyTracker?.endMarkedContent(t),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(t){}endCompat(t){}consumePath(t,e,s){const i=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(s);const n=this.ctx;this.pendingClip?(i||(this.pendingClip===Us?n.clip(e,"evenodd"):n.clip(e)),this.pendingClip=null,this.dependencyTracker?.bboxToClipBoxDropOperation(t).recordFutureForcedDependency("clipPath",t)):this.dependencyTracker?.recordOperation(t),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=Rt(this.ctx);if(0===t[1]&&0===t[2])this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,a;if(0===s&&0===i){const s=Math.abs(e),i=Math.abs(n);if(s===i)if(0===t)r=a=1/s;else{const e=s*t;r=a=e<1?1/e:1}else if(0===t)r=1/s,a=1/i;else{const e=s*t,n=i*t;r=e<1?1/e:1,a=n<1?1/n:1}}else{const o=Math.abs(e*n-s*i),h=Math.hypot(e,s),l=Math.hypot(i,n);if(0===t)r=l/o,a=h/o;else{const e=t*o;r=l>e?l/e:1,a=h>e?h/e:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:s,current:{lineWidth:i}}=this,[n,r]=this.getScaleForStroking();if(n===r)return s.lineWidth=(i||1)*n,void s.stroke(t);const a=s.getLineDash();e&&s.save(),s.scale(n,r),ks.a=1/n,ks.d=1/r;const o=new Path2D;if(o.addPath(t,ks),a.length>0){const t=Math.max(n,r);s.setLineDash(a.map(e=>e/t)),s.lineDashOffset/=t}s.lineWidth=i||1,s.stroke(o),e&&s.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const vn in $)void 0!==js.prototype[vn]&&(js.prototype[$[vn]]=js.prototype[vn]);class Hs{#an=null;#on=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(t,e,s){this._source=t,this.#an=e,this.#on=s}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){return tt(!this._fullReader,"BasePDFStream.getFullReader can only be called once."),this._fullReader=new this.#an(this)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new this.#on(this,t,e);return this._rangeReaders.add(s),s}cancelAllRequests(t){this._fullReader?.cancel(t);for(const e of new Set(this._rangeReaders))e.cancel(t)}}class $s{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(t){this._stream=t}_callOnProgress(){this.onProgress?.({loaded:this._loaded,total:this._contentLength})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){Z("Abstract method `read` called")}cancel(t){Z("Abstract method `cancel` called")}}class zs{_stream=null;constructor(t,e,s){this._stream=t}async read(){Z("Abstract method `read` called")}cancel(t){Z("Abstract method `cancel` called")}}function Gs(t,e){const s=new Headers;if(!t||!e||"object"!=typeof e)return s;for(const i in e){const t=e[i];void 0!==t&&s.append(i,t)}return s}function Ws(t){return URL.parse(t)?.origin??null}function Vs({responseHeaders:t,isHttp:e,rangeChunkSize:s,disableRange:i}){const n={contentLength:0,isRangeSupported:!1},r=parseInt(t.get("Content-Length"),10);return Number.isInteger(r)?(n.contentLength=r,r<=2*s||i||!e||"bytes"!==t.get("Accept-Ranges")||"identity"===(t.get("Content-Encoding")||"identity")&&(n.isRangeSupported=!0),n):n}function Xs(t){const e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,s=i("filename\\*","i").exec(t);if(s){s=s[1];let t=a(s);return t=unescape(t),t=o(t),t=h(t),r(t)}if(s=function(t){const e=[];let s;const n=i("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(s=n.exec(t));){let[,t,i,n]=s;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[i,n]}const r=[];for(let i=0;i<e.length&&i in e;++i){let[t,s]=e[i];s=a(s),t&&(s=unescape(s),0===i&&(s=o(s))),r.push(s)}return r.join("")}(t),s)return r(h(s));if(s=i("filename","i").exec(t),s){s=s[1];let t=a(s);return t=h(t),r(t)}function i(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function n(t,s){if(t){if(!/^[\x00-\xFF]+$/.test(s))return s;try{const i=new TextDecoder(t,{fatal:!0}),n=dt(s);s=i.decode(n),e=!1}catch{}}return s}function r(t){return e&&/[\x80-\xff]/.test(t)&&(t=n("utf-8",t),e&&(t=n("iso-8859-1",t))),t}function a(t){if(t.startsWith('"')){const e=t.slice(1).split('\\"');for(let t=0;t<e.length;++t){const s=e[t].indexOf('"');-1!==s&&(e[t]=e[t].slice(0,s),e.length=t+1),e[t]=e[t].replaceAll(/\\(.)/g,"$1")}t=e.join('"')}return t}function o(t){const e=t.indexOf("'");return-1===e?t:n(t.slice(0,e),t.slice(e+1).replace(/^[^']*'/,""))}function h(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(t,e,s,i){if("q"===s||"Q"===s)return n(e,i=(i=i.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}));try{i=atob(i)}catch{}return n(e,i)})}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(Tt(t))return t}return null}function Ys(t,e){return new ht(`Unexpected server response (${t}) while retrieving PDF "${e.href}".`,t,404===t||0===t&&"file:"===e.protocol)}function qs(t,e){if(t!==e)throw new Error(`Expected range response-origin "${t}" to match "${e}".`)}function Ks(t,e,s,i){return fetch(t,{method:"GET",headers:e,signal:i.signal,mode:"cors",credentials:s?"include":"same-origin",redirect:"follow"})}function Qs(t,e){if(200!==t&&206!==t)throw Ys(t,e)}function Js(t){if(t instanceof Uint8Array)return t.buffer;if(t instanceof ArrayBuffer)return t;throw new Error(`getArrayBuffer - unexpected data: ${t}`)}class Zs extends Hs{_responseOrigin=null;constructor(t){super(t,ti,ei);const{httpHeaders:e,url:s}=t;tt(/https?:/.test(s.protocol),"PDFFetchStream only supports http(s):// URLs."),this.headers=Gs(!0,e)}}class ti extends $s{_abortController=new AbortController;_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:s,rangeChunkSize:i,url:n,withCredentials:r}=t._source;this._isStreamingSupported=!s;const a=new Headers(t.headers);Ks(n,a,r,this._abortController).then(s=>{t._responseOrigin=Ws(s.url),Qs(s.status,n),this._reader=s.body.getReader();const r=s.headers,{contentLength:a,isRangeSupported:o}=Vs({responseHeaders:r,isHttp:!0,rangeChunkSize:i,disableRange:e});this._contentLength=a,this._isRangeSupported=o,this._filename=Xs(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new ct("Streaming is disabled.")),this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:Js(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class ei extends zs{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,s){super(t,e,s);const{url:i,withCredentials:n}=t._source,r=new Headers(t.headers);r.append("Range",`bytes=${e}-${s-1}`),Ks(i,r,n,this._abortController).then(e=>{qs(Ws(e.url),t._responseOrigin),Qs(e.status,i),this._reader=e.body.getReader(),this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:Js(t),done:!1}}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}function si(t){return t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function ii(){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}class ni extends Hs{_progressiveDone=!1;_queuedChunks=[];constructor(t){super(t,ri,ai);const{pdfDataRangeTransport:e}=t,{initialData:s,progressiveDone:i}=e;if(s?.length>0){const t=si(s);this._queuedChunks.push(t)}this._progressiveDone=i,e.transportReady(t=>{switch(t.type){case"range":case"progressiveRead":this.#hn(t.begin,t.chunk);break;case"progressiveDone":this._fullReader?.progressiveDone(),this._progressiveDone=!0}})}#hn(t,e){const s=si(e);if(void 0===t)this._fullReader?this._fullReader._enqueue(s):this._queuedChunks.push(s);else{const e=this._rangeReaders.keys().find(e=>e._begin===t);tt(e,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),e._enqueue(s)}}getFullReader(){const t=super.getFullReader();return this._queuedChunks=null,t}getRangeReader(t,e){const s=super.getRangeReader(t,e);return s&&(s.onDone=()=>this._rangeReaders.delete(s),this._source.pdfDataRangeTransport.requestDataRange(t,e)),s}cancelAllRequests(t){super.cancelAllRequests(t),this._source.pdfDataRangeTransport.abort()}}class ri extends $s{#ln=ii.bind(this);_done=!1;_queuedChunks=null;_requests=[];constructor(t){super(t);const{pdfDataRangeTransport:e,disableRange:s,disableStream:i}=t._source,{length:n,contentDispositionFilename:r}=e;this._queuedChunks=t._queuedChunks||[];for(const o of this._queuedChunks)this._loaded+=o.byteLength;this._done=t._progressiveDone,this._contentLength=n,this._isStreamingSupported=!i,this._isRangeSupported=!s,Tt(r)&&(this._filename=r),this._headersCapability.resolve();const a=this._loaded;Promise.resolve().then(()=>{a>0&&this._loaded===a&&this._callOnProgress()})}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength,this._callOnProgress())}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this.#ln()}progressiveDone(){this._done||=!0,0===this._queuedChunks.length&&this.#ln()}}class ai extends zs{#ln=ii.bind(this);onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(t,e,s){super(t,e,s),this._begin=e}_enqueue(t){this._done||(0===this._requests.length?this._queuedChunk=t:(this._requests.shift().resolve({value:t,done:!1}),this.#ln()),this._done=!0,this.onDone?.())}async read(){if(this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this.#ln(),this.onDone?.()}}class oi extends Hs{#cn=new WeakMap;_responseOrigin=null;constructor(t){super(t,hi,li);const{httpHeaders:e,url:s}=t;this.url=s,this.isHttp=/https?:/.test(s.protocol),this.headers=Gs(this.isHttp,e)}_request(t){const e=new XMLHttpRequest,s={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};this.#cn.set(e,s),e.open("GET",this.url),e.withCredentials=this._source.withCredentials;for(const[i,n]of this.headers)e.setRequestHeader(i,n);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),s.validateStatus=t=>206===t||200===t):s.validateStatus=t=>200===t,e.responseType="arraybuffer",tt(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>t.onError(e.status),e.onreadystatechange=this.#dn.bind(this,e),e.onprogress=this.#un.bind(this,e),e.send(null),e}#un(t,e){const s=this.#cn.get(t);s?.onProgress?.(e)}#dn(t,e){const s=this.#cn.get(t);if(!s)return;if(t.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),4!==t.readyState)return;if(!this.#cn.has(t))return;if(this.#cn.delete(t),0===t.status&&this.isHttp)return void s.onError(t.status);const i=t.status||200;if(!s.validateStatus(i))return void s.onError(t.status);const n=function(t){return"string"!=typeof t?t:dt(t).buffer}(t.response);if(206===i){const e=t.getResponseHeader("Content-Range");/bytes (\d+)-(\d+)\/(\d+)/.test(e)?s.onDone(n):(J('Missing or invalid "Content-Range" header.'),s.onError(0))}else n?s.onDone(n):s.onError(t.status)}_abortRequest(t){this.#cn.has(t)&&(this.#cn.delete(t),t.abort())}getRangeReader(t,e){const s=super.getRangeReader(t,e);return s&&(s.onClosed=()=>this._rangeReaders.delete(s)),s}}class hi extends $s{#ln=ii.bind(this);_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(t){super(t),this._fullRequestXhr=t._request({onHeadersReceived:this.#pn.bind(this),onDone:this.#gn.bind(this),onError:this.#mn.bind(this),onProgress:this.#un.bind(this)})}#pn(){const t=this._stream,{disableRange:e,rangeChunkSize:s}=t._source,i=this._fullRequestXhr;t._responseOrigin=Ws(i.responseURL);const n=i.getAllResponseHeaders(),r=new Headers(n?n.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(t=>{const[e,...s]=t.split(": ");return[e,s.join(": ")]}):[]),{contentLength:a,isRangeSupported:o}=Vs({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:s,disableRange:e});this._contentLength=a,this._isRangeSupported=o,this._filename=Xs(r),this._isRangeSupported&&t._abortRequest(i),this._headersCapability.resolve()}#gn(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._cachedChunks.push(t),this._done=!0,0===this._cachedChunks.length&&this.#ln()}#mn(t){this._storedError=Ys(t,this._stream.url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}#un(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t),this.#ln(),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}}class li extends zs{#ln=ii.bind(this);onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(t,e,s){super(t,e,s),this._requestXhr=t._request({begin:e,end:s,onHeadersReceived:this.#pn.bind(this),onDone:this.#gn.bind(this),onError:this.#mn.bind(this),onProgress:null})}#pn(){const t=Ws(this._requestXhr?.responseURL);try{qs(t,this._stream._responseOrigin)}catch(t){this._storedError=t,this.#mn(0)}}#gn(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0,this.#ln(),this.onClosed?.()}#mn(t){this._storedError??=Ys(t,this._stream.url);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this.#ln(),this._stream._abortRequest(this._requestXhr),this.onClosed?.()}}function ci(t,e=null){const s=process.getBuiltinModule("fs"),{Readable:i}=process.getBuiltinModule("stream"),n=s.createReadStream(t,e);return i.toWeb(n)}class di extends Hs{constructor(t){super(t,ui,pi);const{url:e}=t;tt("file:"===e.protocol,"PDFNodeStream only supports file:// URLs.")}}class ui extends $s{_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:s,rangeChunkSize:i,url:n}=t._source;this._isStreamingSupported=!s,process.getBuiltinModule("fs/promises").lstat(n).then(t=>{const s=ci(n);this._reader=s.getReader();const{size:r}=t;this._contentLength=r,this._isRangeSupported=!e&&r>2*i,!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new ct("Streaming is disabled.")),this._headersCapability.resolve()}).catch(t=>{"ENOENT"===t.code&&(t=Ys(0,n)),this._headersCapability.reject(t)})}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:Js(t),done:!1})}cancel(t){this._reader?.cancel(t)}}class pi extends zs{_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,s){super(t,e,s);const{url:i}=t._source;try{const t=ci(i,{start:e,end:s-1});this._reader=t.getReader(),this._readCapability.resolve()}catch(t){this._readCapability.reject(t)}}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:Js(t),done:!1}}cancel(t){this._reader?.cancel(t)}}class gi{static#fn=null;static#bn="";static get workerPort(){return this.#fn}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#fn=t}static get workerSrc(){return this.#bn}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#bn=t}}class mi{#yn;#An;constructor({parsedData:t,rawData:e}){this.#yn=t,this.#An=e}getRaw(){return this.#An}get(t){return this.#yn.get(t)??null}[Symbol.iterator](){return this.#yn.entries()}}const fi=Symbol("INTERNAL");class bi{#wn=!1;#vn=!1;#_n=!1;#xn=!0;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#wn=!!(t&b),this.#vn=!!(t&y),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(this.#_n)return this.#xn;if(!this.#xn)return!1;const{print:t,view:e}=this.usage;return this.#wn?"OFF"!==e?.viewState:!this.#vn||"OFF"!==t?.printState}_setVisible(t,e,s=!1){t!==fi&&Z("Internal method `_setVisible` called."),this.#_n=s,this.#xn=e}}class yi{#Sn=null;#Cn=new Map;#kn=null;#Tn=null;constructor(t,e=b){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#Tn=t.order;for(const s of t.groups)this.#Cn.set(s.id,new bi(e,s));if("OFF"===t.baseState)for(const t of this.#Cn.values())t._setVisible(fi,!1);for(const e of t.on)this.#Cn.get(e)._setVisible(fi,!0);for(const e of t.off)this.#Cn.get(e)._setVisible(fi,!1);this.#kn=this.getHash()}}#Mn(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const e=t[i];let n;if(Array.isArray(e))n=this.#Mn(e);else{if(!this.#Cn.has(e))return J(`Optional content group not found: ${e}`),!0;n=this.#Cn.get(e).visible}switch(s){case"And":if(!n)return!1;break;case"Or":if(n)return!0;break;case"Not":return!n;default:return!0}}return"And"===s}isVisible(t){if(0===this.#Cn.size)return!0;if(!t)return Q("Optional content group not defined."),!0;if("OCG"===t.type)return this.#Cn.has(t.id)?this.#Cn.get(t.id).visible:(J(`Optional content group not found: ${t.id}`),!0);if("OCMD"===t.type){if(t.expression)return this.#Mn(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#Cn.has(e))return J(`Optional content group not found: ${e}`),!0;if(this.#Cn.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#Cn.has(e))return J(`Optional content group not found: ${e}`),!0;if(!this.#Cn.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#Cn.has(e))return J(`Optional content group not found: ${e}`),!0;if(!this.#Cn.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#Cn.has(e))return J(`Optional content group not found: ${e}`),!0;if(this.#Cn.get(e).visible)return!1}return!0}return J(`Unknown optional content policy ${t.policy}.`),!0}return J(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){const i=this.#Cn.get(t);if(i){if(s&&e&&i.rbGroups.length)for(const e of i.rbGroups)for(const s of e)s!==t&&this.#Cn.get(s)?._setVisible(fi,!1,!0);i._setVisible(fi,!!e,!0),this.#Sn=null}else J(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let s;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const t=this.#Cn.get(i);if(t)switch(s){case"ON":this.setVisibility(i,!0,e);break;case"OFF":this.setVisibility(i,!1,e);break;case"Toggle":this.setVisibility(i,!t.visible,e)}}this.#Sn=null}get hasInitialVisibility(){return null===this.#kn||this.getHash()===this.#kn}getOrder(){return this.#Cn.size?this.#Tn?this.#Tn.slice():[...this.#Cn.keys()]:null}getGroup(t){return this.#Cn.get(t)||null}getHash(){if(null!==this.#Sn)return this.#Sn;const t=new oe;for(const[e,s]of this.#Cn)t.update(`${e}:${s.visible}`);return this.#Sn=t.hexdigest()}[Symbol.iterator](){return this.#Cn.entries()}}class Ai{#En=null;#Pn=null;#Dn=0;#In=null;#Fn=null;get pagesNumber(){return this.#Dn}set pagesNumber(t){this.#Dn!==t&&(this.#Dn=t,this.#En=null,this.#Pn=null)}#Nn(){if(this.#En)return;const t=this.#Dn,e=this.#En=new Uint32Array(t);for(let s=0;s<t;s++)e[s]=s+1;this.#Pn=new Int32Array(e)}#Rn(){const t=new Map,e=this.#En;for(let s=0,i=this.#Dn;s<i;s++){const i=e[s],n=t.get(i);n?n.push(s+1):t.set(i,[s+1])}return t}movePages(t,e,s){this.#Nn();const i=this.#En,n=this.#Rn(),r=e.length,a=new Uint32Array(r);let o=0;for(let d=0;d<r;d++){const t=e[d]-1;a[d]=i[t],t<s&&o++}const h=this.#Dn,l=h-r,c=yt(s-o,0,l);for(let d=0,u=0;d<h;d++)t.has(d+1)||(i[u++]=i[d]);i.copyWithin(c+r,c,l),i.set(a,c),this.#On(n),i.every((t,e)=>t===e+1)&&(this.#En=null)}deletePages(t){this.#Nn();const e=this.#En,s=this.#Rn();this.#Fn={pageNumberToId:e.slice(),pagesNumber:this.#Dn,prevPageNumbers:this.#Pn.slice()};const i=this.#Dn-t.length;this.#Dn=i;const n=this.#En=new Uint32Array(i);this.#Pn=new Int32Array(i);let r=0,a=0;for(const o of t){const t=o-1;t!==r&&(n.set(e.subarray(r,t),a),a+=t-r),r=t+1}r<e.length&&n.set(e.subarray(r),a),this.#On(s,new Set(t))}cancelDelete(){this.#Fn&&(this.#En=this.#Fn.pageNumberToId,this.#Dn=this.#Fn.pagesNumber,this.#Pn=this.#Fn.prevPageNumbers,this.#Fn=null)}cleanSavedData(){this.#Fn=null}copyPages(t){this.#Nn(),this.#In={pageNumbers:t,pageIds:t.map(t=>this.#En[t-1])}}cancelCopy(){this.#In=null}pastePages(t){this.#Nn();const e=this.#En,s=this.#Rn(),{pageNumbers:i,pageIds:n}=this.#In,r=this.#Dn+i.length;this.#Dn=r;const a=this.#En=new Uint32Array(r);this.#Pn=new Int32Array(r),a.set(e.subarray(0,t),0),a.set(n,t),a.set(e.subarray(t),t+i.length),this.#On(s,null,t,i),this.#In=null}#On(t,e=null,s=-1,i=null){const n=this.#Pn,r=this.#En,a=s+(i?.length??0),o=new Map;for(let h=0,l=this.#Dn;h<l;h++){if(h>=s&&h<a){n[h]=-i[h-s];continue}const l=r[h],c=t.get(l);let d=o.get(l)||0;if(e&&c)for(;d<c.length&&e.has(c[d]);)d++;n[h]=c?.[d],o.set(l,d+1)}}hasBeenAltered(){return null!==this.#En}getPageMappingForSaving(t=null){t??=this.#Rn();let e=0;for(const i of t.values())e=Math.max(e,i.length);const s=new Array(e);for(let i=0;i<e;i++)s[i]={document:null,pageIndices:[],includePages:[]};for(const[i,n]of t)for(let t=0,e=n.length;t<e;t++)s[t].includePages.push([i-1,n[t]-1]);for(const{includePages:i,pageIndices:n}of s){i.sort((t,e)=>t[0]-e[0]);for(let t=0,e=i.length;t<e;t++)n.push(i[t][1]),i[t]=i[t][0]}return s}extractPages(t){t=Array.from(t).sort((t,e)=>t-e);const e=new Map;for(let s=0,i=t.length;s<i;s++){const i=this.getPageId(t[s]);e.getOrInsertComputed(i,mt).push(s+1)}return this.getPageMappingForSaving(e)}getPrevPageNumber(t){return this.#Pn?.[t-1]??0}getPageNumber(t){if(!this.#En)return t;const e=this.#En;for(let s=0,i=this.#Dn;s<i;s++)if(e[s]===t)return s+1;return 0}getPageId(t){return this.#En?.[t-1]??t}getMapping(){return this.#En?.subarray(0,this.pagesNumber)}}const wi=Symbol("INITIAL_DATA"),vi=()=>({...Promise.withResolvers(),data:wi});class _i{#Bn=new Map;get(t,e=null){if(e){const s=this.#Bn.getOrInsertComputed(t,vi);return s.promise.then(()=>e(s.data)),null}const s=this.#Bn.get(t);if(!s||s.data===wi)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#Bn.get(t);return!!e&&e.data!==wi}delete(t){const e=this.#Bn.get(t);return!(!e||e.data===wi)&&(this.#Bn.delete(t),!0)}resolve(t,e=null){const s=this.#Bn.getOrInsertComputed(t,vi);if(s.data!==wi)throw new Error(`Object already resolved ${t}.`);s.data=e,s.resolve()}clear(){for(const{data:t}of this.#Bn.values())t?.bitmap?.close();this.#Bn.clear()}*[Symbol.iterator](){for(const[t,{data:e}]of this.#Bn)e!==wi&&(yield[t,e])}}class xi{#Ln=Promise.withResolvers();#Tt=null;#Un=!1;#jn=!!globalThis.FontInspector?.enabled;#Hn=null;#$n=null;#zn=null;#Gn=0;#Wn=0;#Vn=null;#Xn=null;#Yn=0;#qn=0;#Kn=Object.create(null);#Qn=[];#Jn=null;#Zn=[];#tr=new WeakMap;#er=null;static#sr=new Map;static#ir=new Map;static#nr=new WeakMap;static#rr=null;static#ar=new Set;constructor({textContentSource:t,images:e,container:s,viewport:i}){if(t instanceof ReadableStream)this.#Jn=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#Jn=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#Tt=this.#Xn=s,this.#Hn=e,this.#qn=i.scale*Lt.pixelRatio,this.#Yn=i.rotation,this.#zn={div:null,properties:null,ctx:null};const{pageWidth:n,pageHeight:r,pageX:a,pageY:o}=i.rawDims;this.#er=[1,0,0,-1,-a,o+r],this.#Wn=n,this.#Gn=r,xi.#or(),s.style.setProperty("--min-font-size",xi.#rr),Bt(s,i),this.#Ln.promise.finally(()=>{xi.#ar.delete(this),this.#zn=null,this.#Kn=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=ut.platform;return it(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){this.#Hn&&this.#Tt.append(this.#Hn.render());const t=()=>{this.#Vn.read().then(({value:e,done:s})=>{s?this.#Ln.resolve():(this.#$n??=e.lang,Object.assign(this.#Kn,e.styles),this.#hr(e.items),t())},this.#Ln.reject)};return this.#Vn=this.#Jn.getReader(),xi.#ar.add(this),t(),this.#Ln.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*Lt.pixelRatio,i=t.rotation;if(i!==this.#Yn&&(e?.(),this.#Yn=i,Bt(this.#Xn,{rotation:i})),s!==this.#qn){e?.(),this.#qn=s;const t={div:null,properties:null,ctx:xi.#lr(this.#$n)};for(const e of this.#Zn)t.properties=this.#tr.get(e),t.div=e,this.#cr(t)}}cancel(){const t=new ct("TextLayer task cancelled.");this.#Vn?.cancel(t).catch(()=>{}),this.#Vn=null,this.#Ln.reject(t)}get textDivs(){return this.#Zn}get textContentItemsStr(){return this.#Qn}#hr(t){if(this.#Un)return;this.#zn.ctx??=xi.#lr(this.#$n);const e=this.#Zn,s=this.#Qn;for(const i of t){if(e.length>1e5)return J("Ignoring additional textDivs for performance reasons."),void(this.#Un=!0);if(void 0!==i.str)s.push(i.str),this.#dr(i);else if("beginMarkedContentProps"===i.type||"beginMarkedContent"===i.type){const t=this.#Tt;this.#Tt=document.createElement("span"),this.#Tt.classList.add("markedContent"),i.id&&this.#Tt.setAttribute("id",`${i.id}`),"Artifact"===i.tag&&(this.#Tt.ariaHidden=!0),t.append(this.#Tt)}else"endMarkedContent"===i.type&&(this.#Tt=this.#Tt.parentNode)}}#dr(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Zn.push(e);const i=pt.transform(this.#er,t.transform);let n=Math.atan2(i[1],i[0]);const r=this.#Kn[t.fontName];r.vertical&&(n+=Math.PI/2);let a=this.#jn&&r.fontSubstitution||r.fontFamily;a=xi.fontFamilyMap.get(a)||a;const o=Math.hypot(i[2],i[3]),h=o*xi.#ur(a,r,this.#$n);let l,c;0===n?(l=i[4],c=i[5]-h):(l=i[4]+h*Math.sin(n),c=i[5]-h*Math.cos(n));const d=e.style;d.left=`${(100*l/this.#Wn).toFixed(2)}%`,d.top=`${(100*c/this.#Gn).toFixed(2)}%`,d.setProperty("--font-height",`${o.toFixed(2)}px`),d.fontFamily=a,s.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#jn&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),0!==n&&(s.angle=n*(180/Math.PI));let u=!1;if(t.str.length>1)u=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),s=Math.abs(t.transform[3]);e!==s&&Math.max(e,s)/Math.min(e,s)>1.5&&(u=!0)}if(u&&(s.canvasWidth=r.vertical?t.height:t.width),this.#tr.set(e,s),this.#zn.div=e,this.#zn.properties=s,this.#cr(this.#zn),s.hasText&&this.#Tt.append(e),s.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#Tt.append(t)}}#cr(t){const{div:e,properties:s,ctx:i}=t,{style:n}=e;if(0!==s.canvasWidth&&s.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:a}=s;xi.#pr(i,a*this.#qn,t);const{width:o}=i.measureText(e.textContent);o>0&&n.setProperty("--scale-x",r*this.#qn/o)}0!==s.angle&&n.setProperty("--rotate",`${s.angle}deg`)}static cleanup(){if(!(this.#ar.size>0)){this.#sr.clear();for(const{canvas:t}of this.#ir.values())t.remove();this.#ir.clear()}}static#lr(t=null){let e=this.#ir.get(t||="");if(!e){const s=document.createElement("canvas");s.className="hiddenCanvasElement",s.lang=t,document.body.append(s),e=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#ir.set(t,e),this.#nr.set(e,{size:0,family:""})}return e}static#pr(t,e,s){const i=this.#nr.get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)}static#or(){if(null!==this.#rr)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#rr=t.getBoundingClientRect().height,t.remove()}static#ur(t,e,s){const i=this.#sr.get(t);if(i)return i;const n=this.#lr(s);n.canvas.width=n.canvas.height=30,this.#pr(n,30,t);const r=n.measureText(""),a=r.fontBoundingBoxAscent,o=Math.abs(r.fontBoundingBoxDescent);n.canvas.width=n.canvas.height=0;let h=.8;return a?h=a/(a+o):(ut.platform.isFirefox&&J("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),e.ascent?h=e.ascent:e.descent&&(h=1+e.descent)),this.#sr.set(t,h),h}}function Si(t={}){const e=new Ci,{docId:s}=e,i=t.url?function(t){if(t instanceof URL)return t;if("string"==typeof t){if(d){if(/^[a-z][a-z0-9\-+.]+:/i.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}const e=URL.parse(t,window.location);if(e)return e}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,n=t.data?function(t){if(d&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return dt(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,a=!0===t.withCredentials,o=t.password??null,h=t.range instanceof ki?t.range:null,l=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:65536;let c=t.worker instanceof Ei?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||kt(t.docBaseUrl)?null:t.docBaseUrl,g=je(t.cMapUrl),m=!1!==t.cMapPacked,f=je(t.iccUrl),b=je(t.standardFontDataUrl),y=je(t.wasmUrl),A=!0!==t.stopAtErrors,w=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,v="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!d,_="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!d,x=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,S="boolean"==typeof t.disableFontFace?t.disableFontFace:d,C=!0===t.fontExtraProperties,k=!0===t.enableXfa,T=t.ownerDocument||globalThis.document,M=!0===t.disableRange,E=!0===t.disableStream,P=!0===t.disableAutoFetch,D=!0===t.pdfBug,I=t.CanvasFactory||(d?ls:rs),F=t.FilterFactory||(d?hs:os),N=t.BinaryDataFactory||(d?cs:is),R=!0===t.enableHWA,O=!0===t.enableWebGPU?ds.init():Promise.resolve(!1),B=!1!==t.useWasm,L=t.pagesMapper||new Ai,U="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!d&&!S,j="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:!!(N===is&&g&&m&&b&&y&&Et(g,document.baseURI)&&Et(b,document.baseURI)&&Et(y,document.baseURI));q(u);const H={canvasFactory:new I({ownerDocument:T,enableHWA:R}),filterFactory:new F({docId:s,ownerDocument:T}),binaryDataFactory:j?null:new N({cMapUrl:g,standardFontDataUrl:b,wasmUrl:y})};c||(c=Ei.create({verbosity:u,port:gi.workerPort}),e._worker=c);const $={docId:s,apiVersion:"6.0.92",data:n,password:o,disableAutoFetch:P,rangeChunkSize:l,docBaseUrl:p,enableXfa:k,evaluatorOptions:{maxImageSize:w,disableFontFace:S,ignoreErrors:A,isOffscreenCanvasSupported:v,isImageDecoderSupported:_,canvasMaxAreaInBytes:x,fontExtraProperties:C,useSystemFonts:U,useWasm:B,useWorkerFetch:j,cMapUrl:g,cMapPacked:m,iccUrl:f,standardFontDataUrl:b,wasmUrl:y,hasGPU:!1}},z={ownerDocument:T,pdfBug:D,styleElement:null,enableHWA:R,loadingParams:{disableAutoFetch:P,enableXfa:k}};return Promise.all([c.promise,O]).then(function([,t]){if(c.destroyed)throw new Error("Worker was destroyed");$.evaluatorOptions.hasGPU=t;const o=c.messageHandler.sendWithPromise("GetDocRequest",$,n?[n.buffer]:null);let u;if(n);else if(h)u=new ni({pdfDataRangeTransport:h,disableRange:M,disableStream:E});else{if(!i)throw new Error("getDocument - expected either `data`, `range`, or `url` parameter.");{const t=function(t){return Et(t)?Zs:d?di:oi}(i);u=new t({url:i,httpHeaders:r,withCredentials:a,rangeChunkSize:l,disableRange:M,disableStream:E})}}return o.then(t=>{if(c.destroyed)throw new Error("Worker was destroyed");const i=new es(s,t,c.port),n=new Pi(i,e,u,z,H,L);if(e._transport=n,e.destroyed)throw new Error("Loading aborted");i.send("Ready",null)})}).catch(e._capability.reject).finally(e._setupCapability.resolve),e}class Ci{static#_i=0;_capability=Promise.withResolvers();_setupCapability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+Ci.#_i++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0,this._capability.promise.catch(()=>{});try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._setupCapability.promise,await(this._transport?.destroy())}catch(d){throw this._worker?.port&&delete this._worker._pendingDestroy,d}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}}class ki{#Ln=Promise.withResolvers();#gr=null;constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i}onDataRange(t,e){this.#gr({type:"range",begin:t,chunk:e})}onDataProgressiveRead(t){this.#Ln.promise.then(()=>{this.#gr({type:"progressiveRead",chunk:t})})}onDataProgressiveDone(){this.#Ln.promise.then(()=>{this.#gr({type:"progressiveDone"})})}transportReady(t){this.#gr=t,this.#Ln.resolve()}requestDataRange(t,e){Z("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Ti{constructor(t,e){this._pdfInfo=t,this._transport=e}get pagesMapper(){return this._transport.pagesMapper}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return it(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAnnotationsByType(t,e){return this._transport.getAnnotationsByType(t,e)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(t){return this._transport.extractPages(t)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}getRawData(t){return this._transport.getRawData(t)}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class Mi{#mr=!1;#fr=null;constructor(t,e,s,i,n=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=n?new Mt:null,this._pdfBug=n,this.commonObjs=s.commonObjs,this.objs=new _i,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,this.#fr=i,this.imageCoordinates=null}clone(t){const e=new Mi(t,this._pageInfo,this._transport,this.#fr,this._pdfBug);return e.clonedFromIndex=this.clonedFromIndex??this._pageIndex,this._transport.updatePage(e),e}get pageNumber(){return this._pageIndex+1}set pageNumber(t){this._pageIndex=t-1,this._transport.updatePage(this)}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new St({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return it(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:e=t.canvas,viewport:s,intent:i="display",annotationMode:n=S.ENABLE,transform:r=null,background:a=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:l=null,printAnnotationStorage:c=null,isEditing:d=!1,recordImages:u=!1,recordOperations:p=!1,operationsFilter:g=null,renderingBudget:m=null,renderingScheduler:f=null}){this._stats?.time("Overall");const b=this._transport.getRenderingIntent(i,n,c,d),{renderingIntent:A,cacheKey:w}=b;this.#mr=!1,o||=this._transport.getOptionalContentConfig(A);const v=this._intentStates.getOrInsertComputed(w,bt);v.streamReaderCancelTimeout&&(clearTimeout(v.streamReaderCancelTimeout),v.streamReaderCancelTimeout=null);const _=!!(A&y);v.displayReadyCapability||(v.displayReadyCapability=Promise.withResolvers(),v.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(b));const x=!(!this._pdfBug||!globalThis.StepperManager?.enabled),C=!!e&&!this.recordedBBoxes&&(p||x),k=!!e&&!this.imageCoordinates&&u,T=t=>{if(v.renderTasks.delete(P),C){const t=P.gfx?.dependencyTracker.take();t&&(P.stepper?.setOperatorBBoxes(t,P.gfx.dependencyTracker.takeDebugMetadata()),p&&(this.recordedBBoxes=t))}k&&!t&&(this.imageCoordinates=P.gfx?.imagesTracker.take()),_&&(this.#mr=!0),this.#br(),t?(P.capability.reject(t),this._abortOperatorList({intentState:v,reason:t instanceof Error?t:new Error(t)})):P.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))};let M=null,E=null;(C||k)&&(E=new ye(e,v.operatorList.length)),C&&(M=new Ae(E,x));const P=new Ii({callback:T,params:{canvas:e,canvasContext:t,dependencyTracker:M??E,imagesTracker:k?new Me(e):null,viewport:s,transform:r,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:v.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!_,pdfBug:this._pdfBug,pageColors:l,enableHWA:this._transport.enableHWA,operationsFilter:g,renderingBudget:m,renderingScheduler:f});(v.renderTasks||=new Set).add(P);const D=P.task;return Promise.all([v.displayReadyCapability.promise,o]).then(([t,e])=>{if(this.destroyed)T();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&A))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");P.initializeGraphics({transparency:t,optionalContentConfig:e}),P.operatorListChanged()}}).catch(T),D}getOperatorList({intent:t="display",annotationMode:e=S.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){const n=this._transport.getRenderingIntent(t,e,s,i,!0),r=this._intentStates.getOrInsertComputed(n.cacheKey,bt);let a;return r.opListReadCapability||(a=Object.create(null),a.operatorListChanged=function(){r.operatorList.lastChunk&&(r.opListReadCapability.resolve(r.operatorList),r.renderTasks.delete(a))},r.opListReadCapability=Promise.withResolvers(),(r.renderTasks||=new Set).add(a),r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(n)),r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:this.#fr.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}async getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>At.textContent(t));const e=this.streamTextContent(t),s={items:[],styles:Object.create(null),lang:null};for await(const i of e)s.lang??=i.lang,Object.assign(s.styles,i.styles),s.items.push(...i.items);return s}getStructTree(){return this._transport.getStructTree(this._pageIndex)}getGeospatialPDFMetadata(){return this._transport.getGeospatialPDFMetadata(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),this.#mr=!1,Promise.all(t)}cleanup(t=!1){this.#mr=!0;const e=this.#br();return t&&e&&(this._stats&&=new Mt),e}#br(){if(!this.#mr||this.destroyed)return!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#mr=!1,!0}_startRenderPage(t,e){const s=this._intentStates.get(e);s&&(this._stats?.timeEnd("Page Request"),s.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++)e.operatorList.fnArray.push(t.fnArray[s]),e.operatorList.argsArray.push(t.argsArray[s]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const s of e.renderTasks)s.operatorListChanged();t.lastChunk&&this.#br()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:r}=s,a=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageId:this.#fr.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},void 0,r).getReader(),o=this._intentStates.get(e);o.streamReader=a;const h=()=>{a.read().then(({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),h())},t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#br()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}})};h()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!s){if(t.renderTasks.size>0)return;if(e instanceof Ct){let s=100;return e.extraDelay>0&&e.extraDelay<1e3&&(s+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},s))}}if(t.streamReader.cancel(new ct(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[e,s]of this._intentStates)if(s===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class Ei{#Ln=Promise.withResolvers();#yr=null;#fn=null;#Ar=null;static#wr=0;static#vr=!1;static#_r=new WeakMap;static{d&&(this.#vr=!0,gi.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{const s=URL.parse(t);if(!s?.origin||"null"===s.origin)return!1;const i=new URL(e,s);return s.origin===i.origin},this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:s=K()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=s,e){if(Ei.#_r.has(e))throw new Error("Cannot use more than one PDFWorker per port.");Ei.#_r.set(e,this),this.#xr(e)}else this.#Sr()}get promise(){return this.#Ln.promise}#Cr(){this.#Ln.resolve(),this.#yr.send("configure",{verbosity:this.verbosity})}get port(){return this.#fn}get messageHandler(){return this.#yr}#xr(t){this.#fn=t,this.#yr=new es("main","worker",t),this.#yr.on("ready",()=>{}),this.#Cr()}#Sr(){if(Ei.#vr||Ei.#kr)return void this.#Tr();let{workerSrc:t}=Ei;try{Ei._isSameOrigin(window.location,t)||(t=Ei._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new es("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?this.#Ln.reject(new Error("Worker was destroyed")):this.#Tr()},n=new AbortController;e.addEventListener("error",()=>{this.#Ar||i()},{signal:n.signal}),s.on("test",t=>{n.abort(),!this.destroyed&&t?(this.#yr=s,this.#fn=e,this.#Ar=e,this.#Cr()):i()}),s.on("ready",t=>{if(n.abort(),this.destroyed)i();else try{r()}catch{this.#Tr()}});const r=()=>{const t=new Uint8Array;s.send("test",t,[t.buffer])};return void r()}catch{Q("The worker has been disabled.")}this.#Tr()}#Tr(){Ei.#vr||(J("Setting up fake worker."),Ei.#vr=!0),Ei._setupFakeWorkerGlobal.then(t=>{if(this.destroyed)return void this.#Ln.reject(new Error("Worker was destroyed"));const e=new $e;this.#fn=e;const s="fake"+Ei.#wr++,i=new es(s+"_worker",s,e);t.setup(i,e),this.#yr=new es(s,s+"_worker",e),this.#Cr()}).catch(t=>{this.#Ln.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this.#Ar?.terminate(),this.#Ar=null,Ei.#_r.delete(this.#fn),this.#fn=null,this.#yr?.destroy(),this.#yr=null}static create(t){const e=this.#_r.get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new Ei(t)}static get workerSrc(){if(gi.workerSrc)return gi.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#kr(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return it(this,"_setupFakeWorkerGlobal",(async()=>this.#kr?this.#kr:(await(import(
3
3
  /*webpackIgnore: true*/
4
4
  /* @vite-ignore */
5
- this.workerSrc))).WorkerMessageHandler)())}}class Pi{downloadInfoCapability=Promise.withResolvers();#Mr=null;#Er=new Map;#Pr=null;#Dr=new Map;#Ir=new Map;#Fr=new Map;#Nr=null;constructor(t,e,s,i,n,r){this.messageHandler=t,this.loadingTask=e,this.#Pr=s,this.commonObjs=new _i,this.fontLoader=new Ee({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.enableHWA=i.enableHWA,this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.binaryDataFactory=n.binaryDataFactory,this.pagesMapper=r,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler()}updatePage(t){const{_pageIndex:e}=t;this.#Dr.set(e,t),this.#Ir.set(e,Promise.resolve(t))}#Rr(t,e=null){return this.#Er.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,e))}#un({loaded:t,total:e}){this.loadingTask.onProgress?.({loaded:t,total:e,percent:e?yt(Math.round(t/e*100),0,100):NaN})}get annotationStorage(){return it(this,"annotationStorage",new le)}getRenderingIntent(t,e=S.ENABLE,s=null,i=!1,n=!1){let r=b,a=he;switch(t){case"any":r=f;break;case"display":break;case"print":r=y;break;default:J(`getRenderingIntent - invalid intent: ${t}`)}const o=r&y&&s instanceof ce?s:this.annotationStorage;switch(e){case S.DISABLE:r+=v;break;case S.ENABLE:break;case S.ENABLE_FORMS:r+=A;break;case S.ENABLE_STORAGE:r+=w,a=o.serializable;break;default:J(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=_),n&&(r+=x);const{ids:h,hash:l}=o.modifiedIds;return{renderingIntent:r,cacheKey:[r,a.hash,l].join("_"),annotationStorageSerializable:a,modifiedIds:h}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#Nr?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const s of this.#Dr.values())t.push(s._destroy());this.#Dr.clear(),this.#Ir.clear(),this.#Fr.clear(),Object.hasOwn(this,"annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#Er.clear(),this.filterFactory.destroy(),xi.cleanup(),this.#Pr?.cancelAllRequests(new ct("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{tt(this.#Pr,"GetReader - no `BasePDFStream` instance available."),this.#Mr=this.#Pr.getFullReader(),this.#Mr.onProgress=t=>this.#un(t),e.onPull=()=>{this.#Mr.read().then(function({value:t,done:s}){s?e.close():(tt(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{this.#Mr.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}}),t.on("ReaderHeadersReady",async t=>{await this.#Mr.headersReady;const{isStreamingSupported:e,isRangeSupported:s,contentLength:i}=this.#Mr;return e&&s&&(this.#Mr.onProgress=null),{isStreamingSupported:e,isRangeSupported:s,contentLength:i}}),t.on("GetRangeReader",(t,e)=>{tt(this.#Pr,"GetRangeReader - no `BasePDFStream` instance available.");const s=this.#Pr.getRangeReader(t.begin,t.end);s?(e.onPull=()=>{s.read().then(function({value:t,done:s}){s?e.close():(tt(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{s.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}):e.close()}),t.on("GetDoc",({pdfInfo:t})=>{this.pagesMapper.pagesNumber=t.numPages,this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new Ti(t,this))}),t.on("DocException",t=>{e._capability.reject(ts(t))}),t.on("PasswordRequest",t=>{this.#Nr=Promise.withResolvers();try{if(!e.onPassword)throw ts(t);const s=t=>{t instanceof Error?this.#Nr.reject(t):this.#Nr.resolve({password:t})};e.onPassword(s,t.code)}catch(t){this.#Nr.reject(t)}return this.#Nr.promise}),t.on("DataLoaded",t=>{this.#un({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)}),t.on("StartRenderPage",t=>{this.destroyed||this.#Dr.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}),t.on("commonobj",([e,s,i])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(s){case"Font":if("error"in i){const t=i.error;J(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const n=new Be(i),r=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,a=new Pe(n,r,i.charProcOperatorList,i.extra);this.fontLoader.bind(a).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{a.fontExtraProperties||a.clearData(),this.commonObjs.resolve(e,a)});break;case"CopyLocalImage":const{imageRef:o}=i;tt(o,"The imageRef must be defined.");for(const t of this.#Dr.values())for(const[,s]of t.objs){if(s?.ref!==o)continue;if(!s.dataLen)return null;const t=structuredClone(s);return this.commonObjs.resolve(e,t),s.dataLen}break;case"FontPath":this.commonObjs.resolve(e,new Ue(i));break;case"Image":this.commonObjs.resolve(e,i);break;case"Pattern":const h=new Le(i);this.commonObjs.resolve(e,h.getIR());break;default:throw new Error(`Got unknown common object type ${s}`)}return null}),t.on("obj",([t,e,s,i])=>{if(this.destroyed)return;const n=this.#Dr.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(s){case"Image":case"Pattern":n.objs.resolve(t,i);break;default:throw new Error(`Got unknown object type ${s}`)}else i?.bitmap?.close()}),t.on("DocProgress",t=>{this.destroyed||this.#un(t)}),t.on("FetchBinaryData",async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.binaryDataFactory)throw new Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&J("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this.#Mr?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}extractPages(t){const e={pageInfos:t};let s;if(this.annotationStorage.size>0){const t=this.annotationStorage.serializable;let{map:i}=t;s=t.transfer;const n=this.pagesMapper.getMapping();if(n){const t=new Map;for(const[e,s]of i){if(void 0!==s?.pageIndex&&s.pageIndex>=0&&s.pageIndex<n.length){const i=n[s.pageIndex]-1;if(i!==s.pageIndex){t.set(e,{...s,pageIndex:i});continue}}t.set(e,s)}i=t}e.annotationStorage=i}return this.messageHandler.sendWithPromise("ExtractPages",e,s).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this.pagesMapper.pagesNumber)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=this.pagesMapper.getPageId(t)-1,i=this.#Ir.get(e);if(i)return i;const n=this.messageHandler.sendWithPromise("GetPage",{pageIndex:s}).then(t=>{if(this.destroyed)throw new Error("Transport destroyed");t.refStr&&this.#Fr.set(t.refStr,s);const i=new Mi(e,t,this,this.pagesMapper,this._params.pdfBug);return this.#Dr.set(e,i),i});return this.#Ir.set(e,n),n}async getPageIndex(t){if(!He(t))throw new Error("Invalid pageIndex request.");const e=await this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}),s=this.pagesMapper.getPageNumber(e+1);if(0===s)throw new Error("GetPageIndex: page has been removed.");return s-1}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.pagesMapper.getPageId(t+1)-1,intent:e})}getFieldObjects(){return this.#Rr("GetFieldObjects")}hasJSActions(){return this.#Rr("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAnnotationsByType(t,e){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:e})}getDocJSActions(){return this.#Rr("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Rr("GetOptionalContentConfig").then(e=>new yi(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata";return this.#Er.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new mi(t[1]):null,contentDispositionFilename:this.#Mr?.filename??null,contentLength:this.#Mr?.contentLength??null,hasStructTree:t[2]})))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}getRawData(t){return this.messageHandler.sendWithPromise("GetRawData",t)}getGeoPDFMetadata(t){return this.messageHandler.sendWithPromise("GetGeoPDFMetadata",{pageIndex:t})}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#Dr.values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#Er.clear(),this.filterFactory.destroy(!0),xi.cleanup()}}cachedPageNumber(t){if(!He(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`,s=this.#Fr.get(e);if(s>=0){const t=this.pagesMapper.getPageNumber(s+1);if(0!==t)return t}return null}}class Di{_internalRenderTask=null;onContinue=null;onError=null;constructor(t){this._internalRenderTask=t}get promise(){return this._internalRenderTask.capability.promise}cancel(t=0){this._internalRenderTask.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this._internalRenderTask.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this._internalRenderTask;return t.form||t.canvas&&e?.size>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}}class Ii{#Or=null;#Br=null;static#Lr=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:a,canvasFactory:o,filterFactory:h,useRequestAnimationFrame:l=!1,pdfBug:c=!1,pageColors:d=null,enableHWA:u=!1,operationsFilter:p=null,renderingBudget:g=null,renderingScheduler:m=null}){this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=a,this.canvasFactory=o,this.filterFactory=h,this._pdfBug=c,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===l&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new Di(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvas,this._canvasContext=e.canvas?null:e.canvasContext,this._enableHWA=u,this._dependencyTracker=e.dependencyTracker,this._imagesTracker=e.imagesTracker,this._operationsFilter=p,this._renderingBudget=g,this._renderingScheduler=m}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(Ii.#Lr.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");Ii.#Lr.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{viewport:s,transform:i,background:n,dependencyTracker:r,imagesTracker:a}=this.params,o=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new js(o,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,r,a),this.gfx.beginDrawing({transform:i,viewport:s,transparency:t,background:n}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this._cancelScheduledContinue(),Ii.#Lr.delete(this._canvas),t||=new Ct(`Rendering cancelled, page ${this._pageIndex+1}`,e),this.callback(t),this.task.onError?.(t)}_cancelScheduledContinue(){this.#Or&&(window.cancelAnimationFrame(this.#Or),this.#Or=null),this.#Br?.(),this.#Br=null}operatorListChanged(){this.graphicsReady?(this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length),this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){const t=t=>{this.#Or=null,this.#Br=null,this._nextBound(t||null).catch(this._cancelBound)};this._renderingScheduler?.scheduleContinue?this.#Br=this._renderingScheduler.scheduleContinue(t)||null:this._useRequestAnimationFrame?this.#Or=window.requestAnimationFrame(()=>{t(null)}):Promise.resolve().then(()=>t(null)).catch(this._cancelBound)}async _next(t=null){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter,this._renderingBudget,t),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),Ii.#Lr.delete(this._canvas),this.callback())))}}class Fi{#Ur=null;#jr=null;#Hr;#$r=null;#zr=!1;#Gr=!1;#a=null;#Wr;#Vr=null;#y=null;static#Xr=null;static get _keyboardManager(){return it(this,"_keyboardManager",new Kt([[["Escape","mac+Escape"],Fi.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],Fi.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],Fi.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],Fi.prototype._moveToPrevious],[["Home","mac+Home"],Fi.prototype._moveToBeginning],[["End","mac+End"],Fi.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#Gr=!1,this.#a=t):this.#Gr=!0,this.#y=t?._uiManager||e,this.#Wr=this.#y._eventBus,this.#Hr=t?.color?.toUpperCase()||this.#y?.highlightColors.values().next().value||"#FFFF98",Fi.#Xr||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#Ur=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.ariaHasPopup="true",this.#a&&(t.ariaControls=`${this.#a.id}_colorpicker_dropdown`);const e=this.#y._signal;t.addEventListener("click",this.#Yr.bind(this),{signal:e}),t.addEventListener("keydown",this.#qr.bind(this),{signal:e});const s=this.#jr=document.createElement("span");return s.className="swatch",s.ariaHidden="true",s.style.backgroundColor=this.#Hr,t.append(s),t}renderMainDropdown(){const t=this.#$r=this.#Kr();return t.ariaOrientation="horizontal",t.ariaLabelledBy="highlightColorPickerLabel",t}#Kr(){const t=document.createElement("div"),e=this.#y._signal;t.addEventListener("contextmenu",Pt,{signal:e}),t.className="dropdown",t.role="listbox",t.ariaMultiSelectable="false",t.ariaOrientation="vertical",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),this.#a&&(t.id=`${this.#a.id}_colorpicker_dropdown`);for(const[s,i]of this.#y.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",Fi.#Xr[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.ariaSelected=i===this.#Hr,n.addEventListener("click",this.#Qr.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#qr.bind(this),{signal:e}),t}#Qr(t,e){e.stopPropagation(),this.#Wr.dispatch("switchannotationeditorparams",{source:this,type:M.HIGHLIGHT_COLOR,value:t}),this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#Ur)return void this.#Yr(t);const e=t.target.getAttribute("data-color");e&&this.#Qr(e,t)}_moveToNext(t){this.#Jr?t.target!==this.#Ur?t.target.nextSibling?.focus():this.#$r.firstElementChild?.focus():this.#Yr(t)}_moveToPrevious(t){t.target!==this.#$r?.firstElementChild&&t.target!==this.#Ur?(this.#Jr||this.#Yr(t),t.target.previousSibling?.focus()):this.#Jr&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Jr?this.#$r.firstElementChild?.focus():this.#Yr(t)}_moveToEnd(t){this.#Jr?this.#$r.lastElementChild?.focus():this.#Yr(t)}#qr(t){Fi._keyboardManager.exec(this,t)}#Yr(t){if(this.#Jr)return void this.hideDropdown();if(this.#zr=0===t.detail,this.#Vr||(this.#Vr=new AbortController,window.addEventListener("pointerdown",this.#p.bind(this),{signal:this.#y.combinedSignal(this.#Vr)})),this.#Ur.ariaExpanded="true",this.#$r)return void this.#$r.classList.remove("hidden");const e=this.#$r=this.#Kr();this.#Ur.append(e)}#p(t){this.#$r?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#$r?.classList.add("hidden"),this.#Ur.ariaExpanded="false",this.#Vr?.abort(),this.#Vr=null}get#Jr(){return this.#$r&&!this.#$r.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#Gr||(this.#Jr?(this.hideDropdown(),this.#Ur.focus({preventScroll:!0,focusVisible:this.#zr})):this.#a?.unselect())}updateColor(t){if(this.#jr&&(this.#jr.style.backgroundColor=t),!this.#$r)return;const e=this.#y.highlightColors.values();for(const s of this.#$r.children)s.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#Ur?.remove(),this.#Ur=null,this.#jr=null,this.#$r?.remove(),this.#$r=null}}class Ni{#Zr=null;#ta=!1;#a=null;#y=null;static#Xr=null;constructor(t){this.#a=t,this.#y=t._uiManager,Ni.#Xr||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#Zr)return this.#Zr;const{editorType:t,colorType:e,colorAndOpacityType:s,opacityType:i,color:n,opacity:r}=this.#a,a=this.#ta=ut.isAlphaColorInputSupported&&void 0!==i,o=this.#Zr=document.createElement("input");if(o.type="color",a){o.setAttribute("alpha","");const t=pt.hexNums[Math.round(255*(r??1))];o.value=(n||"#000000")+t}else o.value=n||"#000000";return o.className="basicColorPicker",o.tabIndex=0,o.setAttribute("data-l10n-id",Ni.#Xr[t]),o.addEventListener("input",()=>{if(a){const t=Ft(o.value);if(!t)return;const[n,r,a,h]=t,l=pt.makeHexColor(n,r,a);void 0!==s?this.#y.updateParams(s,{color:l,opacity:h}):(this.#y.updateParams(e,l),this.#y.updateParams(i,h))}else this.#y.updateParams(e,o.value)},{signal:this.#y._signal}),o}update(t){if(this.#Zr)if(this.#ta){const e=pt.hexNums[Math.round(255*this.#a.opacity)];this.#Zr.value=t+e}else this.#Zr.value=t}updateOpacity(t){if(!this.#Zr||!this.#ta)return;const e=pt.hexNums[Math.round(255*t)];this.#Zr.value=this.#a.color+e}destroy(){this.#Zr?.remove(),this.#Zr=null}hideDropdown(){}}function Ri(t){return Math.floor(255*yt(t,0,1)).toString(16).padStart(2,"0")}function Oi(t){return 255*yt(t,0,1)}class Bi{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=Oi(t),t,t]}static G_HTML([t]){const e=Ri(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(Oi)}static RGB_HTML(t){return`#${t.map(Ri).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[Oi(1-Math.min(1,t+i)),Oi(1-Math.min(1,s+i)),Oi(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t,n=1-e,r=1-s;return["CMYK",i,n,r,Math.min(i,n,r)]}}const Li=new WeakSet;(new Date).getTimezoneOffset();class Ui{#ea=null;#sa=!1;#ia=null;constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableComment=t.enableComment,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,this.hasOwnCommentButton=!1,e&&(this.contentElement=this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:t,richText:e}){return!(!t?.str&&!e?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Ui._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){const{data:t}=this,e=this.annotationStorage?.getEditor(t.id);return e?e.getData():t}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){const t=this.annotationStorage?.getEditor(this.data.id);if(t)return t.commentButtonPositionInPage;const{quadPoints:e,inkLists:s,rect:i}=this.data;let n=-1/0,r=-1/0;if(e?.length>=8){for(let t=0;t<e.length;t+=8)e[t+1]>r?(r=e[t+1],n=e[t+2]):e[t+1]===r&&(n=Math.max(n,e[t+2]));return[n,r]}if(s?.length>=1){for(const t of s)for(let e=0,s=t.length;e<s;e+=2)t[e+1]>r?(r=t[e+1],n=t[e]):t[e+1]===r&&(n=Math.max(n,t[e]));if(n!==1/0)return[n,r]}return i?[i[2],i[3]]:null}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}}=this.parent;return t[1]=e[3]-t[1]+e[1],t[0]=100*(t[0]-n)/s,t[1]=100*(t[1]-r)/i,t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${k}${t.id}`)?.popup?.contents||t.contentsObj?.str||""}set commentText(t){const{data:e}=this,s={deleted:!t,contents:t||""};this.annotationStorage.updateEditor(e.id,{popup:s})||this.annotationStorage.setValue(`${k}${e.id}`,{id:e.id,annotationType:e.annotationType,page:this.parent.page,popup:s,popupRef:e.popupRef,modificationDate:new Date}),t||this.removePopup()}removePopup(){(this.#ia?.popup||this.popup)?.remove(),this.#ia=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#ea||={rect:this.data.rect.slice(0)});const{rect:e,popup:s}=t;e&&this.#na(e);let i=this.#ia?.popup||this.popup;!i&&s?.text&&(this._createPopup(s),i=this.#ia.popup),i&&(i.updateEdited(t),s?.deleted&&(i.remove(),this.#ia=null,this.popup=null))}resetEdited(){this.#ea&&(this.#na(this.#ea.rect),this.#ia?.popup.resetEdited(),this.#ea=null)}#na(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:a,pageY:o}}}}=this;s?.splice(0,4,...t),e.left=100*(t[0]-a)/n+"%",e.top=100*(r-t[3]+o)/r+"%",0===i?(e.width=100*(t[2]-t[0])/n+"%",e.height=100*(t[3]-t[1])/r+"%"):this.setRotation(i)}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Hi||this instanceof ji||(n.tabIndex=0);const{style:r}=n;if(r.zIndex=this.parent.zIndex,this.parent.zIndex+=2,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof zi){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,n),n}const{width:a,height:o}=this;if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,s=e.borderStyle.verticalCornerRadius;if(t>0||s>0){const e=`calc(${t}px * var(--total-scale-factor)) / calc(${s}px * var(--total-scale-factor))`;r.borderRadius=e}else if(this instanceof $i){const t=`calc(${a}px * var(--total-scale-factor)) / calc(${o}px * var(--total-scale-factor))`;r.borderRadius=t}switch(e.borderStyle.style){case O:r.borderStyle="solid";break;case B:r.borderStyle="dashed";break;case L:J("Unimplemented border style: beveled");break;case U:J("Unimplemented border style: inset");break;case j:r.borderBottomStyle="solid"}const i=e.borderColor||null;i?(this.#sa=!0,r.borderColor=pt.makeHexColor(...i)):r.borderWidth=0}const h=pt.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]),{pageWidth:l,pageHeight:c,pageX:d,pageY:u}=i.rawDims;r.left=100*(h[0]-d)/l+"%",r.top=100*(h[1]-u)/c+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(r.width=100*a/l+"%",r.height=100*o/c+"%"):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims;let{width:n,height:r}=this;t%180!=0&&([n,r]=[r,n]),e.style.width=100*n/s+"%",e.style.height=100*r/i+"%",e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,s)=>{const i=s.detail[t],n=i[0],r=i.slice(1);s.target.style[e]=Bi[`${n}_HTML`](r),this.annotationStorage.setValue(this.data.id,{[e]:Bi[`${n}_rgb`](r)})};return it(this,"_commonActions",{display:t=>{const{display:e}=t.detail,s=e%2==1;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:s,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail)){const n=t[i]||s[i];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const r=s[i];r&&(r({detail:{[i]:n},target:t}),delete e[i])}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map(t=>Math.fround(t));if(8===t.length){const[r,a,o,h]=t.subarray(2,6);if(i===r&&n===a&&e===o&&s===h)return}const{style:r}=this.container;let a;if(this.#sa){const{borderColor:t,borderWidth:e}=r;r.borderWidth=0,a=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${t}" stroke-width="${e}">`],this.container.classList.add("hasBorder")}const o=i-e,h=n-s,{svgFactory:l}=this,c=l.createElement("svg");c.classList.add("quadrilateralsContainer"),c.setAttribute("width",0),c.setAttribute("height",0),c.role="none";const d=l.createElement("defs");c.append(d);const u=l.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),d.append(u);for(let g=2,m=t.length;g<m;g+=8){const s=t[g],i=t[g+1],r=t[g+2],c=t[g+3],d=l.createElement("rect"),p=(r-e)/o,m=(n-i)/h,f=(s-r)/o,b=(i-c)/h;d.setAttribute("x",p),d.setAttribute("y",m),d.setAttribute("width",f),d.setAttribute("height",b),u.append(d),a?.push(`<rect vector-effect="non-scaling-stroke" x="${p}" y="${m}" width="${f}" height="${b}"/>`)}this.#sa&&(a.push("</g></svg>')"),r.backgroundImage=a.join("")),this.container.append(c),this.container.style.clipPath=`url(#${p})`}_createPopup(t=null){const{data:e}=this;let s,i;t?(s={str:t.text},i=t.date):(s=e.contentsObj,i=e.modificationDate),this.#ia=new zi({data:{color:e.color,titleObj:e.titleObj,modificationDate:i,contentsObj:s,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#ia||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#ia}render(){Z("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:t,id:n,exportValues:r}of i){if(-1===t)continue;if(n===e)continue;const i="string"==typeof r?r:null,a=document.querySelector(`[data-element-id="${n}"]`);!a||Li.has(a)?s.push({id:n,exportValue:i,domElement:a}):J(`_getElementsByName - element not allowed: ${n}`)}return s}for(const i of document.getElementsByName(t)){const{exportValue:t}=i,n=i.getAttribute("data-element-id");n!==e&&Li.has(i)&&s.push({id:n,exportValue:t,domElement:i})}return s}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e,mustEnterInEditMode:!0})})}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class ji extends Ui{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,s=document.createElement("a");s.setAttribute("data-element-id",t.id);let i=!1;return t.url?(e.addLinkAttributes(s,t.url,t.newWindow),i=!0):t.action?(this._bindNamedAction(s,t.action,t.overlaidText),i=!0):t.attachment?(this.#ra(s,t.attachment,t.overlaidText,t.attachmentDest),i=!0):t.setOCGState?(this.#aa(s,t.setOCGState,t.overlaidText),i=!0):t.dest?(this._bindLink(s,t.dest,t.overlaidText),i=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(s,t),i=!0),t.resetForm?(this._bindResetFormAction(s,t.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(s,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&(this.contentElement=s,this.container.append(s)),this.container}#oa(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e,s=""){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||""===e)&&this.#oa(),s&&(t.title=s)}_bindNamedAction(t,e,s=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),s&&(t.title=s),this.#oa()}#ra(t,e,s="",i=null){t.href=this.linkService.getAnchorUrl(""),e.description?t.title=e.description:s&&(t.title=s),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,i),!1),this.#oa()}#aa(t,e,s=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),s&&(t.title=s),this.#oa()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(e.actions)){const n=s.get(i);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:i}}),!1))}e.overlaidText&&(t.title=e.overlaidText),t.onclick||(t.onclick=()=>!1),this.#oa()}_bindResetFormAction(t,e){const s=t.onclick;s||(t.href=this.linkService.getAnchorUrl("")),this.#oa(),this._fieldObjects?t.onclick=()=>{s?.();const{fields:t,refs:i,include:n}=e,r=[];if(0!==t.length||0!==i.length){const e=new Set(i);for(const s of t){const t=this._fieldObjects[s]||[];for(const{id:s}of t)e.add(s)}for(const t of Object.values(this._fieldObjects))for(const s of t)e.has(s.id)===n&&r.push(s)}else for(const e of Object.values(this._fieldObjects))r.push(...e);const a=this.annotationStorage,o=[];for(const e of r){const{id:t}=e;switch(o.push(t),e.type){case"text":{const s=e.defaultValue||"";a.setValue(t,{value:s});break}case"checkbox":case"radiobutton":{const s=e.defaultValue===e.exportValues;a.setValue(t,{value:s});break}case"combobox":case"listbox":{const s=e.defaultValue||"";a.setValue(t,{value:s});break}default:continue}const s=document.querySelector(`[data-element-id="${t}"]`);s&&(Li.has(s)?s.dispatchEvent(new Event("resetform")):J(`_bindResetFormAction - element not allowed: ${t}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}:(J('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),s||(t.onclick=()=>!1))}}class Hi extends Ui{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return ut.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})}):t.addEventListener(s,t=>{if("blur"===s){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===s){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(t)}})})}_setEventListeners(t,e,s,i){for(const[n,r]of s)("Action"===r||this.data.actions?.[r])&&("Focus"!==r&&"Blur"!==r||(e||={focused:!1}),this._setEventListener(t,e,n,r,i),"Focus"!==r||this.data.actions?.Blur?"Blur"!==r||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":pt.makeHexColor(...e)}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||9,n=t.style;let r;const a=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(m*i))||1);r=Math.min(i,a(e/m))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(i,a(t/m))}n.fontSize=`calc(${r}px * var(--total-scale-factor))`,n.color=pt.makeHexColor(...s),null!==this.data.textAlignment&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class $i extends Hi{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof i&&(i=i!==e.buttonValue,t.setValue(s,{value:i})),i)for(const r of this._getElementsByName(e.fieldName,s))t.setValue(r.id,{value:!1});const n=document.createElement("input");if(Li.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.tabIndex=0,n.addEventListener("change",e=>{const{name:i,checked:n}=e.target;for(const r of this._getElementsByName(i,s))t.setValue(r.id,{value:!1});t.setValue(s,{value:n})}),n.addEventListener("resetform",t=>{const s=e.defaultFieldValue;t.target.checked=null!=s&&s===e.buttonValue}),this.enableScripting&&this.hasJSActions){const i=e.buttonValue;n.addEventListener("updatefromsandbox",e=>{const n={value:e=>{const n=i===e.detail.value;for(const i of this._getElementsByName(e.target.name)){const e=n&&i.id===s;i.domElement&&(i.domElement.checked=e),t.setValue(i.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class zi extends Ui{constructor(t){const{data:e,elements:s,parent:i}=t,n=!!i._commentManager;if(super(t,{isRenderable:!n&&Ui._hasPopupData(e)}),this.elements=s,n&&Ui._hasPopupData(e)){const t=this.popup=this.#ha();for(const e of s)e.popup=t}else this.popup=null}#ha(){return new Gi({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})}render(){const{container:t}=this;t.classList.add("popupAnnotation"),t.role="comment";const e=this.popup=this.#ha(),s=[];for(const i of this.elements)i.popup=e,i.container.ariaHasPopup="dialog",s.push(i.data.id),i.addHighlightArea();return this.container.setAttribute("aria-controls",s.map(t=>`${C}${t}`).join(",")),this.container}}class Gi{#W=null;#la=this.#qr.bind(this);#ca=this.#da.bind(this);#ua=this.#pa.bind(this);#ga=this.#ma.bind(this);#fa=null;#Tt=null;#ba=null;#ya=null;#Aa=null;#wa=null;#va=null;#_a=!1;#xa=null;#Sa=null;#F=null;#Ca=null;#ka=null;#we=null;#Ta=null;#fe=null;#Ma=null;#ea=null;#Ea=!1;#Pa=null;#Da=null;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:r,richText:a,parent:o,rect:h,parentRect:l,open:c,commentManager:d=null}){this.#Tt=t,this.#Ma=i,this.#ba=r,this.#fe=a,this.#wa=o,this.#fa=e,this.#Ta=h,this.#va=l,this.#Aa=s,this.#W=d,this.#Pa=s[0],this.#ya=It.toDateObject(n),this.trigger=s.flatMap(t=>t.getElementsToTriggerPopup()),d||(this.#Ia(),this.#Tt.hidden=!0,c&&this.#ma())}#Ia(){if(this.#Sa)return;this.#Sa=new AbortController;const{signal:t}=this.#Sa;for(const e of this.trigger)e.addEventListener("click",this.#ga,{signal:t}),e.addEventListener("pointerenter",this.#ua,{signal:t}),e.addEventListener("pointerleave",this.#ca,{signal:t}),e.classList.add("popupTriggerArea");for(const e of this.#Aa)e.container?.addEventListener("keydown",this.#la,{signal:t})}#Fa(){const t=this.#Aa.find(t=>t.hasCommentButton);t&&(this.#ka=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#Ca)return void(this.#Ca.parentNode||this.#Pa.container.after(this.#Ca));if(this.#ka||this.#Fa(),!this.#ka)return;const{signal:t}=this.#Sa=new AbortController,e=this.#Pa.hasOwnCommentButton,s=()=>{this.#W.toggleCommentPopup(this,!0,void 0,!e)},i=()=>{this.#W.toggleCommentPopup(this,!1,!0,!e)},n=()=>{this.#W.toggleCommentPopup(this,!1,!1)};if(e){this.#Ca=this.#Pa.container;for(const e of this.trigger)e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.addEventListener("keydown",this.#la,{signal:t}),e.addEventListener("click",s,{signal:t}),e.addEventListener("pointerenter",i,{signal:t}),e.addEventListener("pointerleave",n,{signal:t}),e.classList.add("popupTriggerArea")}else{const e=this.#Ca=document.createElement("button");e.className="annotationCommentButton";const r=this.#Pa.container;e.style.zIndex=parseInt(r.style.zIndex,10)+1,e.tabIndex=0,e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.setAttribute("data-l10n-id","pdfjs-show-comment-button"),this.#Na(),this.#Ra(),e.addEventListener("keydown",this.#la,{signal:t}),e.addEventListener("click",s,{signal:t}),e.addEventListener("pointerenter",i,{signal:t}),e.addEventListener("pointerleave",n,{signal:t}),r.after(e)}}#Ra(){if(this.#Pa.extraPopupElement&&!this.#Pa.editor)return;this.#Ca||this.renderCommentButton();const[t,e]=this.#ka,{style:s}=this.#Ca;s.left=`calc(${t}%)`,s.top=`calc(${e}% - var(--comment-button-dim))`}#Na(){this.#Pa.extraPopupElement||(this.#Ca||this.renderCommentButton(),this.#Ca.style.backgroundColor=this.commentButtonColor||"")}get commentButtonColor(){const{color:t,opacity:e}=this.#Pa.commentData;return t?this.#wa._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#Ca?.focus()},0)}getData(){const{richText:t,color:e,opacity:s,creationDate:i,modificationDate:n}=this.#Pa.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:s,creationDate:i,modificationDate:n}}get elementBeforePopup(){return this.#Ca}get comment(){return this.#Da||=this.#Pa.commentText,this.#Da}set comment(t){t!==this.comment&&(this.#Pa.commentText=this.#Da=t)}focus(){this.#Pa.container?.focus()}get parentBoundingClientRect(){return this.#Pa.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){this.#Ca&&(this.#Ca.classList.toggle("selected",t),this.#Ca.ariaExpanded=e)}setSelectedCommentButton(t){this.#Ca.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#we)return this.#we;const{x:t,y:e,height:s}=this.#Ca.getBoundingClientRect(),{x:i,y:n,width:r,height:a}=this.#Pa.layer.getBoundingClientRect();return[(t-i)/r,(e+s-n)/a]}set commentPopupPosition(t){this.#we=t}hasDefaultPopupPosition(){return null===this.#we}get commentButtonPosition(){return this.#ka}get commentButtonWidth(){return this.#Ca.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[e,s]=this.#we||this.commentButtonPosition.map(t=>t/100),i=this.parentBoundingClientRect,{x:n,y:r,width:a,height:o}=i;this.#W.showDialog(null,this,n+e*a,r+s*o,{...t,parentDimensions:i})}render(){if(this.#xa)return;const t=this.#xa=document.createElement("div");if(t.className="popup",this.#fa){const e=t.style.outlineColor=pt.makeHexColor(...this.#fa);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");if(e.className="header",this.#Ma?.str){const t=document.createElement("span");t.className="title",e.append(t),({dir:t.dir,str:t.textContent}=this.#Ma)}if(t.append(e),this.#ya){const t=document.createElement("time");t.className="popupDate",t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#ya.valueOf()})),t.dateTime=this.#ya.toISOString(),e.append(t)}Ht({html:this.#Oa||this.#ba.str,dir:this.#ba?.dir,className:"popupContent"},t),this.#Tt.append(t)}get#Oa(){const t=this.#fe,e=this.#ba;return!t?.str||e?.str&&e.str!==t.str?null:this.#fe.html||null}get#Ba(){return this.#Oa?.attributes?.style?.fontSize||0}get#La(){return this.#Oa?.attributes?.style?.color||null}#Ua(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:this.#La,fontSize:this.#Ba?`calc(${this.#Ba}px * var(--total-scale-factor))`:""}};for(const n of t.split("\n"))e.push({name:"span",value:n,attributes:i});return s}#qr(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#_a)&&this.#ma()}updateEdited({rect:t,popup:e,deleted:s}){this.#W?(s?(this.remove(),this.#Da=null):e&&(e.deleted?this.remove():(this.#Na(),this.#Da=e.text)),t&&(this.#ka=null,this.#Fa(),this.#Ra())):s||e?.deleted?this.remove():(this.#Ia(),this.#ea||={contentsObj:this.#ba,richText:this.#fe},t&&(this.#F=null),e&&e.text&&(this.#fe=this.#Ua(e.text),this.#ya=It.toDateObject(e.date),this.#ba=null),this.#xa?.remove(),this.#xa=null)}resetEdited(){this.#ea&&(({contentsObj:this.#ba,richText:this.#fe}=this.#ea),this.#ea=null,this.#xa?.remove(),this.#xa=null,this.#F=null)}remove(){if(this.#Sa?.abort(),this.#Sa=null,this.#xa?.remove(),this.#xa=null,this.#Ea=!1,this.#_a=!1,this.#Ca?.remove(),this.#Ca=null,this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#ja(){if(null!==this.#F)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#wa;let r=!!this.#va,a=r?this.#va:this.#Ta;for(const u of this.#Aa)if(!a||null!==pt.intersect(u.data.rect,a)){a=u.data.rect,r=!0;break}const o=pt.normalizeRect([a[0],t[3]-a[1]+t[1],a[2],t[3]-a[3]+t[1]]),h=r?a[2]-a[0]+5:0,l=o[0]+h,c=o[1];this.#F=[100*(l-i)/e,100*(c-n)/s];const{style:d}=this.#Tt;d.left=`${this.#F[0]}%`,d.top=`${this.#F[1]}%`}#ma(){this.#W?this.#W.toggleCommentPopup(this,!1):(this.#_a=!this.#_a,this.#_a?(this.#pa(),this.#Tt.addEventListener("click",this.#ga),this.#Tt.addEventListener("keydown",this.#la)):(this.#da(),this.#Tt.removeEventListener("click",this.#ga),this.#Tt.removeEventListener("keydown",this.#la)))}#pa(){this.#xa||this.render(),this.isVisible?this.#_a&&this.#Tt.classList.add("focused"):(this.#ja(),this.#Tt.hidden=!1,this.#Tt.style.zIndex=parseInt(this.#Tt.style.zIndex,10)+1e3)}#da(){this.#Tt.classList.remove("focused"),!this.#_a&&this.isVisible&&(this.#Tt.hidden=!0,this.#Tt.style.zIndex=parseInt(this.#Tt.style.zIndex,10)-1e3)}forceHide(){this.#Ea=this.isVisible,this.#Ea&&(this.#Tt.hidden=!0)}maybeShow(){this.#W||(this.#Ia(),this.#Ea&&(this.#xa||this.#pa(),this.#Ea=!1,this.#Tt.hidden=!1))}get isVisible(){return!this.#W&&!1===this.#Tt.hidden}}class Wi extends Ui{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=T.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=this.contentElement=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const s=document.createElement("span");s.textContent=e,t.append(s)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}class Vi extends Ui{#Ha=null;#$a=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType="InkHighlight"===this.data.it?T.HIGHLIGHT:T.INK}#za(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:s,borderStyle:i,popupRef:n}}=this,{transform:r,width:a,height:o}=this.#za(e,t),h=this.svgFactory.create(a,o,!0),l=this.#Ha=this.svgFactory.createElement("svg:g");h.append(l),l.setAttribute("stroke-width",i.width||1),l.setAttribute("stroke-linecap","round"),l.setAttribute("stroke-linejoin","round"),l.setAttribute("stroke-miterlimit",10),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),l.setAttribute("transform",r);for(let c=0,d=s.length;c<d;c++){const t=this.svgFactory.createElement(this.svgElementName);this.#$a.push(t),t.setAttribute("points",s[c].join(",")),l.append(t)}return!n&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(h),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:s,rect:i}=t,n=this.#Ha;if(e>=0&&n.setAttribute("stroke-width",e||1),s)for(let r=0,a=this.#$a.length;r<a;r++)this.#$a[r].setAttribute("points",s[r].join(","));if(i){const{transform:t,width:e,height:s}=this.#za(this.data.rotation,i);n.parentElement.setAttribute("viewBox",`0 0 ${e} ${s}`),n.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#$a}addHighlightArea(){this.container.classList.add("highlightArea")}}class Xi extends Ui{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=T.HIGHLIGHT}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),t){const e=document.createElement("mark");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class Yi extends Ui{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=T.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}const qi=/\r\n?|\n/g;class Ki extends se{#Ga="";#Wa=`${this.id}-editor`;#Va=null;#Ba;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=Ki.prototype,e=t=>t.isEmpty(),s=Jt.TRANSLATE_SMALL,i=Jt.TRANSLATE_BIG;return it(this,"_keyboardManager",new Kt([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}]]))}static _type="freetext";static _editorType=T.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.color=t.color||Ki._defaultColor||se._defaultLineColor,this.#Ba=t.fontSize||Ki._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert(se._l10nAlert.freetext),this.canAddComment=!1}static initialize(t,e){se.initialize(t,e);const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case M.FREETEXT_SIZE:Ki._defaultFontSize=e;break;case M.FREETEXT_COLOR:Ki._defaultColor=e}}updateParams(t,e){switch(t){case M.FREETEXT_SIZE:this.#Xa(e);break;case M.FREETEXT_COLOR:this.#Na(e)}}static get defaultPropertiesToUpdate(){return[[M.FREETEXT_SIZE,Ki._defaultFontSize],[M.FREETEXT_COLOR,Ki._defaultColor||se._defaultLineColor]]}get propertiesToUpdate(){return[[M.FREETEXT_SIZE,this.#Ba],[M.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new Ni(this),[["colorPicker",this._colorPicker]]}get colorType(){return M.FREETEXT_COLOR}#Xa(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`,this.translate(0,-(t-this.#Ba)*this.parentScale),this.#Ba=t,this.#Ya()},s=this.#Ba;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:M.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#Na(t){const e=t=>{this.color=t,this.onUpdatedColor()},s=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:M.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-Ki._internalPadding*t,-(Ki._internalPadding+this.#Ba)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#Va=new AbortController;const t=this._uiManager.combinedSignal(this.#Va);return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){return!!super.disableEditMode()&&(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#Wa),this._isDraggable=!0,this.#Va?.abort(),this.#Va=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0)}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#qa(){const t=[];this.editorDiv.normalize();let e=null;for(const s of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&"BR"===s.nodeName||(t.push(Ki.#Ka(s)),e=s);return t.join("\n")}#Ya(){const[t,e]=this.parentDimensions;let s;if(this.isAttachedToDOM)s=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,i=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),s=e.getBoundingClientRect(),e.remove(),e.style.display=i,e.classList.toggle("hidden",n)}this.rotation%180==this.parentRotation%180?(this.width=s.width/t,this.height=s.height/e):(this.width=s.height/t,this.height=s.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#Ga,e=this.#Ga=this.#qa().trimEnd();if(t===e)return;const s=t=>{this.#Ga=t,t?(this.#Qa(),this._uiManager.rebuild(this),this.#Ya()):this.remove()};this.addCommands({cmd:()=>{s(e)},undo:()=>{s(t)},mustExec:!1}),this.#Ya()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){Ki._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;(this._isCopy||this.annotationElementId)&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#Wa),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:s}=this.editorDiv;if(s.fontSize=`calc(${this.#Ba}px * var(--total-scale-factor))`,s.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){const[s,i]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[r,a]=this.getInitialTranslation();[r,a]=this.pageTranslationToScreen(r,a);const[o,h]=this.pageDimensions,[l,c]=this.pageTranslation;let d,u;switch(this.rotation){case 0:d=t+(n[0]-l)/o,u=e+this.height-(n[1]-c)/h;break;case 90:d=t+(n[0]-l)/o,u=e-(n[1]-c)/h,[r,a]=[a,-r];break;case 180:d=t-this.width+(n[0]-l)/o,u=e-(n[1]-c)/h,[r,a]=[-r,-a];break;case 270:d=t+(n[0]-l-this.height*h)/o,u=e+(n[1]-c-this.width*o)/h,[r,a]=[-a,r]}this.setAt(d*s,u*i,r,a)}else this._moveAfterPaste(t,e);this.#Qa(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#Ka(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(qi,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:s}=e;if(1===s.length&&"text/plain"===s[0])return;t.preventDefault();const i=Ki.#Ja(e.getData("text")||"").replaceAll(qi,"\n");if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const r=n.getRangeAt(0);if(!i.includes("\n"))return r.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),void n.collapseToStart();const{startContainer:a,startOffset:o}=r,h=[],l=[];if(a.nodeType===Node.TEXT_NODE){const t=a.parentElement;if(l.push(a.nodeValue.slice(o).replaceAll(qi,"")),t!==this.editorDiv){let e=h;for(const s of this.editorDiv.childNodes)s!==t?e.push(Ki.#Ka(s)):e=l}h.push(a.nodeValue.slice(0,o).replaceAll(qi,""))}else if(a===this.editorDiv){let t=h,e=0;for(const s of this.editorDiv.childNodes)e++===o&&(t=l),t.push(Ki.#Ka(s))}this.#Ga=`${h.join("\n")}${i}${l.join("\n")}`,this.#Qa();const c=new Range;let d=Math.sumPrecise(h.map(t=>t.length));for(const{firstChild:u}of this.editorDiv.childNodes)if(u.nodeType===Node.TEXT_NODE){const t=u.nodeValue.length;if(d<=t){c.setStart(u,d),c.setEnd(u,d);break}d-=t}n.removeAllRanges(),n.addRange(c)}#Qa(){if(this.editorDiv.replaceChildren(),this.#Ga)for(const t of this.#Ga.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#Za(){return this.#Ga.replaceAll(" "," ")}static#Ja(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){const t=Ki._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,e,s){let i=null;if(t instanceof Wi){const{data:{defaultAppearanceData:{fontSize:e,fontColor:s},rect:n,rotation:r,id:a,popupRef:o,richText:h,contentsObj:l,creationDate:c,modificationDate:d},textContent:u,textPosition:p,parent:{page:{pageNumber:g}}}=t;if(!u||0===u.length)return null;i=t={annotationType:T.FREETEXT,color:Array.from(s),fontSize:e,value:u.join("\n"),position:p,pageIndex:g-1,rect:n.slice(0),rotation:r,annotationElementId:a,id:a,deleted:!1,popupRef:o,comment:l?.str||null,richText:h,creationDate:c,modificationDate:d}}const n=await super.deserialize(t,e,s);return n.#Ba=t.fontSize,n.color=pt.makeHexColor(...t.color),n.#Ga=Ki.#Ja(t.value),n._initialData=i,t.comment&&n.setCommentData(t),n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=se._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),s=Object.assign(super.serialize(t),{color:e,fontSize:this.#Ba,value:this.#Za()});return this.addComment(s),t?(s.isCopy=!0,s):this.annotationElementId&&!this.#to(s)?null:(s.id=this.annotationElementId,s)}#to(t){const{value:e,fontSize:s,color:i,pageIndex:n}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==e||t.fontSize!==s||t.color.some((t,e)=>t!==i[e])||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(!e)return null;const{style:s}=e;s.fontSize=`calc(${this.#Ba}px * var(--total-scale-factor))`,s.color=this.color,e.replaceChildren();for(const i of this.#Ga.split("\n")){const t=document.createElement("div");t.append(i?document.createTextNode(i):document.createElement("br")),e.append(t)}return t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#Ga}}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class Qi{static PRECISION=1e-4;toSVGPath(){Z("Abstract method `toSVGPath` must be implemented.")}get box(){Z("Abstract getter `box` must be implemented.")}serialize(t,e){Z("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2)r[a]=e+t[a]*i,r[a+1]=s+t[a+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2)r[a]=e+t[a+1]*i,r[a+1]=s+t[a]*n;return r}static _translate(t,e,s,i){i||=new Float32Array(t.length);for(let n=0,r=t.length;n<r;n+=2)i[n]=e+t[n],i[n+1]=s+t[n+1];return i}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,e,s,i,n){switch(n){case 90:return[1-e/s,t/i];case 180:return[1-t/s,1-e/i];case 270:return[e/s,1-t/i];default:return[t/s,e/i]}}static _normalizePagePoint(t,e,s){switch(s){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,s,i,n,r){return[(t+5*s)/6,(e+5*i)/6,(5*s+n)/6,(5*i+r)/6,(s+n)/2,(i+r)/2]}}class Ji{#eo;#so=[];#io;#no;#ro=[];#ao=new Float32Array(18);#oo;#ho;#lo;#co;#do;#uo;#po=[];static#go=8;static#mo=2;static#fo=Ji.#go+Ji.#mo;constructor({x:t,y:e},s,i,n,r,a=0){this.#eo=s,this.#uo=n*i,this.#no=r,this.#ao.set([NaN,NaN,NaN,NaN,t,e],6),this.#io=a,this.#co=Ji.#go*i,this.#lo=Ji.#fo*i,this.#do=i,this.#po.push(t,e)}isEmpty(){return isNaN(this.#ao[8])}#bo(){const t=this.#ao.subarray(4,6),e=this.#ao.subarray(16,18),[s,i,n,r]=this.#eo;return[(this.#oo+(t[0]-e[0])/2-s)/n,(this.#ho+(t[1]-e[1])/2-i)/r,(this.#oo+(e[0]-t[0])/2-s)/n,(this.#ho+(e[1]-t[1])/2-i)/r]}add({x:t,y:e}){this.#oo=t,this.#ho=e;const[s,i,n,r]=this.#eo;let[a,o,h,l]=this.#ao.subarray(8,12);const c=t-h,d=e-l,u=Math.hypot(c,d);if(u<this.#lo)return!1;const p=u-this.#co,g=p/u,m=g*c,f=g*d;let b=a,y=o;a=h,o=l,h+=m,l+=f,this.#po?.push(t,e);const A=m/p,w=-f/p*this.#uo,v=A*this.#uo;return this.#ao.set(this.#ao.subarray(2,8),0),this.#ao.set([h+w,l+v],4),this.#ao.set(this.#ao.subarray(14,18),12),this.#ao.set([h-w,l-v],16),isNaN(this.#ao[6])?(0===this.#ro.length&&(this.#ao.set([a+w,o+v],2),this.#ro.push(NaN,NaN,NaN,NaN,(a+w-s)/n,(o+v-i)/r),this.#ao.set([a-w,o-v],14),this.#so.push(NaN,NaN,NaN,NaN,(a-w-s)/n,(o-v-i)/r)),this.#ao.set([b,y,a,o,h,l],6),!this.isEmpty()):(this.#ao.set([b,y,a,o,h,l],6),Math.abs(Math.atan2(y-o,b-a)-Math.atan2(f,m))<Math.PI/2?([a,o,h,l]=this.#ao.subarray(2,6),this.#ro.push(NaN,NaN,NaN,NaN,((a+h)/2-s)/n,((o+l)/2-i)/r),[a,o,b,y]=this.#ao.subarray(14,18),this.#so.push(NaN,NaN,NaN,NaN,((b+a)/2-s)/n,((y+o)/2-i)/r),!0):([b,y,a,o,h,l]=this.#ao.subarray(0,6),this.#ro.push(((b+5*a)/6-s)/n,((y+5*o)/6-i)/r,((5*a+h)/6-s)/n,((5*o+l)/6-i)/r,((a+h)/2-s)/n,((o+l)/2-i)/r),[h,l,a,o,b,y]=this.#ao.subarray(12,18),this.#so.push(((b+5*a)/6-s)/n,((y+5*o)/6-i)/r,((5*a+h)/6-s)/n,((5*o+l)/6-i)/r,((a+h)/2-s)/n,((o+l)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#ro,e=this.#so;if(isNaN(this.#ao[6])&&!this.isEmpty())return this.#yo();const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);this.#Ao(s);for(let i=e.length-6;i>=6;i-=6)isNaN(e[i])?s.push(`L${e[i+4]} ${e[i+5]}`):s.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);return this.#wo(s),s.join(" ")}#yo(){const[t,e,s,i]=this.#eo,[n,r,a,o]=this.#bo();return`M${(this.#ao[2]-t)/s} ${(this.#ao[3]-e)/i} L${(this.#ao[4]-t)/s} ${(this.#ao[5]-e)/i} L${n} ${r} L${a} ${o} L${(this.#ao[16]-t)/s} ${(this.#ao[17]-e)/i} L${(this.#ao[14]-t)/s} ${(this.#ao[15]-e)/i} Z`}#wo(t){const e=this.#so;t.push(`L${e[4]} ${e[5]} Z`)}#Ao(t){const[e,s,i,n]=this.#eo,r=this.#ao.subarray(4,6),a=this.#ao.subarray(16,18),[o,h,l,c]=this.#bo();t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${o} ${h} L${l} ${c} L${(a[0]-e)/i} ${(a[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,r){return new Zi(t,e,s,i,n,r)}getOutlines(){const t=this.#ro,e=this.#so,s=this.#ao,[i,n,r,a]=this.#eo,o=new Float32Array((this.#po?.length??0)+2);for(let c=0,d=o.length-2;c<d;c+=2)o[c]=(this.#po[c]-i)/r,o[c+1]=(this.#po[c+1]-n)/a;if(o[o.length-2]=(this.#oo-i)/r,o[o.length-1]=(this.#ho-n)/a,isNaN(s[6])&&!this.isEmpty())return this.#vo(o);const h=new Float32Array(this.#ro.length+24+this.#so.length);let l=t.length;for(let c=0;c<l;c+=2)isNaN(t[c])?h[c]=h[c+1]=NaN:(h[c]=t[c],h[c+1]=t[c+1]);l=this.#_o(h,l);for(let c=e.length-6;c>=6;c-=6)for(let t=0;t<6;t+=2)isNaN(e[c+t])?(h[l]=h[l+1]=NaN,l+=2):(h[l]=e[c+t],h[l+1]=e[c+t+1],l+=2);return this.#xo(h,l),this.newFreeDrawOutline(h,o,this.#eo,this.#do,this.#io,this.#no)}#vo(t){const e=this.#ao,[s,i,n,r]=this.#eo,[a,o,h,l]=this.#bo(),c=new Float32Array(36);return c.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/r,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/r,NaN,NaN,NaN,NaN,a,o,NaN,NaN,NaN,NaN,h,l,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/r,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/r],0),this.newFreeDrawOutline(c,t,this.#eo,this.#do,this.#io,this.#no)}#xo(t,e){const s=this.#so;return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+6}#_o(t,e){const s=this.#ao.subarray(4,6),i=this.#ao.subarray(16,18),[n,r,a,o]=this.#eo,[h,l,c,d]=this.#bo();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/a,(s[1]-r)/o,NaN,NaN,NaN,NaN,h,l,NaN,NaN,NaN,NaN,c,d,NaN,NaN,NaN,NaN,(i[0]-n)/a,(i[1]-r)/o],e),e+24}}class Zi extends Qi{#eo;#So=new Float32Array(4);#io;#no;#po;#do;#Co;constructor(t,e,s,i,n,r){super(),this.#Co=t,this.#po=e,this.#eo=s,this.#do=i,this.#io=n,this.#no=r,this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],this.#ko(r);const[a,o,h,l]=this.#So;for(let c=0,d=t.length;c<d;c+=2)t[c]=(t[c]-a)/h,t[c+1]=(t[c+1]-o)/l;for(let c=0,d=e.length;c<d;c+=2)e[c]=(e[c]-a)/h,e[c+1]=(e[c+1]-o)/l}toSVGPath(){const t=[`M${this.#Co[4]} ${this.#Co[5]}`];for(let e=6,s=this.#Co.length;e<s;e+=6)isNaN(this.#Co[e])?t.push(`L${this.#Co[e+4]} ${this.#Co[e+5]}`):t.push(`C${this.#Co[e]} ${this.#Co[e+1]} ${this.#Co[e+2]} ${this.#Co[e+3]} ${this.#Co[e+4]} ${this.#Co[e+5]}`);return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const r=s-t,a=i-e;let o,h;switch(n){case 0:o=Qi._rescale(this.#Co,t,i,r,-a),h=Qi._rescale(this.#po,t,i,r,-a);break;case 90:o=Qi._rescaleAndSwap(this.#Co,t,e,r,a),h=Qi._rescaleAndSwap(this.#po,t,e,r,a);break;case 180:o=Qi._rescale(this.#Co,s,e,-r,a),h=Qi._rescale(this.#po,s,e,-r,a);break;case 270:o=Qi._rescaleAndSwap(this.#Co,s,i,-r,-a),h=Qi._rescaleAndSwap(this.#po,s,i,-r,-a)}return{outline:Array.from(o),points:[Array.from(h)]}}#ko(t){const e=this.#Co;let s=e[4],i=e[5];const n=[s,i,s,i];let r=s,a=i,o=s,h=i;const l=t?Math.max:Math.min,c=new Float32Array(4);for(let p=6,g=e.length;p<g;p+=6){const t=e[p+4],d=e[p+5];isNaN(e[p])?(pt.pointBoundingBox(t,d,n),a>d?(r=t,a=d):a===d&&(r=l(r,t)),h<d?(o=t,h=d):h===d&&(o=l(o,t))):(c.set(u,0),pt.bezierBoundingBox(s,i,...e.slice(p,p+6),c),pt.rectBoundingBox(...c,n),a>c[1]?(r=c[0],a=c[1]):a===c[1]&&(r=l(r,c[0])),h<c[3]?(o=c[2],h=c[3]):h===c[3]&&(o=l(o,c[2]))),s=t,i=d}const d=this.#So;d[0]=n[0]-this.#io,d[1]=n[1]-this.#io,d[2]=n[2]-n[0]+2*this.#io,d[3]=n[3]-n[1]+2*this.#io,this.firstPoint=[r,a],this.lastPoint=[o,h]}get box(){return this.#So}newOutliner(t,e,s,i,n,r=0){return new Ji(t,e,s,i,n,r)}getNewOutline(t,e){const[s,i,n,r]=this.#So,[a,o,h,l]=this.#eo,c=n*h,d=r*l,u=s*h+a,p=i*l+o,g=this.newOutliner({x:this.#po[0]*c+u,y:this.#po[1]*d+p},this.#eo,this.#do,t,this.#no,e??this.#io);for(let m=2;m<this.#po.length;m+=2)g.add({x:this.#po[m]*c+u,y:this.#po[m+1]*d+p});return g.getOutlines()}}class tn{#eo;#To;#Mo;#Eo=[];#Po=[];constructor(t,e=0,s=0,i=!0){const n=u.slice(),r=1e-4;for(const{x:u,y:m,width:f,height:b}of t){const t=Math.floor((u-e)/r)*r,s=Math.ceil((u+f+e)/r)*r,i=Math.floor((m-e)/r)*r,a=Math.ceil((m+b+e)/r)*r,o=[t,i,a,!0],h=[s,i,a,!1];this.#Eo.push(o,h),pt.rectBoundingBox(t,i,s,a,n)}const a=n[2]-n[0]+2*s,o=n[3]-n[1]+2*s,h=n[0]-s,l=n[1]-s;let c=i?-1/0:1/0,d=1/0;const p=this.#Eo.at(i?-1:-2),g=[p[0],p[2]];for(const u of this.#Eo){const[t,e,s,n]=u;!n&&i?e<d?(d=e,c=t):e===d&&(c=Math.max(c,t)):n&&!i&&(e<d?(d=e,c=t):e===d&&(c=Math.min(c,t))),u[0]=(t-h)/a,u[1]=(e-l)/o,u[2]=(s-l)/o}this.#eo=new Float32Array([h,l,a,o]),this.#To=[c,d],this.#Mo=g}getOutlines(){this.#Eo.sort((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]);const t=[];for(const e of this.#Eo)e[3]?(t.push(...this.#Do(e)),this.#Io(e)):(this.#Fo(e),t.push(...this.#Do(e)));return this.#No(t)}#No(t){const e=[],s=new Set;for(const r of t){const[t,s,i]=r;e.push([t,s,r],[t,i,r])}e.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let r=0,a=e.length;r<a;r+=2){const t=e[r][2],i=e[r+1][2];t.push(i),i.push(t),s.add(t),s.add(i)}const i=[];let n;for(;s.size>0;){const t=s.values().next().value;let[e,r,a,o,h]=t;s.delete(t);let l=e,c=r;for(n=[e,a],i.push(n);;){let t;if(s.has(o))t=o;else{if(!s.has(h))break;t=h}s.delete(t),[e,r,a,o,h]=t,l!==e&&(n.push(l,c,e,c===r?r:a),l=e),c=c===r?a:r}n.push(l,c)}return new en(i,this.#eo,this.#To,this.#Mo)}#Ro(t){const e=this.#Po;let s=0,i=e.length-1;for(;s<=i;){const n=s+i>>1,r=e[n][0];if(r===t)return n;r<t?s=n+1:i=n-1}return i+1}#Io([,t,e]){const s=this.#Ro(t);this.#Po.splice(s,0,[t,e])}#Fo([,t,e]){const s=this.#Ro(t);for(let i=s;i<this.#Po.length;i++){const[s,n]=this.#Po[i];if(s!==t)break;if(s===t&&n===e)return void this.#Po.splice(i,1)}for(let i=s-1;i>=0;i--){const[s,n]=this.#Po[i];if(s!==t)break;if(s===t&&n===e)return void this.#Po.splice(i,1)}}#Do(t){const[e,s,i]=t,n=[[e,s,i]],r=this.#Ro(i);for(let a=0;a<r;a++){const[t,s]=this.#Po[a];for(let i=0,r=n.length;i<r;i++){const[,a,o]=n[i];if(!(s<=a||o<=t))if(a>=t)if(o>s)n[i][1]=s;else{if(1===r)return[];n.splice(i,1),i--,r--}else n[i][2]=t,o>s&&n.push([e,s,o])}}return n}}class en extends Qi{#eo;#Oo;constructor(t,e,s,i){super(),this.#Oo=t,this.#eo=e,this.firstPoint=s,this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#Oo){let[s,i]=e;t.push(`M${s} ${i}`);for(let n=2;n<e.length;n+=2){const r=e[n],a=e[n+1];r===s?(t.push(`V${a}`),i=a):a===i&&(t.push(`H${r}`),s=r)}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const r=[],a=s-t,o=i-e;for(const h of this.#Oo){const e=new Array(h.length);for(let s=0;s<h.length;s+=2)e[s]=t+h[s]*a,e[s+1]=i-h[s+1]*o;r.push(e)}return r}get box(){return this.#eo}get classNamesForOutlining(){return["highlightOutline"]}}class sn extends Ji{newFreeDrawOutline(t,e,s,i,n,r){return new nn(t,e,s,i,n,r)}}class nn extends Zi{newOutliner(t,e,s,i,n,r=0){return new sn(t,e,s,i,n,r)}}class rn extends se{#Bo=null;#Lo=0;#Uo;#jo=null;#r=null;#Ho=null;#$o=null;#zo=0;#Go=null;#Wo=null;#k=null;#Vo=!1;#To=null;#Mo=null;#Xo=null;#be="";#uo;#Yo="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=T.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=rn.prototype;return it(this,"_keyboardManager",new Kt([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"}),this.color=t.color||rn._defaultColor,this.#uo=t.thickness||rn._defaultThickness,this.opacity=t.opacity||rn._defaultOpacity,this.#Uo=t.boxes||null,this.#Yo=t.methodOfCreation||"",this.#be=t.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-1?(this.#Vo=!0,this.#qo(t),this.#Ko()):this.#Uo&&(this.#Bo=t.anchorNode,this.#Lo=t.anchorOffset,this.#$o=t.focusNode,this.#zo=t.focusOffset,this.#Qo(),this.#Ko(),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert(se._l10nAlert.highlight)}get telemetryInitialData(){return{action:"added",type:this.#Vo?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#uo,methodOfCreation:this.#Yo}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#Qo(){const t=new tn(this.#Uo,.001);this.#Wo=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#Wo.box;const e=new tn(this.#Uo,.0025,.001,"ltr"===this._uiManager.direction);this.#Ho=e.getOutlines();const{firstPoint:s}=this.#Wo;this.#To=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height];const{lastPoint:i}=this.#Ho;this.#Mo=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#qo({highlightOutlines:t,highlightId:e,clipPathId:s}){if(this.#Wo=t,this.#Ho=t.getNewOutline(this.#uo/2+1.5,.0025),e>=0)this.#k=e,this.#jo=s,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#Xo=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#Ho.box,path:{d:this.#Ho.toSVGPath()}},!0);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#k,{bbox:rn.#Jo(this.#Wo.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#Xo,{bbox:rn.#Jo(this.#Ho.box,e),path:{d:this.#Ho.toSVGPath()}})}const[i,n,r,a]=t.box;switch(this.rotation){case 0:this.x=i,this.y=n,this.width=r,this.height=a;break;case 90:{const[t,e]=this.parentDimensions;this.x=n,this.y=1-i,this.width=r*e/t,this.height=a*t/e;break}case 180:this.x=1-i,this.y=1-n,this.width=r,this.height=a;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n,this.y=i,this.width=r*e/t,this.height=a*t/e;break}}const{firstPoint:o}=t;this.#To=[(o[0]-i)/r,(o[1]-n)/a];const{lastPoint:h}=this.#Ho;this.#Mo=[(h[0]-i)/r,(h[1]-n)/a]}static initialize(t,e){se.initialize(t,e),rn._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case M.HIGHLIGHT_COLOR:rn._defaultColor=e;break;case M.HIGHLIGHT_THICKNESS:rn._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#Mo}get commentButtonPosition(){return this.#To}updateParams(t,e){switch(t){case M.HIGHLIGHT_COLOR:this.#Na(e);break;case M.HIGHLIGHT_THICKNESS:this.#Zo(e)}}static get defaultPropertiesToUpdate(){return[[M.HIGHLIGHT_COLOR,rn._defaultColor],[M.HIGHLIGHT_THICKNESS,rn._defaultThickness]]}get propertiesToUpdate(){return[[M.HIGHLIGHT_COLOR,this.color||rn._defaultColor],[M.HIGHLIGHT_THICKNESS,this.#uo||rn._defaultThickness],[M.HIGHLIGHT_FREE,this.#Vo]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#k,{root:{fill:this.color,"fill-opacity":this.opacity}}),this.#r?.updateColor(this.color),super.onUpdatedColor()}#Na(t){const e=(t,e)=>{this.color=t,this.opacity=e,this.onUpdatedColor()},s=this.color,i=this.opacity;this.addCommands({cmd:e.bind(this,t,rn._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:M.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#Zo(t){const e=this.#uo,s=t=>{this.#uo=t,this.#th(t)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:M.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){return this._uiManager.highlightColors?[["colorPicker",this.#r=new Fi({editor:this})]]:super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#eh())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#eh())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#sh(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#Ko(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#sh():t&&(this.#Ko(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#th(t){this.#Vo&&(this.#qo({highlightOutlines:this.#Wo.getNewOutline(t/2)}),this.fixAndSetPosition(),this.setDims())}#sh(){null!==this.#k&&this.parent&&(this.parent.drawLayer.remove(this.#k),this.#k=null,this.parent.drawLayer.remove(this.#Xo),this.#Xo=null)}#Ko(t=this.parent){null===this.#k&&(({id:this.#k,clipPathId:this.#jo}=t.drawLayer.draw({bbox:this.#Wo.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#Vo},path:{d:this.#Wo.toSVGPath()}},!1,!0)),this.#Xo=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Vo},bbox:this.#Ho.box,path:{d:this.#Ho.toSVGPath()}},this.#Vo),this.#Go&&(this.#Go.style.clipPath=this.#jo))}static#Jo([t,e,s,i],n){switch(n){case 90:return[1-e-i,t,i,s];case 180:return[1-t-s,1-e-i,s,i];case 270:return[e,1-t-s,i,s]}return[t,e,s,i]}rotate(t){const{drawLayer:e}=this.parent;let s;this.#Vo?(t=(t-this.rotation+360)%360,s=rn.#Jo(this.#Wo.box,t)):s=rn.#Jo([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#k,{bbox:s,root:{"data-main-rotation":t}}),e.updateProperties(this.#Xo,{bbox:rn.#Jo(this.#Ho.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#be&&(t.setAttribute("aria-label",this.#be),t.setAttribute("role","mark")),this.#Vo?t.classList.add("free"):this.div.addEventListener("keydown",this.#ih.bind(this),{signal:this._uiManager._signal});const e=this.#Go=document.createElement("div");return t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#jo,this.setDims(),Wt(this,this.#Go,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Xo,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Xo,{rootClass:{hovered:!1}})}#ih(t){rn._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#nh(!0);break;case 1:case 3:this.#nh(!1)}}#nh(t){if(!this.#Bo)return;const e=window.getSelection();t?e.setPosition(this.#Bo,this.#Lo):e.setPosition(this.#$o,this.#zo)}select(){super.select(),this.#Xo&&this.parent?.drawLayer.updateProperties(this.#Xo,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#Xo&&(this.parent?.drawLayer.updateProperties(this.#Xo,{rootClass:{selected:!1}}),this.#Vo||this.#nh(!1))}get _mustFixPosition(){return!this.#Vo}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#k,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#Xo,{rootClass:{hidden:!t}}))}#eh(){return this.#Vo?this.rotation:0}#rh(){if(this.#Vo)return null;const[t,e]=this.pageDimensions,[s,i]=this.pageTranslation,n=this.#Uo,r=new Float32Array(8*n.length);let a=0;for(const{x:o,y:h,width:l,height:c}of n){const n=o*t+s,d=(1-h)*e+i;r[a]=r[a+4]=n,r[a+1]=r[a+3]=d,r[a+2]=r[a+6]=n+l*t,r[a+5]=r[a+7]=d-c*e,a+=8}return r}#ah(t){return this.#Wo.serialize(t,this.#eh())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:r,y:a,width:o,height:h}=s.getBoundingClientRect(),l=new AbortController,c=t.combinedSignal(l),d=e=>{l.abort(),this.#oh(t,e)};window.addEventListener("blur",d,{signal:c}),window.addEventListener("pointerup",d,{signal:c}),window.addEventListener("pointerdown",Dt,{capture:!0,passive:!1,signal:c}),window.addEventListener("contextmenu",Pt,{signal:c}),s.addEventListener("pointermove",this.#hh.bind(this,t),{signal:c}),this._freeHighlight=new sn({x:i,y:n},[r,a,o,h],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#hh(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#oh(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,s){let i=null;if(t instanceof Xi){const{data:{quadPoints:e,rect:s,rotation:n,id:r,color:a,opacity:o,popupRef:h,richText:l,contentsObj:c,creationDate:d,modificationDate:u},parent:{page:{pageNumber:p}}}=t;i=t={annotationType:T.HIGHLIGHT,color:Array.from(a),opacity:o,quadPoints:e,boxes:null,pageIndex:p-1,rect:s.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:h,richText:l,comment:c?.str||null,creationDate:d,modificationDate:u}}else if(t instanceof Vi){const{data:{inkLists:e,rect:s,rotation:n,id:r,color:a,borderStyle:{rawWidth:o},popupRef:h,richText:l,contentsObj:c,creationDate:d,modificationDate:u},parent:{page:{pageNumber:p}}}=t;i=t={annotationType:T.HIGHLIGHT,color:Array.from(a),thickness:o,inkLists:e,boxes:null,pageIndex:p-1,rect:s.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:h,richText:l,comment:c?.str||null,creationDate:d,modificationDate:u}}const{color:n,quadPoints:r,inkLists:a,outlines:o,opacity:h}=t,l=await super.deserialize(t,e,s);l.color=pt.makeHexColor(...n),l.opacity=h||1,a&&(l.#uo=t.thickness),l._initialData=i,t.comment&&l.setCommentData(t);const[c,d]=l.pageDimensions,[u,p]=l.pageTranslation;if(r){const t=l.#Uo=[];for(let e=0;e<r.length;e+=8)t.push({x:(r[e]-u)/c,y:1-(r[e+1]-p)/d,width:(r[e+2]-r[e])/c,height:(r[e+1]-r[e+5])/d});l.#Qo(),l.#Ko(),l.rotate(l.rotation)}else if(a||o){l.#Vo=!0;const t=(a||o.points)[0],s={x:t[0]-u,y:d-(t[1]-p)},i=new sn(s,[0,0,c,d],1,l.#uo/2,!0,.001);for(let e=0,a=t.length;e<a;e+=2)s.x=t[e]-u,s.y=d-(t[e+1]-p),i.add(s);const{id:n,clipPathId:r}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:i.toSVGPath()}},!0,!0);l.#qo({highlightOutlines:i.getOutlines(),highlightId:n,clipPathId:r}),l.#Ko(),l.rotate(l.parentRotation)}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=se._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),s=super.serialize(t);return Object.assign(s,{color:e,opacity:this.opacity,thickness:this.#uo,quadPoints:this.#rh(),outlines:this.#ah(s.rect)}),this.addComment(s),this.annotationElementId&&!this.#to(s)?null:(s.id=this.annotationElementId,s)}#to(t){const{color:e}=this._initialData;return this.hasEditedComment||t.color.some((t,s)=>t!==e[s])}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}static canCreateNewEmptyEditor(){return!1}}class an{#lh=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,s]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,s)}updateSVGProperty(t,e){this.#lh[t]=e}toSVGProperties(){const t=this.#lh;return this.#lh=Object.create(null),{root:t}}reset(){this.#lh=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){Z("Not implemented")}}class on extends se{#ch=null;#dh;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#uh=null;static#ph=null;static#gh=null;static _INNER_MARGIN=3;constructor(t){super(t),this.#dh=t.mustBeCommitted||!1,this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color),super.onUpdatedColor()}onUpdatedOpacity(){this._colorPicker?.updateOpacity?.(this.opacity)}_addOutlines(t){t.drawOutlines&&(this.#mh(t),this.#Ko())}#mh({drawOutlines:t,drawId:e,drawingOptions:s}){this.#ch=t,this._drawingOptions||=s,this.annotationElementId||this._uiManager.a11yAlert(se._l10nAlert[this.editorType]),e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#fh(t,this.parent),this.#bh(t.box)}#fh(t,e){const{id:s}=e.drawLayer.draw(on._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return s}static _mergeSVGProperties(t,e){const s=new Set(Object.keys(t));for(const[i,n]of Object.entries(e))s.has(i)?Object.assign(t[i],n):t[i]=n;return t}static getDefaultDrawingOptions(t){Z("Not implemented")}static get typesMap(){Z("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const s=this.typesMap.get(t);s&&this._defaultDrawingOptions.updateProperty(s,e),this._currentParent&&(on.#uh.updateProperty(s,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const s=this.constructor.typesMap.get(t);s&&this._updateProperty(t,s,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[s,i]of this.typesMap)t.push([s,e[i]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[s,i]of this.constructor.typesMap)t.push([s,e[i]]);return t}_updateProperty(t,e,s){const i=this._drawingOptions,n=i[e],r=s=>{i.updateProperty(e,s);const n=this.#ch.updateProperty(e,s);n&&this.#bh(n),this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties()),t===this.colorType?this.onUpdatedColor():t===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:r.bind(this,s),undo:r.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(t,e){const s=this.constructor.typesMap.get(this.colorType),i=this.constructor.typesMap.get(this.opacityType),n=this._drawingOptions,r=n[s],a=n[i],o=(t,e)=>{n.updateProperty(s,t),n.updateProperty(i,e),this.#ch.updateProperty(s,t),this.#ch.updateProperty(i,e),this.parent?.drawLayer.updateProperties(this._drawId,n.toSVGProperties()),this.onUpdatedColor(),this.onUpdatedOpacity()};this.addCommands({cmd:o.bind(this,t,e),undo:o.bind(this,r,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:M.INK_COLOR_AND_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,on._mergeSVGProperties(this.#ch.getPathResizingSVGProperties(this.#yh()),{bbox:this.#Ah()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,on._mergeSVGProperties(this.#ch.getPathResizedSVGProperties(this.#yh()),{bbox:this.#Ah()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Ah()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,on._mergeSVGProperties(this.#ch.getPathTranslatedSVGProperties(this.#yh(),this.parentDimensions),{bbox:this.#Ah()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#dh&&(this.#dh=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#sh(),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#Ko(),this.#bh(this.#ch.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#sh()):t&&(this._uiManager.addShouldRescale(this),this.#Ko(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#sh(){null!==this._drawId&&this.parent&&(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#Ko(t=this.parent){null!==this._drawId&&this.parent===t||(null===this._drawId?(this._drawingOptions.updateAll(),this._drawId=this.#fh(this.#ch,t)):this.parent.drawLayer.updateParent(this._drawId,t.drawLayer))}#wh([t,e,s,i]){const{parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[e,1-t,s*(r/n),i*(n/r)];case 180:return[1-t,1-e,s,i];case 270:return[1-e,t,s*(r/n),i*(n/r)];default:return[t,e,s,i]}}#yh(){const{x:t,y:e,width:s,height:i,parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[1-e,t,s*(n/r),i*(r/n)];case 180:return[1-t,1-e,s,i];case 270:return[e,1-t,s*(n/r),i*(r/n)];default:return[t,e,s,i]}}#bh(t){[this.x,this.y,this.width,this.height]=this.#wh(t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()}#Ah(){const{x:t,y:e,width:s,height:i,rotation:n,parentRotation:r,parentDimensions:[a,o]}=this;switch((4*n+r)/90){case 1:return[1-e-i,t,i,s];case 2:return[1-t-s,1-e-i,s,i];case 3:return[e,1-t-s,i,s];case 4:return[t,e-s*(a/o),i*(o/a),s*(a/o)];case 5:return[1-e,t,s*(a/o),i*(o/a)];case 6:return[1-t-i*(o/a),1-e,i*(o/a),s*(a/o)];case 7:return[e-s*(a/o),1-t-i*(o/a),s*(a/o),i*(o/a)];case 8:return[t-s,e-i,s,i];case 9:return[1-e,t-s,i,s];case 10:return[1-t,1-e,s,i];case 11:return[e-i,1-t,i,s];case 12:return[t-i*(o/a),e,i*(o/a),s*(a/o)];case 13:return[1-e-s*(a/o),t-i*(o/a),s*(a/o),i*(o/a)];case 14:return[1-t,1-e-s*(a/o),i*(o/a),s*(a/o)];case 15:return[e,1-t,s*(a/o),i*(o/a)];default:return[t,e,s,i]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,on._mergeSVGProperties({bbox:this.#Ah()},this.#ch.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#bh(this.#ch.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;this._isCopy&&(t=this.x,e=this.y);const s=super.render();s.classList.add("draw");const i=document.createElement("div");return s.append(i),i.setAttribute("aria-hidden","true"),i.className="internal",this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,e),s}static createDrawerInstance(t,e,s,i,n){Z("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:r,offsetY:a,pointerId:o,pointerType:h}=i;if(Vt.isInitializedAndDifferentPointerType(h))return;const{viewport:{rotation:l}}=t,{width:c,height:d}=n.getBoundingClientRect(),u=on.#ph=new AbortController,p=t.combinedSignal(u);Vt.setPointer(h,o),window.addEventListener("pointerup",t=>{Vt.isSamePointerIdOrRemove(t.pointerId)&&this._endDraw(t)},{signal:p}),window.addEventListener("pointercancel",t=>{Vt.isSamePointerIdOrRemove(t.pointerId)&&this._currentParent.endDrawingSession()},{signal:p}),window.addEventListener("pointerdown",t=>{Vt.isSamePointerType(t.pointerType)&&(Vt.initializeAndAddPointerId(t.pointerId),on.#uh.isCancellable()&&(on.#uh.removeLastElement(),on.#uh.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:p}),window.addEventListener("contextmenu",Pt,{signal:p}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p}),n.addEventListener("touchmove",t=>{Vt.isSameTimeStamp(t.timeStamp)&&Dt(t)},{signal:p}),t.toggleDrawing(),e._editorUndoBar?.hide(),on.#uh?t.drawLayer.updateProperties(this._currentDrawId,on.#uh.startNew(r,a,c,d,l)):(e.updateUIForDefaultProperties(this),on.#uh=this.createDrawerInstance(r,a,c,d,l),on.#gh=this.getDefaultDrawingOptions(),this._currentParent=t,({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(on.#gh.toSVGProperties(),on.#uh.defaultSVGProperties),!0,!1)))}static _drawMove(t){if(Vt.isSameTimeStamp(t.timeStamp),!on.#uh)return;const{offsetX:e,offsetY:s,pointerId:i}=t;Vt.isSamePointerId(i)&&(Vt.isUsingMultiplePointers()?this._endDraw(t):(this._currentParent.drawLayer.updateProperties(this._currentDrawId,on.#uh.add(e,s)),Vt.setTimeStamp(t.timeStamp),Dt(t)))}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,on.#uh=null,on.#gh=null,Vt.clearTimeStamp()),on.#ph&&(on.#ph.abort(),on.#ph=null,Vt.clearPointerIds())}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,on.#uh.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const t=on.#uh,s=this._currentDrawId,i=t.getLastElement();return void e.addCommands({cmd:()=>{e.drawLayer.updateProperties(s,t.setLastElement(i))},undo:()=>{e.drawLayer.updateProperties(s,t.removeLastElement())},mustExec:!1,type:M.DRAW_STEP})}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(M.DRAW_STEP),!on.#uh.isEmpty()){const{pageDimensions:[s,i],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:on.#uh.getOutlines(s*n,i*n,n,this._INNER_MARGIN),drawingOptions:on.#gh,mustBeCommitted:!t});return this._cleanup(!0),r}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,s,i,n,r){Z("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:a}}=e.viewport,o=this.deserializeDraw(r,a,i,n,this._INNER_MARGIN,t),h=await super.deserialize(t,e,s);return h.createDrawingOptions(t),h.#mh({drawOutlines:o}),h.#Ko(),h.onScaleChanging(),h.rotate(),h}serializeDraw(t){const[e,s]=this.pageTranslation,[i,n]=this.pageDimensions;return this.#ch.serialize([e,s,i,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}}class hn{#ao=new Float64Array(6);#vh;#_h;#Yn;#uo;#po;#xh="";#Sh=0;#Oo=new ln;#Ch;#kh;constructor(t,e,s,i,n,r){this.#Ch=s,this.#kh=i,this.#Yn=n,this.#uo=r,[t,e]=this.#Th(t,e);const a=this.#vh=[NaN,NaN,NaN,NaN,t,e];this.#po=[t,e],this.#_h=[{line:a,points:this.#po}],this.#ao.set(a,0)}updateProperty(t,e){"stroke-width"===t&&(this.#uo=e)}#Th(t,e){return Qi._normalizePoint(t,e,this.#Ch,this.#kh,this.#Yn)}isEmpty(){return!this.#_h||0===this.#_h.length}isCancellable(){return this.#po.length<=10}add(t,e){[t,e]=this.#Th(t,e);const[s,i,n,r]=this.#ao.subarray(2,6),a=t-n,o=e-r;return Math.hypot(this.#Ch*a,this.#kh*o)<=2?null:(this.#po.push(t,e),isNaN(s)?(this.#ao.set([n,r,t,e],2),this.#vh.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#ao[0])&&this.#vh.splice(6,6),this.#ao.set([s,i,n,r,t,e],0),this.#vh.push(...Qi.createBezierPoints(s,i,n,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){return this.add(t,e)||(2===this.#po.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,s,i,n){this.#Ch=s,this.#kh=i,this.#Yn=n,[t,e]=this.#Th(t,e);const r=this.#vh=[NaN,NaN,NaN,NaN,t,e];this.#po=[t,e];const a=this.#_h.at(-1);return a&&(a.line=new Float32Array(a.line),a.points=new Float32Array(a.points)),this.#_h.push({line:r,points:this.#po}),this.#ao.set(r,0),this.#Sh=0,this.toSVGPath(),null}getLastElement(){return this.#_h.at(-1)}setLastElement(t){return this.#_h?(this.#_h.push(t),this.#vh=t.line,this.#po=t.points,this.#Sh=0,{path:{d:this.toSVGPath()}}):this.#Oo.setLastElement(t)}removeLastElement(){if(!this.#_h)return this.#Oo.removeLastElement();this.#_h.pop(),this.#xh="";for(let t=0,e=this.#_h.length;t<e;t++){const{line:e,points:s}=this.#_h[t];this.#vh=e,this.#po=s,this.#Sh=0,this.toSVGPath()}return{path:{d:this.#xh}}}toSVGPath(){const t=Qi.svgRound(this.#vh[4]),e=Qi.svgRound(this.#vh[5]);if(2===this.#po.length)return this.#xh=`${this.#xh} M ${t} ${e} Z`,this.#xh;if(this.#po.length<=6){const s=this.#xh.lastIndexOf("M");this.#xh=`${this.#xh.slice(0,s)} M ${t} ${e}`,this.#Sh=6}if(4===this.#po.length){const t=Qi.svgRound(this.#vh[10]),e=Qi.svgRound(this.#vh[11]);return this.#xh=`${this.#xh} L ${t} ${e}`,this.#Sh=12,this.#xh}const s=[];0===this.#Sh&&(s.push(`M ${t} ${e}`),this.#Sh=6);for(let i=this.#Sh,n=this.#vh.length;i<n;i+=6){const[t,e,n,r,a,o]=this.#vh.slice(i,i+6).map(Qi.svgRound);s.push(`C${t} ${e} ${n} ${r} ${a} ${o}`)}return this.#xh+=s.join(" "),this.#Sh=this.#vh.length,this.#xh}getOutlines(t,e,s,i){const n=this.#_h.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#Oo.build(this.#_h,t,e,s,this.#Yn,this.#uo,i),this.#ao=null,this.#vh=null,this.#_h=null,this.#xh=null,this.#Oo}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class ln extends Qi{#So;#Mh=0;#io;#_h;#Ch;#kh;#Eh;#Yn;#uo;build(t,e,s,i,n,r,a){this.#Ch=e,this.#kh=s,this.#Eh=i,this.#Yn=n,this.#uo=r,this.#io=a??0,this.#_h=t,this.#Ph()}get thickness(){return this.#uo}setLastElement(t){return this.#_h.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#_h.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#_h)if(t.push(`M${Qi.svgRound(e[4])} ${Qi.svgRound(e[5])}`),6!==e.length)if(12===e.length&&isNaN(e[6]))t.push(`L${Qi.svgRound(e[10])} ${Qi.svgRound(e[11])}`);else for(let s=6,i=e.length;s<i;s+=6){const[i,n,r,a,o,h]=e.subarray(s,s+6).map(Qi.svgRound);t.push(`C${i} ${n} ${r} ${a} ${o} ${h}`)}else t.push("Z");return t.join("")}serialize([t,e,s,i],n){const r=[],a=[],[o,h,l,c]=this.#Dh();let d,u,p,g,m,f,b,y,A;switch(this.#Yn){case 0:A=Qi._rescale,d=t,u=e+i,p=s,g=-i,m=t+o*s,f=e+(1-h-c)*i,b=t+(o+l)*s,y=e+(1-h)*i;break;case 90:A=Qi._rescaleAndSwap,d=t,u=e,p=s,g=i,m=t+h*s,f=e+o*i,b=t+(h+c)*s,y=e+(o+l)*i;break;case 180:A=Qi._rescale,d=t+s,u=e,p=-s,g=i,m=t+(1-o-l)*s,f=e+h*i,b=t+(1-o)*s,y=e+(h+c)*i;break;case 270:A=Qi._rescaleAndSwap,d=t+s,u=e+i,p=-s,g=-i,m=t+(1-h-c)*s,f=e+(1-o-l)*i,b=t+(1-h)*s,y=e+(1-o)*i}for(const{line:w,points:v}of this.#_h)r.push(A(w,d,u,p,g,n?new Array(w.length):null)),a.push(A(v,d,u,p,g,n?new Array(v.length):null));return{lines:r,points:a,rect:[m,f,b,y]}}static deserialize(t,e,s,i,n,{paths:{lines:r,points:a},rotation:o,thickness:h}){const l=[];let c,d,u,p,g;switch(o){case 0:g=Qi._rescale,c=-t/s,d=e/i+1,u=1/s,p=-1/i;break;case 90:g=Qi._rescaleAndSwap,c=-e/i,d=-t/s,u=1/i,p=1/s;break;case 180:g=Qi._rescale,c=t/s+1,d=-e/i,u=-1/s,p=1/i;break;case 270:g=Qi._rescaleAndSwap,c=e/i+1,d=t/s+1,u=-1/i,p=-1/s}if(!r){r=[];for(const t of a){const e=t.length;if(2===e){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const s=new Float32Array(3*(e-2));r.push(s);let[i,n,a,o]=t.subarray(0,4);s.set([NaN,NaN,NaN,NaN,i,n],0);for(let r=4;r<e;r+=2){const e=t[r],h=t[r+1];s.set(Qi.createBezierPoints(i,n,a,o,e,h),3*(r-2)),[i,n,a,o]=[a,o,e,h]}}}for(let f=0,b=r.length;f<b;f++)l.push({line:g(r[f].map(t=>t??NaN),c,d,u,p),points:g(a[f].map(t=>t??NaN),c,d,u,p)});const m=new this.prototype.constructor;return m.build(l,s,i,1,o,h,n),m}#Ih(t=this.#uo){const e=this.#io+t/2*this.#Eh;return this.#Yn%180==0?[e/this.#Ch,e/this.#kh]:[e/this.#kh,e/this.#Ch]}#Dh(){const[t,e,s,i]=this.#So,[n,r]=this.#Ih(0);return[t+n,e+r,s-2*n,i-2*r]}#Ph(){const t=this.#So=p.slice();for(const{line:i}of this.#_h){if(i.length<=12){for(let e=4,s=i.length;e<s;e+=6)pt.pointBoundingBox(i[e],i[e+1],t);continue}let e=i[4],s=i[5];for(let n=6,r=i.length;n<r;n+=6){const[r,a,o,h,l,c]=i.subarray(n,n+6);pt.bezierBoundingBox(e,s,r,a,o,h,l,c,t),e=l,s=c}}const[e,s]=this.#Ih();t[0]=yt(t[0]-e,0,1),t[1]=yt(t[1]-s,0,1),t[2]=yt(t[2]+e,0,1),t[3]=yt(t[3]+s,0,1),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#So}updateProperty(t,e){return"stroke-width"===t?this.#Zo(e):null}#Zo(t){const[e,s]=this.#Ih();this.#uo=t;const[i,n]=this.#Ih(),[r,a]=[i-e,n-s],o=this.#So;return o[0]-=r,o[1]-=a,o[2]+=2*r,o[3]+=2*a,o}updateParentDimensions([t,e],s){const[i,n]=this.#Ih();this.#Ch=t,this.#kh=e,this.#Eh=s;const[r,a]=this.#Ih(),o=r-i,h=a-n,l=this.#So;return l[0]-=o,l[1]-=h,l[2]+=2*o,l[3]+=2*h,l}updateRotation(t){return this.#Mh=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#So.map(Qi.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#So;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Qi.svgRound(t)} ${Qi.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#So;let s=0,i=0,n=0,r=0,a=0,o=0;switch(this.#Mh){case 90:i=e/t,n=-t/e,a=t;break;case 180:s=-1,r=-1,a=t,o=e;break;case 270:i=-e/t,n=t/e,o=e;break;default:return""}return`matrix(${s} ${i} ${n} ${r} ${Qi.svgRound(a)} ${Qi.svgRound(o)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,r]=this.#Ih(),[a,o,h,l]=this.#So;if(Math.abs(h-n)<=Qi.PRECISION||Math.abs(l-r)<=Qi.PRECISION){const n=t+s/2-(a+h/2),r=e+i/2-(o+l/2);return{path:{"transform-origin":`${Qi.svgRound(t)} ${Qi.svgRound(e)}`,transform:`${this.rotationTransform} translate(${n} ${r})`}}}const c=(s-2*n)/(h-2*n),d=(i-2*r)/(l-2*r),u=h/s,p=l/i;return{path:{"transform-origin":`${Qi.svgRound(a)} ${Qi.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${Qi.svgRound(n)} ${Qi.svgRound(r)}) scale(${c} ${d}) translate(${Qi.svgRound(-n)} ${Qi.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,r]=this.#Ih(),a=this.#So,[o,h,l,c]=a;if(a[0]=t,a[1]=e,a[2]=s,a[3]=i,Math.abs(l-n)<=Qi.PRECISION||Math.abs(c-r)<=Qi.PRECISION){const n=t+s/2-(o+l/2),r=e+i/2-(h+c/2);for(const{line:t,points:e}of this.#_h)Qi._translate(t,n,r,t),Qi._translate(e,n,r,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Qi.svgRound(t)} ${Qi.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(s-2*n)/(l-2*n),u=(i-2*r)/(c-2*r),p=-d*(o+n)+t+n,g=-u*(h+r)+e+r;if(1!==d||1!==u||0!==p||0!==g)for(const{line:m,points:f}of this.#_h)Qi._rescale(m,p,g,d,u,m),Qi._rescale(f,p,g,d,u,f);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Qi.svgRound(t)} ${Qi.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],s){const[i,n]=s,r=this.#So,a=t-r[0],o=e-r[1];if(this.#Ch===i&&this.#kh===n)for(const{line:h,points:l}of this.#_h)Qi._translate(h,a,o,h),Qi._translate(l,a,o,l);else{const t=this.#Ch/i,e=this.#kh/n;this.#Ch=i,this.#kh=n;for(const{line:s,points:i}of this.#_h)Qi._rescale(s,a,o,t,e,s),Qi._rescale(i,a,o,t,e,i);r[2]*=t,r[3]*=e}return r[0]=t,r[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Qi.svgRound(t)} ${Qi.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#So;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Qi.svgRound(t[0])} ${Qi.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class cn extends an{constructor(t){super(),this._viewParameters=t,super.updateProperties({fill:"none",stroke:se._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){"stroke-width"===t&&(e??=this["stroke-width"],e*=this._viewParameters.realScale),super.updateSVGProperty(t,e)}clone(){const t=new cn(this._viewParameters);return t.updateAll(this),t}}class dn extends on{static _type="ink";static _editorType=T.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){se.initialize(t,e),this._defaultDrawingOptions=new cn(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return it(this,"typesMap",new Map([[M.INK_THICKNESS,"stroke-width"],[M.INK_COLOR,"stroke"],[M.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new hn(t,e,s,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,s,i,n,r){return ln.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){let i=null;if(t instanceof Vi){const{data:{inkLists:e,rect:s,rotation:n,id:r,color:a,opacity:o,borderStyle:{rawWidth:h},popupRef:l,richText:c,contentsObj:d,creationDate:u,modificationDate:p},parent:{page:{pageNumber:g}}}=t;i=t={annotationType:T.INK,color:Array.from(a),thickness:h,opacity:o,paths:{points:e},boxes:null,pageIndex:g-1,rect:s.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:c,comment:d?.str||null,creationDate:u,modificationDate:p}}const n=await super.deserialize(t,e,s);return n._initialData=i,t.comment&&n.setCommentData(t),n}get toolbarButtons(){return this._colorPicker||=new Ni(this),[["colorPicker",this._colorPicker]]}get colorType(){return M.INK_COLOR}get colorAndOpacityType(){return M.INK_COLOR_AND_OPACITY}get opacityType(){return M.INK_OPACITY}updateParams(t,e){t!==M.INK_COLOR_AND_OPACITY?super.updateParams(t,e):this._updateColorAndOpacity(e.color,e.opacity)}static updateDefaultParams(t,e){t!==M.INK_COLOR_AND_OPACITY?super.updateDefaultParams(t,e):(super.updateDefaultParams(M.INK_COLOR,e.color),super.updateDefaultParams(M.INK_OPACITY,e.opacity))}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:s}=this;e.updateSVGProperty("stroke-width"),s.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:s}){this._drawingOptions=dn.getDefaultDrawingOptions({stroke:pt.makeHexColor(...t),"stroke-width":e,"stroke-opacity":s})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:s}=this.serializeDraw(t),{_drawingOptions:{stroke:i,"stroke-opacity":n,"stroke-width":r}}=this,a=Object.assign(super.serialize(t),{color:se._colorManager.convert(i),opacity:n,thickness:r,paths:{lines:e,points:s}});return this.addComment(a),t?(a.isCopy=!0,a):this.annotationElementId&&!this.#to(a)?null:(a.id=this.annotationElementId,a)}#to(t){const{color:e,thickness:s,opacity:i,pageIndex:n}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((t,s)=>t!==e[s])||t.thickness!==s||t.opacity!==i||t.pageIndex!==n}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const{points:e,rect:s}=this.serializeDraw(!1);return t.updateEdited({rect:s,thickness:this._drawingOptions["stroke-width"],points:e,popup:this.comment}),null}}class un extends ln{toSVGPath(){let t=super.toSVGPath();return t.endsWith("Z")||(t+="Z"),t}}class pn{static#Fh={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#Nh(t,e,s,i){return i-=e,0===(s-=t)?i>0?0:4:1===s?i+6:2-i}static#Rh=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#Oh(t,e,s,i,n,r,a){const o=this.#Nh(s,i,n,r);for(let h=0;h<8;h++){const n=(-h+o-a+16)%8;if(0!==t[(s+this.#Rh[2*n])*e+(i+this.#Rh[2*n+1])])return n}return-1}static#Bh(t,e,s,i,n,r,a){const o=this.#Nh(s,i,n,r);for(let h=0;h<8;h++){const n=(h+o+a+16)%8;if(0!==t[(s+this.#Rh[2*n])*e+(i+this.#Rh[2*n+1])])return n}return-1}static#Lh(t,e,s,i){const n=t.length,r=new Int32Array(n);for(let l=0;l<n;l++)r[l]=t[l]<=i?1:0;for(let l=1;l<s-1;l++)r[l*e]=r[l*e+e-1]=0;for(let l=0;l<e;l++)r[l]=r[e*s-1-l]=0;let a,o=1;const h=[];for(let l=1;l<s-1;l++){a=1;for(let t=1;t<e-1;t++){const s=l*e+t,i=r[s];if(0===i)continue;let n=l,c=t;if(1===i&&0===r[s-1])o+=1,c-=1;else{if(!(i>=1&&0===r[s+1])){1!==i&&(a=Math.abs(i));continue}o+=1,c+=1,i>1&&(a=i)}const d=[t,l],u=c===t+1,p={isHole:u,points:d,id:o,parent:0};let g;h.push(p);for(const t of h)if(t.id===a){g=t;break}g?g.isHole?p.parent=u?g.parent:a:p.parent=u?a:g.parent:p.parent=u?a:0;const m=this.#Oh(r,e,l,t,n,c,0);if(-1===m){r[s]=-o,1!==r[s]&&(a=Math.abs(r[s]));continue}let f=this.#Rh[2*m],b=this.#Rh[2*m+1];const y=l+f,A=t+b;n=y,c=A;let w=l,v=t;for(;;){const i=this.#Bh(r,e,w,v,n,c,1);f=this.#Rh[2*i],b=this.#Rh[2*i+1];const h=w+f,u=v+b;d.push(u,h);const p=w*e+v;if(0===r[p+1]?r[p]=-o:1===r[p]&&(r[p]=o),h===l&&u===t&&w===y&&v===A){1!==r[s]&&(a=Math.abs(r[s]));break}n=w,c=v,w=h,v=u}}}return h}static#Uh(t,e,s,i){if(s-e<=4){for(let n=e;n<s-2;n+=2)i.push(t[n],t[n+1]);return}const n=t[e],r=t[e+1],a=t[s-4]-n,o=t[s-3]-r,h=Math.hypot(a,o),l=a/h,c=o/h,d=l*r-c*n,u=o/a,p=1/h,g=Math.atan(u),m=Math.cos(g),f=Math.sin(g),b=p*(Math.abs(m)+Math.abs(f)),y=p*(1-b+b**2),A=Math.max(Math.atan(Math.abs(f+m)*y),Math.atan(Math.abs(f-m)*y));let w=0,v=e;for(let _=e+2;_<s-2;_+=2){const e=Math.abs(d-l*t[_+1]+c*t[_]);e>w&&(v=_,w=e)}w>(h*A)**2?(this.#Uh(t,e,v+2,i),this.#Uh(t,v,s,i)):i.push(n,r)}static#jh(t){const e=[],s=t.length;return this.#Uh(t,0,s,e),e.push(t[s-2],t[s-1]),e.length<=4?null:e}static#Hh(t,e,s,i,n,r){const a=new Float32Array(r**2),o=-2*i**2,h=r>>1;for(let g=0;g<r;g++){const t=(g-h)**2;for(let e=0;e<r;e++)a[g*r+e]=Math.exp((t+(e-h)**2)/o)}const l=new Float32Array(256),c=-2*n**2;for(let g=0;g<256;g++)l[g]=Math.exp(g**2/c);const d=t.length,u=new Uint8Array(d),p=new Uint32Array(256);for(let g=0;g<s;g++)for(let i=0;i<e;i++){const n=g*e+i,o=t[n];let c=0,d=0;for(let u=0;u<r;u++){const n=g+u-h;if(!(n<0||n>=s))for(let s=0;s<r;s++){const p=i+s-h;if(p<0||p>=e)continue;const g=t[n*e+p],m=a[u*r+s]*l[Math.abs(g-o)];c+=g*m,d+=m}}p[u[n]=Math.round(c/d)]++}return[u,p]}static#$h(t){const e=new Uint32Array(256);for(const s of t)e[s]++;return e}static#zh(t){const e=t.length,s=new Uint8ClampedArray(e>>2);let i=-1/0,n=1/0;for(let a=0,o=s.length;a<o;a++){const e=s[a]=t[a<<2];i=Math.max(i,e),n=Math.min(n,e)}const r=255/(i-n);for(let a=0,o=s.length;a<o;a++)s[a]=(s[a]-n)*r;return s}static#Gh(t){let e,s=-1/0,i=-1/0;const n=t.findIndex(t=>0!==t);let r=n,a=n;for(e=n;e<256;e++){const n=t[e];n>s&&(e-r>i&&(i=e-r,a=e-1),s=n,r=e)}for(e=a-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#Wh(t){const e=t,{width:s,height:i}=t,{maxDim:n}=this.#Fh;let r=s,a=i;if(s>n||i>n){let o=s,h=i,l=Math.log2(Math.max(s,i)/n);const c=Math.floor(l);l=l===c?c-1:c;for(let s=0;s<l;s++){r=Math.ceil(o/2),a=Math.ceil(h/2);const s=new OffscreenCanvas(r,a);s.getContext("2d").drawImage(t,0,0,o,h,0,0,r,a),o=r,h=a,t!==e&&t.close(),t=s.transferToImageBitmap()}const d=Math.min(n/r,n/a);r=Math.round(r*d),a=Math.round(a*d)}const o=new OffscreenCanvas(r,a).getContext("2d",{willReadFrequently:!0});o.fillStyle="white",o.fillRect(0,0,r,a),o.filter="grayscale(1)",o.drawImage(t,0,0,t.width,t.height,0,0,r,a);const h=o.getImageData(0,0,r,a).data;return[this.#zh(h),r,a]}static extractContoursFromText(t,{fontFamily:e,fontStyle:s,fontWeight:i},n,r,a,o){let h=new OffscreenCanvas(1,1),l=h.getContext("2d",{alpha:!1});const c=l.font=`${s} ${i} 200px ${e}`,{actualBoundingBoxLeft:d,actualBoundingBoxRight:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g,fontBoundingBoxAscent:m,fontBoundingBoxDescent:f,width:b}=l.measureText(t),y=1.5,A=Math.ceil(Math.max(Math.abs(d)+Math.abs(u)||0,b)*y),w=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||200,Math.abs(m)+Math.abs(f)||200)*y);h=new OffscreenCanvas(A,w),l=h.getContext("2d",{alpha:!0,willReadFrequently:!0}),l.font=c,l.filter="grayscale(1)",l.fillStyle="white",l.fillRect(0,0,A,w),l.fillStyle="black",l.fillText(t,.5*A/2,1.5*w/2);const v=this.#zh(l.getImageData(0,0,A,w).data),_=this.#$h(v),x=this.#Gh(_),S=this.#Lh(v,A,w,x);return this.processDrawnLines({lines:{curves:S,width:A,height:w},pageWidth:n,pageHeight:r,rotation:a,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,s,i,n){const[r,a,o]=this.#Wh(t),[h,l]=this.#Hh(r,a,o,Math.hypot(a,o)*this.#Fh.sigmaSFactor,this.#Fh.sigmaR,this.#Fh.kernelSize),c=this.#Gh(l),d=this.#Lh(h,a,o,c);return this.processDrawnLines({lines:{curves:d,width:a,height:o},pageWidth:e,pageHeight:s,rotation:i,innerMargin:n,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:s,rotation:i,innerMargin:n,mustSmooth:r,areContours:a}){i%180!=0&&([e,s]=[s,e]);const{curves:o,width:h,height:l}=t,c=t.thickness??0,d=[],u=Math.min(e/h,s/l),p=u/e,g=u/s,m=[];for(const{points:b}of o){const t=r?this.#jh(b):b;if(!t)continue;m.push(t);const e=t.length,s=new Float32Array(e),i=new Float32Array(3*(2===e?2:e-2));if(d.push({line:i,points:s}),2===e){s[0]=t[0]*p,s[1]=t[1]*g,i.set([NaN,NaN,NaN,NaN,s[0],s[1]],0);continue}let[n,a,o,h]=t;n*=p,a*=g,o*=p,h*=g,s.set([n,a,o,h],0),i.set([NaN,NaN,NaN,NaN,n,a],0);for(let r=4;r<e;r+=2){const e=s[r]=t[r]*p,l=s[r+1]=t[r+1]*g;i.set(Qi.createBezierPoints(n,a,o,h,e,l),3*(r-2)),[n,a,o,h]=[o,h,e,l]}}if(0===d.length)return null;const f=a?new un:new ln;return f.build(d,e,s,1,i,a?0:c,n),{outline:f,newCurves:m,areContours:a,thickness:c,width:h,height:l}}static async compressSignature({outlines:t,areContours:e,thickness:s,width:i,height:n}){let r,a=1/0,o=-1/0,h=0;for(const f of t){h+=f.length;for(let t=2,e=f.length;t<e;t++){const e=f[t]-f[t-2];a=Math.min(a,e),o=Math.max(o,e)}}r=a>=-128&&o<=127?Int8Array:a>=-32768&&o<=32767?Int16Array:Int32Array;const l=t.length,c=8+3*l,d=new Uint32Array(c);let u=0;d[u++]=c*Uint32Array.BYTES_PER_ELEMENT+(h-2*l)*r.BYTES_PER_ELEMENT,d[u++]=0,d[u++]=i,d[u++]=n,d[u++]=e?0:1,d[u++]=Math.max(0,Math.floor(s??0)),d[u++]=l,d[u++]=r.BYTES_PER_ELEMENT;for(const f of t)d[u++]=f.length-2,d[u++]=f[0],d[u++]=f[1];const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready,g.write(d);const m=r.prototype.constructor;for(const f of t){const t=new m(f.length-2);for(let e=2,s=f.length;e<s;e++)t[e-2]=f[e]-f[e-2];g.write(t)}return g.close(),(await new Response(p.readable).bytes()).toBase64()}static async decompressSignature(t){try{const e=Uint8Array.fromBase64(t),{readable:s,writable:i}=new DecompressionStream("deflate-raw"),n=i.getWriter();await n.ready,n.write(e).then(async()=>{await n.ready,await n.close()}).catch(()=>{});let r=null,a=0;for await(const t of s)r||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]),r.set(t,a),a+=t.length;const o=new Uint32Array(r.buffer,0,r.length>>2),h=o[1];if(0!==h)throw new Error(`Invalid version: ${h}`);const l=o[2],c=o[3],d=0===o[4],u=o[5],p=o[6],g=o[7],m=[],f=(8+3*p)*Uint32Array.BYTES_PER_ELEMENT;let b;switch(g){case Int8Array.BYTES_PER_ELEMENT:b=new Int8Array(r.buffer,f);break;case Int16Array.BYTES_PER_ELEMENT:b=new Int16Array(r.buffer,f);break;case Int32Array.BYTES_PER_ELEMENT:b=new Int32Array(r.buffer,f)}a=0;for(let t=0;t<p;t++){const e=o[3*t+8],s=new Float32Array(e+2);m.push(s);for(let i=0;i<2;i++)s[i]=o[3*t+8+i+1];for(let t=0;t<e;t++)s[t+2]=s[t]+b[a++]}return{areContours:d,thickness:u,outlines:m,width:l,height:c}}catch(t){return J(`decompressSignature: ${t}`),null}}}class gn extends an{constructor(){super(),super.updateProperties({fill:se._defaultLineColor,"stroke-width":0})}clone(){const t=new gn;return t.updateAll(this),t}}class mn extends cn{constructor(t){super(t),super.updateProperties({stroke:se._defaultLineColor,"stroke-width":1})}clone(){const t=new mn(this._viewParameters);return t.updateAll(this),t}}class fn extends on{#Vh=!1;#Xh=null;#Yh=null;#qh=null;static _type="signature";static _editorType=T.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"}),this._willKeepAspectRatio=!0,this.#Yh=t.signatureData||null,this.#Xh=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){se.initialize(t,e),this._defaultDrawingOptions=new gn,this._defaultDrawnSignatureOptions=new mn(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!1}static get typesMap(){return it(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#Xh}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){null!==this._drawId&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:s}=this;if(s&&(this._isCopy=!1,t=this.x,e=this.y),super.render(),null===this._drawId)if(this.#Yh){const{lines:t,mustSmooth:e,areContours:s,description:i,uuid:n,heightInPage:r}=this.#Yh,{rawDims:{pageWidth:a,pageHeight:o},rotation:h}=this.parent.viewport,l=pn.processDrawnLines({lines:t,pageWidth:a,pageHeight:o,rotation:h,innerMargin:fn._INNER_MARGIN,mustSmooth:e,areContours:s});this.addSignature(l,r,i,n)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);else this.div.setAttribute("data-l10n-args",JSON.stringify({description:this.#Xh||""}));return s&&(this._isCopy=!0,this._moveAfterPaste(t,e)),this.div}setUuid(t){this.#qh=t,this.addEditToolbar()}getUuid(){return this.#qh}get description(){return this.#Xh}set description(t){this.#Xh=t,this.div&&(this.div.setAttribute("data-l10n-args",JSON.stringify({description:t})),super.addEditToolbar().then(e=>{e?.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:s,width:i,height:n}=this.#Yh,r=Math.max(i,n);return{areContours:e,outline:pn.processDrawnLines({lines:{curves:t.map(t=>({points:t})),thickness:s,width:i,height:n},pageWidth:r,pageHeight:r,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,e,s,i){const{x:n,y:r}=this,{outline:a}=this.#Yh=t;let o;this.#Vh=a instanceof un,this.description=s,this.#Vh?o=fn.getDefaultDrawingOptions():(o=fn._defaultDrawnSignatureOptions.clone(),o.updateProperties({"stroke-width":a.thickness})),this._addOutlines({drawOutlines:a,drawingOptions:o});const[,h]=this.pageDimensions;let l=e/h;l=l>=1?.5:l,this.width*=l/this.height,this.width>=1&&(l*=.9/this.width,this.width=.9),this.height=l,this.setDims(),this.x=n,this.y=r,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(i),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!i,hasDescription:!!s}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:s},rotation:i}=this.parent.viewport;return pn.process(t,e,s,i,fn._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:s,pageHeight:i},rotation:n}=this.parent.viewport;return pn.extractContoursFromText(t,e,s,i,n,fn._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:s},rotation:i}=this.parent.viewport;return pn.processDrawnLines({lines:t,pageWidth:e,pageHeight:s,rotation:i,innerMargin:fn._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){t?this._drawingOptions=fn.getDefaultDrawingOptions():(this._drawingOptions=fn._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":e}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:s}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":i}}=this,n=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#Vh,color:[0,0,0],thickness:this.#Vh?0:i});return this.addComment(n),t?(n.paths={lines:e,points:s},n.uuid=this.#qh,n.isCopy=!0):n.lines=e,this.#Xh&&(n.accessibilityData={type:"Figure",alt:this.#Xh}),n}static deserializeDraw(t,e,s,i,n,r){return r.areContours?un.deserialize(t,e,s,i,n,r):ln.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){const i=await super.deserialize(t,e,s);return i.#Vh=t.areContours,i.description=t.accessibilityData?.alt||"",i.#qh=t.uuid,i}}class bn extends se{#Kh=null;#Qh=null;#Jh=null;#Zh=null;#tl=null;#el="";#sl=null;#il=!1;#nl=null;#rl=!1;#al=!1;static _type="stamp";static _editorType=T.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#Zh=t.bitmapUrl,this.#tl=t.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){se.initialize(t,e)}static isHandlingMimeForPasting(t){return Ut.includes(t)}static paste(t,e){e.pasteEditor({mode:T.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#ol(t,e=!1){t?(this.#Kh=t.bitmap,e||(this.#Qh=t.id,this.#rl=t.isSvg),t.file&&(this.#el=t.file.name),this.#hl()):this.remove()}#ll(){if(this.#Jh=null,this._uiManager.enableWaiting(!1),this.#sl)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Kh)this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Kh){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:s}=this._uiManager;if(!s)throw new Error("No ML.");if(!await s.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:n,height:r}=t||this.copyCanvas(null,null,!0).imageData,a=await s.guess({name:"altText",request:{data:i,width:n,height:r,channels:i.length/(n*r)}});if(!a)throw new Error("No response from the AI service.");if(a.error)throw new Error("Error from the AI service.");if(a.cancel)return null;if(!a.output)throw new Error("No valid response from the AI service.");const o=a.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#cl(){if(this.#Qh)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#Qh).then(t=>this.#ol(t,!0)).finally(()=>this.#ll());if(this.#Zh){const t=this.#Zh;return this.#Zh=null,this._uiManager.enableWaiting(!0),void(this.#Jh=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#ol(t)).finally(()=>this.#ll()))}if(this.#tl){const t=this.#tl;return this.#tl=null,this._uiManager.enableWaiting(!0),void(this.#Jh=this._uiManager.imageManager.getFromFile(t).then(t=>this.#ol(t)).finally(()=>this.#ll()))}const t=document.createElement("input");t.type="file",t.accept=Ut.join(",");const e=this._uiManager._signal;this.#Jh=new Promise(s=>{t.addEventListener("change",async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#ol(e)}else this.remove();s()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),s()},{signal:e})}).finally(()=>this.#ll()),t.click()}remove(){this.#Qh&&(this.#Kh=null,this._uiManager.imageManager.deleteId(this.#Qh),this.#sl?.remove(),this.#sl=null,this.#nl&&(clearTimeout(this.#nl),this.#nl=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#Qh&&null===this.#sl&&this.#cl(),this.isAttachedToDOM||this.parent.add(this))):this.#Qh&&this.#cl()}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#Jh||this.#Kh||this.#Zh||this.#tl||this.#Qh||this.#il)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;return this._isCopy&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.createAltText(),this.#il||(this.#Kh?this.#hl():this.#cl()),this._isCopy&&this._moveAfterPaste(t,e),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,e){const{id:s,bitmap:i}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove(),s&&this._uiManager.imageManager.isValidId(s)&&(this.#Qh=s,i&&(this.#Kh=i),this.#il=!1,this.#hl())}_onResized(){this.onScaleChanging()}onScaleChanging(){this.parent&&(null!==this.#nl&&clearTimeout(this.#nl),this.#nl=setTimeout(()=>{this.#nl=null,this.#dl()},200))}#hl(){const{div:t}=this;let{width:e,height:s}=this.#Kh;const[i,n]=this.pageDimensions,r=.75;if(this.width)e=this.width*i,s=this.height*n;else if(e>r*i||s>r*n){const t=Math.min(r*i/e,r*n/s);e*=t,s*=t}this._uiManager.enableWaiting(!1);const a=this.#sl=document.createElement("canvas");a.setAttribute("role","img"),this.addContainer(a),this.width=e/i,this.height=s/n,this.setDims(),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#dl(),this.#al||(this.parent.addUndoableEditor(this),this.#al=!0),this._reportTelemetry({action:"inserted_image"}),this.#el&&this.div.setAttribute("aria-description",this.#el),this.annotationElementId||this._uiManager.a11yAlert(se._l10nAlert.stamp)}copyCanvas(t,e,s=!1){t||(t=224);const{width:i,height:n}=this.#Kh,r=new Lt;let a=this.#Kh,o=i,h=n,l=null;if(e){if(i>e||n>e){const t=Math.min(e/i,e/n);o=Math.floor(i*t),h=Math.floor(n*t)}l=document.createElement("canvas");const t=l.width=Math.ceil(o*r.sx),s=l.height=Math.ceil(h*r.sy);this.#rl||(a=this.#ul(t,s));const c=l.getContext("2d");c.filter=this._uiManager.hcmFilter;let d="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":jt.isDarkMode&&(d="#8f8f9d",u="#42414d");const p=15,g=p*r.sx,m=p*r.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=d,b.fillRect(0,0,2*g,2*m),b.fillStyle=u,b.fillRect(0,0,g,m),b.fillRect(g,m,g,m),c.fillStyle=c.createPattern(f,"repeat"),c.fillRect(0,0,t,s),c.drawImage(a,0,0,a.width,a.height,0,0,t,s)}let c=null;if(s){let e,s;if(r.symmetric&&a.width<t&&a.height<t)e=a.width,s=a.height;else if(a=this.#Kh,i>t||n>t){const r=Math.min(t/i,t/n);e=Math.floor(i*r),s=Math.floor(n*r),this.#rl||(a=this.#ul(e,s))}const o=new OffscreenCanvas(e,s).getContext("2d",{willReadFrequently:!0});o.drawImage(a,0,0,a.width,a.height,0,0,e,s),c={width:e,height:s,data:o.getImageData(0,0,e,s).data}}return{canvas:l,width:o,height:h,imageData:c}}#ul(t,e){const{width:s,height:i}=this.#Kh;let n=s,r=i,a=this.#Kh;for(;n>2*t||r>2*e;){const s=n,i=r;n>2*t&&(n=Math.ceil(n/2)),r>2*e&&(r=Math.ceil(r/2));const o=new OffscreenCanvas(n,r);o.getContext("2d").drawImage(a,0,0,s,i,0,0,n,r),a=o.transferToImageBitmap()}return a}#dl(){const[t,e]=this.parentDimensions,{width:s,height:i}=this,n=new Lt,r=Math.ceil(s*t*n.sx),a=Math.ceil(i*e*n.sy),o=this.#sl;if(!o||o.width===r&&o.height===a)return;o.width=r,o.height=a;const h=this.#rl?this.#Kh:this.#ul(r,a),l=o.getContext("2d");l.filter=this._uiManager.hcmFilter,l.drawImage(h,0,0,h.width,h.height,0,0,r,a)}#pl(t){if(t){if(this.#rl){const t=this._uiManager.imageManager.getSvgUrl(this.#Qh);if(t)return t}const t=document.createElement("canvas");return({width:t.width,height:t.height}=this.#Kh),t.getContext("2d").drawImage(this.#Kh,0,0),t.toDataURL()}if(this.#rl){const[t,e]=this.pageDimensions,s=Math.round(this.width*t*_t.PDF_TO_CSS_UNITS),i=Math.round(this.height*e*_t.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(s,i);return n.getContext("2d").drawImage(this.#Kh,0,0,this.#Kh.width,this.#Kh.height,0,0,s,i),n.transferToImageBitmap()}return structuredClone(this.#Kh)}static async deserialize(t,e,s){let i=null,n=!1;if(t instanceof Yi){const{data:{rect:r,rotation:a,id:o,structParent:h,popupRef:l,richText:c,contentsObj:d,creationDate:u,modificationDate:p},container:g,parent:{page:{pageNumber:m}},canvas:f}=t;let b,y;f?(delete t.canvas,({id:b,bitmap:y}=s.imageManager.getFromCanvas(g.id,f)),f.remove()):(n=!0,t._hasNoCanvas=!0);const A=(await e._structTree.getAriaAttributes(`${C}${o}`))?.get("aria-label")||"";i=t={annotationType:T.STAMP,bitmapId:b,bitmap:y,pageIndex:m-1,rect:r.slice(0),rotation:a,annotationElementId:o,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:A},isSvg:!1,structParent:h,popupRef:l,richText:c,comment:d?.str||null,creationDate:u,modificationDate:p}}const r=await super.deserialize(t,e,s),{rect:a,bitmap:o,bitmapUrl:h,bitmapId:l,isSvg:c,accessibilityData:d}=t;n?(s.addMissingCanvas(t.id,r),r.#il=!0):l&&s.imageManager.isValidId(l)?(r.#Qh=l,o&&(r.#Kh=o)):r.#Zh=h,r.#rl=c;const[u,p]=r.pageDimensions;return r.width=(a[2]-a[0])/u,r.height=(a[3]-a[1])/p,d&&(r.altTextData=d),r._initialData=i,t.comment&&r.setCommentData(t),r.#al=!!i,r}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s=Object.assign(super.serialize(t),{bitmapId:this.#Qh,isSvg:this.#rl});if(this.addComment(s),t)return s.bitmapUrl=this.#pl(!0),s.accessibilityData=this.serializeAltText(!0),s.isCopy=!0,s;const{decorative:i,altText:n}=this.serializeAltText(!1);if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const t=this.#to(s);return t.isSame?null:(t.isSameAltText?delete s.accessibilityData:s.accessibilityData.structParent=this._initialData.structParent??-1,s.id=this.annotationElementId,delete s.bitmapId,s)}if(null===e)return s;e.stamps||=new Map;const r=this.#rl?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(e.stamps.has(this.#Qh)){if(this.#rl){const t=e.stamps.get(this.#Qh);r>t.area&&(t.area=r,t.serialized.bitmap.close(),t.serialized.bitmap=this.#pl(!1))}}else e.stamps.set(this.#Qh,{area:r,serialized:s}),s.bitmap=this.#pl(!1);return s}#to(t){const{pageIndex:e,accessibilityData:{altText:s}}=this._initialData,i=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===s;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&i&&n,isSameAltText:n}}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}new Map([Ki,dn,bn,rn,fn].map(t=>[t._editorType,t]));globalThis._pdfjsTestingUtils={HighlightOutliner:tn};const yn={fonts:globalThis.fonts,createElement:t=>"canvas"===t.toLowerCase()?new OffscreenCanvas(1,1):null};class An{constructor(){this._pdfDocument=null,this._page=null,this._geospatialMetadata=null,this._baseViewport=null,this._inverseBaseViewport=null,this._pdfWorker=null,this._pdfWorkerBlobUrl=null}async loadPDF(s,o={}){h()||await l(),i(o);const[{data:c},d]=await Promise.all([e(s.url,{responseType:"array-buffer",signal:o?.signal}),this._getPDFWorker(o)]),u=Si({data:c,wasmUrl:t("esri/libs/pdfjs/wasm/"),ownerDocument:yn,enableHWA:!0,useWorkerFetch:!0,worker:d});return this._pdfDocument=await u.promise,i(o),this._page=await this._pdfDocument.getPage(s.page),i(o),this._geospatialMetadata=await this._page.getGeoPDFMetadata(),i(o),this._baseViewport=this._page.getViewport({scale:1}),this._inverseBaseViewport=n(),a(this._inverseBaseViewport,r(...this._baseViewport.transform)),{geospatialMetadata:this._geospatialMetadata}}destroy(){this._page?.cleanup?.(),this._page=null,this._pdfDocument?.cleanup(),this._pdfDocument=null,this._geospatialMetadata=null,this._baseViewport=null,this._inverseBaseViewport=null,this._pdfWorker?.destroy(),this._pdfWorker=null,this._pdfWorkerBlobUrl&&(URL.revokeObjectURL(this._pdfWorkerBlobUrl),this._pdfWorkerBlobUrl=null)}async renderPDF(t,e={}){if(!this._page||!this._baseViewport||!this._inverseBaseViewport)throw new s("geospatial-pdf-layer-worker:not-loaded","PDF not loaded");i(e);const{width:n,height:r,sourceExtentAsJSON:a,currentRing:h,ctm:l}=t,d=o.fromJSON(a),u=await c(d,n,r,l,this._page,this._baseViewport,this._inverseBaseViewport,h,e);return i(e),wn(u,n,r)}async _getPDFWorker(s={}){if(this._pdfWorker)return this._pdfWorker;const i=t("esri/libs/pdfjs/pdf.worker.mjs"),n=(await e(i,{responseType:"blob",authMode:"anonymous",signal:s.signal})).data,r="application/javascript"===n.type||"text/javascript"===n.type?n:new Blob([n],{type:"application/javascript"}),a=URL.createObjectURL(r);try{const t=new Worker(a,{type:"module",name:"geospatial-pdf-pdfjs-worker"}),e=new Ei({port:t});return await e.promise,this._pdfWorker=e,this._pdfWorkerBlobUrl=a,e}catch(o){throw URL.revokeObjectURL(a),o}}}function wn(t,e,i){const n=t.getContext("2d");if(!n)throw new s("geospatial-pdf-raster:canvas","Failed to create canvas context.");const r=n.getImageData(0,0,e,i).data,a=e*i,o=new Uint8Array(a),h=new Uint8Array(a),l=new Uint8Array(a),c=new Uint8Array(a);for(let s=0,d=0;s<a;s++,d+=4)o[s]=r[d],h[s]=r[d+1],l[s]=r[d+2],c[s]=r[d+3];return{width:e,height:i,red:o,green:h,blue:l,mask:c}}export{An as default};
5
+ this.workerSrc))).WorkerMessageHandler)())}}class Pi{downloadInfoCapability=Promise.withResolvers();#Mr=null;#Er=new Map;#Pr=null;#Dr=new Map;#Ir=new Map;#Fr=new Map;#Nr=null;constructor(t,e,s,i,n,r){this.messageHandler=t,this.loadingTask=e,this.#Pr=s,this.commonObjs=new _i,this.fontLoader=new Ee({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.enableHWA=i.enableHWA,this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.binaryDataFactory=n.binaryDataFactory,this.pagesMapper=r,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler()}updatePage(t){const{_pageIndex:e}=t;this.#Dr.set(e,t),this.#Ir.set(e,Promise.resolve(t))}#Rr(t,e=null){return this.#Er.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,e))}#un({loaded:t,total:e}){this.loadingTask.onProgress?.({loaded:t,total:e,percent:e?yt(Math.round(t/e*100),0,100):NaN})}get annotationStorage(){return it(this,"annotationStorage",new le)}getRenderingIntent(t,e=S.ENABLE,s=null,i=!1,n=!1){let r=b,a=he;switch(t){case"any":r=f;break;case"display":break;case"print":r=y;break;default:J(`getRenderingIntent - invalid intent: ${t}`)}const o=r&y&&s instanceof ce?s:this.annotationStorage;switch(e){case S.DISABLE:r+=v;break;case S.ENABLE:break;case S.ENABLE_FORMS:r+=A;break;case S.ENABLE_STORAGE:r+=w,a=o.serializable;break;default:J(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=_),n&&(r+=x);const{ids:h,hash:l}=o.modifiedIds;return{renderingIntent:r,cacheKey:[r,a.hash,l].join("_"),annotationStorageSerializable:a,modifiedIds:h}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#Nr?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const s of this.#Dr.values())t.push(s._destroy());this.#Dr.clear(),this.#Ir.clear(),this.#Fr.clear(),Object.hasOwn(this,"annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#Er.clear(),this.filterFactory.destroy(),xi.cleanup(),this.#Pr?.cancelAllRequests(new ct("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{tt(this.#Pr,"GetReader - no `BasePDFStream` instance available."),this.#Mr=this.#Pr.getFullReader(),this.#Mr.onProgress=t=>this.#un(t),e.onPull=()=>{this.#Mr.read().then(function({value:t,done:s}){s?e.close():(tt(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{this.#Mr.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}}),t.on("ReaderHeadersReady",async t=>{await this.#Mr.headersReady;const{isStreamingSupported:e,isRangeSupported:s,contentLength:i}=this.#Mr;return e&&s&&(this.#Mr.onProgress=null),{isStreamingSupported:e,isRangeSupported:s,contentLength:i}}),t.on("GetRangeReader",(t,e)=>{tt(this.#Pr,"GetRangeReader - no `BasePDFStream` instance available.");const s=this.#Pr.getRangeReader(t.begin,t.end);s?(e.onPull=()=>{s.read().then(function({value:t,done:s}){s?e.close():(tt(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{s.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}):e.close()}),t.on("GetDoc",({pdfInfo:t})=>{this.pagesMapper.pagesNumber=t.numPages,this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new Ti(t,this))}),t.on("DocException",t=>{e._capability.reject(ts(t))}),t.on("PasswordRequest",t=>{this.#Nr=Promise.withResolvers();try{if(!e.onPassword)throw ts(t);const s=t=>{t instanceof Error?this.#Nr.reject(t):this.#Nr.resolve({password:t})};e.onPassword(s,t.code)}catch(t){this.#Nr.reject(t)}return this.#Nr.promise}),t.on("DataLoaded",t=>{this.#un({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)}),t.on("StartRenderPage",t=>{this.destroyed||this.#Dr.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}),t.on("commonobj",([e,s,i])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(s){case"Font":if("error"in i){const t=i.error;J(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const n=new Be(i),r=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,a=new Pe(n,r,i.charProcOperatorList,i.extra);this.fontLoader.bind(a).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{a.fontExtraProperties||a.clearData(),this.commonObjs.resolve(e,a)});break;case"CopyLocalImage":const{imageRef:o}=i;tt(o,"The imageRef must be defined.");for(const t of this.#Dr.values())for(const[,s]of t.objs){if(s?.ref!==o)continue;if(!s.dataLen)return null;const t=structuredClone(s);return this.commonObjs.resolve(e,t),s.dataLen}break;case"FontPath":this.commonObjs.resolve(e,new Ue(i));break;case"Image":this.commonObjs.resolve(e,i);break;case"Pattern":const h=new Le(i);this.commonObjs.resolve(e,h.getIR());break;default:throw new Error(`Got unknown common object type ${s}`)}return null}),t.on("obj",([t,e,s,i])=>{if(this.destroyed)return;const n=this.#Dr.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(s){case"Image":case"Pattern":n.objs.resolve(t,i);break;default:throw new Error(`Got unknown object type ${s}`)}else i?.bitmap?.close()}),t.on("DocProgress",t=>{this.destroyed||this.#un(t)}),t.on("FetchBinaryData",async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.binaryDataFactory)throw new Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&J("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this.#Mr?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}extractPages(t){const e={pageInfos:t};let s;if(this.annotationStorage.size>0){const t=this.annotationStorage.serializable;let{map:i}=t;s=t.transfer;const n=this.pagesMapper.getMapping();if(n){const t=new Map;for(const[e,s]of i){if(void 0!==s?.pageIndex&&s.pageIndex>=0&&s.pageIndex<n.length){const i=n[s.pageIndex]-1;if(i!==s.pageIndex){t.set(e,{...s,pageIndex:i});continue}}t.set(e,s)}i=t}e.annotationStorage=i}return this.messageHandler.sendWithPromise("ExtractPages",e,s).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this.pagesMapper.pagesNumber)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=this.pagesMapper.getPageId(t)-1,i=this.#Ir.get(e);if(i)return i;const n=this.messageHandler.sendWithPromise("GetPage",{pageIndex:s}).then(t=>{if(this.destroyed)throw new Error("Transport destroyed");t.refStr&&this.#Fr.set(t.refStr,s);const i=new Mi(e,t,this,this.pagesMapper,this._params.pdfBug);return this.#Dr.set(e,i),i});return this.#Ir.set(e,n),n}async getPageIndex(t){if(!He(t))throw new Error("Invalid pageIndex request.");const e=await this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}),s=this.pagesMapper.getPageNumber(e+1);if(0===s)throw new Error("GetPageIndex: page has been removed.");return s-1}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.pagesMapper.getPageId(t+1)-1,intent:e})}getFieldObjects(){return this.#Rr("GetFieldObjects")}hasJSActions(){return this.#Rr("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAnnotationsByType(t,e){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:e})}getDocJSActions(){return this.#Rr("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Rr("GetOptionalContentConfig").then(e=>new yi(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata";return this.#Er.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new mi(t[1]):null,contentDispositionFilename:this.#Mr?.filename??null,contentLength:this.#Mr?.contentLength??null,hasStructTree:t[2]})))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}getRawData(t){return this.messageHandler.sendWithPromise("GetRawData",t)}getGeospatialPDFMetadata(t){return this.messageHandler.sendWithPromise("GetGeospatialPDFMetadata",{pageIndex:t})}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#Dr.values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#Er.clear(),this.filterFactory.destroy(!0),xi.cleanup()}}cachedPageNumber(t){if(!He(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`,s=this.#Fr.get(e);if(s>=0){const t=this.pagesMapper.getPageNumber(s+1);if(0!==t)return t}return null}}class Di{_internalRenderTask=null;onContinue=null;onError=null;constructor(t){this._internalRenderTask=t}get promise(){return this._internalRenderTask.capability.promise}cancel(t=0){this._internalRenderTask.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this._internalRenderTask.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this._internalRenderTask;return t.form||t.canvas&&e?.size>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}}class Ii{#Or=null;#Br=null;static#Lr=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:a,canvasFactory:o,filterFactory:h,useRequestAnimationFrame:l=!1,pdfBug:c=!1,pageColors:d=null,enableHWA:u=!1,operationsFilter:p=null,renderingBudget:g=null,renderingScheduler:m=null}){this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=a,this.canvasFactory=o,this.filterFactory=h,this._pdfBug=c,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===l&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new Di(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvas,this._canvasContext=e.canvas?null:e.canvasContext,this._enableHWA=u,this._dependencyTracker=e.dependencyTracker,this._imagesTracker=e.imagesTracker,this._operationsFilter=p,this._renderingBudget=g,this._renderingScheduler=m}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(Ii.#Lr.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");Ii.#Lr.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{viewport:s,transform:i,background:n,dependencyTracker:r,imagesTracker:a}=this.params,o=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new js(o,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,r,a),this.gfx.beginDrawing({transform:i,viewport:s,transparency:t,background:n}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this._cancelScheduledContinue(),Ii.#Lr.delete(this._canvas),t||=new Ct(`Rendering cancelled, page ${this._pageIndex+1}`,e),this.callback(t),this.task.onError?.(t)}_cancelScheduledContinue(){this.#Or&&(window.cancelAnimationFrame(this.#Or),this.#Or=null),this.#Br?.(),this.#Br=null}operatorListChanged(){this.graphicsReady?(this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length),this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){const t=t=>{this.#Or=null,this.#Br=null,this._nextBound(t||null).catch(this._cancelBound)};this._renderingScheduler?.scheduleContinue?this.#Br=this._renderingScheduler.scheduleContinue(t)||null:this._useRequestAnimationFrame?this.#Or=window.requestAnimationFrame(()=>{t(null)}):Promise.resolve().then(()=>t(null)).catch(this._cancelBound)}async _next(t=null){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter,this._renderingBudget,t),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),Ii.#Lr.delete(this._canvas),this.callback())))}}class Fi{#Ur=null;#jr=null;#Hr;#$r=null;#zr=!1;#Gr=!1;#a=null;#Wr;#Vr=null;#y=null;static#Xr=null;static get _keyboardManager(){return it(this,"_keyboardManager",new Kt([[["Escape","mac+Escape"],Fi.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],Fi.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],Fi.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],Fi.prototype._moveToPrevious],[["Home","mac+Home"],Fi.prototype._moveToBeginning],[["End","mac+End"],Fi.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#Gr=!1,this.#a=t):this.#Gr=!0,this.#y=t?._uiManager||e,this.#Wr=this.#y._eventBus,this.#Hr=t?.color?.toUpperCase()||this.#y?.highlightColors.values().next().value||"#FFFF98",Fi.#Xr||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#Ur=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.ariaHasPopup="true",this.#a&&(t.ariaControls=`${this.#a.id}_colorpicker_dropdown`);const e=this.#y._signal;t.addEventListener("click",this.#Yr.bind(this),{signal:e}),t.addEventListener("keydown",this.#qr.bind(this),{signal:e});const s=this.#jr=document.createElement("span");return s.className="swatch",s.ariaHidden="true",s.style.backgroundColor=this.#Hr,t.append(s),t}renderMainDropdown(){const t=this.#$r=this.#Kr();return t.ariaOrientation="horizontal",t.ariaLabelledBy="highlightColorPickerLabel",t}#Kr(){const t=document.createElement("div"),e=this.#y._signal;t.addEventListener("contextmenu",Pt,{signal:e}),t.className="dropdown",t.role="listbox",t.ariaMultiSelectable="false",t.ariaOrientation="vertical",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),this.#a&&(t.id=`${this.#a.id}_colorpicker_dropdown`);for(const[s,i]of this.#y.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",Fi.#Xr[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.ariaSelected=i===this.#Hr,n.addEventListener("click",this.#Qr.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#qr.bind(this),{signal:e}),t}#Qr(t,e){e.stopPropagation(),this.#Wr.dispatch("switchannotationeditorparams",{source:this,type:M.HIGHLIGHT_COLOR,value:t}),this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#Ur)return void this.#Yr(t);const e=t.target.getAttribute("data-color");e&&this.#Qr(e,t)}_moveToNext(t){this.#Jr?t.target!==this.#Ur?t.target.nextSibling?.focus():this.#$r.firstElementChild?.focus():this.#Yr(t)}_moveToPrevious(t){t.target!==this.#$r?.firstElementChild&&t.target!==this.#Ur?(this.#Jr||this.#Yr(t),t.target.previousSibling?.focus()):this.#Jr&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Jr?this.#$r.firstElementChild?.focus():this.#Yr(t)}_moveToEnd(t){this.#Jr?this.#$r.lastElementChild?.focus():this.#Yr(t)}#qr(t){Fi._keyboardManager.exec(this,t)}#Yr(t){if(this.#Jr)return void this.hideDropdown();if(this.#zr=0===t.detail,this.#Vr||(this.#Vr=new AbortController,window.addEventListener("pointerdown",this.#p.bind(this),{signal:this.#y.combinedSignal(this.#Vr)})),this.#Ur.ariaExpanded="true",this.#$r)return void this.#$r.classList.remove("hidden");const e=this.#$r=this.#Kr();this.#Ur.append(e)}#p(t){this.#$r?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#$r?.classList.add("hidden"),this.#Ur.ariaExpanded="false",this.#Vr?.abort(),this.#Vr=null}get#Jr(){return this.#$r&&!this.#$r.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#Gr||(this.#Jr?(this.hideDropdown(),this.#Ur.focus({preventScroll:!0,focusVisible:this.#zr})):this.#a?.unselect())}updateColor(t){if(this.#jr&&(this.#jr.style.backgroundColor=t),!this.#$r)return;const e=this.#y.highlightColors.values();for(const s of this.#$r.children)s.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#Ur?.remove(),this.#Ur=null,this.#jr=null,this.#$r?.remove(),this.#$r=null}}class Ni{#Zr=null;#ta=!1;#a=null;#y=null;static#Xr=null;constructor(t){this.#a=t,this.#y=t._uiManager,Ni.#Xr||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#Zr)return this.#Zr;const{editorType:t,colorType:e,colorAndOpacityType:s,opacityType:i,color:n,opacity:r}=this.#a,a=this.#ta=ut.isAlphaColorInputSupported&&void 0!==i,o=this.#Zr=document.createElement("input");if(o.type="color",a){o.setAttribute("alpha","");const t=pt.hexNums[Math.round(255*(r??1))];o.value=(n||"#000000")+t}else o.value=n||"#000000";return o.className="basicColorPicker",o.tabIndex=0,o.setAttribute("data-l10n-id",Ni.#Xr[t]),o.addEventListener("input",()=>{if(a){const t=Ft(o.value);if(!t)return;const[n,r,a,h]=t,l=pt.makeHexColor(n,r,a);void 0!==s?this.#y.updateParams(s,{color:l,opacity:h}):(this.#y.updateParams(e,l),this.#y.updateParams(i,h))}else this.#y.updateParams(e,o.value)},{signal:this.#y._signal}),o}update(t){if(this.#Zr)if(this.#ta){const e=pt.hexNums[Math.round(255*this.#a.opacity)];this.#Zr.value=t+e}else this.#Zr.value=t}updateOpacity(t){if(!this.#Zr||!this.#ta)return;const e=pt.hexNums[Math.round(255*t)];this.#Zr.value=this.#a.color+e}destroy(){this.#Zr?.remove(),this.#Zr=null}hideDropdown(){}}function Ri(t){return Math.floor(255*yt(t,0,1)).toString(16).padStart(2,"0")}function Oi(t){return 255*yt(t,0,1)}class Bi{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=Oi(t),t,t]}static G_HTML([t]){const e=Ri(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(Oi)}static RGB_HTML(t){return`#${t.map(Ri).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[Oi(1-Math.min(1,t+i)),Oi(1-Math.min(1,s+i)),Oi(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t,n=1-e,r=1-s;return["CMYK",i,n,r,Math.min(i,n,r)]}}const Li=new WeakSet;(new Date).getTimezoneOffset();class Ui{#ea=null;#sa=!1;#ia=null;constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableComment=t.enableComment,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,this.hasOwnCommentButton=!1,e&&(this.contentElement=this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:t,richText:e}){return!(!t?.str&&!e?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Ui._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){const{data:t}=this,e=this.annotationStorage?.getEditor(t.id);return e?e.getData():t}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){const t=this.annotationStorage?.getEditor(this.data.id);if(t)return t.commentButtonPositionInPage;const{quadPoints:e,inkLists:s,rect:i}=this.data;let n=-1/0,r=-1/0;if(e?.length>=8){for(let t=0;t<e.length;t+=8)e[t+1]>r?(r=e[t+1],n=e[t+2]):e[t+1]===r&&(n=Math.max(n,e[t+2]));return[n,r]}if(s?.length>=1){for(const t of s)for(let e=0,s=t.length;e<s;e+=2)t[e+1]>r?(r=t[e+1],n=t[e]):t[e+1]===r&&(n=Math.max(n,t[e]));if(n!==1/0)return[n,r]}return i?[i[2],i[3]]:null}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}}=this.parent;return t[1]=e[3]-t[1]+e[1],t[0]=100*(t[0]-n)/s,t[1]=100*(t[1]-r)/i,t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${k}${t.id}`)?.popup?.contents||t.contentsObj?.str||""}set commentText(t){const{data:e}=this,s={deleted:!t,contents:t||""};this.annotationStorage.updateEditor(e.id,{popup:s})||this.annotationStorage.setValue(`${k}${e.id}`,{id:e.id,annotationType:e.annotationType,page:this.parent.page,popup:s,popupRef:e.popupRef,modificationDate:new Date}),t||this.removePopup()}removePopup(){(this.#ia?.popup||this.popup)?.remove(),this.#ia=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#ea||={rect:this.data.rect.slice(0)});const{rect:e,popup:s}=t;e&&this.#na(e);let i=this.#ia?.popup||this.popup;!i&&s?.text&&(this._createPopup(s),i=this.#ia.popup),i&&(i.updateEdited(t),s?.deleted&&(i.remove(),this.#ia=null,this.popup=null))}resetEdited(){this.#ea&&(this.#na(this.#ea.rect),this.#ia?.popup.resetEdited(),this.#ea=null)}#na(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:a,pageY:o}}}}=this;s?.splice(0,4,...t),e.left=100*(t[0]-a)/n+"%",e.top=100*(r-t[3]+o)/r+"%",0===i?(e.width=100*(t[2]-t[0])/n+"%",e.height=100*(t[3]-t[1])/r+"%"):this.setRotation(i)}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Hi||this instanceof ji||(n.tabIndex=0);const{style:r}=n;if(r.zIndex=this.parent.zIndex,this.parent.zIndex+=2,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof zi){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,n),n}const{width:a,height:o}=this;if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,s=e.borderStyle.verticalCornerRadius;if(t>0||s>0){const e=`calc(${t}px * var(--total-scale-factor)) / calc(${s}px * var(--total-scale-factor))`;r.borderRadius=e}else if(this instanceof $i){const t=`calc(${a}px * var(--total-scale-factor)) / calc(${o}px * var(--total-scale-factor))`;r.borderRadius=t}switch(e.borderStyle.style){case O:r.borderStyle="solid";break;case B:r.borderStyle="dashed";break;case L:J("Unimplemented border style: beveled");break;case U:J("Unimplemented border style: inset");break;case j:r.borderBottomStyle="solid"}const i=e.borderColor||null;i?(this.#sa=!0,r.borderColor=pt.makeHexColor(...i)):r.borderWidth=0}const h=pt.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]),{pageWidth:l,pageHeight:c,pageX:d,pageY:u}=i.rawDims;r.left=100*(h[0]-d)/l+"%",r.top=100*(h[1]-u)/c+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(r.width=100*a/l+"%",r.height=100*o/c+"%"):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims;let{width:n,height:r}=this;t%180!=0&&([n,r]=[r,n]),e.style.width=100*n/s+"%",e.style.height=100*r/i+"%",e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,s)=>{const i=s.detail[t],n=i[0],r=i.slice(1);s.target.style[e]=Bi[`${n}_HTML`](r),this.annotationStorage.setValue(this.data.id,{[e]:Bi[`${n}_rgb`](r)})};return it(this,"_commonActions",{display:t=>{const{display:e}=t.detail,s=e%2==1;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:s,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail)){const n=t[i]||s[i];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const r=s[i];r&&(r({detail:{[i]:n},target:t}),delete e[i])}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map(t=>Math.fround(t));if(8===t.length){const[r,a,o,h]=t.subarray(2,6);if(i===r&&n===a&&e===o&&s===h)return}const{style:r}=this.container;let a;if(this.#sa){const{borderColor:t,borderWidth:e}=r;r.borderWidth=0,a=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${t}" stroke-width="${e}">`],this.container.classList.add("hasBorder")}const o=i-e,h=n-s,{svgFactory:l}=this,c=l.createElement("svg");c.classList.add("quadrilateralsContainer"),c.setAttribute("width",0),c.setAttribute("height",0),c.role="none";const d=l.createElement("defs");c.append(d);const u=l.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),d.append(u);for(let g=2,m=t.length;g<m;g+=8){const s=t[g],i=t[g+1],r=t[g+2],c=t[g+3],d=l.createElement("rect"),p=(r-e)/o,m=(n-i)/h,f=(s-r)/o,b=(i-c)/h;d.setAttribute("x",p),d.setAttribute("y",m),d.setAttribute("width",f),d.setAttribute("height",b),u.append(d),a?.push(`<rect vector-effect="non-scaling-stroke" x="${p}" y="${m}" width="${f}" height="${b}"/>`)}this.#sa&&(a.push("</g></svg>')"),r.backgroundImage=a.join("")),this.container.append(c),this.container.style.clipPath=`url(#${p})`}_createPopup(t=null){const{data:e}=this;let s,i;t?(s={str:t.text},i=t.date):(s=e.contentsObj,i=e.modificationDate),this.#ia=new zi({data:{color:e.color,titleObj:e.titleObj,modificationDate:i,contentsObj:s,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#ia||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#ia}render(){Z("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:t,id:n,exportValues:r}of i){if(-1===t)continue;if(n===e)continue;const i="string"==typeof r?r:null,a=document.querySelector(`[data-element-id="${n}"]`);!a||Li.has(a)?s.push({id:n,exportValue:i,domElement:a}):J(`_getElementsByName - element not allowed: ${n}`)}return s}for(const i of document.getElementsByName(t)){const{exportValue:t}=i,n=i.getAttribute("data-element-id");n!==e&&Li.has(i)&&s.push({id:n,exportValue:t,domElement:i})}return s}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e,mustEnterInEditMode:!0})})}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class ji extends Ui{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,s=document.createElement("a");s.setAttribute("data-element-id",t.id);let i=!1;return t.url?(e.addLinkAttributes(s,t.url,t.newWindow),i=!0):t.action?(this._bindNamedAction(s,t.action,t.overlaidText),i=!0):t.attachment?(this.#ra(s,t.attachment,t.overlaidText,t.attachmentDest),i=!0):t.setOCGState?(this.#aa(s,t.setOCGState,t.overlaidText),i=!0):t.dest?(this._bindLink(s,t.dest,t.overlaidText),i=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(s,t),i=!0),t.resetForm?(this._bindResetFormAction(s,t.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(s,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&(this.contentElement=s,this.container.append(s)),this.container}#oa(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e,s=""){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||""===e)&&this.#oa(),s&&(t.title=s)}_bindNamedAction(t,e,s=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),s&&(t.title=s),this.#oa()}#ra(t,e,s="",i=null){t.href=this.linkService.getAnchorUrl(""),e.description?t.title=e.description:s&&(t.title=s),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,i),!1),this.#oa()}#aa(t,e,s=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),s&&(t.title=s),this.#oa()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(e.actions)){const n=s.get(i);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:i}}),!1))}e.overlaidText&&(t.title=e.overlaidText),t.onclick||(t.onclick=()=>!1),this.#oa()}_bindResetFormAction(t,e){const s=t.onclick;s||(t.href=this.linkService.getAnchorUrl("")),this.#oa(),this._fieldObjects?t.onclick=()=>{s?.();const{fields:t,refs:i,include:n}=e,r=[];if(0!==t.length||0!==i.length){const e=new Set(i);for(const s of t){const t=this._fieldObjects[s]||[];for(const{id:s}of t)e.add(s)}for(const t of Object.values(this._fieldObjects))for(const s of t)e.has(s.id)===n&&r.push(s)}else for(const e of Object.values(this._fieldObjects))r.push(...e);const a=this.annotationStorage,o=[];for(const e of r){const{id:t}=e;switch(o.push(t),e.type){case"text":{const s=e.defaultValue||"";a.setValue(t,{value:s});break}case"checkbox":case"radiobutton":{const s=e.defaultValue===e.exportValues;a.setValue(t,{value:s});break}case"combobox":case"listbox":{const s=e.defaultValue||"";a.setValue(t,{value:s});break}default:continue}const s=document.querySelector(`[data-element-id="${t}"]`);s&&(Li.has(s)?s.dispatchEvent(new Event("resetform")):J(`_bindResetFormAction - element not allowed: ${t}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}:(J('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),s||(t.onclick=()=>!1))}}class Hi extends Ui{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return ut.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})}):t.addEventListener(s,t=>{if("blur"===s){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===s){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(t)}})})}_setEventListeners(t,e,s,i){for(const[n,r]of s)("Action"===r||this.data.actions?.[r])&&("Focus"!==r&&"Blur"!==r||(e||={focused:!1}),this._setEventListener(t,e,n,r,i),"Focus"!==r||this.data.actions?.Blur?"Blur"!==r||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":pt.makeHexColor(...e)}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||9,n=t.style;let r;const a=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(m*i))||1);r=Math.min(i,a(e/m))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(i,a(t/m))}n.fontSize=`calc(${r}px * var(--total-scale-factor))`,n.color=pt.makeHexColor(...s),null!==this.data.textAlignment&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class $i extends Hi{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof i&&(i=i!==e.buttonValue,t.setValue(s,{value:i})),i)for(const r of this._getElementsByName(e.fieldName,s))t.setValue(r.id,{value:!1});const n=document.createElement("input");if(Li.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.tabIndex=0,n.addEventListener("change",e=>{const{name:i,checked:n}=e.target;for(const r of this._getElementsByName(i,s))t.setValue(r.id,{value:!1});t.setValue(s,{value:n})}),n.addEventListener("resetform",t=>{const s=e.defaultFieldValue;t.target.checked=null!=s&&s===e.buttonValue}),this.enableScripting&&this.hasJSActions){const i=e.buttonValue;n.addEventListener("updatefromsandbox",e=>{const n={value:e=>{const n=i===e.detail.value;for(const i of this._getElementsByName(e.target.name)){const e=n&&i.id===s;i.domElement&&(i.domElement.checked=e),t.setValue(i.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class zi extends Ui{constructor(t){const{data:e,elements:s,parent:i}=t,n=!!i._commentManager;if(super(t,{isRenderable:!n&&Ui._hasPopupData(e)}),this.elements=s,n&&Ui._hasPopupData(e)){const t=this.popup=this.#ha();for(const e of s)e.popup=t}else this.popup=null}#ha(){return new Gi({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})}render(){const{container:t}=this;t.classList.add("popupAnnotation"),t.role="comment";const e=this.popup=this.#ha(),s=[];for(const i of this.elements)i.popup=e,i.container.ariaHasPopup="dialog",s.push(i.data.id),i.addHighlightArea();return this.container.setAttribute("aria-controls",s.map(t=>`${C}${t}`).join(",")),this.container}}class Gi{#W=null;#la=this.#qr.bind(this);#ca=this.#da.bind(this);#ua=this.#pa.bind(this);#ga=this.#ma.bind(this);#fa=null;#Tt=null;#ba=null;#ya=null;#Aa=null;#wa=null;#va=null;#_a=!1;#xa=null;#Sa=null;#F=null;#Ca=null;#ka=null;#we=null;#Ta=null;#fe=null;#Ma=null;#ea=null;#Ea=!1;#Pa=null;#Da=null;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:r,richText:a,parent:o,rect:h,parentRect:l,open:c,commentManager:d=null}){this.#Tt=t,this.#Ma=i,this.#ba=r,this.#fe=a,this.#wa=o,this.#fa=e,this.#Ta=h,this.#va=l,this.#Aa=s,this.#W=d,this.#Pa=s[0],this.#ya=It.toDateObject(n),this.trigger=s.flatMap(t=>t.getElementsToTriggerPopup()),d||(this.#Ia(),this.#Tt.hidden=!0,c&&this.#ma())}#Ia(){if(this.#Sa)return;this.#Sa=new AbortController;const{signal:t}=this.#Sa;for(const e of this.trigger)e.addEventListener("click",this.#ga,{signal:t}),e.addEventListener("pointerenter",this.#ua,{signal:t}),e.addEventListener("pointerleave",this.#ca,{signal:t}),e.classList.add("popupTriggerArea");for(const e of this.#Aa)e.container?.addEventListener("keydown",this.#la,{signal:t})}#Fa(){const t=this.#Aa.find(t=>t.hasCommentButton);t&&(this.#ka=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#Ca)return void(this.#Ca.parentNode||this.#Pa.container.after(this.#Ca));if(this.#ka||this.#Fa(),!this.#ka)return;const{signal:t}=this.#Sa=new AbortController,e=this.#Pa.hasOwnCommentButton,s=()=>{this.#W.toggleCommentPopup(this,!0,void 0,!e)},i=()=>{this.#W.toggleCommentPopup(this,!1,!0,!e)},n=()=>{this.#W.toggleCommentPopup(this,!1,!1)};if(e){this.#Ca=this.#Pa.container;for(const e of this.trigger)e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.addEventListener("keydown",this.#la,{signal:t}),e.addEventListener("click",s,{signal:t}),e.addEventListener("pointerenter",i,{signal:t}),e.addEventListener("pointerleave",n,{signal:t}),e.classList.add("popupTriggerArea")}else{const e=this.#Ca=document.createElement("button");e.className="annotationCommentButton";const r=this.#Pa.container;e.style.zIndex=parseInt(r.style.zIndex,10)+1,e.tabIndex=0,e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.setAttribute("data-l10n-id","pdfjs-show-comment-button"),this.#Na(),this.#Ra(),e.addEventListener("keydown",this.#la,{signal:t}),e.addEventListener("click",s,{signal:t}),e.addEventListener("pointerenter",i,{signal:t}),e.addEventListener("pointerleave",n,{signal:t}),r.after(e)}}#Ra(){if(this.#Pa.extraPopupElement&&!this.#Pa.editor)return;this.#Ca||this.renderCommentButton();const[t,e]=this.#ka,{style:s}=this.#Ca;s.left=`calc(${t}%)`,s.top=`calc(${e}% - var(--comment-button-dim))`}#Na(){this.#Pa.extraPopupElement||(this.#Ca||this.renderCommentButton(),this.#Ca.style.backgroundColor=this.commentButtonColor||"")}get commentButtonColor(){const{color:t,opacity:e}=this.#Pa.commentData;return t?this.#wa._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#Ca?.focus()},0)}getData(){const{richText:t,color:e,opacity:s,creationDate:i,modificationDate:n}=this.#Pa.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:s,creationDate:i,modificationDate:n}}get elementBeforePopup(){return this.#Ca}get comment(){return this.#Da||=this.#Pa.commentText,this.#Da}set comment(t){t!==this.comment&&(this.#Pa.commentText=this.#Da=t)}focus(){this.#Pa.container?.focus()}get parentBoundingClientRect(){return this.#Pa.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){this.#Ca&&(this.#Ca.classList.toggle("selected",t),this.#Ca.ariaExpanded=e)}setSelectedCommentButton(t){this.#Ca.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#we)return this.#we;const{x:t,y:e,height:s}=this.#Ca.getBoundingClientRect(),{x:i,y:n,width:r,height:a}=this.#Pa.layer.getBoundingClientRect();return[(t-i)/r,(e+s-n)/a]}set commentPopupPosition(t){this.#we=t}hasDefaultPopupPosition(){return null===this.#we}get commentButtonPosition(){return this.#ka}get commentButtonWidth(){return this.#Ca.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[e,s]=this.#we||this.commentButtonPosition.map(t=>t/100),i=this.parentBoundingClientRect,{x:n,y:r,width:a,height:o}=i;this.#W.showDialog(null,this,n+e*a,r+s*o,{...t,parentDimensions:i})}render(){if(this.#xa)return;const t=this.#xa=document.createElement("div");if(t.className="popup",this.#fa){const e=t.style.outlineColor=pt.makeHexColor(...this.#fa);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");if(e.className="header",this.#Ma?.str){const t=document.createElement("span");t.className="title",e.append(t),({dir:t.dir,str:t.textContent}=this.#Ma)}if(t.append(e),this.#ya){const t=document.createElement("time");t.className="popupDate",t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#ya.valueOf()})),t.dateTime=this.#ya.toISOString(),e.append(t)}Ht({html:this.#Oa||this.#ba.str,dir:this.#ba?.dir,className:"popupContent"},t),this.#Tt.append(t)}get#Oa(){const t=this.#fe,e=this.#ba;return!t?.str||e?.str&&e.str!==t.str?null:this.#fe.html||null}get#Ba(){return this.#Oa?.attributes?.style?.fontSize||0}get#La(){return this.#Oa?.attributes?.style?.color||null}#Ua(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:this.#La,fontSize:this.#Ba?`calc(${this.#Ba}px * var(--total-scale-factor))`:""}};for(const n of t.split("\n"))e.push({name:"span",value:n,attributes:i});return s}#qr(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#_a)&&this.#ma()}updateEdited({rect:t,popup:e,deleted:s}){this.#W?(s?(this.remove(),this.#Da=null):e&&(e.deleted?this.remove():(this.#Na(),this.#Da=e.text)),t&&(this.#ka=null,this.#Fa(),this.#Ra())):s||e?.deleted?this.remove():(this.#Ia(),this.#ea||={contentsObj:this.#ba,richText:this.#fe},t&&(this.#F=null),e&&e.text&&(this.#fe=this.#Ua(e.text),this.#ya=It.toDateObject(e.date),this.#ba=null),this.#xa?.remove(),this.#xa=null)}resetEdited(){this.#ea&&(({contentsObj:this.#ba,richText:this.#fe}=this.#ea),this.#ea=null,this.#xa?.remove(),this.#xa=null,this.#F=null)}remove(){if(this.#Sa?.abort(),this.#Sa=null,this.#xa?.remove(),this.#xa=null,this.#Ea=!1,this.#_a=!1,this.#Ca?.remove(),this.#Ca=null,this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#ja(){if(null!==this.#F)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#wa;let r=!!this.#va,a=r?this.#va:this.#Ta;for(const u of this.#Aa)if(!a||null!==pt.intersect(u.data.rect,a)){a=u.data.rect,r=!0;break}const o=pt.normalizeRect([a[0],t[3]-a[1]+t[1],a[2],t[3]-a[3]+t[1]]),h=r?a[2]-a[0]+5:0,l=o[0]+h,c=o[1];this.#F=[100*(l-i)/e,100*(c-n)/s];const{style:d}=this.#Tt;d.left=`${this.#F[0]}%`,d.top=`${this.#F[1]}%`}#ma(){this.#W?this.#W.toggleCommentPopup(this,!1):(this.#_a=!this.#_a,this.#_a?(this.#pa(),this.#Tt.addEventListener("click",this.#ga),this.#Tt.addEventListener("keydown",this.#la)):(this.#da(),this.#Tt.removeEventListener("click",this.#ga),this.#Tt.removeEventListener("keydown",this.#la)))}#pa(){this.#xa||this.render(),this.isVisible?this.#_a&&this.#Tt.classList.add("focused"):(this.#ja(),this.#Tt.hidden=!1,this.#Tt.style.zIndex=parseInt(this.#Tt.style.zIndex,10)+1e3)}#da(){this.#Tt.classList.remove("focused"),!this.#_a&&this.isVisible&&(this.#Tt.hidden=!0,this.#Tt.style.zIndex=parseInt(this.#Tt.style.zIndex,10)-1e3)}forceHide(){this.#Ea=this.isVisible,this.#Ea&&(this.#Tt.hidden=!0)}maybeShow(){this.#W||(this.#Ia(),this.#Ea&&(this.#xa||this.#pa(),this.#Ea=!1,this.#Tt.hidden=!1))}get isVisible(){return!this.#W&&!1===this.#Tt.hidden}}class Wi extends Ui{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=T.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=this.contentElement=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const s=document.createElement("span");s.textContent=e,t.append(s)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}class Vi extends Ui{#Ha=null;#$a=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType="InkHighlight"===this.data.it?T.HIGHLIGHT:T.INK}#za(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:s,borderStyle:i,popupRef:n}}=this,{transform:r,width:a,height:o}=this.#za(e,t),h=this.svgFactory.create(a,o,!0),l=this.#Ha=this.svgFactory.createElement("svg:g");h.append(l),l.setAttribute("stroke-width",i.width||1),l.setAttribute("stroke-linecap","round"),l.setAttribute("stroke-linejoin","round"),l.setAttribute("stroke-miterlimit",10),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),l.setAttribute("transform",r);for(let c=0,d=s.length;c<d;c++){const t=this.svgFactory.createElement(this.svgElementName);this.#$a.push(t),t.setAttribute("points",s[c].join(",")),l.append(t)}return!n&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(h),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:s,rect:i}=t,n=this.#Ha;if(e>=0&&n.setAttribute("stroke-width",e||1),s)for(let r=0,a=this.#$a.length;r<a;r++)this.#$a[r].setAttribute("points",s[r].join(","));if(i){const{transform:t,width:e,height:s}=this.#za(this.data.rotation,i);n.parentElement.setAttribute("viewBox",`0 0 ${e} ${s}`),n.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#$a}addHighlightArea(){this.container.classList.add("highlightArea")}}class Xi extends Ui{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=T.HIGHLIGHT}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),t){const e=document.createElement("mark");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class Yi extends Ui{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=T.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}const qi=/\r\n?|\n/g;class Ki extends se{#Ga="";#Wa=`${this.id}-editor`;#Va=null;#Ba;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=Ki.prototype,e=t=>t.isEmpty(),s=Jt.TRANSLATE_SMALL,i=Jt.TRANSLATE_BIG;return it(this,"_keyboardManager",new Kt([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}]]))}static _type="freetext";static _editorType=T.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.color=t.color||Ki._defaultColor||se._defaultLineColor,this.#Ba=t.fontSize||Ki._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert(se._l10nAlert.freetext),this.canAddComment=!1}static initialize(t,e){se.initialize(t,e);const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case M.FREETEXT_SIZE:Ki._defaultFontSize=e;break;case M.FREETEXT_COLOR:Ki._defaultColor=e}}updateParams(t,e){switch(t){case M.FREETEXT_SIZE:this.#Xa(e);break;case M.FREETEXT_COLOR:this.#Na(e)}}static get defaultPropertiesToUpdate(){return[[M.FREETEXT_SIZE,Ki._defaultFontSize],[M.FREETEXT_COLOR,Ki._defaultColor||se._defaultLineColor]]}get propertiesToUpdate(){return[[M.FREETEXT_SIZE,this.#Ba],[M.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new Ni(this),[["colorPicker",this._colorPicker]]}get colorType(){return M.FREETEXT_COLOR}#Xa(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`,this.translate(0,-(t-this.#Ba)*this.parentScale),this.#Ba=t,this.#Ya()},s=this.#Ba;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:M.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#Na(t){const e=t=>{this.color=t,this.onUpdatedColor()},s=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:M.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-Ki._internalPadding*t,-(Ki._internalPadding+this.#Ba)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#Va=new AbortController;const t=this._uiManager.combinedSignal(this.#Va);return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){return!!super.disableEditMode()&&(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#Wa),this._isDraggable=!0,this.#Va?.abort(),this.#Va=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0)}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#qa(){const t=[];this.editorDiv.normalize();let e=null;for(const s of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&"BR"===s.nodeName||(t.push(Ki.#Ka(s)),e=s);return t.join("\n")}#Ya(){const[t,e]=this.parentDimensions;let s;if(this.isAttachedToDOM)s=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,i=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),s=e.getBoundingClientRect(),e.remove(),e.style.display=i,e.classList.toggle("hidden",n)}this.rotation%180==this.parentRotation%180?(this.width=s.width/t,this.height=s.height/e):(this.width=s.height/t,this.height=s.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#Ga,e=this.#Ga=this.#qa().trimEnd();if(t===e)return;const s=t=>{this.#Ga=t,t?(this.#Qa(),this._uiManager.rebuild(this),this.#Ya()):this.remove()};this.addCommands({cmd:()=>{s(e)},undo:()=>{s(t)},mustExec:!1}),this.#Ya()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){Ki._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;(this._isCopy||this.annotationElementId)&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#Wa),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:s}=this.editorDiv;if(s.fontSize=`calc(${this.#Ba}px * var(--total-scale-factor))`,s.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){const[s,i]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[r,a]=this.getInitialTranslation();[r,a]=this.pageTranslationToScreen(r,a);const[o,h]=this.pageDimensions,[l,c]=this.pageTranslation;let d,u;switch(this.rotation){case 0:d=t+(n[0]-l)/o,u=e+this.height-(n[1]-c)/h;break;case 90:d=t+(n[0]-l)/o,u=e-(n[1]-c)/h,[r,a]=[a,-r];break;case 180:d=t-this.width+(n[0]-l)/o,u=e-(n[1]-c)/h,[r,a]=[-r,-a];break;case 270:d=t+(n[0]-l-this.height*h)/o,u=e+(n[1]-c-this.width*o)/h,[r,a]=[-a,r]}this.setAt(d*s,u*i,r,a)}else this._moveAfterPaste(t,e);this.#Qa(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#Ka(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(qi,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:s}=e;if(1===s.length&&"text/plain"===s[0])return;t.preventDefault();const i=Ki.#Ja(e.getData("text")||"").replaceAll(qi,"\n");if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const r=n.getRangeAt(0);if(!i.includes("\n"))return r.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),void n.collapseToStart();const{startContainer:a,startOffset:o}=r,h=[],l=[];if(a.nodeType===Node.TEXT_NODE){const t=a.parentElement;if(l.push(a.nodeValue.slice(o).replaceAll(qi,"")),t!==this.editorDiv){let e=h;for(const s of this.editorDiv.childNodes)s!==t?e.push(Ki.#Ka(s)):e=l}h.push(a.nodeValue.slice(0,o).replaceAll(qi,""))}else if(a===this.editorDiv){let t=h,e=0;for(const s of this.editorDiv.childNodes)e++===o&&(t=l),t.push(Ki.#Ka(s))}this.#Ga=`${h.join("\n")}${i}${l.join("\n")}`,this.#Qa();const c=new Range;let d=Math.sumPrecise(h.map(t=>t.length));for(const{firstChild:u}of this.editorDiv.childNodes)if(u.nodeType===Node.TEXT_NODE){const t=u.nodeValue.length;if(d<=t){c.setStart(u,d),c.setEnd(u,d);break}d-=t}n.removeAllRanges(),n.addRange(c)}#Qa(){if(this.editorDiv.replaceChildren(),this.#Ga)for(const t of this.#Ga.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#Za(){return this.#Ga.replaceAll(" "," ")}static#Ja(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){const t=Ki._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,e,s){let i=null;if(t instanceof Wi){const{data:{defaultAppearanceData:{fontSize:e,fontColor:s},rect:n,rotation:r,id:a,popupRef:o,richText:h,contentsObj:l,creationDate:c,modificationDate:d},textContent:u,textPosition:p,parent:{page:{pageNumber:g}}}=t;if(!u||0===u.length)return null;i=t={annotationType:T.FREETEXT,color:Array.from(s),fontSize:e,value:u.join("\n"),position:p,pageIndex:g-1,rect:n.slice(0),rotation:r,annotationElementId:a,id:a,deleted:!1,popupRef:o,comment:l?.str||null,richText:h,creationDate:c,modificationDate:d}}const n=await super.deserialize(t,e,s);return n.#Ba=t.fontSize,n.color=pt.makeHexColor(...t.color),n.#Ga=Ki.#Ja(t.value),n._initialData=i,t.comment&&n.setCommentData(t),n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=se._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),s=Object.assign(super.serialize(t),{color:e,fontSize:this.#Ba,value:this.#Za()});return this.addComment(s),t?(s.isCopy=!0,s):this.annotationElementId&&!this.#to(s)?null:(s.id=this.annotationElementId,s)}#to(t){const{value:e,fontSize:s,color:i,pageIndex:n}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==e||t.fontSize!==s||t.color.some((t,e)=>t!==i[e])||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(!e)return null;const{style:s}=e;s.fontSize=`calc(${this.#Ba}px * var(--total-scale-factor))`,s.color=this.color,e.replaceChildren();for(const i of this.#Ga.split("\n")){const t=document.createElement("div");t.append(i?document.createTextNode(i):document.createElement("br")),e.append(t)}return t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#Ga}}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class Qi{static PRECISION=1e-4;toSVGPath(){Z("Abstract method `toSVGPath` must be implemented.")}get box(){Z("Abstract getter `box` must be implemented.")}serialize(t,e){Z("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2)r[a]=e+t[a]*i,r[a+1]=s+t[a+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2)r[a]=e+t[a+1]*i,r[a+1]=s+t[a]*n;return r}static _translate(t,e,s,i){i||=new Float32Array(t.length);for(let n=0,r=t.length;n<r;n+=2)i[n]=e+t[n],i[n+1]=s+t[n+1];return i}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,e,s,i,n){switch(n){case 90:return[1-e/s,t/i];case 180:return[1-t/s,1-e/i];case 270:return[e/s,1-t/i];default:return[t/s,e/i]}}static _normalizePagePoint(t,e,s){switch(s){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,s,i,n,r){return[(t+5*s)/6,(e+5*i)/6,(5*s+n)/6,(5*i+r)/6,(s+n)/2,(i+r)/2]}}class Ji{#eo;#so=[];#io;#no;#ro=[];#ao=new Float32Array(18);#oo;#ho;#lo;#co;#do;#uo;#po=[];static#go=8;static#mo=2;static#fo=Ji.#go+Ji.#mo;constructor({x:t,y:e},s,i,n,r,a=0){this.#eo=s,this.#uo=n*i,this.#no=r,this.#ao.set([NaN,NaN,NaN,NaN,t,e],6),this.#io=a,this.#co=Ji.#go*i,this.#lo=Ji.#fo*i,this.#do=i,this.#po.push(t,e)}isEmpty(){return isNaN(this.#ao[8])}#bo(){const t=this.#ao.subarray(4,6),e=this.#ao.subarray(16,18),[s,i,n,r]=this.#eo;return[(this.#oo+(t[0]-e[0])/2-s)/n,(this.#ho+(t[1]-e[1])/2-i)/r,(this.#oo+(e[0]-t[0])/2-s)/n,(this.#ho+(e[1]-t[1])/2-i)/r]}add({x:t,y:e}){this.#oo=t,this.#ho=e;const[s,i,n,r]=this.#eo;let[a,o,h,l]=this.#ao.subarray(8,12);const c=t-h,d=e-l,u=Math.hypot(c,d);if(u<this.#lo)return!1;const p=u-this.#co,g=p/u,m=g*c,f=g*d;let b=a,y=o;a=h,o=l,h+=m,l+=f,this.#po?.push(t,e);const A=m/p,w=-f/p*this.#uo,v=A*this.#uo;return this.#ao.set(this.#ao.subarray(2,8),0),this.#ao.set([h+w,l+v],4),this.#ao.set(this.#ao.subarray(14,18),12),this.#ao.set([h-w,l-v],16),isNaN(this.#ao[6])?(0===this.#ro.length&&(this.#ao.set([a+w,o+v],2),this.#ro.push(NaN,NaN,NaN,NaN,(a+w-s)/n,(o+v-i)/r),this.#ao.set([a-w,o-v],14),this.#so.push(NaN,NaN,NaN,NaN,(a-w-s)/n,(o-v-i)/r)),this.#ao.set([b,y,a,o,h,l],6),!this.isEmpty()):(this.#ao.set([b,y,a,o,h,l],6),Math.abs(Math.atan2(y-o,b-a)-Math.atan2(f,m))<Math.PI/2?([a,o,h,l]=this.#ao.subarray(2,6),this.#ro.push(NaN,NaN,NaN,NaN,((a+h)/2-s)/n,((o+l)/2-i)/r),[a,o,b,y]=this.#ao.subarray(14,18),this.#so.push(NaN,NaN,NaN,NaN,((b+a)/2-s)/n,((y+o)/2-i)/r),!0):([b,y,a,o,h,l]=this.#ao.subarray(0,6),this.#ro.push(((b+5*a)/6-s)/n,((y+5*o)/6-i)/r,((5*a+h)/6-s)/n,((5*o+l)/6-i)/r,((a+h)/2-s)/n,((o+l)/2-i)/r),[h,l,a,o,b,y]=this.#ao.subarray(12,18),this.#so.push(((b+5*a)/6-s)/n,((y+5*o)/6-i)/r,((5*a+h)/6-s)/n,((5*o+l)/6-i)/r,((a+h)/2-s)/n,((o+l)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#ro,e=this.#so;if(isNaN(this.#ao[6])&&!this.isEmpty())return this.#yo();const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);this.#Ao(s);for(let i=e.length-6;i>=6;i-=6)isNaN(e[i])?s.push(`L${e[i+4]} ${e[i+5]}`):s.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);return this.#wo(s),s.join(" ")}#yo(){const[t,e,s,i]=this.#eo,[n,r,a,o]=this.#bo();return`M${(this.#ao[2]-t)/s} ${(this.#ao[3]-e)/i} L${(this.#ao[4]-t)/s} ${(this.#ao[5]-e)/i} L${n} ${r} L${a} ${o} L${(this.#ao[16]-t)/s} ${(this.#ao[17]-e)/i} L${(this.#ao[14]-t)/s} ${(this.#ao[15]-e)/i} Z`}#wo(t){const e=this.#so;t.push(`L${e[4]} ${e[5]} Z`)}#Ao(t){const[e,s,i,n]=this.#eo,r=this.#ao.subarray(4,6),a=this.#ao.subarray(16,18),[o,h,l,c]=this.#bo();t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${o} ${h} L${l} ${c} L${(a[0]-e)/i} ${(a[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,r){return new Zi(t,e,s,i,n,r)}getOutlines(){const t=this.#ro,e=this.#so,s=this.#ao,[i,n,r,a]=this.#eo,o=new Float32Array((this.#po?.length??0)+2);for(let c=0,d=o.length-2;c<d;c+=2)o[c]=(this.#po[c]-i)/r,o[c+1]=(this.#po[c+1]-n)/a;if(o[o.length-2]=(this.#oo-i)/r,o[o.length-1]=(this.#ho-n)/a,isNaN(s[6])&&!this.isEmpty())return this.#vo(o);const h=new Float32Array(this.#ro.length+24+this.#so.length);let l=t.length;for(let c=0;c<l;c+=2)isNaN(t[c])?h[c]=h[c+1]=NaN:(h[c]=t[c],h[c+1]=t[c+1]);l=this.#_o(h,l);for(let c=e.length-6;c>=6;c-=6)for(let t=0;t<6;t+=2)isNaN(e[c+t])?(h[l]=h[l+1]=NaN,l+=2):(h[l]=e[c+t],h[l+1]=e[c+t+1],l+=2);return this.#xo(h,l),this.newFreeDrawOutline(h,o,this.#eo,this.#do,this.#io,this.#no)}#vo(t){const e=this.#ao,[s,i,n,r]=this.#eo,[a,o,h,l]=this.#bo(),c=new Float32Array(36);return c.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/r,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/r,NaN,NaN,NaN,NaN,a,o,NaN,NaN,NaN,NaN,h,l,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/r,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/r],0),this.newFreeDrawOutline(c,t,this.#eo,this.#do,this.#io,this.#no)}#xo(t,e){const s=this.#so;return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+6}#_o(t,e){const s=this.#ao.subarray(4,6),i=this.#ao.subarray(16,18),[n,r,a,o]=this.#eo,[h,l,c,d]=this.#bo();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/a,(s[1]-r)/o,NaN,NaN,NaN,NaN,h,l,NaN,NaN,NaN,NaN,c,d,NaN,NaN,NaN,NaN,(i[0]-n)/a,(i[1]-r)/o],e),e+24}}class Zi extends Qi{#eo;#So=new Float32Array(4);#io;#no;#po;#do;#Co;constructor(t,e,s,i,n,r){super(),this.#Co=t,this.#po=e,this.#eo=s,this.#do=i,this.#io=n,this.#no=r,this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],this.#ko(r);const[a,o,h,l]=this.#So;for(let c=0,d=t.length;c<d;c+=2)t[c]=(t[c]-a)/h,t[c+1]=(t[c+1]-o)/l;for(let c=0,d=e.length;c<d;c+=2)e[c]=(e[c]-a)/h,e[c+1]=(e[c+1]-o)/l}toSVGPath(){const t=[`M${this.#Co[4]} ${this.#Co[5]}`];for(let e=6,s=this.#Co.length;e<s;e+=6)isNaN(this.#Co[e])?t.push(`L${this.#Co[e+4]} ${this.#Co[e+5]}`):t.push(`C${this.#Co[e]} ${this.#Co[e+1]} ${this.#Co[e+2]} ${this.#Co[e+3]} ${this.#Co[e+4]} ${this.#Co[e+5]}`);return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const r=s-t,a=i-e;let o,h;switch(n){case 0:o=Qi._rescale(this.#Co,t,i,r,-a),h=Qi._rescale(this.#po,t,i,r,-a);break;case 90:o=Qi._rescaleAndSwap(this.#Co,t,e,r,a),h=Qi._rescaleAndSwap(this.#po,t,e,r,a);break;case 180:o=Qi._rescale(this.#Co,s,e,-r,a),h=Qi._rescale(this.#po,s,e,-r,a);break;case 270:o=Qi._rescaleAndSwap(this.#Co,s,i,-r,-a),h=Qi._rescaleAndSwap(this.#po,s,i,-r,-a)}return{outline:Array.from(o),points:[Array.from(h)]}}#ko(t){const e=this.#Co;let s=e[4],i=e[5];const n=[s,i,s,i];let r=s,a=i,o=s,h=i;const l=t?Math.max:Math.min,c=new Float32Array(4);for(let p=6,g=e.length;p<g;p+=6){const t=e[p+4],d=e[p+5];isNaN(e[p])?(pt.pointBoundingBox(t,d,n),a>d?(r=t,a=d):a===d&&(r=l(r,t)),h<d?(o=t,h=d):h===d&&(o=l(o,t))):(c.set(u,0),pt.bezierBoundingBox(s,i,...e.slice(p,p+6),c),pt.rectBoundingBox(...c,n),a>c[1]?(r=c[0],a=c[1]):a===c[1]&&(r=l(r,c[0])),h<c[3]?(o=c[2],h=c[3]):h===c[3]&&(o=l(o,c[2]))),s=t,i=d}const d=this.#So;d[0]=n[0]-this.#io,d[1]=n[1]-this.#io,d[2]=n[2]-n[0]+2*this.#io,d[3]=n[3]-n[1]+2*this.#io,this.firstPoint=[r,a],this.lastPoint=[o,h]}get box(){return this.#So}newOutliner(t,e,s,i,n,r=0){return new Ji(t,e,s,i,n,r)}getNewOutline(t,e){const[s,i,n,r]=this.#So,[a,o,h,l]=this.#eo,c=n*h,d=r*l,u=s*h+a,p=i*l+o,g=this.newOutliner({x:this.#po[0]*c+u,y:this.#po[1]*d+p},this.#eo,this.#do,t,this.#no,e??this.#io);for(let m=2;m<this.#po.length;m+=2)g.add({x:this.#po[m]*c+u,y:this.#po[m+1]*d+p});return g.getOutlines()}}class tn{#eo;#To;#Mo;#Eo=[];#Po=[];constructor(t,e=0,s=0,i=!0){const n=u.slice(),r=1e-4;for(const{x:u,y:m,width:f,height:b}of t){const t=Math.floor((u-e)/r)*r,s=Math.ceil((u+f+e)/r)*r,i=Math.floor((m-e)/r)*r,a=Math.ceil((m+b+e)/r)*r,o=[t,i,a,!0],h=[s,i,a,!1];this.#Eo.push(o,h),pt.rectBoundingBox(t,i,s,a,n)}const a=n[2]-n[0]+2*s,o=n[3]-n[1]+2*s,h=n[0]-s,l=n[1]-s;let c=i?-1/0:1/0,d=1/0;const p=this.#Eo.at(i?-1:-2),g=[p[0],p[2]];for(const u of this.#Eo){const[t,e,s,n]=u;!n&&i?e<d?(d=e,c=t):e===d&&(c=Math.max(c,t)):n&&!i&&(e<d?(d=e,c=t):e===d&&(c=Math.min(c,t))),u[0]=(t-h)/a,u[1]=(e-l)/o,u[2]=(s-l)/o}this.#eo=new Float32Array([h,l,a,o]),this.#To=[c,d],this.#Mo=g}getOutlines(){this.#Eo.sort((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]);const t=[];for(const e of this.#Eo)e[3]?(t.push(...this.#Do(e)),this.#Io(e)):(this.#Fo(e),t.push(...this.#Do(e)));return this.#No(t)}#No(t){const e=[],s=new Set;for(const r of t){const[t,s,i]=r;e.push([t,s,r],[t,i,r])}e.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let r=0,a=e.length;r<a;r+=2){const t=e[r][2],i=e[r+1][2];t.push(i),i.push(t),s.add(t),s.add(i)}const i=[];let n;for(;s.size>0;){const t=s.values().next().value;let[e,r,a,o,h]=t;s.delete(t);let l=e,c=r;for(n=[e,a],i.push(n);;){let t;if(s.has(o))t=o;else{if(!s.has(h))break;t=h}s.delete(t),[e,r,a,o,h]=t,l!==e&&(n.push(l,c,e,c===r?r:a),l=e),c=c===r?a:r}n.push(l,c)}return new en(i,this.#eo,this.#To,this.#Mo)}#Ro(t){const e=this.#Po;let s=0,i=e.length-1;for(;s<=i;){const n=s+i>>1,r=e[n][0];if(r===t)return n;r<t?s=n+1:i=n-1}return i+1}#Io([,t,e]){const s=this.#Ro(t);this.#Po.splice(s,0,[t,e])}#Fo([,t,e]){const s=this.#Ro(t);for(let i=s;i<this.#Po.length;i++){const[s,n]=this.#Po[i];if(s!==t)break;if(s===t&&n===e)return void this.#Po.splice(i,1)}for(let i=s-1;i>=0;i--){const[s,n]=this.#Po[i];if(s!==t)break;if(s===t&&n===e)return void this.#Po.splice(i,1)}}#Do(t){const[e,s,i]=t,n=[[e,s,i]],r=this.#Ro(i);for(let a=0;a<r;a++){const[t,s]=this.#Po[a];for(let i=0,r=n.length;i<r;i++){const[,a,o]=n[i];if(!(s<=a||o<=t))if(a>=t)if(o>s)n[i][1]=s;else{if(1===r)return[];n.splice(i,1),i--,r--}else n[i][2]=t,o>s&&n.push([e,s,o])}}return n}}class en extends Qi{#eo;#Oo;constructor(t,e,s,i){super(),this.#Oo=t,this.#eo=e,this.firstPoint=s,this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#Oo){let[s,i]=e;t.push(`M${s} ${i}`);for(let n=2;n<e.length;n+=2){const r=e[n],a=e[n+1];r===s?(t.push(`V${a}`),i=a):a===i&&(t.push(`H${r}`),s=r)}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const r=[],a=s-t,o=i-e;for(const h of this.#Oo){const e=new Array(h.length);for(let s=0;s<h.length;s+=2)e[s]=t+h[s]*a,e[s+1]=i-h[s+1]*o;r.push(e)}return r}get box(){return this.#eo}get classNamesForOutlining(){return["highlightOutline"]}}class sn extends Ji{newFreeDrawOutline(t,e,s,i,n,r){return new nn(t,e,s,i,n,r)}}class nn extends Zi{newOutliner(t,e,s,i,n,r=0){return new sn(t,e,s,i,n,r)}}class rn extends se{#Bo=null;#Lo=0;#Uo;#jo=null;#r=null;#Ho=null;#$o=null;#zo=0;#Go=null;#Wo=null;#k=null;#Vo=!1;#To=null;#Mo=null;#Xo=null;#be="";#uo;#Yo="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=T.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=rn.prototype;return it(this,"_keyboardManager",new Kt([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"}),this.color=t.color||rn._defaultColor,this.#uo=t.thickness||rn._defaultThickness,this.opacity=t.opacity||rn._defaultOpacity,this.#Uo=t.boxes||null,this.#Yo=t.methodOfCreation||"",this.#be=t.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-1?(this.#Vo=!0,this.#qo(t),this.#Ko()):this.#Uo&&(this.#Bo=t.anchorNode,this.#Lo=t.anchorOffset,this.#$o=t.focusNode,this.#zo=t.focusOffset,this.#Qo(),this.#Ko(),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert(se._l10nAlert.highlight)}get telemetryInitialData(){return{action:"added",type:this.#Vo?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#uo,methodOfCreation:this.#Yo}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#Qo(){const t=new tn(this.#Uo,.001);this.#Wo=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#Wo.box;const e=new tn(this.#Uo,.0025,.001,"ltr"===this._uiManager.direction);this.#Ho=e.getOutlines();const{firstPoint:s}=this.#Wo;this.#To=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height];const{lastPoint:i}=this.#Ho;this.#Mo=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#qo({highlightOutlines:t,highlightId:e,clipPathId:s}){if(this.#Wo=t,this.#Ho=t.getNewOutline(this.#uo/2+1.5,.0025),e>=0)this.#k=e,this.#jo=s,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#Xo=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#Ho.box,path:{d:this.#Ho.toSVGPath()}},!0);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#k,{bbox:rn.#Jo(this.#Wo.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#Xo,{bbox:rn.#Jo(this.#Ho.box,e),path:{d:this.#Ho.toSVGPath()}})}const[i,n,r,a]=t.box;switch(this.rotation){case 0:this.x=i,this.y=n,this.width=r,this.height=a;break;case 90:{const[t,e]=this.parentDimensions;this.x=n,this.y=1-i,this.width=r*e/t,this.height=a*t/e;break}case 180:this.x=1-i,this.y=1-n,this.width=r,this.height=a;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n,this.y=i,this.width=r*e/t,this.height=a*t/e;break}}const{firstPoint:o}=t;this.#To=[(o[0]-i)/r,(o[1]-n)/a];const{lastPoint:h}=this.#Ho;this.#Mo=[(h[0]-i)/r,(h[1]-n)/a]}static initialize(t,e){se.initialize(t,e),rn._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case M.HIGHLIGHT_COLOR:rn._defaultColor=e;break;case M.HIGHLIGHT_THICKNESS:rn._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#Mo}get commentButtonPosition(){return this.#To}updateParams(t,e){switch(t){case M.HIGHLIGHT_COLOR:this.#Na(e);break;case M.HIGHLIGHT_THICKNESS:this.#Zo(e)}}static get defaultPropertiesToUpdate(){return[[M.HIGHLIGHT_COLOR,rn._defaultColor],[M.HIGHLIGHT_THICKNESS,rn._defaultThickness]]}get propertiesToUpdate(){return[[M.HIGHLIGHT_COLOR,this.color||rn._defaultColor],[M.HIGHLIGHT_THICKNESS,this.#uo||rn._defaultThickness],[M.HIGHLIGHT_FREE,this.#Vo]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#k,{root:{fill:this.color,"fill-opacity":this.opacity}}),this.#r?.updateColor(this.color),super.onUpdatedColor()}#Na(t){const e=(t,e)=>{this.color=t,this.opacity=e,this.onUpdatedColor()},s=this.color,i=this.opacity;this.addCommands({cmd:e.bind(this,t,rn._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:M.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#Zo(t){const e=this.#uo,s=t=>{this.#uo=t,this.#th(t)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:M.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){return this._uiManager.highlightColors?[["colorPicker",this.#r=new Fi({editor:this})]]:super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#eh())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#eh())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#sh(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#Ko(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#sh():t&&(this.#Ko(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#th(t){this.#Vo&&(this.#qo({highlightOutlines:this.#Wo.getNewOutline(t/2)}),this.fixAndSetPosition(),this.setDims())}#sh(){null!==this.#k&&this.parent&&(this.parent.drawLayer.remove(this.#k),this.#k=null,this.parent.drawLayer.remove(this.#Xo),this.#Xo=null)}#Ko(t=this.parent){null===this.#k&&(({id:this.#k,clipPathId:this.#jo}=t.drawLayer.draw({bbox:this.#Wo.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#Vo},path:{d:this.#Wo.toSVGPath()}},!1,!0)),this.#Xo=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Vo},bbox:this.#Ho.box,path:{d:this.#Ho.toSVGPath()}},this.#Vo),this.#Go&&(this.#Go.style.clipPath=this.#jo))}static#Jo([t,e,s,i],n){switch(n){case 90:return[1-e-i,t,i,s];case 180:return[1-t-s,1-e-i,s,i];case 270:return[e,1-t-s,i,s]}return[t,e,s,i]}rotate(t){const{drawLayer:e}=this.parent;let s;this.#Vo?(t=(t-this.rotation+360)%360,s=rn.#Jo(this.#Wo.box,t)):s=rn.#Jo([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#k,{bbox:s,root:{"data-main-rotation":t}}),e.updateProperties(this.#Xo,{bbox:rn.#Jo(this.#Ho.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#be&&(t.setAttribute("aria-label",this.#be),t.setAttribute("role","mark")),this.#Vo?t.classList.add("free"):this.div.addEventListener("keydown",this.#ih.bind(this),{signal:this._uiManager._signal});const e=this.#Go=document.createElement("div");return t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#jo,this.setDims(),Wt(this,this.#Go,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Xo,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Xo,{rootClass:{hovered:!1}})}#ih(t){rn._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#nh(!0);break;case 1:case 3:this.#nh(!1)}}#nh(t){if(!this.#Bo)return;const e=window.getSelection();t?e.setPosition(this.#Bo,this.#Lo):e.setPosition(this.#$o,this.#zo)}select(){super.select(),this.#Xo&&this.parent?.drawLayer.updateProperties(this.#Xo,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#Xo&&(this.parent?.drawLayer.updateProperties(this.#Xo,{rootClass:{selected:!1}}),this.#Vo||this.#nh(!1))}get _mustFixPosition(){return!this.#Vo}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#k,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#Xo,{rootClass:{hidden:!t}}))}#eh(){return this.#Vo?this.rotation:0}#rh(){if(this.#Vo)return null;const[t,e]=this.pageDimensions,[s,i]=this.pageTranslation,n=this.#Uo,r=new Float32Array(8*n.length);let a=0;for(const{x:o,y:h,width:l,height:c}of n){const n=o*t+s,d=(1-h)*e+i;r[a]=r[a+4]=n,r[a+1]=r[a+3]=d,r[a+2]=r[a+6]=n+l*t,r[a+5]=r[a+7]=d-c*e,a+=8}return r}#ah(t){return this.#Wo.serialize(t,this.#eh())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:r,y:a,width:o,height:h}=s.getBoundingClientRect(),l=new AbortController,c=t.combinedSignal(l),d=e=>{l.abort(),this.#oh(t,e)};window.addEventListener("blur",d,{signal:c}),window.addEventListener("pointerup",d,{signal:c}),window.addEventListener("pointerdown",Dt,{capture:!0,passive:!1,signal:c}),window.addEventListener("contextmenu",Pt,{signal:c}),s.addEventListener("pointermove",this.#hh.bind(this,t),{signal:c}),this._freeHighlight=new sn({x:i,y:n},[r,a,o,h],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#hh(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#oh(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,s){let i=null;if(t instanceof Xi){const{data:{quadPoints:e,rect:s,rotation:n,id:r,color:a,opacity:o,popupRef:h,richText:l,contentsObj:c,creationDate:d,modificationDate:u},parent:{page:{pageNumber:p}}}=t;i=t={annotationType:T.HIGHLIGHT,color:Array.from(a),opacity:o,quadPoints:e,boxes:null,pageIndex:p-1,rect:s.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:h,richText:l,comment:c?.str||null,creationDate:d,modificationDate:u}}else if(t instanceof Vi){const{data:{inkLists:e,rect:s,rotation:n,id:r,color:a,borderStyle:{rawWidth:o},popupRef:h,richText:l,contentsObj:c,creationDate:d,modificationDate:u},parent:{page:{pageNumber:p}}}=t;i=t={annotationType:T.HIGHLIGHT,color:Array.from(a),thickness:o,inkLists:e,boxes:null,pageIndex:p-1,rect:s.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:h,richText:l,comment:c?.str||null,creationDate:d,modificationDate:u}}const{color:n,quadPoints:r,inkLists:a,outlines:o,opacity:h}=t,l=await super.deserialize(t,e,s);l.color=pt.makeHexColor(...n),l.opacity=h||1,a&&(l.#uo=t.thickness),l._initialData=i,t.comment&&l.setCommentData(t);const[c,d]=l.pageDimensions,[u,p]=l.pageTranslation;if(r){const t=l.#Uo=[];for(let e=0;e<r.length;e+=8)t.push({x:(r[e]-u)/c,y:1-(r[e+1]-p)/d,width:(r[e+2]-r[e])/c,height:(r[e+1]-r[e+5])/d});l.#Qo(),l.#Ko(),l.rotate(l.rotation)}else if(a||o){l.#Vo=!0;const t=(a||o.points)[0],s={x:t[0]-u,y:d-(t[1]-p)},i=new sn(s,[0,0,c,d],1,l.#uo/2,!0,.001);for(let e=0,a=t.length;e<a;e+=2)s.x=t[e]-u,s.y=d-(t[e+1]-p),i.add(s);const{id:n,clipPathId:r}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:i.toSVGPath()}},!0,!0);l.#qo({highlightOutlines:i.getOutlines(),highlightId:n,clipPathId:r}),l.#Ko(),l.rotate(l.parentRotation)}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=se._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),s=super.serialize(t);return Object.assign(s,{color:e,opacity:this.opacity,thickness:this.#uo,quadPoints:this.#rh(),outlines:this.#ah(s.rect)}),this.addComment(s),this.annotationElementId&&!this.#to(s)?null:(s.id=this.annotationElementId,s)}#to(t){const{color:e}=this._initialData;return this.hasEditedComment||t.color.some((t,s)=>t!==e[s])}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}static canCreateNewEmptyEditor(){return!1}}class an{#lh=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,s]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,s)}updateSVGProperty(t,e){this.#lh[t]=e}toSVGProperties(){const t=this.#lh;return this.#lh=Object.create(null),{root:t}}reset(){this.#lh=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){Z("Not implemented")}}class on extends se{#ch=null;#dh;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#uh=null;static#ph=null;static#gh=null;static _INNER_MARGIN=3;constructor(t){super(t),this.#dh=t.mustBeCommitted||!1,this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color),super.onUpdatedColor()}onUpdatedOpacity(){this._colorPicker?.updateOpacity?.(this.opacity)}_addOutlines(t){t.drawOutlines&&(this.#mh(t),this.#Ko())}#mh({drawOutlines:t,drawId:e,drawingOptions:s}){this.#ch=t,this._drawingOptions||=s,this.annotationElementId||this._uiManager.a11yAlert(se._l10nAlert[this.editorType]),e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#fh(t,this.parent),this.#bh(t.box)}#fh(t,e){const{id:s}=e.drawLayer.draw(on._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return s}static _mergeSVGProperties(t,e){const s=new Set(Object.keys(t));for(const[i,n]of Object.entries(e))s.has(i)?Object.assign(t[i],n):t[i]=n;return t}static getDefaultDrawingOptions(t){Z("Not implemented")}static get typesMap(){Z("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const s=this.typesMap.get(t);s&&this._defaultDrawingOptions.updateProperty(s,e),this._currentParent&&(on.#uh.updateProperty(s,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const s=this.constructor.typesMap.get(t);s&&this._updateProperty(t,s,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[s,i]of this.typesMap)t.push([s,e[i]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[s,i]of this.constructor.typesMap)t.push([s,e[i]]);return t}_updateProperty(t,e,s){const i=this._drawingOptions,n=i[e],r=s=>{i.updateProperty(e,s);const n=this.#ch.updateProperty(e,s);n&&this.#bh(n),this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties()),t===this.colorType?this.onUpdatedColor():t===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:r.bind(this,s),undo:r.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(t,e){const s=this.constructor.typesMap.get(this.colorType),i=this.constructor.typesMap.get(this.opacityType),n=this._drawingOptions,r=n[s],a=n[i],o=(t,e)=>{n.updateProperty(s,t),n.updateProperty(i,e),this.#ch.updateProperty(s,t),this.#ch.updateProperty(i,e),this.parent?.drawLayer.updateProperties(this._drawId,n.toSVGProperties()),this.onUpdatedColor(),this.onUpdatedOpacity()};this.addCommands({cmd:o.bind(this,t,e),undo:o.bind(this,r,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:M.INK_COLOR_AND_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,on._mergeSVGProperties(this.#ch.getPathResizingSVGProperties(this.#yh()),{bbox:this.#Ah()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,on._mergeSVGProperties(this.#ch.getPathResizedSVGProperties(this.#yh()),{bbox:this.#Ah()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Ah()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,on._mergeSVGProperties(this.#ch.getPathTranslatedSVGProperties(this.#yh(),this.parentDimensions),{bbox:this.#Ah()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#dh&&(this.#dh=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#sh(),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#Ko(),this.#bh(this.#ch.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#sh()):t&&(this._uiManager.addShouldRescale(this),this.#Ko(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#sh(){null!==this._drawId&&this.parent&&(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#Ko(t=this.parent){null!==this._drawId&&this.parent===t||(null===this._drawId?(this._drawingOptions.updateAll(),this._drawId=this.#fh(this.#ch,t)):this.parent.drawLayer.updateParent(this._drawId,t.drawLayer))}#wh([t,e,s,i]){const{parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[e,1-t,s*(r/n),i*(n/r)];case 180:return[1-t,1-e,s,i];case 270:return[1-e,t,s*(r/n),i*(n/r)];default:return[t,e,s,i]}}#yh(){const{x:t,y:e,width:s,height:i,parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[1-e,t,s*(n/r),i*(r/n)];case 180:return[1-t,1-e,s,i];case 270:return[e,1-t,s*(n/r),i*(r/n)];default:return[t,e,s,i]}}#bh(t){[this.x,this.y,this.width,this.height]=this.#wh(t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()}#Ah(){const{x:t,y:e,width:s,height:i,rotation:n,parentRotation:r,parentDimensions:[a,o]}=this;switch((4*n+r)/90){case 1:return[1-e-i,t,i,s];case 2:return[1-t-s,1-e-i,s,i];case 3:return[e,1-t-s,i,s];case 4:return[t,e-s*(a/o),i*(o/a),s*(a/o)];case 5:return[1-e,t,s*(a/o),i*(o/a)];case 6:return[1-t-i*(o/a),1-e,i*(o/a),s*(a/o)];case 7:return[e-s*(a/o),1-t-i*(o/a),s*(a/o),i*(o/a)];case 8:return[t-s,e-i,s,i];case 9:return[1-e,t-s,i,s];case 10:return[1-t,1-e,s,i];case 11:return[e-i,1-t,i,s];case 12:return[t-i*(o/a),e,i*(o/a),s*(a/o)];case 13:return[1-e-s*(a/o),t-i*(o/a),s*(a/o),i*(o/a)];case 14:return[1-t,1-e-s*(a/o),i*(o/a),s*(a/o)];case 15:return[e,1-t,s*(a/o),i*(o/a)];default:return[t,e,s,i]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,on._mergeSVGProperties({bbox:this.#Ah()},this.#ch.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#bh(this.#ch.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;this._isCopy&&(t=this.x,e=this.y);const s=super.render();s.classList.add("draw");const i=document.createElement("div");return s.append(i),i.setAttribute("aria-hidden","true"),i.className="internal",this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,e),s}static createDrawerInstance(t,e,s,i,n){Z("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:r,offsetY:a,pointerId:o,pointerType:h}=i;if(Vt.isInitializedAndDifferentPointerType(h))return;const{viewport:{rotation:l}}=t,{width:c,height:d}=n.getBoundingClientRect(),u=on.#ph=new AbortController,p=t.combinedSignal(u);Vt.setPointer(h,o),window.addEventListener("pointerup",t=>{Vt.isSamePointerIdOrRemove(t.pointerId)&&this._endDraw(t)},{signal:p}),window.addEventListener("pointercancel",t=>{Vt.isSamePointerIdOrRemove(t.pointerId)&&this._currentParent.endDrawingSession()},{signal:p}),window.addEventListener("pointerdown",t=>{Vt.isSamePointerType(t.pointerType)&&(Vt.initializeAndAddPointerId(t.pointerId),on.#uh.isCancellable()&&(on.#uh.removeLastElement(),on.#uh.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:p}),window.addEventListener("contextmenu",Pt,{signal:p}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p}),n.addEventListener("touchmove",t=>{Vt.isSameTimeStamp(t.timeStamp)&&Dt(t)},{signal:p}),t.toggleDrawing(),e._editorUndoBar?.hide(),on.#uh?t.drawLayer.updateProperties(this._currentDrawId,on.#uh.startNew(r,a,c,d,l)):(e.updateUIForDefaultProperties(this),on.#uh=this.createDrawerInstance(r,a,c,d,l),on.#gh=this.getDefaultDrawingOptions(),this._currentParent=t,({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(on.#gh.toSVGProperties(),on.#uh.defaultSVGProperties),!0,!1)))}static _drawMove(t){if(Vt.isSameTimeStamp(t.timeStamp),!on.#uh)return;const{offsetX:e,offsetY:s,pointerId:i}=t;Vt.isSamePointerId(i)&&(Vt.isUsingMultiplePointers()?this._endDraw(t):(this._currentParent.drawLayer.updateProperties(this._currentDrawId,on.#uh.add(e,s)),Vt.setTimeStamp(t.timeStamp),Dt(t)))}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,on.#uh=null,on.#gh=null,Vt.clearTimeStamp()),on.#ph&&(on.#ph.abort(),on.#ph=null,Vt.clearPointerIds())}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,on.#uh.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const t=on.#uh,s=this._currentDrawId,i=t.getLastElement();return void e.addCommands({cmd:()=>{e.drawLayer.updateProperties(s,t.setLastElement(i))},undo:()=>{e.drawLayer.updateProperties(s,t.removeLastElement())},mustExec:!1,type:M.DRAW_STEP})}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(M.DRAW_STEP),!on.#uh.isEmpty()){const{pageDimensions:[s,i],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:on.#uh.getOutlines(s*n,i*n,n,this._INNER_MARGIN),drawingOptions:on.#gh,mustBeCommitted:!t});return this._cleanup(!0),r}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,s,i,n,r){Z("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:a}}=e.viewport,o=this.deserializeDraw(r,a,i,n,this._INNER_MARGIN,t),h=await super.deserialize(t,e,s);return h.createDrawingOptions(t),h.#mh({drawOutlines:o}),h.#Ko(),h.onScaleChanging(),h.rotate(),h}serializeDraw(t){const[e,s]=this.pageTranslation,[i,n]=this.pageDimensions;return this.#ch.serialize([e,s,i,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}}class hn{#ao=new Float64Array(6);#vh;#_h;#Yn;#uo;#po;#xh="";#Sh=0;#Oo=new ln;#Ch;#kh;constructor(t,e,s,i,n,r){this.#Ch=s,this.#kh=i,this.#Yn=n,this.#uo=r,[t,e]=this.#Th(t,e);const a=this.#vh=[NaN,NaN,NaN,NaN,t,e];this.#po=[t,e],this.#_h=[{line:a,points:this.#po}],this.#ao.set(a,0)}updateProperty(t,e){"stroke-width"===t&&(this.#uo=e)}#Th(t,e){return Qi._normalizePoint(t,e,this.#Ch,this.#kh,this.#Yn)}isEmpty(){return!this.#_h||0===this.#_h.length}isCancellable(){return this.#po.length<=10}add(t,e){[t,e]=this.#Th(t,e);const[s,i,n,r]=this.#ao.subarray(2,6),a=t-n,o=e-r;return Math.hypot(this.#Ch*a,this.#kh*o)<=2?null:(this.#po.push(t,e),isNaN(s)?(this.#ao.set([n,r,t,e],2),this.#vh.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#ao[0])&&this.#vh.splice(6,6),this.#ao.set([s,i,n,r,t,e],0),this.#vh.push(...Qi.createBezierPoints(s,i,n,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){return this.add(t,e)||(2===this.#po.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,s,i,n){this.#Ch=s,this.#kh=i,this.#Yn=n,[t,e]=this.#Th(t,e);const r=this.#vh=[NaN,NaN,NaN,NaN,t,e];this.#po=[t,e];const a=this.#_h.at(-1);return a&&(a.line=new Float32Array(a.line),a.points=new Float32Array(a.points)),this.#_h.push({line:r,points:this.#po}),this.#ao.set(r,0),this.#Sh=0,this.toSVGPath(),null}getLastElement(){return this.#_h.at(-1)}setLastElement(t){return this.#_h?(this.#_h.push(t),this.#vh=t.line,this.#po=t.points,this.#Sh=0,{path:{d:this.toSVGPath()}}):this.#Oo.setLastElement(t)}removeLastElement(){if(!this.#_h)return this.#Oo.removeLastElement();this.#_h.pop(),this.#xh="";for(let t=0,e=this.#_h.length;t<e;t++){const{line:e,points:s}=this.#_h[t];this.#vh=e,this.#po=s,this.#Sh=0,this.toSVGPath()}return{path:{d:this.#xh}}}toSVGPath(){const t=Qi.svgRound(this.#vh[4]),e=Qi.svgRound(this.#vh[5]);if(2===this.#po.length)return this.#xh=`${this.#xh} M ${t} ${e} Z`,this.#xh;if(this.#po.length<=6){const s=this.#xh.lastIndexOf("M");this.#xh=`${this.#xh.slice(0,s)} M ${t} ${e}`,this.#Sh=6}if(4===this.#po.length){const t=Qi.svgRound(this.#vh[10]),e=Qi.svgRound(this.#vh[11]);return this.#xh=`${this.#xh} L ${t} ${e}`,this.#Sh=12,this.#xh}const s=[];0===this.#Sh&&(s.push(`M ${t} ${e}`),this.#Sh=6);for(let i=this.#Sh,n=this.#vh.length;i<n;i+=6){const[t,e,n,r,a,o]=this.#vh.slice(i,i+6).map(Qi.svgRound);s.push(`C${t} ${e} ${n} ${r} ${a} ${o}`)}return this.#xh+=s.join(" "),this.#Sh=this.#vh.length,this.#xh}getOutlines(t,e,s,i){const n=this.#_h.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#Oo.build(this.#_h,t,e,s,this.#Yn,this.#uo,i),this.#ao=null,this.#vh=null,this.#_h=null,this.#xh=null,this.#Oo}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class ln extends Qi{#So;#Mh=0;#io;#_h;#Ch;#kh;#Eh;#Yn;#uo;build(t,e,s,i,n,r,a){this.#Ch=e,this.#kh=s,this.#Eh=i,this.#Yn=n,this.#uo=r,this.#io=a??0,this.#_h=t,this.#Ph()}get thickness(){return this.#uo}setLastElement(t){return this.#_h.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#_h.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#_h)if(t.push(`M${Qi.svgRound(e[4])} ${Qi.svgRound(e[5])}`),6!==e.length)if(12===e.length&&isNaN(e[6]))t.push(`L${Qi.svgRound(e[10])} ${Qi.svgRound(e[11])}`);else for(let s=6,i=e.length;s<i;s+=6){const[i,n,r,a,o,h]=e.subarray(s,s+6).map(Qi.svgRound);t.push(`C${i} ${n} ${r} ${a} ${o} ${h}`)}else t.push("Z");return t.join("")}serialize([t,e,s,i],n){const r=[],a=[],[o,h,l,c]=this.#Dh();let d,u,p,g,m,f,b,y,A;switch(this.#Yn){case 0:A=Qi._rescale,d=t,u=e+i,p=s,g=-i,m=t+o*s,f=e+(1-h-c)*i,b=t+(o+l)*s,y=e+(1-h)*i;break;case 90:A=Qi._rescaleAndSwap,d=t,u=e,p=s,g=i,m=t+h*s,f=e+o*i,b=t+(h+c)*s,y=e+(o+l)*i;break;case 180:A=Qi._rescale,d=t+s,u=e,p=-s,g=i,m=t+(1-o-l)*s,f=e+h*i,b=t+(1-o)*s,y=e+(h+c)*i;break;case 270:A=Qi._rescaleAndSwap,d=t+s,u=e+i,p=-s,g=-i,m=t+(1-h-c)*s,f=e+(1-o-l)*i,b=t+(1-h)*s,y=e+(1-o)*i}for(const{line:w,points:v}of this.#_h)r.push(A(w,d,u,p,g,n?new Array(w.length):null)),a.push(A(v,d,u,p,g,n?new Array(v.length):null));return{lines:r,points:a,rect:[m,f,b,y]}}static deserialize(t,e,s,i,n,{paths:{lines:r,points:a},rotation:o,thickness:h}){const l=[];let c,d,u,p,g;switch(o){case 0:g=Qi._rescale,c=-t/s,d=e/i+1,u=1/s,p=-1/i;break;case 90:g=Qi._rescaleAndSwap,c=-e/i,d=-t/s,u=1/i,p=1/s;break;case 180:g=Qi._rescale,c=t/s+1,d=-e/i,u=-1/s,p=1/i;break;case 270:g=Qi._rescaleAndSwap,c=e/i+1,d=t/s+1,u=-1/i,p=-1/s}if(!r){r=[];for(const t of a){const e=t.length;if(2===e){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const s=new Float32Array(3*(e-2));r.push(s);let[i,n,a,o]=t.subarray(0,4);s.set([NaN,NaN,NaN,NaN,i,n],0);for(let r=4;r<e;r+=2){const e=t[r],h=t[r+1];s.set(Qi.createBezierPoints(i,n,a,o,e,h),3*(r-2)),[i,n,a,o]=[a,o,e,h]}}}for(let f=0,b=r.length;f<b;f++)l.push({line:g(r[f].map(t=>t??NaN),c,d,u,p),points:g(a[f].map(t=>t??NaN),c,d,u,p)});const m=new this.prototype.constructor;return m.build(l,s,i,1,o,h,n),m}#Ih(t=this.#uo){const e=this.#io+t/2*this.#Eh;return this.#Yn%180==0?[e/this.#Ch,e/this.#kh]:[e/this.#kh,e/this.#Ch]}#Dh(){const[t,e,s,i]=this.#So,[n,r]=this.#Ih(0);return[t+n,e+r,s-2*n,i-2*r]}#Ph(){const t=this.#So=p.slice();for(const{line:i}of this.#_h){if(i.length<=12){for(let e=4,s=i.length;e<s;e+=6)pt.pointBoundingBox(i[e],i[e+1],t);continue}let e=i[4],s=i[5];for(let n=6,r=i.length;n<r;n+=6){const[r,a,o,h,l,c]=i.subarray(n,n+6);pt.bezierBoundingBox(e,s,r,a,o,h,l,c,t),e=l,s=c}}const[e,s]=this.#Ih();t[0]=yt(t[0]-e,0,1),t[1]=yt(t[1]-s,0,1),t[2]=yt(t[2]+e,0,1),t[3]=yt(t[3]+s,0,1),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#So}updateProperty(t,e){return"stroke-width"===t?this.#Zo(e):null}#Zo(t){const[e,s]=this.#Ih();this.#uo=t;const[i,n]=this.#Ih(),[r,a]=[i-e,n-s],o=this.#So;return o[0]-=r,o[1]-=a,o[2]+=2*r,o[3]+=2*a,o}updateParentDimensions([t,e],s){const[i,n]=this.#Ih();this.#Ch=t,this.#kh=e,this.#Eh=s;const[r,a]=this.#Ih(),o=r-i,h=a-n,l=this.#So;return l[0]-=o,l[1]-=h,l[2]+=2*o,l[3]+=2*h,l}updateRotation(t){return this.#Mh=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#So.map(Qi.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#So;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Qi.svgRound(t)} ${Qi.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#So;let s=0,i=0,n=0,r=0,a=0,o=0;switch(this.#Mh){case 90:i=e/t,n=-t/e,a=t;break;case 180:s=-1,r=-1,a=t,o=e;break;case 270:i=-e/t,n=t/e,o=e;break;default:return""}return`matrix(${s} ${i} ${n} ${r} ${Qi.svgRound(a)} ${Qi.svgRound(o)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,r]=this.#Ih(),[a,o,h,l]=this.#So;if(Math.abs(h-n)<=Qi.PRECISION||Math.abs(l-r)<=Qi.PRECISION){const n=t+s/2-(a+h/2),r=e+i/2-(o+l/2);return{path:{"transform-origin":`${Qi.svgRound(t)} ${Qi.svgRound(e)}`,transform:`${this.rotationTransform} translate(${n} ${r})`}}}const c=(s-2*n)/(h-2*n),d=(i-2*r)/(l-2*r),u=h/s,p=l/i;return{path:{"transform-origin":`${Qi.svgRound(a)} ${Qi.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${Qi.svgRound(n)} ${Qi.svgRound(r)}) scale(${c} ${d}) translate(${Qi.svgRound(-n)} ${Qi.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,r]=this.#Ih(),a=this.#So,[o,h,l,c]=a;if(a[0]=t,a[1]=e,a[2]=s,a[3]=i,Math.abs(l-n)<=Qi.PRECISION||Math.abs(c-r)<=Qi.PRECISION){const n=t+s/2-(o+l/2),r=e+i/2-(h+c/2);for(const{line:t,points:e}of this.#_h)Qi._translate(t,n,r,t),Qi._translate(e,n,r,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Qi.svgRound(t)} ${Qi.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(s-2*n)/(l-2*n),u=(i-2*r)/(c-2*r),p=-d*(o+n)+t+n,g=-u*(h+r)+e+r;if(1!==d||1!==u||0!==p||0!==g)for(const{line:m,points:f}of this.#_h)Qi._rescale(m,p,g,d,u,m),Qi._rescale(f,p,g,d,u,f);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Qi.svgRound(t)} ${Qi.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],s){const[i,n]=s,r=this.#So,a=t-r[0],o=e-r[1];if(this.#Ch===i&&this.#kh===n)for(const{line:h,points:l}of this.#_h)Qi._translate(h,a,o,h),Qi._translate(l,a,o,l);else{const t=this.#Ch/i,e=this.#kh/n;this.#Ch=i,this.#kh=n;for(const{line:s,points:i}of this.#_h)Qi._rescale(s,a,o,t,e,s),Qi._rescale(i,a,o,t,e,i);r[2]*=t,r[3]*=e}return r[0]=t,r[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Qi.svgRound(t)} ${Qi.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#So;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Qi.svgRound(t[0])} ${Qi.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class cn extends an{constructor(t){super(),this._viewParameters=t,super.updateProperties({fill:"none",stroke:se._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){"stroke-width"===t&&(e??=this["stroke-width"],e*=this._viewParameters.realScale),super.updateSVGProperty(t,e)}clone(){const t=new cn(this._viewParameters);return t.updateAll(this),t}}class dn extends on{static _type="ink";static _editorType=T.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){se.initialize(t,e),this._defaultDrawingOptions=new cn(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return it(this,"typesMap",new Map([[M.INK_THICKNESS,"stroke-width"],[M.INK_COLOR,"stroke"],[M.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new hn(t,e,s,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,s,i,n,r){return ln.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){let i=null;if(t instanceof Vi){const{data:{inkLists:e,rect:s,rotation:n,id:r,color:a,opacity:o,borderStyle:{rawWidth:h},popupRef:l,richText:c,contentsObj:d,creationDate:u,modificationDate:p},parent:{page:{pageNumber:g}}}=t;i=t={annotationType:T.INK,color:Array.from(a),thickness:h,opacity:o,paths:{points:e},boxes:null,pageIndex:g-1,rect:s.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:c,comment:d?.str||null,creationDate:u,modificationDate:p}}const n=await super.deserialize(t,e,s);return n._initialData=i,t.comment&&n.setCommentData(t),n}get toolbarButtons(){return this._colorPicker||=new Ni(this),[["colorPicker",this._colorPicker]]}get colorType(){return M.INK_COLOR}get colorAndOpacityType(){return M.INK_COLOR_AND_OPACITY}get opacityType(){return M.INK_OPACITY}updateParams(t,e){t!==M.INK_COLOR_AND_OPACITY?super.updateParams(t,e):this._updateColorAndOpacity(e.color,e.opacity)}static updateDefaultParams(t,e){t!==M.INK_COLOR_AND_OPACITY?super.updateDefaultParams(t,e):(super.updateDefaultParams(M.INK_COLOR,e.color),super.updateDefaultParams(M.INK_OPACITY,e.opacity))}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:s}=this;e.updateSVGProperty("stroke-width"),s.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:s}){this._drawingOptions=dn.getDefaultDrawingOptions({stroke:pt.makeHexColor(...t),"stroke-width":e,"stroke-opacity":s})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:s}=this.serializeDraw(t),{_drawingOptions:{stroke:i,"stroke-opacity":n,"stroke-width":r}}=this,a=Object.assign(super.serialize(t),{color:se._colorManager.convert(i),opacity:n,thickness:r,paths:{lines:e,points:s}});return this.addComment(a),t?(a.isCopy=!0,a):this.annotationElementId&&!this.#to(a)?null:(a.id=this.annotationElementId,a)}#to(t){const{color:e,thickness:s,opacity:i,pageIndex:n}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((t,s)=>t!==e[s])||t.thickness!==s||t.opacity!==i||t.pageIndex!==n}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const{points:e,rect:s}=this.serializeDraw(!1);return t.updateEdited({rect:s,thickness:this._drawingOptions["stroke-width"],points:e,popup:this.comment}),null}}class un extends ln{toSVGPath(){let t=super.toSVGPath();return t.endsWith("Z")||(t+="Z"),t}}class pn{static#Fh={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#Nh(t,e,s,i){return i-=e,0===(s-=t)?i>0?0:4:1===s?i+6:2-i}static#Rh=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#Oh(t,e,s,i,n,r,a){const o=this.#Nh(s,i,n,r);for(let h=0;h<8;h++){const n=(-h+o-a+16)%8;if(0!==t[(s+this.#Rh[2*n])*e+(i+this.#Rh[2*n+1])])return n}return-1}static#Bh(t,e,s,i,n,r,a){const o=this.#Nh(s,i,n,r);for(let h=0;h<8;h++){const n=(h+o+a+16)%8;if(0!==t[(s+this.#Rh[2*n])*e+(i+this.#Rh[2*n+1])])return n}return-1}static#Lh(t,e,s,i){const n=t.length,r=new Int32Array(n);for(let l=0;l<n;l++)r[l]=t[l]<=i?1:0;for(let l=1;l<s-1;l++)r[l*e]=r[l*e+e-1]=0;for(let l=0;l<e;l++)r[l]=r[e*s-1-l]=0;let a,o=1;const h=[];for(let l=1;l<s-1;l++){a=1;for(let t=1;t<e-1;t++){const s=l*e+t,i=r[s];if(0===i)continue;let n=l,c=t;if(1===i&&0===r[s-1])o+=1,c-=1;else{if(!(i>=1&&0===r[s+1])){1!==i&&(a=Math.abs(i));continue}o+=1,c+=1,i>1&&(a=i)}const d=[t,l],u=c===t+1,p={isHole:u,points:d,id:o,parent:0};let g;h.push(p);for(const t of h)if(t.id===a){g=t;break}g?g.isHole?p.parent=u?g.parent:a:p.parent=u?a:g.parent:p.parent=u?a:0;const m=this.#Oh(r,e,l,t,n,c,0);if(-1===m){r[s]=-o,1!==r[s]&&(a=Math.abs(r[s]));continue}let f=this.#Rh[2*m],b=this.#Rh[2*m+1];const y=l+f,A=t+b;n=y,c=A;let w=l,v=t;for(;;){const i=this.#Bh(r,e,w,v,n,c,1);f=this.#Rh[2*i],b=this.#Rh[2*i+1];const h=w+f,u=v+b;d.push(u,h);const p=w*e+v;if(0===r[p+1]?r[p]=-o:1===r[p]&&(r[p]=o),h===l&&u===t&&w===y&&v===A){1!==r[s]&&(a=Math.abs(r[s]));break}n=w,c=v,w=h,v=u}}}return h}static#Uh(t,e,s,i){if(s-e<=4){for(let n=e;n<s-2;n+=2)i.push(t[n],t[n+1]);return}const n=t[e],r=t[e+1],a=t[s-4]-n,o=t[s-3]-r,h=Math.hypot(a,o),l=a/h,c=o/h,d=l*r-c*n,u=o/a,p=1/h,g=Math.atan(u),m=Math.cos(g),f=Math.sin(g),b=p*(Math.abs(m)+Math.abs(f)),y=p*(1-b+b**2),A=Math.max(Math.atan(Math.abs(f+m)*y),Math.atan(Math.abs(f-m)*y));let w=0,v=e;for(let _=e+2;_<s-2;_+=2){const e=Math.abs(d-l*t[_+1]+c*t[_]);e>w&&(v=_,w=e)}w>(h*A)**2?(this.#Uh(t,e,v+2,i),this.#Uh(t,v,s,i)):i.push(n,r)}static#jh(t){const e=[],s=t.length;return this.#Uh(t,0,s,e),e.push(t[s-2],t[s-1]),e.length<=4?null:e}static#Hh(t,e,s,i,n,r){const a=new Float32Array(r**2),o=-2*i**2,h=r>>1;for(let g=0;g<r;g++){const t=(g-h)**2;for(let e=0;e<r;e++)a[g*r+e]=Math.exp((t+(e-h)**2)/o)}const l=new Float32Array(256),c=-2*n**2;for(let g=0;g<256;g++)l[g]=Math.exp(g**2/c);const d=t.length,u=new Uint8Array(d),p=new Uint32Array(256);for(let g=0;g<s;g++)for(let i=0;i<e;i++){const n=g*e+i,o=t[n];let c=0,d=0;for(let u=0;u<r;u++){const n=g+u-h;if(!(n<0||n>=s))for(let s=0;s<r;s++){const p=i+s-h;if(p<0||p>=e)continue;const g=t[n*e+p],m=a[u*r+s]*l[Math.abs(g-o)];c+=g*m,d+=m}}p[u[n]=Math.round(c/d)]++}return[u,p]}static#$h(t){const e=new Uint32Array(256);for(const s of t)e[s]++;return e}static#zh(t){const e=t.length,s=new Uint8ClampedArray(e>>2);let i=-1/0,n=1/0;for(let a=0,o=s.length;a<o;a++){const e=s[a]=t[a<<2];i=Math.max(i,e),n=Math.min(n,e)}const r=255/(i-n);for(let a=0,o=s.length;a<o;a++)s[a]=(s[a]-n)*r;return s}static#Gh(t){let e,s=-1/0,i=-1/0;const n=t.findIndex(t=>0!==t);let r=n,a=n;for(e=n;e<256;e++){const n=t[e];n>s&&(e-r>i&&(i=e-r,a=e-1),s=n,r=e)}for(e=a-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#Wh(t){const e=t,{width:s,height:i}=t,{maxDim:n}=this.#Fh;let r=s,a=i;if(s>n||i>n){let o=s,h=i,l=Math.log2(Math.max(s,i)/n);const c=Math.floor(l);l=l===c?c-1:c;for(let s=0;s<l;s++){r=Math.ceil(o/2),a=Math.ceil(h/2);const s=new OffscreenCanvas(r,a);s.getContext("2d").drawImage(t,0,0,o,h,0,0,r,a),o=r,h=a,t!==e&&t.close(),t=s.transferToImageBitmap()}const d=Math.min(n/r,n/a);r=Math.round(r*d),a=Math.round(a*d)}const o=new OffscreenCanvas(r,a).getContext("2d",{willReadFrequently:!0});o.fillStyle="white",o.fillRect(0,0,r,a),o.filter="grayscale(1)",o.drawImage(t,0,0,t.width,t.height,0,0,r,a);const h=o.getImageData(0,0,r,a).data;return[this.#zh(h),r,a]}static extractContoursFromText(t,{fontFamily:e,fontStyle:s,fontWeight:i},n,r,a,o){let h=new OffscreenCanvas(1,1),l=h.getContext("2d",{alpha:!1});const c=l.font=`${s} ${i} 200px ${e}`,{actualBoundingBoxLeft:d,actualBoundingBoxRight:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g,fontBoundingBoxAscent:m,fontBoundingBoxDescent:f,width:b}=l.measureText(t),y=1.5,A=Math.ceil(Math.max(Math.abs(d)+Math.abs(u)||0,b)*y),w=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||200,Math.abs(m)+Math.abs(f)||200)*y);h=new OffscreenCanvas(A,w),l=h.getContext("2d",{alpha:!0,willReadFrequently:!0}),l.font=c,l.filter="grayscale(1)",l.fillStyle="white",l.fillRect(0,0,A,w),l.fillStyle="black",l.fillText(t,.5*A/2,1.5*w/2);const v=this.#zh(l.getImageData(0,0,A,w).data),_=this.#$h(v),x=this.#Gh(_),S=this.#Lh(v,A,w,x);return this.processDrawnLines({lines:{curves:S,width:A,height:w},pageWidth:n,pageHeight:r,rotation:a,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,s,i,n){const[r,a,o]=this.#Wh(t),[h,l]=this.#Hh(r,a,o,Math.hypot(a,o)*this.#Fh.sigmaSFactor,this.#Fh.sigmaR,this.#Fh.kernelSize),c=this.#Gh(l),d=this.#Lh(h,a,o,c);return this.processDrawnLines({lines:{curves:d,width:a,height:o},pageWidth:e,pageHeight:s,rotation:i,innerMargin:n,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:s,rotation:i,innerMargin:n,mustSmooth:r,areContours:a}){i%180!=0&&([e,s]=[s,e]);const{curves:o,width:h,height:l}=t,c=t.thickness??0,d=[],u=Math.min(e/h,s/l),p=u/e,g=u/s,m=[];for(const{points:b}of o){const t=r?this.#jh(b):b;if(!t)continue;m.push(t);const e=t.length,s=new Float32Array(e),i=new Float32Array(3*(2===e?2:e-2));if(d.push({line:i,points:s}),2===e){s[0]=t[0]*p,s[1]=t[1]*g,i.set([NaN,NaN,NaN,NaN,s[0],s[1]],0);continue}let[n,a,o,h]=t;n*=p,a*=g,o*=p,h*=g,s.set([n,a,o,h],0),i.set([NaN,NaN,NaN,NaN,n,a],0);for(let r=4;r<e;r+=2){const e=s[r]=t[r]*p,l=s[r+1]=t[r+1]*g;i.set(Qi.createBezierPoints(n,a,o,h,e,l),3*(r-2)),[n,a,o,h]=[o,h,e,l]}}if(0===d.length)return null;const f=a?new un:new ln;return f.build(d,e,s,1,i,a?0:c,n),{outline:f,newCurves:m,areContours:a,thickness:c,width:h,height:l}}static async compressSignature({outlines:t,areContours:e,thickness:s,width:i,height:n}){let r,a=1/0,o=-1/0,h=0;for(const f of t){h+=f.length;for(let t=2,e=f.length;t<e;t++){const e=f[t]-f[t-2];a=Math.min(a,e),o=Math.max(o,e)}}r=a>=-128&&o<=127?Int8Array:a>=-32768&&o<=32767?Int16Array:Int32Array;const l=t.length,c=8+3*l,d=new Uint32Array(c);let u=0;d[u++]=c*Uint32Array.BYTES_PER_ELEMENT+(h-2*l)*r.BYTES_PER_ELEMENT,d[u++]=0,d[u++]=i,d[u++]=n,d[u++]=e?0:1,d[u++]=Math.max(0,Math.floor(s??0)),d[u++]=l,d[u++]=r.BYTES_PER_ELEMENT;for(const f of t)d[u++]=f.length-2,d[u++]=f[0],d[u++]=f[1];const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready,g.write(d);const m=r.prototype.constructor;for(const f of t){const t=new m(f.length-2);for(let e=2,s=f.length;e<s;e++)t[e-2]=f[e]-f[e-2];g.write(t)}return g.close(),(await new Response(p.readable).bytes()).toBase64()}static async decompressSignature(t){try{const e=Uint8Array.fromBase64(t),{readable:s,writable:i}=new DecompressionStream("deflate-raw"),n=i.getWriter();await n.ready,n.write(e).then(async()=>{await n.ready,await n.close()}).catch(()=>{});let r=null,a=0;for await(const t of s)r||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]),r.set(t,a),a+=t.length;const o=new Uint32Array(r.buffer,0,r.length>>2),h=o[1];if(0!==h)throw new Error(`Invalid version: ${h}`);const l=o[2],c=o[3],d=0===o[4],u=o[5],p=o[6],g=o[7],m=[],f=(8+3*p)*Uint32Array.BYTES_PER_ELEMENT;let b;switch(g){case Int8Array.BYTES_PER_ELEMENT:b=new Int8Array(r.buffer,f);break;case Int16Array.BYTES_PER_ELEMENT:b=new Int16Array(r.buffer,f);break;case Int32Array.BYTES_PER_ELEMENT:b=new Int32Array(r.buffer,f)}a=0;for(let t=0;t<p;t++){const e=o[3*t+8],s=new Float32Array(e+2);m.push(s);for(let i=0;i<2;i++)s[i]=o[3*t+8+i+1];for(let t=0;t<e;t++)s[t+2]=s[t]+b[a++]}return{areContours:d,thickness:u,outlines:m,width:l,height:c}}catch(t){return J(`decompressSignature: ${t}`),null}}}class gn extends an{constructor(){super(),super.updateProperties({fill:se._defaultLineColor,"stroke-width":0})}clone(){const t=new gn;return t.updateAll(this),t}}class mn extends cn{constructor(t){super(t),super.updateProperties({stroke:se._defaultLineColor,"stroke-width":1})}clone(){const t=new mn(this._viewParameters);return t.updateAll(this),t}}class fn extends on{#Vh=!1;#Xh=null;#Yh=null;#qh=null;static _type="signature";static _editorType=T.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"}),this._willKeepAspectRatio=!0,this.#Yh=t.signatureData||null,this.#Xh=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){se.initialize(t,e),this._defaultDrawingOptions=new gn,this._defaultDrawnSignatureOptions=new mn(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!1}static get typesMap(){return it(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#Xh}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){null!==this._drawId&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:s}=this;if(s&&(this._isCopy=!1,t=this.x,e=this.y),super.render(),null===this._drawId)if(this.#Yh){const{lines:t,mustSmooth:e,areContours:s,description:i,uuid:n,heightInPage:r}=this.#Yh,{rawDims:{pageWidth:a,pageHeight:o},rotation:h}=this.parent.viewport,l=pn.processDrawnLines({lines:t,pageWidth:a,pageHeight:o,rotation:h,innerMargin:fn._INNER_MARGIN,mustSmooth:e,areContours:s});this.addSignature(l,r,i,n)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);else this.div.setAttribute("data-l10n-args",JSON.stringify({description:this.#Xh||""}));return s&&(this._isCopy=!0,this._moveAfterPaste(t,e)),this.div}setUuid(t){this.#qh=t,this.addEditToolbar()}getUuid(){return this.#qh}get description(){return this.#Xh}set description(t){this.#Xh=t,this.div&&(this.div.setAttribute("data-l10n-args",JSON.stringify({description:t})),super.addEditToolbar().then(e=>{e?.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:s,width:i,height:n}=this.#Yh,r=Math.max(i,n);return{areContours:e,outline:pn.processDrawnLines({lines:{curves:t.map(t=>({points:t})),thickness:s,width:i,height:n},pageWidth:r,pageHeight:r,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,e,s,i){const{x:n,y:r}=this,{outline:a}=this.#Yh=t;let o;this.#Vh=a instanceof un,this.description=s,this.#Vh?o=fn.getDefaultDrawingOptions():(o=fn._defaultDrawnSignatureOptions.clone(),o.updateProperties({"stroke-width":a.thickness})),this._addOutlines({drawOutlines:a,drawingOptions:o});const[,h]=this.pageDimensions;let l=e/h;l=l>=1?.5:l,this.width*=l/this.height,this.width>=1&&(l*=.9/this.width,this.width=.9),this.height=l,this.setDims(),this.x=n,this.y=r,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(i),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!i,hasDescription:!!s}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:s},rotation:i}=this.parent.viewport;return pn.process(t,e,s,i,fn._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:s,pageHeight:i},rotation:n}=this.parent.viewport;return pn.extractContoursFromText(t,e,s,i,n,fn._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:s},rotation:i}=this.parent.viewport;return pn.processDrawnLines({lines:t,pageWidth:e,pageHeight:s,rotation:i,innerMargin:fn._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){t?this._drawingOptions=fn.getDefaultDrawingOptions():(this._drawingOptions=fn._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":e}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:s}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":i}}=this,n=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#Vh,color:[0,0,0],thickness:this.#Vh?0:i});return this.addComment(n),t?(n.paths={lines:e,points:s},n.uuid=this.#qh,n.isCopy=!0):n.lines=e,this.#Xh&&(n.accessibilityData={type:"Figure",alt:this.#Xh}),n}static deserializeDraw(t,e,s,i,n,r){return r.areContours?un.deserialize(t,e,s,i,n,r):ln.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){const i=await super.deserialize(t,e,s);return i.#Vh=t.areContours,i.description=t.accessibilityData?.alt||"",i.#qh=t.uuid,i}}class bn extends se{#Kh=null;#Qh=null;#Jh=null;#Zh=null;#tl=null;#el="";#sl=null;#il=!1;#nl=null;#rl=!1;#al=!1;static _type="stamp";static _editorType=T.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#Zh=t.bitmapUrl,this.#tl=t.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){se.initialize(t,e)}static isHandlingMimeForPasting(t){return Ut.includes(t)}static paste(t,e){e.pasteEditor({mode:T.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#ol(t,e=!1){t?(this.#Kh=t.bitmap,e||(this.#Qh=t.id,this.#rl=t.isSvg),t.file&&(this.#el=t.file.name),this.#hl()):this.remove()}#ll(){if(this.#Jh=null,this._uiManager.enableWaiting(!1),this.#sl)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Kh)this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Kh){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:s}=this._uiManager;if(!s)throw new Error("No ML.");if(!await s.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:n,height:r}=t||this.copyCanvas(null,null,!0).imageData,a=await s.guess({name:"altText",request:{data:i,width:n,height:r,channels:i.length/(n*r)}});if(!a)throw new Error("No response from the AI service.");if(a.error)throw new Error("Error from the AI service.");if(a.cancel)return null;if(!a.output)throw new Error("No valid response from the AI service.");const o=a.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#cl(){if(this.#Qh)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#Qh).then(t=>this.#ol(t,!0)).finally(()=>this.#ll());if(this.#Zh){const t=this.#Zh;return this.#Zh=null,this._uiManager.enableWaiting(!0),void(this.#Jh=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#ol(t)).finally(()=>this.#ll()))}if(this.#tl){const t=this.#tl;return this.#tl=null,this._uiManager.enableWaiting(!0),void(this.#Jh=this._uiManager.imageManager.getFromFile(t).then(t=>this.#ol(t)).finally(()=>this.#ll()))}const t=document.createElement("input");t.type="file",t.accept=Ut.join(",");const e=this._uiManager._signal;this.#Jh=new Promise(s=>{t.addEventListener("change",async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#ol(e)}else this.remove();s()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),s()},{signal:e})}).finally(()=>this.#ll()),t.click()}remove(){this.#Qh&&(this.#Kh=null,this._uiManager.imageManager.deleteId(this.#Qh),this.#sl?.remove(),this.#sl=null,this.#nl&&(clearTimeout(this.#nl),this.#nl=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#Qh&&null===this.#sl&&this.#cl(),this.isAttachedToDOM||this.parent.add(this))):this.#Qh&&this.#cl()}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#Jh||this.#Kh||this.#Zh||this.#tl||this.#Qh||this.#il)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;return this._isCopy&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.createAltText(),this.#il||(this.#Kh?this.#hl():this.#cl()),this._isCopy&&this._moveAfterPaste(t,e),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,e){const{id:s,bitmap:i}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove(),s&&this._uiManager.imageManager.isValidId(s)&&(this.#Qh=s,i&&(this.#Kh=i),this.#il=!1,this.#hl())}_onResized(){this.onScaleChanging()}onScaleChanging(){this.parent&&(null!==this.#nl&&clearTimeout(this.#nl),this.#nl=setTimeout(()=>{this.#nl=null,this.#dl()},200))}#hl(){const{div:t}=this;let{width:e,height:s}=this.#Kh;const[i,n]=this.pageDimensions,r=.75;if(this.width)e=this.width*i,s=this.height*n;else if(e>r*i||s>r*n){const t=Math.min(r*i/e,r*n/s);e*=t,s*=t}this._uiManager.enableWaiting(!1);const a=this.#sl=document.createElement("canvas");a.setAttribute("role","img"),this.addContainer(a),this.width=e/i,this.height=s/n,this.setDims(),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#dl(),this.#al||(this.parent.addUndoableEditor(this),this.#al=!0),this._reportTelemetry({action:"inserted_image"}),this.#el&&this.div.setAttribute("aria-description",this.#el),this.annotationElementId||this._uiManager.a11yAlert(se._l10nAlert.stamp)}copyCanvas(t,e,s=!1){t||(t=224);const{width:i,height:n}=this.#Kh,r=new Lt;let a=this.#Kh,o=i,h=n,l=null;if(e){if(i>e||n>e){const t=Math.min(e/i,e/n);o=Math.floor(i*t),h=Math.floor(n*t)}l=document.createElement("canvas");const t=l.width=Math.ceil(o*r.sx),s=l.height=Math.ceil(h*r.sy);this.#rl||(a=this.#ul(t,s));const c=l.getContext("2d");c.filter=this._uiManager.hcmFilter;let d="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":jt.isDarkMode&&(d="#8f8f9d",u="#42414d");const p=15,g=p*r.sx,m=p*r.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=d,b.fillRect(0,0,2*g,2*m),b.fillStyle=u,b.fillRect(0,0,g,m),b.fillRect(g,m,g,m),c.fillStyle=c.createPattern(f,"repeat"),c.fillRect(0,0,t,s),c.drawImage(a,0,0,a.width,a.height,0,0,t,s)}let c=null;if(s){let e,s;if(r.symmetric&&a.width<t&&a.height<t)e=a.width,s=a.height;else if(a=this.#Kh,i>t||n>t){const r=Math.min(t/i,t/n);e=Math.floor(i*r),s=Math.floor(n*r),this.#rl||(a=this.#ul(e,s))}const o=new OffscreenCanvas(e,s).getContext("2d",{willReadFrequently:!0});o.drawImage(a,0,0,a.width,a.height,0,0,e,s),c={width:e,height:s,data:o.getImageData(0,0,e,s).data}}return{canvas:l,width:o,height:h,imageData:c}}#ul(t,e){const{width:s,height:i}=this.#Kh;let n=s,r=i,a=this.#Kh;for(;n>2*t||r>2*e;){const s=n,i=r;n>2*t&&(n=Math.ceil(n/2)),r>2*e&&(r=Math.ceil(r/2));const o=new OffscreenCanvas(n,r);o.getContext("2d").drawImage(a,0,0,s,i,0,0,n,r),a=o.transferToImageBitmap()}return a}#dl(){const[t,e]=this.parentDimensions,{width:s,height:i}=this,n=new Lt,r=Math.ceil(s*t*n.sx),a=Math.ceil(i*e*n.sy),o=this.#sl;if(!o||o.width===r&&o.height===a)return;o.width=r,o.height=a;const h=this.#rl?this.#Kh:this.#ul(r,a),l=o.getContext("2d");l.filter=this._uiManager.hcmFilter,l.drawImage(h,0,0,h.width,h.height,0,0,r,a)}#pl(t){if(t){if(this.#rl){const t=this._uiManager.imageManager.getSvgUrl(this.#Qh);if(t)return t}const t=document.createElement("canvas");return({width:t.width,height:t.height}=this.#Kh),t.getContext("2d").drawImage(this.#Kh,0,0),t.toDataURL()}if(this.#rl){const[t,e]=this.pageDimensions,s=Math.round(this.width*t*_t.PDF_TO_CSS_UNITS),i=Math.round(this.height*e*_t.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(s,i);return n.getContext("2d").drawImage(this.#Kh,0,0,this.#Kh.width,this.#Kh.height,0,0,s,i),n.transferToImageBitmap()}return structuredClone(this.#Kh)}static async deserialize(t,e,s){let i=null,n=!1;if(t instanceof Yi){const{data:{rect:r,rotation:a,id:o,structParent:h,popupRef:l,richText:c,contentsObj:d,creationDate:u,modificationDate:p},container:g,parent:{page:{pageNumber:m}},canvas:f}=t;let b,y;f?(delete t.canvas,({id:b,bitmap:y}=s.imageManager.getFromCanvas(g.id,f)),f.remove()):(n=!0,t._hasNoCanvas=!0);const A=(await e._structTree.getAriaAttributes(`${C}${o}`))?.get("aria-label")||"";i=t={annotationType:T.STAMP,bitmapId:b,bitmap:y,pageIndex:m-1,rect:r.slice(0),rotation:a,annotationElementId:o,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:A},isSvg:!1,structParent:h,popupRef:l,richText:c,comment:d?.str||null,creationDate:u,modificationDate:p}}const r=await super.deserialize(t,e,s),{rect:a,bitmap:o,bitmapUrl:h,bitmapId:l,isSvg:c,accessibilityData:d}=t;n?(s.addMissingCanvas(t.id,r),r.#il=!0):l&&s.imageManager.isValidId(l)?(r.#Qh=l,o&&(r.#Kh=o)):r.#Zh=h,r.#rl=c;const[u,p]=r.pageDimensions;return r.width=(a[2]-a[0])/u,r.height=(a[3]-a[1])/p,d&&(r.altTextData=d),r._initialData=i,t.comment&&r.setCommentData(t),r.#al=!!i,r}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s=Object.assign(super.serialize(t),{bitmapId:this.#Qh,isSvg:this.#rl});if(this.addComment(s),t)return s.bitmapUrl=this.#pl(!0),s.accessibilityData=this.serializeAltText(!0),s.isCopy=!0,s;const{decorative:i,altText:n}=this.serializeAltText(!1);if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const t=this.#to(s);return t.isSame?null:(t.isSameAltText?delete s.accessibilityData:s.accessibilityData.structParent=this._initialData.structParent??-1,s.id=this.annotationElementId,delete s.bitmapId,s)}if(null===e)return s;e.stamps||=new Map;const r=this.#rl?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(e.stamps.has(this.#Qh)){if(this.#rl){const t=e.stamps.get(this.#Qh);r>t.area&&(t.area=r,t.serialized.bitmap.close(),t.serialized.bitmap=this.#pl(!1))}}else e.stamps.set(this.#Qh,{area:r,serialized:s}),s.bitmap=this.#pl(!1);return s}#to(t){const{pageIndex:e,accessibilityData:{altText:s}}=this._initialData,i=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===s;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&i&&n,isSameAltText:n}}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}new Map([Ki,dn,bn,rn,fn].map(t=>[t._editorType,t]));globalThis._pdfjsTestingUtils={HighlightOutliner:tn};const yn={fonts:globalThis.fonts,createElement:t=>"canvas"===t.toLowerCase()?new OffscreenCanvas(1,1):null};class An{constructor(){this._pdfDocument=null,this._page=null,this._geospatialMetadata=null,this._baseViewport=null,this._inverseBaseViewport=null,this._pdfWorker=null,this._pdfWorkerBlobUrl=null}async loadPDF(s,o={}){h()||await l(),i(o);const[{data:c},d]=await Promise.all([e(s.url,{responseType:"array-buffer",signal:o?.signal}),this._getPDFWorker(o)]),u=Si({data:c,wasmUrl:t("esri/libs/pdfjs/wasm/"),ownerDocument:yn,enableHWA:!0,useWorkerFetch:!0,worker:d});return this._pdfDocument=await u.promise,i(o),this._page=await this._pdfDocument.getPage(s.page),i(o),this._geospatialMetadata=await this._page.getGeospatialPDFMetadata(),i(o),this._baseViewport=this._page.getViewport({scale:1}),this._inverseBaseViewport=n(),a(this._inverseBaseViewport,r(...this._baseViewport.transform)),{geospatialMetadata:this._geospatialMetadata}}destroy(){this._page?.cleanup?.(),this._page=null,this._pdfDocument?.cleanup(),this._pdfDocument=null,this._geospatialMetadata=null,this._baseViewport=null,this._inverseBaseViewport=null,this._pdfWorker?.destroy(),this._pdfWorker=null,this._pdfWorkerBlobUrl&&(URL.revokeObjectURL(this._pdfWorkerBlobUrl),this._pdfWorkerBlobUrl=null)}async renderPDF(t,e={}){if(!this._page||!this._baseViewport||!this._inverseBaseViewport)throw new s("geospatial-pdf-layer-worker:not-loaded","PDF not loaded");i(e);const{width:n,height:r,sourceExtentAsJSON:a,currentRing:h,ctm:l}=t,d=o.fromJSON(a),u=await c(d,n,r,l,this._page,this._baseViewport,this._inverseBaseViewport,h,e);return i(e),wn(u,n,r)}async _getPDFWorker(s={}){if(this._pdfWorker)return this._pdfWorker;const i=t("esri/libs/pdfjs/pdf.worker.mjs"),n=(await e(i,{responseType:"blob",authMode:"anonymous",signal:s.signal})).data,r="application/javascript"===n.type||"text/javascript"===n.type?n:new Blob([n],{type:"application/javascript"}),a=URL.createObjectURL(r);try{const t=new Worker(a,{type:"module",name:"geospatial-pdf-pdfjs-worker"}),e=new Ei({port:t});return await e.promise,this._pdfWorker=e,this._pdfWorkerBlobUrl=a,e}catch(o){throw URL.revokeObjectURL(a),o}}}function wn(t,e,i){const n=t.getContext("2d");if(!n)throw new s("geospatial-pdf-raster:canvas","Failed to create canvas context.");const r=n.getImageData(0,0,e,i).data,a=e*i,o=new Uint8Array(a),h=new Uint8Array(a),l=new Uint8Array(a),c=new Uint8Array(a);for(let s=0,d=0;s<a;s++,d+=4)o[s]=r[d],h[s]=r[d+1],l[s]=r[d+2],c[s]=r[d+3];return{width:e,height:i,red:o,green:h,blue:l,mask:c}}export{An as default};