@poe-platform/safe-bash 0.1.811 → 0.1.813

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 (351) hide show
  1. package/dist/audio-ast/id3-source.d.ts +27 -0
  2. package/dist/audio-ast/index.d.ts +5 -0
  3. package/dist/audio-ast/index.js +1001 -596
  4. package/dist/audio-ast/mp3-source.d.ts +18 -0
  5. package/dist/audio-ast/ogg-source.d.ts +25 -0
  6. package/dist/audio-ast/ogg-stream-source.d.ts +22 -0
  7. package/dist/audio-ast/vorbis.d.ts +14 -0
  8. package/dist/image-ast/index.js +139 -9
  9. package/dist/mp4-ast/containers/adapters.d.ts +7 -0
  10. package/dist/office-xml/retained-xml-document.d.ts +8 -0
  11. package/dist/pdf-ast/ast.d.ts +2 -0
  12. package/dist/pdf-ast/content/dictionary-cursor.d.ts +15 -0
  13. package/dist/pdf-ast/content/range-operator-parser.d.ts +4 -0
  14. package/dist/pdf-ast/content/stored-dictionary.d.ts +10 -0
  15. package/dist/pdf-ast/cos/lexer.d.ts +8 -5
  16. package/dist/pdf-ast/cos/object-reader.d.ts +4 -3
  17. package/dist/pdf-ast/cos/range-parser.d.ts +4 -0
  18. package/dist/pdf-ast/cos/retained-objects.d.ts +1 -0
  19. package/dist/pdf-ast/cos/retained-writer.d.ts +1 -0
  20. package/dist/pdf-ast/cos/value-parser.d.ts +32 -2
  21. package/dist/pdf-ast/edit/retained-append-attachments.d.ts +13 -0
  22. package/dist/pdf-ast/edit/retained-bookmarks.d.ts +13 -0
  23. package/dist/pdf-ast/edit/retained-graph.d.ts +6 -0
  24. package/dist/pdf-ast/edit/retained-save.d.ts +2 -0
  25. package/dist/pdf-ast/edit/retained-stamps.d.ts +9 -0
  26. package/dist/pdf-ast/extract/retained-form-field-details.d.ts +20 -0
  27. package/dist/pdf-ast/extract/retained-form-fields.d.ts +17 -4
  28. package/dist/pdf-ast/fonts/resolve.d.ts +3 -1
  29. package/dist/pdf-ast/index.d.ts +4 -1
  30. package/dist/pdf-ast/index.js +2127 -975
  31. package/dist/pdf-ast/retained-document.d.ts +4 -0
  32. package/dist/safe-bash/audio-ast.browser.js +7 -1
  33. package/dist/safe-bash/chunks/{chunk-HHSOUC3Z.js → chunk-HPQE675Q.js} +1 -1
  34. package/dist/safe-bash/chunks/{chunk-BUYRKFW2.js → chunk-I6ECNJMR.js} +1 -1
  35. package/dist/safe-bash/chunks/{pdftk-WRYEP3CA.js → pdftk-Y2TX74LY.js} +2 -1
  36. package/dist/safe-bash/command-chunks/biff-4ALVARRF-7SRX6R6N.js +5192 -0
  37. package/dist/safe-bash/command-chunks/{chunk-EHSM5ZQS.js → chunk-2DGJOOXM.js} +8 -8
  38. package/dist/safe-bash/command-chunks/{chunk-Q6S57NOQ.js → chunk-2E2H7MBH.js} +7 -7
  39. package/dist/safe-bash/command-chunks/{chunk-MMBZTYXO.js → chunk-2PQRZDNR.js} +221 -0
  40. package/dist/safe-bash/command-chunks/{chunk-5OO2P27R.js → chunk-2V6FOLXV.js} +78 -25
  41. package/dist/safe-bash/command-chunks/{chunk-56NYSX65.js → chunk-2Z3WRRFT.js} +9 -9
  42. package/dist/safe-bash/command-chunks/chunk-3D24WDND.js +63 -0
  43. package/dist/safe-bash/command-chunks/{chunk-47NEG4UO.js → chunk-3JST2Q7G.js} +219 -43
  44. package/dist/safe-bash/command-chunks/{chunk-WGG6G2KG.js → chunk-3LJAXFH5.js} +7 -7
  45. package/dist/safe-bash/command-chunks/{chunk-AHA6IWAJ.js → chunk-3TYDSGAH.js} +6 -6
  46. package/dist/safe-bash/command-chunks/{chunk-YSMNXMAO.js → chunk-3Y4XZB24.js} +4 -4
  47. package/dist/safe-bash/command-chunks/{chunk-ZIIO6GRY.js → chunk-4PBNMKAT.js} +7 -7
  48. package/dist/safe-bash/command-chunks/{chunk-JFYWVQ4V.js → chunk-4Z6W5EOC.js} +8 -8
  49. package/dist/safe-bash/command-chunks/{chunk-GEM47B2P.js → chunk-57DDYKE5.js} +7 -7
  50. package/dist/safe-bash/command-chunks/{chunk-HARUYHH7.js → chunk-5HUICAWD.js} +1 -1
  51. package/dist/safe-bash/command-chunks/{chunk-4CKFNXRN.js → chunk-5IFRAI7Y.js} +1 -1
  52. package/dist/safe-bash/command-chunks/{chunk-RHYJVTJO.js → chunk-5KGEZ3RW.js} +2 -2
  53. package/dist/safe-bash/command-chunks/{chunk-A5FZBR7X.js → chunk-5MFDRSGG.js} +4 -4
  54. package/dist/safe-bash/command-chunks/{chunk-7GKKMNL6.js → chunk-5P6I2T63.js} +8 -8
  55. package/dist/safe-bash/command-chunks/{chunk-6M6TM5Z5.js → chunk-5VQVZPP3.js} +3 -3
  56. package/dist/safe-bash/command-chunks/{chunk-MIRL7HTF.js → chunk-6244HYJY.js} +1 -1
  57. package/dist/safe-bash/command-chunks/chunk-63EMPQ7Z.js +115 -0
  58. package/dist/safe-bash/command-chunks/{chunk-XRVKWGVQ.js → chunk-6CY5BHBS.js} +6 -6
  59. package/dist/safe-bash/command-chunks/{chunk-XVP6V5K3.js → chunk-6IWE7PTK.js} +6 -6
  60. package/dist/safe-bash/command-chunks/{chunk-6QBMND4A.js → chunk-6SRHWVEB.js} +1 -1
  61. package/dist/safe-bash/command-chunks/chunk-6ZHQB453.js +35 -0
  62. package/dist/safe-bash/command-chunks/chunk-73NYFNAS.js +173 -0
  63. package/dist/safe-bash/command-chunks/{chunk-VU3EQF7F.js → chunk-7NXTEWPR.js} +229 -75
  64. package/dist/safe-bash/command-chunks/{chunk-554Z6IKP.js → chunk-7PRL6RJ6.js} +2 -2
  65. package/dist/safe-bash/command-chunks/{chunk-SDTPO2VV.js → chunk-7PZHWMK6.js} +7 -7
  66. package/dist/safe-bash/command-chunks/{chunk-XZ2FWFNV.js → chunk-7QZ2HP2F.js} +6 -6
  67. package/dist/safe-bash/command-chunks/{chunk-OEJM666F.js → chunk-7UC2Q6Z6.js} +5 -5
  68. package/dist/safe-bash/command-chunks/{chunk-COKYZUBW.js → chunk-AJI55RS7.js} +1 -1
  69. package/dist/safe-bash/command-chunks/{chunk-2VCKUNDZ.js → chunk-B2C3UPJS.js} +27 -17
  70. package/dist/safe-bash/command-chunks/{chunk-WXRYDALR.js → chunk-BBAB7LC4.js} +4 -4
  71. package/dist/safe-bash/command-chunks/{chunk-QYMEASQ6.js → chunk-BEHUSUOY.js} +4 -4
  72. package/dist/safe-bash/command-chunks/{chunk-Z2JW6M2D.js → chunk-BK7ISUJL.js} +3 -3
  73. package/dist/safe-bash/command-chunks/{chunk-33YCKZZX.js → chunk-C5KLFZGT.js} +6 -6
  74. package/dist/safe-bash/command-chunks/{chunk-TVH4JORU.js → chunk-C5QDEB3I.js} +3 -3
  75. package/dist/safe-bash/command-chunks/{chunk-N4R2SHSS.js → chunk-CCZZVCHX.js} +2 -2
  76. package/dist/safe-bash/command-chunks/{chunk-2VLAXKTS.js → chunk-CTDC4LJT.js} +121 -85
  77. package/dist/safe-bash/command-chunks/{chunk-S6R3IB36.js → chunk-D55REQA3.js} +1 -1
  78. package/dist/safe-bash/command-chunks/{chunk-Y4EYCZFT.js → chunk-D6WJY6QO.js} +10 -10
  79. package/dist/safe-bash/command-chunks/{chunk-2CORNDGF.js → chunk-DBLHCJJU.js} +2 -2
  80. package/dist/safe-bash/command-chunks/{chunk-SPW4GW4Z.js → chunk-DFI7QF3M.js} +2 -2
  81. package/dist/safe-bash/command-chunks/{chunk-456PHA3L.js → chunk-DMCI6T6N.js} +1 -1
  82. package/dist/safe-bash/command-chunks/{chunk-TW73OXPR.js → chunk-EJTNVXWF.js} +6 -6
  83. package/dist/safe-bash/command-chunks/{chunk-QD7ZRDUN.js → chunk-ET2VPDUA.js} +1 -1
  84. package/dist/safe-bash/command-chunks/{chunk-5LI2DLNZ.js → chunk-EXOQGXEU.js} +26 -26
  85. package/dist/safe-bash/command-chunks/{chunk-CRV2Q3PB.js → chunk-EZ4NQIPL.js} +1 -1
  86. package/dist/safe-bash/command-chunks/chunk-FWKLBDMK.js +0 -0
  87. package/dist/safe-bash/command-chunks/{chunk-22MOB45U.js → chunk-FWPVQGYK.js} +6 -6
  88. package/dist/safe-bash/command-chunks/{chunk-QC5RMGSA.js → chunk-G3RUXKVY.js} +3 -3
  89. package/dist/safe-bash/command-chunks/{chunk-JYUJAF4L.js → chunk-G7NENPYV.js} +4 -0
  90. package/dist/safe-bash/command-chunks/{chunk-KCOJA7EM.js → chunk-GKILM4HZ.js} +7 -7
  91. package/dist/safe-bash/command-chunks/{chunk-HTVIYLVB.js → chunk-GNXTMSYN.js} +4 -4
  92. package/dist/safe-bash/command-chunks/{chunk-D2ASPM7R.js → chunk-GOBUDKZ3.js} +3 -3
  93. package/dist/safe-bash/command-chunks/{chunk-RNSKXOG3.js → chunk-GVWVRPG6.js} +6 -6
  94. package/dist/safe-bash/command-chunks/{chunk-ZHRGYR7B.js → chunk-HCKYUQ3L.js} +7 -7
  95. package/dist/safe-bash/command-chunks/{chunk-AGLK7OJR.js → chunk-HDSIIQBS.js} +1 -1
  96. package/dist/safe-bash/command-chunks/{chunk-DM2CPMB4.js → chunk-HKOMXGJS.js} +2 -2
  97. package/dist/safe-bash/command-chunks/{chunk-IT7TAC3F.js → chunk-HVW53ARH.js} +16 -16
  98. package/dist/safe-bash/command-chunks/{chunk-M7QE2MN7.js → chunk-I4GMCWAT.js} +6 -6
  99. package/dist/safe-bash/command-chunks/{chunk-5MB64DWR.js → chunk-IHSOOSNC.js} +9 -9
  100. package/dist/safe-bash/command-chunks/{chunk-LCZDBW55.js → chunk-JAHJWVGF.js} +5 -5
  101. package/dist/safe-bash/command-chunks/{chunk-MOZD7RUY.js → chunk-JORIVUPM.js} +27 -11
  102. package/dist/safe-bash/command-chunks/{chunk-PMAM4N33.js → chunk-JUJHYPYL.js} +9 -9
  103. package/dist/safe-bash/command-chunks/{chunk-ENT3IV2G.js → chunk-KBUBSMCQ.js} +12 -12
  104. package/dist/safe-bash/command-chunks/{chunk-ZXR6LXV5.js → chunk-KCE5D4Z4.js} +48 -4
  105. package/dist/safe-bash/command-chunks/{chunk-FIIAYCWS.js → chunk-KZ5ODST6.js} +2 -2
  106. package/dist/safe-bash/command-chunks/{chunk-PNGDJA6M.js → chunk-LD7BONZY.js} +2 -2
  107. package/dist/safe-bash/command-chunks/{chunk-KJ4XXZIL.js → chunk-M3Z5PU2M.js} +582 -59
  108. package/dist/safe-bash/command-chunks/{chunk-LXLLA4PM.js → chunk-MKX4JAZ6.js} +17 -17
  109. package/dist/safe-bash/command-chunks/{chunk-RQIQ75W5.js → chunk-MNHBQBF6.js} +5 -5
  110. package/dist/safe-bash/command-chunks/{chunk-A2CLZMQZ.js → chunk-MPKY37QR.js} +1 -1
  111. package/dist/safe-bash/command-chunks/{chunk-K5GB2YMN.js → chunk-MUUWBZIC.js} +10 -10
  112. package/dist/safe-bash/command-chunks/{chunk-JOCFI7TG.js → chunk-N32GSM3J.js} +1 -1
  113. package/dist/safe-bash/command-chunks/{chunk-EUT24Y5Z.js → chunk-NKTULXVD.js} +8 -8
  114. package/dist/safe-bash/command-chunks/{chunk-5HPU7D36.js → chunk-NMPED6L5.js} +4 -4
  115. package/dist/safe-bash/command-chunks/{chunk-QZZ73J2O.js → chunk-NPFHUS4X.js} +6 -6
  116. package/dist/safe-bash/command-chunks/{chunk-X7FA7ZD5.js → chunk-O675URF4.js} +8 -8
  117. package/dist/safe-bash/command-chunks/{chunk-R6EGGK5M.js → chunk-P7EL2FWW.js} +7 -7
  118. package/dist/safe-bash/command-chunks/{chunk-YS25EI54.js → chunk-PCCFLPUQ.js} +2 -2
  119. package/dist/safe-bash/command-chunks/{chunk-RRL3Y562.js → chunk-PI6MOMHA.js} +11 -11
  120. package/dist/safe-bash/command-chunks/{chunk-26VCZHLJ.js → chunk-PIOQBOEK.js} +1 -1
  121. package/dist/safe-bash/command-chunks/chunk-PK36TVXB.js +175 -0
  122. package/dist/safe-bash/command-chunks/{chunk-72C3TZ2U.js → chunk-PKLJRB7W.js} +264 -129
  123. package/dist/safe-bash/command-chunks/{chunk-6CCQI6XZ.js → chunk-PSCOXGCA.js} +12 -12
  124. package/dist/safe-bash/command-chunks/{chunk-XPD636C4.js → chunk-PVGZMLC6.js} +3 -3
  125. package/dist/safe-bash/command-chunks/{chunk-JQVHUSDD.js → chunk-PXWS3Q7L.js} +5 -5
  126. package/dist/safe-bash/command-chunks/{chunk-HDJVJTCK.js → chunk-QFF5KBOM.js} +9 -9
  127. package/dist/safe-bash/command-chunks/{chunk-MPUHH2KR.js → chunk-QM2HZJSJ.js} +3 -3
  128. package/dist/safe-bash/command-chunks/{chunk-UAXSE3XE.js → chunk-R2BMZAHG.js} +5 -5
  129. package/dist/safe-bash/command-chunks/{chunk-KB7DUBVL.js → chunk-RGOQKIG6.js} +5 -5
  130. package/dist/safe-bash/command-chunks/{chunk-D2KZ66W4.js → chunk-RLCQ7BN3.js} +187 -39
  131. package/dist/safe-bash/command-chunks/{chunk-B5LDP7AA.js → chunk-S2N2V5U4.js} +2 -2
  132. package/dist/safe-bash/command-chunks/{chunk-OA75SGN2.js → chunk-SGPCXAG7.js} +7 -7
  133. package/dist/safe-bash/command-chunks/{chunk-Z5QOVRVH.js → chunk-SU26FZLJ.js} +1 -1
  134. package/dist/safe-bash/command-chunks/{chunk-QUM3SYAJ.js → chunk-SYSX46IV.js} +3 -3
  135. package/dist/safe-bash/command-chunks/chunk-T3E5RV3U.js +737 -0
  136. package/dist/safe-bash/command-chunks/{chunk-YORJDX4V.js → chunk-T5ERNELL.js} +4 -4
  137. package/dist/safe-bash/command-chunks/{chunk-KL3OIBKB.js → chunk-T6C5QP7T.js} +6495 -6343
  138. package/dist/safe-bash/command-chunks/{chunk-ATTWQVR2.js → chunk-TKRLZIFI.js} +17 -17
  139. package/dist/safe-bash/command-chunks/{chunk-ZMHEGDU2.js → chunk-TODWFDYB.js} +2 -2
  140. package/dist/safe-bash/command-chunks/{chunk-YSY6R6AS.js → chunk-TQEB4DH4.js} +703 -102
  141. package/dist/safe-bash/command-chunks/{chunk-36XGIPOG.js → chunk-U5TWQFZY.js} +1 -1
  142. package/dist/safe-bash/command-chunks/{chunk-APEWTWCC.js → chunk-UAF4IX5H.js} +6 -6
  143. package/dist/safe-bash/command-chunks/{chunk-6VPQ3CDZ.js → chunk-V37D6AHO.js} +5 -5
  144. package/dist/safe-bash/command-chunks/{chunk-RID6VYS3.js → chunk-V6XBEYPC.js} +8 -8
  145. package/dist/safe-bash/command-chunks/{chunk-WJCN2IXI.js → chunk-VQOINPVF.js} +2 -2
  146. package/dist/safe-bash/command-chunks/{chunk-W5YSINXC.js → chunk-VVWXY6IA.js} +6 -6
  147. package/dist/safe-bash/command-chunks/{chunk-HKATEVAP.js → chunk-WPVBUVFK.js} +6 -6
  148. package/dist/safe-bash/command-chunks/{chunk-UYWSIIUX.js → chunk-X53AEG36.js} +7 -7
  149. package/dist/safe-bash/command-chunks/{chunk-L5MCW6CM.js → chunk-X64XGIXZ.js} +9 -155
  150. package/dist/safe-bash/command-chunks/{chunk-Q73EMLLZ.js → chunk-X6RHJ6YN.js} +84 -5
  151. package/dist/safe-bash/command-chunks/{chunk-7PVHO47B.js → chunk-XG6UWQV5.js} +6 -6
  152. package/dist/safe-bash/command-chunks/{chunk-NQDIT667.js → chunk-XIDGHIGB.js} +5 -5
  153. package/dist/safe-bash/command-chunks/{chunk-DPR5CYQV.js → chunk-XITDDJFT.js} +2 -0
  154. package/dist/safe-bash/command-chunks/{chunk-CV7M2QJU.js → chunk-XLYIVBAR.js} +7 -7
  155. package/dist/safe-bash/command-chunks/{chunk-WVMHRNXZ.js → chunk-YUXTK3XA.js} +3 -3
  156. package/dist/safe-bash/command-chunks/{chunk-SPLOIABU.js → chunk-YXD6VGVG.js} +3 -3
  157. package/dist/safe-bash/command-chunks/{chunk-2ZFLMWOX.js → chunk-Z5BIM5B7.js} +1 -1
  158. package/dist/safe-bash/command-chunks/chunk-ZYLGNIGA.js +156 -0
  159. package/dist/safe-bash/command-chunks/{command-engine-BEWABZ75.js → command-engine-X3OLN7N6.js} +206 -86
  160. package/dist/safe-bash/command-chunks/{engine-AXXFTGCL-QBQNBI6K.js → engine-XUCIFZ7V-LJFGZM6O.js} +1 -1
  161. package/dist/safe-bash/command-chunks/paradox-4FCZE53D-LQPGVMEL.js +365 -0
  162. package/dist/safe-bash/commands/pandoc/index.browser.js +1 -1
  163. package/dist/safe-bash/full-core.browser.js +2 -2
  164. package/dist/safe-bash/plugins/index.browser.js +2 -2
  165. package/dist/safe-bash-command-apply-patch/apply.js +4 -4
  166. package/dist/safe-bash-command-apply-patch/index.js +4 -4
  167. package/dist/safe-bash-command-apply-patch/matcher.js +2 -2
  168. package/dist/safe-bash-command-apply-patch/parser.js +2 -2
  169. package/dist/safe-bash-command-apply-patch/shared.d.ts +2 -0
  170. package/dist/safe-bash-command-apply-patch/shared.js +1 -1
  171. package/dist/safe-bash-command-diff/diff.js +1 -1
  172. package/dist/safe-bash-command-diff/index.js +1 -1
  173. package/dist/safe-bash-command-ffmpeg/index.js +1 -1
  174. package/dist/safe-bash-command-ffprobe/index.js +2 -2
  175. package/dist/safe-bash-command-ffprobe/media.d.ts +3 -1
  176. package/dist/safe-bash-command-ffprobe/media.js +2 -2
  177. package/dist/safe-bash-command-html-to-markdown/budget.js +2 -1
  178. package/dist/safe-bash-command-html-to-markdown/entities.js +4 -3
  179. package/dist/safe-bash-command-html-to-markdown/index.js +564 -110
  180. package/dist/safe-bash-command-html-to-markdown/input.js +6 -5
  181. package/dist/safe-bash-command-html-to-markdown/options.js +2 -1
  182. package/dist/safe-bash-command-html-to-markdown/parser.js +5 -4
  183. package/dist/safe-bash-command-html-to-markdown/render.js +6 -5
  184. package/dist/safe-bash-command-html-to-markdown/text.js +3 -2
  185. package/dist/safe-bash-command-htmlq/index.js +361 -37
  186. package/dist/safe-bash-command-htmlq/tree.d.ts +3 -2
  187. package/dist/safe-bash-command-pandoc/command.js +7 -7
  188. package/dist/safe-bash-command-pandoc/index.js +55 -55
  189. package/dist/safe-bash-command-patch/index.js +6 -6
  190. package/dist/safe-bash-command-patch/patch-envelope.js +53 -3
  191. package/dist/safe-bash-command-patch/patch-formats.d.ts +2 -2
  192. package/dist/safe-bash-command-patch/patch-formats.js +2 -2
  193. package/dist/safe-bash-command-patch/patch-gnu-reject.d.ts +2 -1
  194. package/dist/safe-bash-command-patch/patch-gnu-reject.js +4 -3
  195. package/dist/safe-bash-command-patch/patch-publication.js +2 -1
  196. package/dist/safe-bash-command-patch/patch.js +6 -6
  197. package/dist/safe-bash-command-patch/unified.d.ts +10 -2
  198. package/dist/safe-bash-command-patch/unified.js +1 -1
  199. package/dist/safe-bash-command-pdftk/index.d.ts +6 -2
  200. package/dist/safe-bash-command-pdftk/index.js +835 -243
  201. package/dist/safe-bash-command-pptx/command-engine.d.ts +15 -3
  202. package/dist/safe-bash-command-pptx/engine.d.ts +2 -2
  203. package/dist/safe-bash-command-pptx/engine.js +1 -1
  204. package/dist/safe-bash-command-pptx/index.js +9 -2
  205. package/dist/safe-bash-command-soffice/index.js +1 -1
  206. package/dist/safe-bash-command-ssconvert/index.js +2 -2
  207. package/dist/safe-bash-command-xmllint/index.js +22 -31
  208. package/dist/safe-bash-diff-engine/document.d.ts +2 -1
  209. package/dist/safe-bash-diff-engine/document.js +7 -4
  210. package/dist/safe-bash-presentation-engine/accessibility.js +31 -30
  211. package/dist/safe-bash-presentation-engine/animation-editing.js +16 -15
  212. package/dist/safe-bash-presentation-engine/animations.js +16 -15
  213. package/dist/safe-bash-presentation-engine/backgrounds.js +17 -16
  214. package/dist/safe-bash-presentation-engine/bytes.js +3 -3
  215. package/dist/safe-bash-presentation-engine/chart-editing.js +34 -33
  216. package/dist/safe-bash-presentation-engine/chart-object-operations.js +25 -24
  217. package/dist/safe-bash-presentation-engine/charts.js +31 -30
  218. package/dist/safe-bash-presentation-engine/command-placeholder.js +59 -55
  219. package/dist/safe-bash-presentation-engine/comments.js +17 -16
  220. package/dist/safe-bash-presentation-engine/connector-operations.js +32 -31
  221. package/dist/safe-bash-presentation-engine/connectors.js +29 -28
  222. package/dist/safe-bash-presentation-engine/content-types.js +4 -4
  223. package/dist/safe-bash-presentation-engine/creation.js +6 -6
  224. package/dist/safe-bash-presentation-engine/diff.js +32 -31
  225. package/dist/safe-bash-presentation-engine/drawing-enums.d.ts +10 -10
  226. package/dist/safe-bash-presentation-engine/drawing-format.js +20 -19
  227. package/dist/safe-bash-presentation-engine/drawing-operations.js +31 -30
  228. package/dist/safe-bash-presentation-engine/drawing-schema.js +21 -20
  229. package/dist/safe-bash-presentation-engine/equations.js +17 -16
  230. package/dist/safe-bash-presentation-engine/errors.js +2 -2
  231. package/dist/safe-bash-presentation-engine/fields.js +17 -16
  232. package/dist/safe-bash-presentation-engine/font-metrics.js +3 -3
  233. package/dist/safe-bash-presentation-engine/image-extraction.js +20 -19
  234. package/dist/safe-bash-presentation-engine/image-formatting.js +32 -31
  235. package/dist/safe-bash-presentation-engine/image-insertion.js +18 -17
  236. package/dist/safe-bash-presentation-engine/image-replacement.js +21 -20
  237. package/dist/safe-bash-presentation-engine/image-value.js +4 -4
  238. package/dist/safe-bash-presentation-engine/images.js +19 -18
  239. package/dist/safe-bash-presentation-engine/index.d.ts +6 -2
  240. package/dist/safe-bash-presentation-engine/index.js +112 -97
  241. package/dist/safe-bash-presentation-engine/layouts.js +16 -15
  242. package/dist/safe-bash-presentation-engine/length.js +3 -3
  243. package/dist/safe-bash-presentation-engine/links.js +16 -15
  244. package/dist/safe-bash-presentation-engine/masters.js +15 -14
  245. package/dist/safe-bash-presentation-engine/media-editing.js +24 -23
  246. package/dist/safe-bash-presentation-engine/media-extraction.js +17 -16
  247. package/dist/safe-bash-presentation-engine/media.js +16 -15
  248. package/dist/safe-bash-presentation-engine/memberships.js +15 -14
  249. package/dist/safe-bash-presentation-engine/notes.js +16 -15
  250. package/dist/safe-bash-presentation-engine/ole-enum.js +4 -4
  251. package/dist/safe-bash-presentation-engine/ole-insertion.js +20 -19
  252. package/dist/safe-bash-presentation-engine/opaque-objects.js +9 -9
  253. package/dist/safe-bash-presentation-engine/package-reader.js +5 -5
  254. package/dist/safe-bash-presentation-engine/package-tools.d.ts +3 -0
  255. package/dist/safe-bash-presentation-engine/package-tools.js +27 -17
  256. package/dist/safe-bash-presentation-engine/package-uri.js +3 -3
  257. package/dist/safe-bash-presentation-engine/package-writer.js +4 -4
  258. package/dist/safe-bash-presentation-engine/presentation-model.js +58 -54
  259. package/dist/safe-bash-presentation-engine/presentation-settings.js +14 -13
  260. package/dist/safe-bash-presentation-engine/properties.js +16 -15
  261. package/dist/safe-bash-presentation-engine/relationships.js +4 -4
  262. package/dist/safe-bash-presentation-engine/resource-limits.js +1 -1
  263. package/dist/safe-bash-presentation-engine/retained-archive-staging.d.ts +19 -0
  264. package/dist/safe-bash-presentation-engine/retained-extraction-output.d.ts +18 -0
  265. package/dist/safe-bash-presentation-engine/retained-inspection.js +14 -12
  266. package/dist/safe-bash-presentation-engine/retained-package-extraction.d.ts +22 -0
  267. package/dist/safe-bash-presentation-engine/retained-package-packing.d.ts +19 -0
  268. package/dist/safe-bash-presentation-engine/retained-package.d.ts +2 -0
  269. package/dist/safe-bash-presentation-engine/retained-package.js +6 -4
  270. package/dist/safe-bash-presentation-engine/retained-slide-publication.d.ts +24 -0
  271. package/dist/safe-bash-presentation-engine/retained-text.js +19 -17
  272. package/dist/safe-bash-presentation-engine/retained-xml-parts.d.ts +5 -1
  273. package/dist/safe-bash-presentation-engine/retained-xml-publication.d.ts +18 -0
  274. package/dist/safe-bash-presentation-engine/retained-xml-replacement.d.ts +13 -0
  275. package/dist/safe-bash-presentation-engine/sanitize.js +17 -16
  276. package/dist/safe-bash-presentation-engine/selectors.js +10 -10
  277. package/dist/safe-bash-presentation-engine/shape-groups.js +31 -30
  278. package/dist/safe-bash-presentation-engine/shape-operations.js +30 -29
  279. package/dist/safe-bash-presentation-engine/shape-path-operations.js +32 -31
  280. package/dist/safe-bash-presentation-engine/shape-paths.js +16 -15
  281. package/dist/safe-bash-presentation-engine/shape-presets.js +3 -3
  282. package/dist/safe-bash-presentation-engine/shape-selection.js +31 -30
  283. package/dist/safe-bash-presentation-engine/shape-transforms.js +18 -17
  284. package/dist/safe-bash-presentation-engine/shapes.d.ts +1 -1
  285. package/dist/safe-bash-presentation-engine/shapes.js +27 -26
  286. package/dist/safe-bash-presentation-engine/slide-copy.js +17 -16
  287. package/dist/safe-bash-presentation-engine/slide-import.js +18 -17
  288. package/dist/safe-bash-presentation-engine/slide-merge-split.js +20 -19
  289. package/dist/safe-bash-presentation-engine/slide-model.js +43 -42
  290. package/dist/safe-bash-presentation-engine/slide-removal.js +18 -17
  291. package/dist/safe-bash-presentation-engine/slide-transfer-budget.js +9 -9
  292. package/dist/safe-bash-presentation-engine/slides.d.ts +1 -0
  293. package/dist/safe-bash-presentation-engine/slides.js +23 -17
  294. package/dist/safe-bash-presentation-engine/table-operations.js +33 -32
  295. package/dist/safe-bash-presentation-engine/table-spans.js +32 -31
  296. package/dist/safe-bash-presentation-engine/tables.js +31 -30
  297. package/dist/safe-bash-presentation-engine/tags.js +16 -15
  298. package/dist/safe-bash-presentation-engine/template-bindings.js +33 -32
  299. package/dist/safe-bash-presentation-engine/template-repeat.js +40 -39
  300. package/dist/safe-bash-presentation-engine/text-fitting.js +27 -26
  301. package/dist/safe-bash-presentation-engine/text-frames.js +27 -26
  302. package/dist/safe-bash-presentation-engine/text-paragraphs.js +27 -26
  303. package/dist/safe-bash-presentation-engine/text-reading.js +11 -11
  304. package/dist/safe-bash-presentation-engine/text-replacement.js +17 -16
  305. package/dist/safe-bash-presentation-engine/text-runs.js +20 -19
  306. package/dist/safe-bash-presentation-engine/themes.js +16 -15
  307. package/dist/safe-bash-presentation-engine/transitions.js +16 -15
  308. package/dist/safe-bash-presentation-engine/validation.js +10 -9
  309. package/dist/safe-bash-presentation-engine/xml-parts.d.ts +2 -0
  310. package/dist/safe-bash-presentation-engine/xml-parts.js +23 -15
  311. package/dist/safe-bash-presentation-engine/xml-view.js +3 -3
  312. package/dist/safe-bash-presentation-engine/xml.js +3 -3
  313. package/dist/safe-bash-regex-engine/index.js +1 -1
  314. package/dist/safe-bash-regex-engine/python-glob.js +1 -1
  315. package/dist/safe-bash-regex-engine/text/regex.d.ts +19 -0
  316. package/dist/safe-bash-regex-engine/text/regex.js +1 -1
  317. package/dist/safe-bash-xml-engine/document.js +3 -3
  318. package/dist/safe-bash-xml-engine/evaluate.js +1 -1
  319. package/dist/safe-bash-xml-engine/index.d.ts +1 -0
  320. package/dist/safe-bash-xml-engine/index.js +8 -4
  321. package/dist/safe-bash-xml-engine/query.js +2 -2
  322. package/dist/safe-bash-xml-engine/recovery.d.ts +10 -0
  323. package/dist/safe-bash-xml-engine/stored-document.d.ts +1 -1
  324. package/dist/safe-bash-xml-engine/stored-document.js +1 -1
  325. package/dist/safe-bash-xml-engine/stored-evaluate.js +1 -1
  326. package/dist/spreadsheet-engine/formulas/functions/python-printf.js +56 -33
  327. package/dist/spreadsheet-format-xls/biff-encrypted-properties.d.ts +2 -2
  328. package/dist/spreadsheet-format-xls/biff-encrypted-properties.js +86 -24
  329. package/dist/spreadsheet-format-xls/biff-metadata.d.ts +1 -0
  330. package/dist/spreadsheet-format-xls/biff-metadata.js +2 -2
  331. package/dist/spreadsheet-format-xls/biff-properties-merge.d.ts +6 -2
  332. package/dist/spreadsheet-format-xls/biff-properties-merge.js +413 -296
  333. package/dist/spreadsheet-format-xls/biff-properties-write.js +40 -23
  334. package/dist/spreadsheet-format-xls/biff-properties.js +3 -68
  335. package/dist/spreadsheet-format-xls/biff-property-index.d.ts +23 -0
  336. package/dist/spreadsheet-format-xls/biff-property-index.js +93 -0
  337. package/dist/spreadsheet-format-xls/biff-property-name.d.ts +4 -0
  338. package/dist/spreadsheet-format-xls/biff-property-name.js +114 -0
  339. package/dist/spreadsheet-format-xls/biff-property-text.d.ts +6 -0
  340. package/dist/spreadsheet-format-xls/biff-property-text.js +68 -0
  341. package/dist/spreadsheet-format-xls/biff-property-transcode.d.ts +5 -0
  342. package/dist/spreadsheet-format-xls/biff-property-transcode.js +45 -0
  343. package/dist/spreadsheet-format-xls/biff-write-metadata.js +10 -1
  344. package/package.json +6 -3
  345. package/dist/safe-bash/command-chunks/biff-3EFLKBAH-NYWZOYQS.js +0 -4942
  346. package/dist/safe-bash/command-chunks/chunk-5Q22ZLNC.js +0 -127
  347. package/dist/safe-bash/command-chunks/chunk-JKLOBSMP.js +0 -56
  348. package/dist/safe-bash/command-chunks/chunk-JYTESTBS.js +0 -99
  349. package/dist/safe-bash/command-chunks/chunk-WH3TIOTS.js +0 -326
  350. package/dist/safe-bash/command-chunks/paradox-ZWWXYY4J-JYOSWSBL.js +0 -362
  351. package/dist/spreadsheet-format-xls/biff-properties-layout.js +0 -56
@@ -1,16 +1,51 @@
1
1
  import "../safe-bash/command-chunks/chunk-65DS4IOB.js";
2
2
 
3
- // packages/safe-bash-command-pdftk/src/retained.ts
4
- import { PdfError, PdfFileSource, PdfRetainedDocument, retainedCosObjects } from "../pdf-ast/index.js";
5
- import { FsError } from "../safe-bash-contracts/errors.js";
6
- import { writeBytes } from "../safe-bash-contracts/io.js";
7
- import { resolvePath } from "../safe-bash-contracts/path.js";
8
- import { writeFileOutput } from "../safe-bash-contracts/filesystem-output-budget.js";
3
+ // packages/safe-bash-command-pdftk/src/burst-filename.ts
4
+ function formatBurstFilename(pattern, pageNum) {
5
+ let out = "";
6
+ let replaced = false;
7
+ for (let i = 0; i < pattern.length; i++) {
8
+ if (pattern[i] !== "%") {
9
+ out += pattern[i];
10
+ continue;
11
+ }
12
+ if (pattern[i + 1] === "%") {
13
+ out += "%";
14
+ i++;
15
+ continue;
16
+ }
17
+ if (!replaced) {
18
+ let j = i + 1;
19
+ let zeroPad = false;
20
+ if (pattern[j] === "0") {
21
+ zeroPad = true;
22
+ j++;
23
+ }
24
+ let widthStr = "";
25
+ while (j < pattern.length && pattern[j] >= "0" && pattern[j] <= "9") {
26
+ widthStr += pattern[j];
27
+ j++;
28
+ }
29
+ if (pattern[j] === "d") {
30
+ const width = widthStr ? Number.parseInt(widthStr, 10) : 1;
31
+ out += zeroPad ? String(pageNum).padStart(width, "0") : String(pageNum);
32
+ replaced = true;
33
+ i = j;
34
+ continue;
35
+ }
36
+ }
37
+ out += "%";
38
+ }
39
+ return out;
40
+ }
9
41
 
10
- // packages/safe-bash-command-pdftk/src/retained-annots.ts
42
+ // packages/safe-bash-command-pdftk/src/retained-burst.ts
43
+ import { createRetainedPageCopy, saveRetainedDocumentChunks } from "../pdf-ast/index.js";
44
+
45
+ // packages/safe-bash-command-pdftk/src/retained-inspection.ts
11
46
  import { IntegerTable, PagedStorage } from "@poe-platform/safe-fs/storage";
12
- import { PdfMutableObjectStore, decodePdfString, dictGet } from "../pdf-ast/index.js";
13
- async function* retainedAnnotationReport(document, storage, utf8, signal) {
47
+ import { PdfMutableObjectStore, PdfNameIndex, cosArray, cosNumber, decodePdfString, dictGet } from "../pdf-ast/index.js";
48
+ async function* retainedInspectionReport(document, storage, utf8, signal, kind) {
14
49
  const backing = new PagedStorage({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), pages = new IntegerTable(backing, 64);
15
50
  let pageCount = 0, work = 0, failed = false;
16
51
  const encoder = new TextEncoder();
@@ -41,26 +76,34 @@ async function* retainedAnnotationReport(document, storage, utf8, signal) {
41
76
  if (!start) return;
42
77
  const stack = new PdfMutableObjectStore(storage, { signal }), seen = new IntegerTable(backing, 64);
43
78
  let pending = 0, failed2 = false;
44
- const push = async (value) => {
79
+ const push = async (value, level = 1) => {
45
80
  await checkpoint();
46
- await stack.set({ objectNumber: ++pending, generationNumber: 0, value });
81
+ await stack.set({ objectNumber: ++pending, generationNumber: 0, value: cosArray([value, cosNumber(level)]) });
47
82
  };
48
83
  try {
49
84
  await push(start);
50
85
  while (pending) {
51
86
  await checkpoint();
52
- const raw = (await stack.get(pending--)).value;
87
+ const frame = (await stack.get(pending--)).value;
88
+ if (frame.kind !== "array") continue;
89
+ const raw = frame.items[0], levelNode = frame.items[1], level = levelNode.kind === "number" ? levelNode.value : 1;
53
90
  if (raw.kind === "ref") {
54
91
  if (await seen.get(BigInt(raw.objectNumber))) continue;
55
92
  await seen.set(BigInt(raw.objectNumber), 1n);
56
93
  }
57
94
  const value = await resolve(raw);
58
95
  if (value?.kind === "array" && key === "Next") {
59
- for (let i = value.items.length - 1; i >= 0; i--) await push(value.items[i]);
96
+ for (let i = value.items.length - 1; i >= 0; i--) await push(value.items[i], level);
60
97
  continue;
61
98
  }
62
99
  if (value?.kind !== "dict") continue;
63
- yield value;
100
+ yield { dict: value, level };
101
+ if (key === "Outlines") {
102
+ const next = dictGet(value, "Next"), first = dictGet(value, "First");
103
+ if (next) await push(next, level);
104
+ if (first) await push(first, level + 1);
105
+ continue;
106
+ }
64
107
  const child = dictGet(value, key);
65
108
  if (key === "Next") {
66
109
  if (child) await push(child);
@@ -93,7 +136,7 @@ async function* retainedAnnotationReport(document, storage, utf8, signal) {
93
136
  if (legacy?.kind === "dict") target = dictGet(legacy, name);
94
137
  if (!target) {
95
138
  const names = await resolve(dictGet(root, "Names"));
96
- if (names?.kind === "dict") for await (const branch of walk(dictGet(names, "Dests"), "Kids")) {
139
+ if (names?.kind === "dict") for await (const { dict: branch } of walk(dictGet(names, "Dests"), "Kids")) {
97
140
  const pairs = await resolve(dictGet(branch, "Names"));
98
141
  if (pairs?.kind === "array") for (let i = 0; i + 1 < pairs.items.length; i += 2) {
99
142
  const key = await resolve(pairs.items[i]);
@@ -147,6 +190,40 @@ async function* retainedAnnotationReport(document, storage, utf8, signal) {
147
190
  pageCount++;
148
191
  if (page.reference && !await pages.get(BigInt(page.reference.objectNumber))) await pages.set(BigInt(page.reference.objectNumber), BigInt(page.index + 1));
149
192
  }
193
+ if (kind === "document") {
194
+ const emitted = new PdfNameIndex(storage, Infinity, signal);
195
+ let failed2 = false;
196
+ try {
197
+ const info = await resolve(document.crossReference.infoRef);
198
+ if (info?.kind === "dict") {
199
+ for (const key of ["Title", "Author", "Subject", "Keywords", "Creator", "Producer"]) {
200
+ const node = await resolve(dictGet(info, key));
201
+ const value = node?.kind === "string" ? decodePdfString(node) : node?.kind === "name" ? node.decoded : "";
202
+ if (value) {
203
+ await emitted.intern(key);
204
+ yield* line("", "InfoBegin");
205
+ yield* line("InfoKey: ", key, true);
206
+ yield* line("InfoValue: ", value, true);
207
+ }
208
+ }
209
+ for (const entry of info.entries) {
210
+ const node = await resolve(entry.value), value = node?.kind === "string" ? decodePdfString(node) : "";
211
+ if (value && (await emitted.intern(entry.key.decoded)).added) {
212
+ yield* line("", "InfoBegin");
213
+ yield* line("InfoKey: ", entry.key.decoded, true);
214
+ yield* line("InfoValue: ", value, true);
215
+ }
216
+ }
217
+ }
218
+ } catch (error) {
219
+ failed2 = true;
220
+ throw error;
221
+ } finally {
222
+ await emitted.close().catch((error) => {
223
+ if (!failed2) throw error;
224
+ });
225
+ }
226
+ }
150
227
  for (let i = 0; i < 2; i++) {
151
228
  const id = await resolve(document.crossReference.idArray?.items[i]);
152
229
  if (id?.kind !== "string") yield* line(`PdfID${i}: `, "00000000000000000000000000000000");
@@ -162,6 +239,75 @@ async function* retainedAnnotationReport(document, storage, utf8, signal) {
162
239
  }
163
240
  }
164
241
  yield* line("NumberOfPages: ", pageCount);
242
+ if (kind === "document") {
243
+ const catalog = await resolve(document.crossReference.rootRef);
244
+ const outlines = catalog?.kind === "dict" ? await resolve(dictGet(catalog, "Outlines")) : void 0;
245
+ if (outlines?.kind === "dict") for await (const { dict, level } of walk(dictGet(outlines, "First"), "Outlines")) {
246
+ const titleNode = await resolve(dictGet(dict, "Title"));
247
+ const title = titleNode?.kind === "string" ? decodePdfString(titleNode) : titleNode?.kind === "name" ? titleNode.decoded : "";
248
+ const index = await destinationIndex(dictGet(dict, "Dest") ?? dictGet(dict, "A"));
249
+ if (title) {
250
+ yield* line("", "BookmarkBegin");
251
+ yield* line("BookmarkTitle: ", title, true);
252
+ yield* line("BookmarkLevel: ", level);
253
+ yield* line("BookmarkPageNumber: ", index === void 0 ? 1 : index + 1);
254
+ }
255
+ }
256
+ async function rectangle(raw, strict) {
257
+ const node = await resolve(raw);
258
+ if (node?.kind !== "array" || node.items.length < 4) return;
259
+ const result = [];
260
+ for (const item of node.items.slice(0, 4)) {
261
+ const number = await resolve(item);
262
+ if (strict && number?.kind !== "number") return;
263
+ result.push(number?.kind === "number" ? number.value : 0);
264
+ }
265
+ return result;
266
+ }
267
+ for await (const page of document.pages()) {
268
+ let media, rotate, hasMedia = false, hasRotate = false;
269
+ for await (const parent of document.pageAncestors(page.dict)) {
270
+ if (!hasMedia && dictGet(parent, "MediaBox")) {
271
+ hasMedia = true;
272
+ media = dictGet(parent, "MediaBox");
273
+ }
274
+ if (!hasRotate && dictGet(parent, "Rotate")) {
275
+ hasRotate = true;
276
+ rotate = dictGet(parent, "Rotate");
277
+ }
278
+ if (hasMedia && hasRotate) break;
279
+ }
280
+ const box = await rectangle(media, true) ?? [0, 0, 612, 792], width = Math.abs(box[2] - box[0]), height = Math.abs(box[3] - box[1]);
281
+ const rotation = await resolve(rotate), norm = rotation?.kind === "number" ? (rotation.value % 360 + 360) % 360 : 0;
282
+ const direct = await rectangle(dictGet(page.dict, "MediaBox"), false) ?? [0, 0, width, height];
283
+ yield* line("", "PageMediaBegin");
284
+ yield* line("PageMediaNumber: ", page.index + 1);
285
+ yield* line("PageMediaRotation: ", norm === 90 || norm === 180 || norm === 270 ? norm : 0);
286
+ yield* line("PageMediaRect: ", direct.join(" "));
287
+ yield* line("PageMediaDimensions: ", `${width} ${height}`);
288
+ const crop = await rectangle(dictGet(page.dict, "CropBox"), false);
289
+ if (crop) {
290
+ yield* line("PageMediaCropBox: ", crop.join(" "));
291
+ yield* line("PageMediaCropRect: ", crop.join(" "));
292
+ }
293
+ }
294
+ const styles = { D: "DecimalArabicNumerals", R: "UppercaseRomanNumerals", r: "LowercaseRomanNumerals", A: "UppercaseLetters", a: "LowercaseLetters" };
295
+ if (catalog?.kind === "dict") for await (const { dict } of walk(dictGet(catalog, "PageLabels"), "Kids")) {
296
+ const pairs = await resolve(dictGet(dict, "Nums"));
297
+ if (pairs?.kind !== "array") continue;
298
+ for (let i = 0; i + 1 < pairs.items.length; i += 2) {
299
+ const number = await resolve(pairs.items[i]), label = await resolve(pairs.items[i + 1]);
300
+ if (number?.kind !== "number" || label?.kind !== "dict") continue;
301
+ const start = await resolve(dictGet(label, "St")), prefix = await resolve(dictGet(label, "P")), style = await resolve(dictGet(label, "S"));
302
+ yield* line("", "PageLabelBegin");
303
+ yield* line("PageLabelNewIndex: ", Math.max(1, number.value + 1));
304
+ yield* line("PageLabelStart: ", start?.kind === "number" ? start.value : 1);
305
+ if (prefix?.kind === "string" && decodePdfString(prefix)) yield* line("PageLabelPrefix: ", decodePdfString(prefix), true);
306
+ yield* line("PageLabelNumStyle: ", style?.kind === "name" ? styles[style.decoded] ?? "NoNumber" : "NoNumber");
307
+ }
308
+ }
309
+ return;
310
+ }
165
311
  for await (const page of document.pages()) {
166
312
  const annotations = await resolve(dictGet(page.dict, "Annots"));
167
313
  if (annotations?.kind !== "array") continue;
@@ -195,7 +341,7 @@ async function* retainedAnnotationReport(document, storage, utf8, signal) {
195
341
  yield* line("AnnotFlags: ", flags?.kind === "number" ? flags.value : 0);
196
342
  yield* line("AnnotPageNumber: ", page.index + 1);
197
343
  const action = dictGet(annotation, "A");
198
- if (action) for await (const dict of walk(action, "Next")) {
344
+ if (action) for await (const { dict } of walk(action, "Next")) {
199
345
  const type = await resolve(dictGet(dict, "S"));
200
346
  if (type?.kind === "name" && type.decoded) yield* line("AnnotActionType: ", type.decoded);
201
347
  yield* stringField(dict, "URI", "AnnotActionURI: ");
@@ -229,10 +375,466 @@ async function* retainedAnnotationReport(document, storage, utf8, signal) {
229
375
  }
230
376
  }
231
377
 
378
+ // packages/safe-bash-command-pdftk/src/retained-burst.ts
379
+ async function* retainedBurst(document, storage, options, pageCount, signal) {
380
+ const pattern = options.outputTarget ?? "pg_%04d.pdf";
381
+ const slash = pattern.lastIndexOf("/");
382
+ const report = slash < 0 ? "doc_data.txt" : `${pattern.slice(0, slash + 1)}doc_data.txt`;
383
+ const repeated = formatBurstFilename(pattern, 1) === formatBurstFilename(pattern, 2);
384
+ for (let index = repeated ? Math.max(0, pageCount - 1) : 0; index < pageCount; index++) {
385
+ signal.throwIfAborted();
386
+ const path = formatBurstFilename(pattern, index + 1);
387
+ if (path === "-" || path === report) continue;
388
+ const copy = await createRetainedPageCopy(document, [index], storage, { signal });
389
+ let failed = false;
390
+ try {
391
+ const chunks = options.compressStreams || options.uncompressStreams ? saveRetainedDocumentChunks(await copy.openDocument(), storage, { signal, streamMode: options.uncompressStreams ? "uncompress" : "compress" }) : copy.chunks();
392
+ yield { path, chunks };
393
+ } catch (error) {
394
+ failed = true;
395
+ throw error;
396
+ } finally {
397
+ await copy.close().catch((error) => {
398
+ if (!failed) throw error;
399
+ });
400
+ }
401
+ }
402
+ yield { path: report, chunks: retainedInspectionReport(document, storage, false, signal, "document") };
403
+ }
404
+
405
+ // packages/safe-bash-command-pdftk/src/retained-rotate.ts
406
+ import { PagedStorage as PagedStorage2 } from "@poe-platform/safe-fs/storage";
407
+ async function* retainedRotations(args, handles, primaryHandle, pageCount, storage, signal) {
408
+ const records = new PagedStorage2({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
409
+ const base = records.allocate(pageCount * 16);
410
+ let failed = false, work = 0;
411
+ try {
412
+ for (const arg of args) for (const selection of iteratePdftkRangeToken(arg, handles, primaryHandle)) {
413
+ signal.throwIfAborted();
414
+ if (++work % 64 === 0) await new Promise((resolve) => setTimeout(resolve, 0));
415
+ if (!selection.rotation || selection.pageNumber > pageCount) continue;
416
+ const bytes = new Uint8Array(16), view = new DataView(bytes.buffer);
417
+ view.setFloat64(0, selection.rotation.kind === "relative" ? 2 : 1);
418
+ view.setFloat64(8, selection.rotation.degrees);
419
+ await records.write(base + (selection.pageNumber - 1) * 16, bytes);
420
+ }
421
+ for (let pageIndex = 0; pageIndex < pageCount; pageIndex++) {
422
+ signal.throwIfAborted();
423
+ if (++work % 64 === 0) await new Promise((resolve) => setTimeout(resolve, 0));
424
+ const bytes = await records.read(base + pageIndex * 16, 16), view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length), kind = view.getFloat64(0);
425
+ if (kind) yield { pageIndex, degrees: view.getFloat64(8), relative: kind === 2 };
426
+ }
427
+ } catch (error) {
428
+ failed = true;
429
+ throw error;
430
+ } finally {
431
+ await records.close().catch((error) => {
432
+ if (!failed) throw error;
433
+ });
434
+ }
435
+ }
436
+
437
+ // packages/safe-bash-command-pdftk/src/retained-output.ts
438
+ import { editRetainedDocument, PdfFileSource, PdfMutableObjectStore as PdfMutableObjectStore2, PdfRetainedDocument, cosBool, dictDelete, dictGet as dictGet2, dictSet, encryptRetainedPdfChunks, retainedCosObjects, saveRetainedDocumentChunks as saveRetainedDocumentChunks2 } from "../pdf-ast/index.js";
439
+ async function* retainedOutput(source, storage, options, selectedId, signal, handles, pageCount, attachments, attachmentPage, stamps) {
440
+ const store = new PdfMutableObjectStore2(storage, { signal });
441
+ let edited;
442
+ let document, plaintext, failed = false;
443
+ try {
444
+ if (options.operation === "attach_files" || stamps) {
445
+ const pageIndex = attachmentPage !== void 0 && pageCount > 0 ? attachmentPage.toLowerCase() === "end" ? pageCount - 1 : Math.max(0, Math.min(pageCount - 1, (Number.parseInt(attachmentPage, 10) || 1) - 1)) : void 0;
446
+ edited = await editRetainedDocument(source, storage, { signal, ...options.operation === "attach_files" ? { appendAttachments: attachments } : {}, ...stamps ? { stamps } : {}, ...pageIndex !== void 0 ? { attachmentPageIndex: pageIndex } : {} });
447
+ }
448
+ const input = edited?.document ?? source;
449
+ const pageReferences = edited ? { pageReferences: async function* () {
450
+ for await (const page of input.pages()) if (page.reference) yield page.reference;
451
+ } } : {};
452
+ for await (const object of retainedCosObjects(input, storage, { signal })) await store.set(object);
453
+ const reference = source.crossReference;
454
+ const idArray = options.keepFinalId || options.keepFirstId ? selectedId ?? reference.idArray : reference.idArray ?? selectedId;
455
+ document = await PdfRetainedDocument.openStore(store, storage, { rootRef: reference.rootRef, version: reference.version, ...pageReferences, ...reference.infoRef ? { infoRef: reference.infoRef } : {}, ...idArray ? { idArray } : {}, signal });
456
+ const root = await document.lookup(reference.rootRef);
457
+ if (root?.value.kind === "dict" && !root.stream && root.reference) {
458
+ const form = await document.lookup(dictGet2(root.value, "AcroForm"));
459
+ if (form?.value.kind === "dict" && !form.stream) {
460
+ if (options.dropXfa) dictDelete(form.value, "XFA");
461
+ if (options.needAppearances) dictSet(form.value, "NeedAppearances", cosBool(true));
462
+ if (form.reference) await store.set({ objectNumber: form.reference.objectNumber, generationNumber: form.reference.generationNumber, value: form.value });
463
+ else dictSet(root.value, "AcroForm", form.value);
464
+ }
465
+ await store.set({ objectNumber: root.reference.objectNumber, generationNumber: root.reference.generationNumber, value: root.value });
466
+ }
467
+ const chunks = saveRetainedDocumentChunks2(document, storage, { signal, ...options.operation === "rotate" ? { rotations: retainedRotations(options.opArgs, handles, options.inputs[0].handle, pageCount, storage, signal) } : {}, removeMetadata: options.dropXmp, streamMode: options.uncompressStreams ? "uncompress" : options.compressStreams ? "compress" : "preserve" });
468
+ if (!options.userPassword && !options.ownerPassword) {
469
+ yield* chunks;
470
+ return;
471
+ }
472
+ plaintext = await PdfFileSource.fromStream(storage.fs, storage.directory, chunks, { signal });
473
+ const allow = options.allowPermissions, all = allow.has("allfeatures");
474
+ yield* encryptRetainedPdfChunks(plaintext, storage, {
475
+ userPassword: options.userPassword ?? "",
476
+ ownerPassword: options.ownerPassword ?? options.userPassword ?? "owner",
477
+ revision: 6,
478
+ signal,
479
+ ...allow.size ? { permissions: { print: all || allow.has("printing") || allow.has("degradedprinting"), modify: all || allow.has("modifycontents"), copy: all || allow.has("copycontents"), addNotes: all || allow.has("modifyannotations"), fillForms: all || allow.has("fillin") || allow.has("modifyannotations"), extractAccessibility: all || allow.has("screenreaders"), assemble: all || allow.has("assembly") || allow.has("modifycontents"), printHighRes: all || allow.has("printing") } } : {}
480
+ });
481
+ } catch (error) {
482
+ failed = true;
483
+ throw error;
484
+ } finally {
485
+ const results = await Promise.allSettled([document?.close(), plaintext?.close(), store.close(), edited?.close()]);
486
+ if (!failed) {
487
+ for (const result of results) if (result.status === "rejected") await Promise.reject(result.reason);
488
+ }
489
+ }
490
+ }
491
+
492
+ // packages/safe-bash-command-pdftk/src/retained-unpack.ts
493
+ import { IntegerTable as IntegerTable2, PagedStorage as PagedStorage3 } from "@poe-platform/safe-fs/storage";
494
+ import { PdfFileSource as PdfFileSource2, PdfMutableObjectStore as PdfMutableObjectStore3, PdfNameIndex as PdfNameIndex2, cosDict, cosString, decodePdfString as decodePdfString2, dictGet as dictGet3 } from "../pdf-ast/index.js";
495
+ async function* retainedUnpack(document, storage, directory, inputNames, signal) {
496
+ const names = new PdfNameIndex2(storage, Infinity, signal), outputs = new PdfMutableObjectStore3(storage, { signal });
497
+ const stack = new PdfMutableObjectStore3(storage, { signal }), backing = new PagedStorage3({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), seen = new IntegerTable2(backing, 64);
498
+ const cleanDir = directory.endsWith("/") ? directory.slice(0, -1) : directory;
499
+ let pending = 0, work = 0, failed = false;
500
+ async function checkpoint() {
501
+ signal.throwIfAborted();
502
+ if (++work % 64 === 0) await new Promise((resolve2) => setTimeout(resolve2, 0));
503
+ signal.throwIfAborted();
504
+ }
505
+ async function resolve(node) {
506
+ await checkpoint();
507
+ const found = await document.lookup(node);
508
+ return found?.stream ? void 0 : found?.value;
509
+ }
510
+ async function spec(raw, fallback = "attachment.bin") {
511
+ const dict = await resolve(raw);
512
+ if (dict?.kind !== "dict") return;
513
+ const filename = await resolve(dictGet3(dict, "UF") ?? dictGet3(dict, "F"));
514
+ const name = filename?.kind === "string" ? decodePdfString2(filename) : fallback;
515
+ const leaf = name.slice(Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")) + 1);
516
+ if (!leaf || leaf === "." || leaf === ".." || leaf.includes("\0")) throw new Error("Invalid embedded attachment filename");
517
+ const ef = await resolve(dictGet3(dict, "EF"));
518
+ if (ef?.kind !== "dict") return;
519
+ const data = await document.lookup(dictGet3(ef, "UF") ?? dictGet3(ef, "F") ?? dictGet3(ef, "DOS") ?? dictGet3(ef, "Mac") ?? dictGet3(ef, "Unix"));
520
+ if (!data?.stream || !data.reference) return;
521
+ const path = cleanDir && cleanDir !== "." ? `${cleanDir}/${leaf}` : leaf;
522
+ const nameIndex = await names.intern(path);
523
+ const staged = await PdfFileSource2.fromStream(storage.fs, storage.directory, document.objects.decodeStream(data.reference.objectNumber, data.reference.generationNumber), { signal });
524
+ let failed2 = false;
525
+ try {
526
+ await outputs.set({ objectNumber: nameIndex.index + 1, generationNumber: 0, value: cosDict({ Path: cosString(path) }), stream: { length: staged.size, chunks: staged.stream(0, staged.size, signal) } });
527
+ } catch (error) {
528
+ failed2 = true;
529
+ throw error;
530
+ } finally {
531
+ await staged.close().catch((error) => {
532
+ if (!failed2) throw error;
533
+ });
534
+ }
535
+ }
536
+ const push = async (value) => {
537
+ await checkpoint();
538
+ await stack.set({ objectNumber: ++pending, generationNumber: 0, value });
539
+ };
540
+ async function associated(raw) {
541
+ const array = await resolve(raw);
542
+ if (array?.kind === "array") for (const item of array.items) await spec(item);
543
+ }
544
+ try {
545
+ for (const name of inputNames) await names.intern(name);
546
+ const root = await resolve(document.crossReference.rootRef);
547
+ if (root?.kind === "dict") {
548
+ const dictionary = await resolve(dictGet3(root, "Names")), tree = dictionary?.kind === "dict" ? dictGet3(dictionary, "EmbeddedFiles") : void 0;
549
+ if (tree) await push(tree);
550
+ while (pending) {
551
+ await checkpoint();
552
+ const raw = (await stack.get(pending--)).value;
553
+ if (raw.kind === "ref") {
554
+ if (await seen.get(BigInt(raw.objectNumber))) continue;
555
+ await seen.set(BigInt(raw.objectNumber), 1n);
556
+ }
557
+ const branch = await resolve(raw);
558
+ if (branch?.kind !== "dict") continue;
559
+ const pairs = await resolve(dictGet3(branch, "Names"));
560
+ if (pairs?.kind === "array") for (let i = 0; i + 1 < pairs.items.length; i += 2) {
561
+ const name = await resolve(pairs.items[i]);
562
+ await spec(pairs.items[i + 1], name?.kind === "string" ? decodePdfString2(name) : "attachment.bin");
563
+ }
564
+ const kids = await resolve(dictGet3(branch, "Kids"));
565
+ if (kids?.kind === "array") for (let i = kids.items.length - 1; i >= 0; i--) await push(kids.items[i]);
566
+ }
567
+ await associated(dictGet3(root, "AF"));
568
+ }
569
+ for await (const page of document.pages()) {
570
+ await associated(dictGet3(page.dict, "AF"));
571
+ const annotations = await resolve(dictGet3(page.dict, "Annots"));
572
+ if (annotations?.kind === "array") for (const raw of annotations.items) {
573
+ const annotation = await resolve(raw);
574
+ if (annotation?.kind !== "dict") continue;
575
+ const type = await resolve(dictGet3(annotation, "Subtype"));
576
+ if (type?.kind === "name" && type.decoded === "FileAttachment") await spec(dictGet3(annotation, "FS"));
577
+ }
578
+ }
579
+ for await (const output of outputs.objects()) {
580
+ const path = output.value.kind === "dict" ? dictGet3(output.value, "Path") : void 0;
581
+ if (path?.kind === "string" && output.stream) {
582
+ const name = decodePdfString2(path);
583
+ if (name !== "-") yield { path: name, chunks: output.stream.chunks };
584
+ }
585
+ }
586
+ } catch (error) {
587
+ failed = true;
588
+ throw error;
589
+ } finally {
590
+ const results = await Promise.allSettled([names.close(), outputs.close(), stack.close(), backing.close()]);
591
+ if (!failed) {
592
+ for (const result of results) if (result.status === "rejected") await Promise.reject(result.reason);
593
+ }
594
+ }
595
+ }
596
+
597
+ // packages/safe-bash-command-pdftk/src/retained-fdf.ts
598
+ import { PdfError, PdfFileSource as PdfFileSource3, PdfMutableObjectStore as PdfMutableObjectStore4, PdfNameIndex as PdfNameIndex3, cosArray as cosArray2, cosDict as cosDict2, cosNumber as cosNumber2, cosString as cosString2, decodePdfString as decodePdfString3, dictGet as dictGet4 } from "../pdf-ast/index.js";
599
+ async function* retainedFdf(document, storage, signal) {
600
+ const names = new PdfNameIndex3(storage, Infinity, signal);
601
+ const values = new PdfMutableObjectStore4(storage, { signal });
602
+ const tree = new PdfMutableObjectStore4(storage, { signal });
603
+ const encoder = new TextEncoder();
604
+ let work = 0, failed = false;
605
+ async function checkpoint() {
606
+ signal.throwIfAborted();
607
+ if (++work % 64 === 0) await new Promise((resolve2) => setTimeout(resolve2, 0));
608
+ signal.throwIfAborted();
609
+ }
610
+ async function resolve(node) {
611
+ await checkpoint();
612
+ const found = await document.lookup(node);
613
+ return found?.stream ? void 0 : found?.value;
614
+ }
615
+ async function* text(value, escape = false) {
616
+ let chunk = "";
617
+ for (const char of value) {
618
+ chunk += escape ? char === "\\" || char === "(" || char === ")" ? `\\${char}` : char === "\r" ? "\\r" : char === "\n" ? "\\n" : char : char;
619
+ if (chunk.length >= 4096) {
620
+ await checkpoint();
621
+ yield encoder.encode(chunk);
622
+ chunk = "";
623
+ }
624
+ }
625
+ if (chunk) {
626
+ signal.throwIfAborted();
627
+ yield encoder.encode(chunk);
628
+ }
629
+ }
630
+ async function* fieldValue(field) {
631
+ if (field.checked !== void 0) {
632
+ yield* text(`/${field.checked ? field.stateValue ?? "Yes" : "Off"}`);
633
+ return;
634
+ }
635
+ let count = 0;
636
+ for await (const ignored of field.values()) {
637
+ void ignored;
638
+ if (++count > 1) break;
639
+ }
640
+ if (count > 1) yield* text("[ ");
641
+ let first = true;
642
+ for await (const value of field.values()) {
643
+ if (!first) yield* text(" ");
644
+ first = false;
645
+ yield* text("(");
646
+ yield* text(value, true);
647
+ yield* text(")");
648
+ }
649
+ if (count > 1) yield* text(" ]");
650
+ }
651
+ async function record(id) {
652
+ const node = (await tree.get(id))?.value;
653
+ if (node?.kind !== "array") throw new PdfError("E_PARSE", "Invalid FDF traversal record");
654
+ return node.items;
655
+ }
656
+ const number = (items, at) => {
657
+ const node = items[at];
658
+ if (node?.kind !== "number") throw new PdfError("E_PARSE", "Invalid FDF traversal number");
659
+ return node.value;
660
+ };
661
+ const string = (items, at) => {
662
+ const node = items[at];
663
+ if (node?.kind !== "string") throw new PdfError("E_PARSE", "Invalid FDF traversal name");
664
+ return decodePdfString3(node);
665
+ };
666
+ const save = async (id, items) => tree.set({ objectNumber: id, generationNumber: 0, value: cosArray2(items) });
667
+ try {
668
+ for await (const field of document.formFieldDetails()) {
669
+ for await (const ignored of field.options()) void ignored;
670
+ const name = await names.intern(field.name);
671
+ const staged = await PdfFileSource3.fromStream(storage.fs, storage.directory, fieldValue(field), { signal });
672
+ let valueFailed = false;
673
+ try {
674
+ await values.set({ objectNumber: name.index + 1, generationNumber: 0, value: cosDict2({}), stream: { length: staged.size, chunks: staged.stream(0, staged.size, signal) } });
675
+ } catch (error) {
676
+ valueFailed = true;
677
+ throw error;
678
+ } finally {
679
+ await staged.close().catch((error) => {
680
+ if (!valueFailed) throw error;
681
+ });
682
+ }
683
+ }
684
+ const catalog = await resolve(document.crossReference.rootRef);
685
+ const form = catalog?.kind === "dict" ? await resolve(dictGet4(catalog, "AcroForm")) : void 0;
686
+ const roots = form?.kind === "dict" ? await resolve(dictGet4(form, "Fields")) : void 0;
687
+ await save(1, [cosDict2({}), cosString2(""), cosString2(""), ...Array.from({ length: 6 }, () => cosNumber2(0))]);
688
+ let top = 1, next = 1;
689
+ while (top) {
690
+ await checkpoint();
691
+ const frame = await record(top), node = await resolve(frame[0]);
692
+ const kids = top === 1 ? roots : node?.kind === "dict" ? await resolve(dictGet4(node, "Kids")) : void 0;
693
+ let descended = false, cursor = number(frame, 3);
694
+ while (kids?.kind === "array" && cursor < kids.items.length) {
695
+ const childNode = kids.items[cursor++], child = await resolve(childNode);
696
+ if (child?.kind !== "dict" || top !== 1 && !dictGet4(child, "T")) continue;
697
+ const name = await resolve(dictGet4(child, "T")), partial = name?.kind === "string" ? decodePdfString3(name) : "";
698
+ const prefix = string(frame, 1), full = prefix && partial ? `${prefix}.${partial}` : partial || prefix;
699
+ const depth = number(frame, 8) + 1;
700
+ if (depth > document.depthLimit) throw new PdfError("E_LIMIT", "PDF FDF field depth limit exceeded");
701
+ frame[3] = cosNumber2(cursor);
702
+ await save(top, frame);
703
+ await save(++next, [childNode, cosString2(full), cosString2(partial), cosNumber2(0), cosNumber2(0), cosNumber2(0), cosNumber2(0), cosNumber2(top), cosNumber2(depth)]);
704
+ top = next;
705
+ descended = true;
706
+ break;
707
+ }
708
+ if (descended) continue;
709
+ const parent = number(frame, 7);
710
+ if (parent && (number(frame, 4) || string(frame, 1) || string(frame, 2))) {
711
+ const owner = await record(parent), last = number(owner, 5);
712
+ if (last) {
713
+ const sibling = await record(last);
714
+ sibling[6] = cosNumber2(top);
715
+ await save(last, sibling);
716
+ } else owner[4] = cosNumber2(top);
717
+ owner[5] = cosNumber2(top);
718
+ await save(parent, owner);
719
+ }
720
+ top = parent;
721
+ }
722
+ yield* text("%FDF-1.2\n1 0 obj\n<< /FDF << /Fields [\n");
723
+ let current = number(await record(1), 4);
724
+ if (current) yield* text(" ");
725
+ while (current) {
726
+ await checkpoint();
727
+ const frame = await record(current), child = number(frame, 4);
728
+ yield* text("<< /T (");
729
+ yield* text(string(frame, 2) || string(frame, 1), true);
730
+ yield* text(")");
731
+ if (child) {
732
+ yield* text(" /Kids [ ");
733
+ current = child;
734
+ continue;
735
+ }
736
+ yield* text(" /V ");
737
+ const name = await names.intern(string(frame, 1)), value = name.added ? void 0 : await values.get(name.index + 1);
738
+ if (value?.stream) yield* value.stream.chunks;
739
+ else {
740
+ const dict = await resolve(frame[0]), raw = dict?.kind === "dict" ? await resolve(dictGet4(dict, "V")) : void 0;
741
+ if (raw?.kind === "name") yield* text(`/${raw.decoded}`);
742
+ else {
743
+ yield* text("(");
744
+ if (raw?.kind === "string") yield* text(decodePdfString3(raw), true);
745
+ yield* text(")");
746
+ }
747
+ }
748
+ yield* text(" >>");
749
+ while (current) {
750
+ const done = await record(current), sibling = number(done, 6), parent = number(done, 7);
751
+ if (sibling) {
752
+ yield* text(parent === 1 ? "\n " : " ");
753
+ current = sibling;
754
+ break;
755
+ }
756
+ current = parent === 1 ? 0 : parent;
757
+ if (current) yield* text(" ] >>");
758
+ }
759
+ }
760
+ yield* text("\n] >> >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n");
761
+ } catch (error) {
762
+ failed = true;
763
+ throw error;
764
+ } finally {
765
+ const results = await Promise.allSettled([names.close(), values.close(), tree.close()]);
766
+ if (!failed) {
767
+ for (const result of results) if (result.status === "rejected") await Promise.reject(result.reason);
768
+ }
769
+ }
770
+ }
771
+
772
+ // packages/safe-bash-command-pdftk/src/retained-fields.ts
773
+ async function* retainedFieldReport(document, utf8, signal) {
774
+ const encoder = new TextEncoder();
775
+ let work = 0;
776
+ async function* line(prefix, value) {
777
+ let part = prefix;
778
+ for (const char of String(value)) {
779
+ const code = char.codePointAt(0);
780
+ part += !utf8 && code > 127 ? `&#${code};` : char;
781
+ if (part.length >= 4096) {
782
+ signal.throwIfAborted();
783
+ if (++work % 16 === 0) await new Promise((resolve) => setTimeout(resolve, 0));
784
+ yield encoder.encode(part);
785
+ part = "";
786
+ }
787
+ }
788
+ signal.throwIfAborted();
789
+ yield encoder.encode(part + "\n");
790
+ }
791
+ for await (const field of document.formFieldDetails()) {
792
+ yield encoder.encode("---\n");
793
+ yield* line("FieldType: ", field.type === "checkbox" ? "Button" : field.type === "choice" ? "Choice" : "Text");
794
+ yield* line("FieldName: ", field.name);
795
+ if (field.altName) yield* line("FieldNameAlt: ", field.altName);
796
+ yield* line("FieldFlags: ", field.flags);
797
+ for await (const value of field.values()) yield* line("FieldValue: ", value);
798
+ if (field.defaultValue !== void 0 && field.defaultValue !== "") yield* line("FieldValueDefault: ", field.defaultValue);
799
+ yield* line("FieldJustification: ", field.justification);
800
+ for await (const option of field.options()) yield* line("FieldStateOption: ", option);
801
+ if (field.maxLength !== void 0) yield* line("FieldMaxLength: ", field.maxLength);
802
+ }
803
+ }
804
+
232
805
  // packages/safe-bash-command-pdftk/src/retained.ts
806
+ import { PdfError as PdfError2, PdfFileSource as PdfFileSource4, PdfRetainedDocument as PdfRetainedDocument2, retainedCosObjects as retainedCosObjects2 } from "../pdf-ast/index.js";
807
+ import { FsError } from "../safe-bash-contracts/errors.js";
808
+ import { writeBytes } from "../safe-bash-contracts/io.js";
809
+ import { resolvePath } from "../safe-bash-contracts/path.js";
810
+ import { writeFileOutput } from "../safe-bash-contracts/filesystem-output-budget.js";
233
811
  async function executeRetainedPdftk(context, options) {
234
812
  const signal = context.signal, storage = { fs: context.fs, directory: resolvePath(context.cwd, context.env.TMPDIR || "/tmp") };
813
+ const handles = /* @__PURE__ */ new Map();
814
+ for (const input of options.inputs) {
815
+ handles.set(input.handle, input);
816
+ if (!handles.has("")) handles.set("", input);
817
+ }
818
+ const primary = options.inputs[0];
819
+ let idInput = handles.values().next().value;
820
+ if (options.keepFinalId) for (const input of handles.values()) idInput = input;
821
+ let selectedId;
822
+ const counts = /* @__PURE__ */ new Map();
235
823
  const inputs = /* @__PURE__ */ new Map();
824
+ const overlayPath = ["stamp", "multistamp", "background", "multibackground"].includes(options.operation) ? options.opArgs[0] ?? "-" : void 0;
825
+ const attachmentPaths = [];
826
+ let attachmentPage;
827
+ if (options.operation === "attach_files") for (let i = 0; i < options.opArgs.length; i++) {
828
+ if (options.opArgs[i].toLowerCase() === "to_page") attachmentPage = options.opArgs[++i];
829
+ else attachmentPaths.push(options.opArgs[i]);
830
+ }
831
+ async function* attachments() {
832
+ for (const path of attachmentPaths) {
833
+ const source = inputs.get(path);
834
+ if (source) yield { filename: path.slice(path.lastIndexOf("/") + 1), chunks: source.stream(0, source.size, signal) };
835
+ }
836
+ }
837
+ let overlayDocument;
236
838
  let document, output, total = 0, failed = false;
237
839
  const diagnostic = async (message) => {
238
840
  await writeBytes(context.stderr, new TextEncoder().encode(message), signal);
@@ -241,20 +843,20 @@ async function executeRetainedPdftk(context, options) {
241
843
  try {
242
844
  await context.fs.mkdir(storage.directory, { recursive: true, signal });
243
845
  const maximum = context.inputBudget?.maxBytes ?? Infinity;
244
- if (options.inputs.some((input) => input.file === "-")) {
245
- const source = await PdfFileSource.fromStream(context.fs, storage.directory, context.stdin, { signal, maxInputBytes: maximum });
846
+ if (options.inputs.some((input) => input.file === "-") || attachmentPaths.includes("-") || overlayPath === "-") {
847
+ const source = await PdfFileSource4.fromStream(context.fs, storage.directory, context.stdin, { signal, maxInputBytes: maximum });
246
848
  inputs.set("-", source);
247
849
  total += source.size;
248
850
  context.inputBudget?.check(total);
249
851
  }
250
- for (const input of options.inputs) {
852
+ for (const input of [...options.inputs, ...attachmentPaths.map((file) => ({ file })), ...overlayPath !== void 0 ? [{ file: overlayPath }] : []]) {
251
853
  if (inputs.has(input.file)) continue;
252
854
  let source;
253
855
  try {
254
- source = await PdfFileSource.open(context.fs, resolvePath(context.cwd, input.file), { signal, maxInputBytes: maximum - total });
856
+ source = await PdfFileSource4.open(context.fs, resolvePath(context.cwd, input.file), { signal, maxInputBytes: maximum - total });
255
857
  } catch (error) {
256
858
  signal.throwIfAborted();
257
- if (error instanceof Error && "code" in error && ["ENOENT", "ENOTDIR", "EACCES", "EISDIR"].includes(String(error.code)) || error instanceof PdfError && error.message === "PDF source must be a regular file") {
859
+ if (error instanceof Error && "code" in error && ["ENOENT", "ENOTDIR", "EACCES", "EISDIR"].includes(String(error.code)) || error instanceof PdfError2 && error.message === "PDF source must be a regular file") {
258
860
  inputs.set(input.file, void 0);
259
861
  continue;
260
862
  }
@@ -269,12 +871,18 @@ async function executeRetainedPdftk(context, options) {
269
871
  if (!source) return await diagnostic(`Error: Unable to find file '${input.file}'
270
872
  `);
271
873
  try {
272
- document = await PdfRetainedDocument.open(source, storage, { signal, recovery: "strict", ...input.password ? { password: input.password } : {} });
273
- for await (const object of retainedCosObjects(document, storage, { signal })) if (object.stream) for await (const ignored of object.stream.chunks) void ignored;
274
- for await (const ignored of document.pages()) void ignored;
874
+ document = await PdfRetainedDocument2.open(source, storage, { signal, recovery: "strict", ...input.password ? { password: input.password } : {} });
875
+ if (input === idInput) selectedId = document.crossReference.idArray;
876
+ for await (const object of retainedCosObjects2(document, storage, { signal })) if (object.stream) for await (const ignored of object.stream.chunks) void ignored;
877
+ let count = 0;
878
+ for await (const ignored of document.pages()) {
879
+ void ignored;
880
+ count++;
881
+ }
882
+ counts.set(input, count);
275
883
  } catch (error) {
276
884
  signal.throwIfAborted();
277
- if (!(error instanceof PdfError) || error.code === "E_LIMIT" || error.code === "E_CANCELLED") throw error;
885
+ if (!(error instanceof PdfError2) || error.code === "E_LIMIT" || error.code === "E_CANCELLED") throw error;
278
886
  return await diagnostic(`Error: Failed to open PDF '${input.file}': ${error.message}
279
887
  `);
280
888
  }
@@ -282,14 +890,42 @@ async function executeRetainedPdftk(context, options) {
282
890
  document = void 0;
283
891
  await source.releaseCache();
284
892
  }
285
- const primary = options.inputs[0];
286
- document = await PdfRetainedDocument.open(inputs.get(primary.file), storage, { signal, recovery: "strict", ...primary.password ? { password: primary.password } : {} });
287
- output = await PdfFileSource.fromStream(context.fs, storage.directory, retainedAnnotationReport(document, storage, options.operation.endsWith("_utf8"), signal), { signal });
893
+ document = await PdfRetainedDocument2.open(inputs.get(primary.file), storage, { signal, recovery: "strict", ...primary.password ? { password: primary.password } : {} });
894
+ let overlayPages = 0;
895
+ if (overlayPath !== void 0) {
896
+ const source = inputs.get(overlayPath);
897
+ if (!source) return await diagnostic(`Error: Unable to open '${overlayPath}'
898
+ `);
899
+ overlayDocument = await PdfRetainedDocument2.open(source, storage, { signal, recovery: "strict" });
900
+ for await (const object of retainedCosObjects2(overlayDocument, storage, { signal })) if (object.stream) for await (const ignored of object.stream.chunks) void ignored;
901
+ for await (const ignored of overlayDocument.pages()) {
902
+ void ignored;
903
+ overlayPages++;
904
+ }
905
+ }
906
+ async function* stampPages() {
907
+ if (overlayPages) for (let targetIndex = 0; targetIndex < counts.get(primary); targetIndex++) yield { targetIndex, sourceIndex: options.operation.startsWith("multi") ? Math.min(targetIndex, overlayPages - 1) : 0 };
908
+ }
909
+ if (options.operation === "unpack_files" || options.operation === "burst") {
910
+ const files = options.operation === "burst" ? retainedBurst(document, storage, options, counts.get(primary), signal) : retainedUnpack(document, storage, options.outputTarget ?? ".", inputs.keys(), signal);
911
+ for await (const file of files) {
912
+ try {
913
+ await publish(context, resolvePath(context.cwd, file.path), file.chunks);
914
+ } catch (error) {
915
+ signal.throwIfAborted();
916
+ if (!(error instanceof Error) || !("code" in error)) throw error;
917
+ return await diagnostic(`Error: Failed to open output file '${file.path}': ${error.code}.
918
+ `);
919
+ }
920
+ }
921
+ return { exitCode: 0 };
922
+ }
923
+ output = await PdfFileSource4.fromStream(context.fs, storage.directory, ["output", "rotate", "attach_files", "stamp", "multistamp", "background", "multibackground"].includes(options.operation) ? retainedOutput(document, storage, options, selectedId, signal, new Map([...handles].map(([handle, input]) => [handle, { pageCount: counts.get(input) }])), counts.get(primary), attachments(), attachmentPage, overlayDocument ? [{ source: overlayDocument, mode: options.operation.includes("background") ? "underlay" : "overlay", preserveStreams: true, pages: stampPages() }] : void 0) : options.operation === "generate_fdf" ? retainedFdf(document, storage, signal) : options.operation === "dump_data_fields" || options.operation === "dump_data_fields_utf8" ? retainedFieldReport(document, options.operation.endsWith("_utf8"), signal) : retainedInspectionReport(document, storage, options.operation.endsWith("_utf8"), signal, options.operation === "dump_data" || options.operation === "dump_data_utf8" ? "document" : "annotations"), { signal });
288
924
  const destination = options.outputTarget;
289
925
  if (!destination || destination === "-") for await (const bytes of output.stream(0, output.size, signal)) await writeBytes(context.stdout, bytes, signal);
290
926
  else {
291
927
  try {
292
- await publish(context, resolvePath(context.cwd, destination), output);
928
+ await publish(context, resolvePath(context.cwd, destination), output.stream(0, output.size, signal));
293
929
  } catch (error) {
294
930
  signal.throwIfAborted();
295
931
  if (!(error instanceof Error) || !("code" in error)) throw error;
@@ -302,13 +938,13 @@ async function executeRetainedPdftk(context, options) {
302
938
  failed = true;
303
939
  throw error;
304
940
  } finally {
305
- const results = await Promise.allSettled([document?.close(), output?.close(), ...[...inputs.values()].map((source) => source?.close())]);
941
+ const results = await Promise.allSettled([document?.close(), overlayDocument?.close(), output?.close(), ...[...inputs.values()].map((source) => source?.close())]);
306
942
  if (!failed) {
307
943
  for (const result of results) if (result.status === "rejected") await Promise.reject(result.reason);
308
944
  }
309
945
  }
310
946
  }
311
- async function publish(context, path, source) {
947
+ async function publish(context, path, chunks) {
312
948
  const fs = context.fs, signal = context.signal;
313
949
  const capabilities = await fs.capabilitiesFor?.(path, { signal, create: true, stagingAncestry: true }) ?? fs.capabilities;
314
950
  if (!capabilities.atomicFileStaging || !capabilities.retainedStagingWrite || !capabilities.retainedStagingCleanup || !capabilities.atomicStagingAncestry || !fs.prepareStagingResolution || !fs.createStagedFile || !fs.publishStagedFile) throw new FsError("ENOTSUP", { path, message: "PDF output requires retained atomic staging" });
@@ -317,7 +953,7 @@ async function publish(context, path, source) {
317
953
  let failed = false;
318
954
  try {
319
955
  if (!staging.writer || !staging.cleanup) throw new FsError("ENOTSUP", { path, message: "PDF backend omitted retained staging handles" });
320
- for await (const bytes of source.stream(0, source.size, signal)) await writeFileOutput(context, bytes, (data) => staging.writer.write(data, { signal }));
956
+ for await (const bytes of chunks) await writeFileOutput(context, bytes, (data) => staging.writer.write(data, { signal }));
321
957
  const stat = await staging.writer.finish({ signal });
322
958
  await fs.publishStagedFile({ ...staging, file: { ...staging.file, stat } }, resolution.path, { parent: resolution.parent, destination: resolution.destination, ancestors: resolution.ancestors, commitGuard: resolution.validate, signal });
323
959
  } catch (error) {
@@ -515,17 +1151,17 @@ import { readBytes, writeBytes as writeBytes2 } from "../safe-bash-contracts/io.
515
1151
  import { createOutputOperation } from "../safe-bash-contracts/output.js";
516
1152
  import {
517
1153
  PdfDocument,
518
- cosArray,
519
- cosDict,
1154
+ cosArray as cosArray3,
1155
+ cosDict as cosDict3,
520
1156
  cosHexString,
521
1157
  cosName,
522
- cosNumber,
1158
+ cosNumber as cosNumber3,
523
1159
  cosStream,
524
- cosString,
525
- decodePdfString as decodePdfString2,
526
- dictDelete,
527
- dictGet as dictGet2,
528
- dictSet,
1160
+ cosString as cosString3,
1161
+ decodePdfString as decodePdfString4,
1162
+ dictDelete as dictDelete2,
1163
+ dictGet as dictGet5,
1164
+ dictSet as dictSet2,
529
1165
  flattenDocumentFormFields,
530
1166
  getDocumentFormFields,
531
1167
  parseFormDataBytes,
@@ -583,6 +1219,9 @@ function resolvePageEndpoint(token, totalPages) {
583
1219
  return Number.isFinite(num) && num >= 1 ? Math.min(totalPages, num) : 1;
584
1220
  }
585
1221
  function parsePdftkRangeToken(token, handles, defaultHandle) {
1222
+ return Array.from(iteratePdftkRangeToken(token, handles, defaultHandle));
1223
+ }
1224
+ function* iteratePdftkRangeToken(token, handles, defaultHandle) {
586
1225
  let work = token.trim();
587
1226
  let handle = defaultHandle;
588
1227
  const sortedHandleKeys = [...handles.keys()].sort((a, b) => b.length - a.length);
@@ -628,22 +1267,11 @@ function parsePdftkRangeToken(token, handles, defaultHandle) {
628
1267
  endPage = resolvePageEndpoint(work.slice(dashIdx + 1), totalPages);
629
1268
  }
630
1269
  }
631
- const pages = [];
632
- if (startPage <= endPage) {
633
- for (let p = startPage; p <= endPage; p++) pages.push(p);
634
- } else {
635
- for (let p = startPage; p >= endPage; p--) pages.push(p);
1270
+ const step = startPage <= endPage ? 1 : -1;
1271
+ for (let pageNumber = startPage; step > 0 ? pageNumber <= endPage : pageNumber >= endPage; pageNumber += step) {
1272
+ if (qualifier === "even" && pageNumber % 2 !== 0 || qualifier === "odd" && pageNumber % 2 !== 1) continue;
1273
+ yield { handle, pageNumber, rotation };
636
1274
  }
637
- const filtered = pages.filter((p) => {
638
- if (qualifier === "even") return p % 2 === 0;
639
- if (qualifier === "odd") return p % 2 === 1;
640
- return true;
641
- });
642
- return filtered.map((pageNumber) => ({
643
- handle,
644
- pageNumber,
645
- rotation
646
- }));
647
1275
  }
648
1276
  function encodePdftkText(str, utf8) {
649
1277
  if (utf8) return str;
@@ -740,40 +1368,40 @@ function formatDumpDataAnnots(doc, utf8 = false) {
740
1368
  lines.push(`NumberOfPages: ${doc.pageCount}`);
741
1369
  for (let p = 0; p < doc.pageCount; p++) {
742
1370
  const pageDict = doc.getPage(p).pageDict;
743
- const annotsArr = doc.cos.resolveArray(dictGet2(pageDict, "Annots"));
1371
+ const annotsArr = doc.cos.resolveArray(dictGet5(pageDict, "Annots"));
744
1372
  if (!annotsArr) continue;
745
1373
  for (const item of annotsArr.items) {
746
1374
  const annotDict = doc.cos.resolveDict(item);
747
1375
  if (!annotDict) continue;
748
- const subNode = doc.cos.resolve(dictGet2(annotDict, "Subtype"));
1376
+ const subNode = doc.cos.resolve(dictGet5(annotDict, "Subtype"));
749
1377
  const subtype = subNode?.kind === "name" ? subNode.decoded : "Annot";
750
- const rectArr = doc.cos.resolveArray(dictGet2(annotDict, "Rect"));
1378
+ const rectArr = doc.cos.resolveArray(dictGet5(annotDict, "Rect"));
751
1379
  const rectNums = rectArr ? rectArr.items.map((it) => {
752
1380
  const r = doc.cos.resolve(it);
753
1381
  return r?.kind === "number" ? r.value : 0;
754
1382
  }) : [0, 0, 0, 0];
755
- const flagsNode = doc.cos.resolve(dictGet2(annotDict, "F"));
1383
+ const flagsNode = doc.cos.resolve(dictGet5(annotDict, "F"));
756
1384
  const flags = flagsNode?.kind === "number" ? flagsNode.value : 0;
757
1385
  lines.push("---");
758
1386
  lines.push(`AnnotSubtype: ${subtype}`);
759
1387
  lines.push(`AnnotRect: ${rectNums.slice(0, 4).join(" ")}`);
760
- const nmNode = doc.cos.resolve(dictGet2(annotDict, "NM"));
1388
+ const nmNode = doc.cos.resolve(dictGet5(annotDict, "NM"));
761
1389
  if (nmNode?.kind === "string") {
762
- lines.push(`AnnotName: ${encodePdftkText(decodePdfString2(nmNode), utf8)}`);
1390
+ lines.push(`AnnotName: ${encodePdftkText(decodePdfString4(nmNode), utf8)}`);
763
1391
  }
764
- const tNode = doc.cos.resolve(dictGet2(annotDict, "T"));
1392
+ const tNode = doc.cos.resolve(dictGet5(annotDict, "T"));
765
1393
  if (tNode?.kind === "string") {
766
- lines.push(`AnnotTitle: ${encodePdftkText(decodePdfString2(tNode), utf8)}`);
1394
+ lines.push(`AnnotTitle: ${encodePdftkText(decodePdfString4(tNode), utf8)}`);
767
1395
  }
768
- const subjNode = doc.cos.resolve(dictGet2(annotDict, "Subj"));
1396
+ const subjNode = doc.cos.resolve(dictGet5(annotDict, "Subj"));
769
1397
  if (subjNode?.kind === "string") {
770
- lines.push(`AnnotSubj: ${encodePdftkText(decodePdfString2(subjNode), utf8)}`);
1398
+ lines.push(`AnnotSubj: ${encodePdftkText(decodePdfString4(subjNode), utf8)}`);
771
1399
  }
772
- const cNode = doc.cos.resolve(dictGet2(annotDict, "Contents"));
1400
+ const cNode = doc.cos.resolve(dictGet5(annotDict, "Contents"));
773
1401
  if (cNode?.kind === "string") {
774
- lines.push(`AnnotContents: ${encodePdftkText(decodePdfString2(cNode), utf8)}`);
1402
+ lines.push(`AnnotContents: ${encodePdftkText(decodePdfString4(cNode), utf8)}`);
775
1403
  }
776
- const colArr = doc.cos.resolveArray(dictGet2(annotDict, "C"));
1404
+ const colArr = doc.cos.resolveArray(dictGet5(annotDict, "C"));
777
1405
  if (colArr && colArr.items.length >= 3) {
778
1406
  const colNums = colArr.items.slice(0, 3).map((it) => {
779
1407
  const r = doc.cos.resolve(it);
@@ -781,20 +1409,20 @@ function formatDumpDataAnnots(doc, utf8 = false) {
781
1409
  });
782
1410
  lines.push(`AnnotColor: ${colNums.join(" ")}`);
783
1411
  }
784
- const openNode = doc.cos.resolve(dictGet2(annotDict, "Open"));
1412
+ const openNode = doc.cos.resolve(dictGet5(annotDict, "Open"));
785
1413
  if (openNode?.kind === "boolean") {
786
1414
  lines.push(`AnnotOpen: ${openNode.value}`);
787
1415
  }
788
- const mNode = doc.cos.resolve(dictGet2(annotDict, "M"));
1416
+ const mNode = doc.cos.resolve(dictGet5(annotDict, "M"));
789
1417
  if (mNode?.kind === "string") {
790
- lines.push(`AnnotModificationDate: ${encodePdftkText(decodePdfString2(mNode), utf8)}`);
1418
+ lines.push(`AnnotModificationDate: ${encodePdftkText(decodePdfString4(mNode), utf8)}`);
791
1419
  }
792
1420
  lines.push(`AnnotFlags: ${flags}`);
793
1421
  lines.push(`AnnotPageNumber: ${p + 1}`);
794
1422
  const formatDestTarget = (dRaw) => {
795
1423
  if (!dRaw) return void 0;
796
1424
  const resolved = doc.cos.resolve(dRaw);
797
- if (resolved?.kind === "string") return decodePdfString2(resolved);
1425
+ if (resolved?.kind === "string") return decodePdfString4(resolved);
798
1426
  if (resolved?.kind === "name") return resolved.decoded;
799
1427
  if (resolved?.kind === "array" && resolved.items.length > 0) {
800
1428
  const first = resolved.items[0];
@@ -827,16 +1455,16 @@ function formatDumpDataAnnots(doc, utf8 = false) {
827
1455
  }
828
1456
  const actionDict = doc.cos.resolveDict(aNode);
829
1457
  if (!actionDict) return;
830
- const sNode = doc.cos.resolve(dictGet2(actionDict, "S"));
1458
+ const sNode = doc.cos.resolve(dictGet5(actionDict, "S"));
831
1459
  const sType = sNode?.kind === "name" ? sNode.decoded : "";
832
1460
  if (sType) {
833
1461
  lines.push(`AnnotActionType: ${sType}`);
834
1462
  }
835
- const uriNode = doc.cos.resolve(dictGet2(actionDict, "URI"));
1463
+ const uriNode = doc.cos.resolve(dictGet5(actionDict, "URI"));
836
1464
  if (uriNode?.kind === "string") {
837
- lines.push(`AnnotActionURI: ${encodePdftkText(decodePdfString2(uriNode), utf8)}`);
1465
+ lines.push(`AnnotActionURI: ${encodePdftkText(decodePdfString4(uriNode), utf8)}`);
838
1466
  }
839
- const dNode = dictGet2(actionDict, "D");
1467
+ const dNode = dictGet5(actionDict, "D");
840
1468
  const destTarget = formatDestTarget(dNode);
841
1469
  if (destTarget) {
842
1470
  lines.push(`AnnotActionDest: ${encodePdftkText(destTarget, utf8)}`);
@@ -845,23 +1473,23 @@ function formatDumpDataAnnots(doc, utf8 = false) {
845
1473
  if (resolvedIdx !== void 0) {
846
1474
  lines.push(`AnnotActionPageNumber: ${resolvedIdx + 1}`);
847
1475
  }
848
- const fRaw = doc.cos.resolve(dictGet2(actionDict, "F"));
1476
+ const fRaw = doc.cos.resolve(dictGet5(actionDict, "F"));
849
1477
  if (fRaw?.kind === "string") {
850
- lines.push(`AnnotActionFile: ${encodePdftkText(decodePdfString2(fRaw), utf8)}`);
1478
+ lines.push(`AnnotActionFile: ${encodePdftkText(decodePdfString4(fRaw), utf8)}`);
851
1479
  } else if (fRaw?.kind === "dict") {
852
- const ufNode = doc.cos.resolve(dictGet2(fRaw, "UF") ?? dictGet2(fRaw, "F"));
1480
+ const ufNode = doc.cos.resolve(dictGet5(fRaw, "UF") ?? dictGet5(fRaw, "F"));
853
1481
  if (ufNode?.kind === "string") {
854
- lines.push(`AnnotActionFile: ${encodePdftkText(decodePdfString2(ufNode), utf8)}`);
1482
+ lines.push(`AnnotActionFile: ${encodePdftkText(decodePdfString4(ufNode), utf8)}`);
855
1483
  }
856
1484
  }
857
- emitActionChain(dictGet2(actionDict, "Next"), visited);
1485
+ emitActionChain(dictGet5(actionDict, "Next"), visited);
858
1486
  };
859
- const rawA = dictGet2(annotDict, "A");
1487
+ const rawA = dictGet5(annotDict, "A");
860
1488
  if (rawA) {
861
1489
  emitActionChain(rawA);
862
- } else if (dictGet2(annotDict, "Dest")) {
1490
+ } else if (dictGet5(annotDict, "Dest")) {
863
1491
  lines.push("AnnotActionType: GoTo");
864
- const dNode = dictGet2(annotDict, "Dest");
1492
+ const dNode = dictGet5(annotDict, "Dest");
865
1493
  const destTarget = formatDestTarget(dNode);
866
1494
  if (destTarget) {
867
1495
  lines.push(`AnnotActionDest: ${encodePdftkText(destTarget, utf8)}`);
@@ -907,18 +1535,18 @@ function collectOutlineBookmarks(doc, firstNode, level, out, visited = /* @__PUR
907
1535
  }
908
1536
  const dict = doc.cos.resolveDict(curr);
909
1537
  if (!dict) break;
910
- const titleNode = doc.cos.resolve(dictGet2(dict, "Title"));
911
- const title = titleNode?.kind === "string" ? decodePdfString2(titleNode) : titleNode?.kind === "name" ? titleNode.decoded : "";
912
- const resolvedIdx = resolveDestinationPageIndex(doc, dictGet2(dict, "Dest") ?? dictGet2(dict, "A"));
1538
+ const titleNode = doc.cos.resolve(dictGet5(dict, "Title"));
1539
+ const title = titleNode?.kind === "string" ? decodePdfString4(titleNode) : titleNode?.kind === "name" ? titleNode.decoded : "";
1540
+ const resolvedIdx = resolveDestinationPageIndex(doc, dictGet5(dict, "Dest") ?? dictGet5(dict, "A"));
913
1541
  const pageNumber = resolvedIdx !== void 0 ? resolvedIdx + 1 : 1;
914
1542
  if (title) {
915
1543
  out.push({ title, level, pageNumber });
916
1544
  }
917
- const childFirst = dictGet2(dict, "First");
1545
+ const childFirst = dictGet5(dict, "First");
918
1546
  if (childFirst) {
919
1547
  collectOutlineBookmarks(doc, childFirst, level + 1, out, visited);
920
1548
  }
921
- curr = dictGet2(dict, "Next");
1549
+ curr = dictGet5(dict, "Next");
922
1550
  }
923
1551
  }
924
1552
  function collectNameTreePairs(doc, nodeOrRef, out, visited = /* @__PURE__ */ new Set()) {
@@ -929,16 +1557,16 @@ function collectNameTreePairs(doc, nodeOrRef, out, visited = /* @__PURE__ */ new
929
1557
  }
930
1558
  const dict = doc.cos.resolveDict(nodeOrRef);
931
1559
  if (!dict) return;
932
- const namesArr = doc.cos.resolveArray(dictGet2(dict, "Names"));
1560
+ const namesArr = doc.cos.resolveArray(dictGet5(dict, "Names"));
933
1561
  if (namesArr) {
934
1562
  for (let i = 0; i + 1 < namesArr.items.length; i += 2) {
935
1563
  const k = doc.cos.resolve(namesArr.items[i]);
936
1564
  const v = namesArr.items[i + 1];
937
- const name = k?.kind === "string" ? decodePdfString2(k) : "attachment.bin";
1565
+ const name = k?.kind === "string" ? decodePdfString4(k) : "attachment.bin";
938
1566
  out.push({ name, value: v });
939
1567
  }
940
1568
  }
941
- const kidsArr = doc.cos.resolveArray(dictGet2(dict, "Kids"));
1569
+ const kidsArr = doc.cos.resolveArray(dictGet5(dict, "Kids"));
942
1570
  if (kidsArr) {
943
1571
  for (const kid of kidsArr.items) {
944
1572
  collectNameTreePairs(doc, kid, out, visited);
@@ -953,7 +1581,7 @@ function collectNumberTreePairs(doc, nodeOrRef, out, visited = /* @__PURE__ */ n
953
1581
  }
954
1582
  const dict = doc.cos.resolveDict(nodeOrRef);
955
1583
  if (!dict) return;
956
- const numsArr = doc.cos.resolveArray(dictGet2(dict, "Nums"));
1584
+ const numsArr = doc.cos.resolveArray(dictGet5(dict, "Nums"));
957
1585
  if (numsArr) {
958
1586
  for (let i = 0; i + 1 < numsArr.items.length; i += 2) {
959
1587
  const k = doc.cos.resolve(numsArr.items[i]);
@@ -963,7 +1591,7 @@ function collectNumberTreePairs(doc, nodeOrRef, out, visited = /* @__PURE__ */ n
963
1591
  }
964
1592
  }
965
1593
  }
966
- const kidsArr = doc.cos.resolveArray(dictGet2(dict, "Kids"));
1594
+ const kidsArr = doc.cos.resolveArray(dictGet5(dict, "Kids"));
967
1595
  if (kidsArr) {
968
1596
  for (const kid of kidsArr.items) {
969
1597
  collectNumberTreePairs(doc, kid, out, visited);
@@ -1017,7 +1645,7 @@ function formatDumpData(doc, utf8 = true) {
1017
1645
  if (emittedKeys.has(k)) continue;
1018
1646
  const r = doc.cos.resolve(entry.value);
1019
1647
  if (r?.kind === "string") {
1020
- const val = decodePdfString2(r);
1648
+ const val = decodePdfString4(r);
1021
1649
  if (val) {
1022
1650
  emittedKeys.add(k);
1023
1651
  lines.push(
@@ -1038,10 +1666,10 @@ function formatDumpData(doc, utf8 = true) {
1038
1666
  lines.push(`PdfID1: ${id1Hex}`);
1039
1667
  lines.push(`NumberOfPages: ${doc.pageCount}`);
1040
1668
  const catalog = doc.cos.resolveDict(doc.cos.rootRef);
1041
- const outlinesDict = catalog ? doc.cos.resolveDict(dictGet2(catalog, "Outlines")) : void 0;
1669
+ const outlinesDict = catalog ? doc.cos.resolveDict(dictGet5(catalog, "Outlines")) : void 0;
1042
1670
  if (outlinesDict) {
1043
1671
  const bookmarks = [];
1044
- collectOutlineBookmarks(doc, dictGet2(outlinesDict, "First"), 1, bookmarks);
1672
+ collectOutlineBookmarks(doc, dictGet5(outlinesDict, "First"), 1, bookmarks);
1045
1673
  for (const bm of bookmarks) {
1046
1674
  lines.push(
1047
1675
  "BookmarkBegin",
@@ -1055,7 +1683,7 @@ function formatDumpData(doc, utf8 = true) {
1055
1683
  const page = doc.getPage(i);
1056
1684
  const { width, height } = page.getSize();
1057
1685
  const rot = page.getRotation();
1058
- const mbArr = doc.cos.resolveArray(dictGet2(page.pageDict, "MediaBox"));
1686
+ const mbArr = doc.cos.resolveArray(dictGet5(page.pageDict, "MediaBox"));
1059
1687
  let mbRectStr = `0 0 ${width} ${height}`;
1060
1688
  if (mbArr && mbArr.items.length >= 4) {
1061
1689
  const mbNums = mbArr.items.slice(0, 4).map((item) => {
@@ -1071,7 +1699,7 @@ function formatDumpData(doc, utf8 = true) {
1071
1699
  `PageMediaRect: ${mbRectStr}`,
1072
1700
  `PageMediaDimensions: ${width} ${height}`
1073
1701
  );
1074
- const cbArr = doc.cos.resolveArray(dictGet2(page.pageDict, "CropBox"));
1702
+ const cbArr = doc.cos.resolveArray(dictGet5(page.pageDict, "CropBox"));
1075
1703
  if (cbArr && cbArr.items.length >= 4) {
1076
1704
  const nums = cbArr.items.slice(0, 4).map((item) => {
1077
1705
  const r = doc.cos.resolve(item);
@@ -1083,17 +1711,17 @@ function formatDumpData(doc, utf8 = true) {
1083
1711
  }
1084
1712
  const pageLabelsPairs = [];
1085
1713
  if (catalog) {
1086
- collectNumberTreePairs(doc, dictGet2(catalog, "PageLabels"), pageLabelsPairs);
1714
+ collectNumberTreePairs(doc, dictGet5(catalog, "PageLabels"), pageLabelsPairs);
1087
1715
  }
1088
1716
  for (const pair of pageLabelsPairs) {
1089
1717
  const lblDict = doc.cos.resolveDict(pair.value);
1090
1718
  if (lblDict) {
1091
1719
  const newIndex = Math.max(1, pair.num + 1);
1092
- const stNode = doc.cos.resolve(dictGet2(lblDict, "St"));
1720
+ const stNode = doc.cos.resolve(dictGet5(lblDict, "St"));
1093
1721
  const startNum = stNode?.kind === "number" ? stNode.value : 1;
1094
- const pNode = doc.cos.resolve(dictGet2(lblDict, "P"));
1095
- const prefix = pNode?.kind === "string" ? decodePdfString2(pNode) : void 0;
1096
- const sNode = doc.cos.resolve(dictGet2(lblDict, "S"));
1722
+ const pNode = doc.cos.resolve(dictGet5(lblDict, "P"));
1723
+ const prefix = pNode?.kind === "string" ? decodePdfString4(pNode) : void 0;
1724
+ const sNode = doc.cos.resolve(dictGet5(lblDict, "S"));
1097
1725
  const styleCode = sNode?.kind === "name" ? sNode.decoded : "";
1098
1726
  const numStyle = PDF_TO_PAGE_LABEL_STYLE[styleCode] ?? "NoNumber";
1099
1727
  lines.push(
@@ -1124,23 +1752,23 @@ function formatGenerateFdf(doc) {
1124
1752
  }
1125
1753
  return `(${escapeFdfString(String(f.value ?? ""))})`;
1126
1754
  }
1127
- const vNode = doc.cos.resolve(dictGet2(dict, "V"));
1755
+ const vNode = doc.cos.resolve(dictGet5(dict, "V"));
1128
1756
  if (vNode?.kind === "name") return `/${vNode.decoded}`;
1129
- if (vNode?.kind === "string") return `(${escapeFdfString(decodePdfString2(vNode))})`;
1757
+ if (vNode?.kind === "string") return `(${escapeFdfString(decodePdfString4(vNode))})`;
1130
1758
  return "()";
1131
1759
  };
1132
1760
  const serializeCosFieldNode = (nodeOrRef, prefix) => {
1133
1761
  const dict = doc.cos.resolveDict(nodeOrRef);
1134
1762
  if (!dict) return void 0;
1135
- const tNode = doc.cos.resolve(dictGet2(dict, "T"));
1136
- const partialName = tNode?.kind === "string" ? decodePdfString2(tNode) : "";
1763
+ const tNode = doc.cos.resolve(dictGet5(dict, "T"));
1764
+ const partialName = tNode?.kind === "string" ? decodePdfString4(tNode) : "";
1137
1765
  const fullName = prefix && partialName ? `${prefix}.${partialName}` : partialName || prefix;
1138
- const kidsArr = doc.cos.resolveArray(dictGet2(dict, "Kids"));
1766
+ const kidsArr = doc.cos.resolveArray(dictGet5(dict, "Kids"));
1139
1767
  const namedKids = [];
1140
1768
  if (kidsArr) {
1141
1769
  for (const k of kidsArr.items) {
1142
1770
  const kDict = doc.cos.resolveDict(k);
1143
- if (kDict && dictGet2(kDict, "T")) {
1771
+ if (kDict && dictGet5(kDict, "T")) {
1144
1772
  const serializedKid = serializeCosFieldNode(k, fullName);
1145
1773
  if (serializedKid) namedKids.push(serializedKid);
1146
1774
  }
@@ -1154,8 +1782,8 @@ function formatGenerateFdf(doc) {
1154
1782
  };
1155
1783
  const entries = [];
1156
1784
  const catalog = doc.cos.resolveDict(doc.cos.rootRef);
1157
- const acroForm = catalog ? doc.cos.resolveDict(dictGet2(catalog, "AcroForm")) : void 0;
1158
- const fieldsArr = acroForm ? doc.cos.resolveArray(dictGet2(acroForm, "Fields")) : void 0;
1785
+ const acroForm = catalog ? doc.cos.resolveDict(dictGet5(catalog, "AcroForm")) : void 0;
1786
+ const fieldsArr = acroForm ? doc.cos.resolveArray(dictGet5(acroForm, "Fields")) : void 0;
1159
1787
  if (fieldsArr && fieldsArr.items.length > 0) {
1160
1788
  for (const item of fieldsArr.items) {
1161
1789
  const s = serializeCosFieldNode(item, "");
@@ -1163,7 +1791,7 @@ function formatGenerateFdf(doc) {
1163
1791
  }
1164
1792
  } else {
1165
1793
  for (const f of fields) {
1166
- entries.push(`<< /T (${escapeFdfString(f.name)}) /V ${formatFieldVal(f.name, cosDict({}))} >>`);
1794
+ entries.push(`<< /T (${escapeFdfString(f.name)}) /V ${formatFieldVal(f.name, cosDict3({}))} >>`);
1167
1795
  }
1168
1796
  }
1169
1797
  return `%FDF-1.2
@@ -1181,9 +1809,9 @@ function setDocumentBookmarks(doc, bookmarks) {
1181
1809
  if (bookmarks.length === 0 || doc.pageCount === 0) return;
1182
1810
  const catalog = doc.cos.resolveDict(doc.cos.rootRef);
1183
1811
  if (!catalog) return;
1184
- const outlinesDict = cosDict({ Type: cosName("Outlines") });
1812
+ const outlinesDict = cosDict3({ Type: cosName("Outlines") });
1185
1813
  const outlinesRef = doc.cos.allocateObject(outlinesDict);
1186
- dictSet(catalog, "Outlines", outlinesRef);
1814
+ dictSet2(catalog, "Outlines", outlinesRef);
1187
1815
  const stack = [{ ref: outlinesRef, dict: outlinesDict, children: [] }];
1188
1816
  for (const bm of bookmarks) {
1189
1817
  const targetLevel = Math.max(1, bm.level);
@@ -1202,22 +1830,22 @@ function setDocumentBookmarks(doc, bookmarks) {
1202
1830
  const parentState = stack[stack.length - 1];
1203
1831
  const pageIdx = Math.max(0, Math.min(doc.pageCount - 1, bm.pageNumber - 1));
1204
1832
  const pageRef = doc.getPage(pageIdx).ref;
1205
- const itemDict = cosDict({
1206
- Title: cosString(bm.title),
1833
+ const itemDict = cosDict3({
1834
+ Title: cosString3(bm.title),
1207
1835
  Parent: parentState.ref,
1208
- Dest: cosArray([pageRef, cosName("XYZ"), { kind: "null" }, { kind: "null" }, { kind: "null" }])
1836
+ Dest: cosArray3([pageRef, cosName("XYZ"), { kind: "null" }, { kind: "null" }, { kind: "null" }])
1209
1837
  });
1210
1838
  const itemRef = doc.cos.allocateObject(itemDict);
1211
1839
  const prevSibling = parentState.children[parentState.children.length - 1];
1212
1840
  if (prevSibling) {
1213
- dictSet(prevSibling.dict, "Next", itemRef);
1214
- dictSet(itemDict, "Prev", prevSibling.ref);
1841
+ dictSet2(prevSibling.dict, "Next", itemRef);
1842
+ dictSet2(itemDict, "Prev", prevSibling.ref);
1215
1843
  } else {
1216
- dictSet(parentState.dict, "First", itemRef);
1844
+ dictSet2(parentState.dict, "First", itemRef);
1217
1845
  }
1218
- dictSet(parentState.dict, "Last", itemRef);
1846
+ dictSet2(parentState.dict, "Last", itemRef);
1219
1847
  parentState.children.push({ ref: itemRef, dict: itemDict });
1220
- dictSet(parentState.dict, "Count", cosNumber(parentState.children.length));
1848
+ dictSet2(parentState.dict, "Count", cosNumber3(parentState.children.length));
1221
1849
  }
1222
1850
  }
1223
1851
  function applyUpdateInfoText(doc, text) {
@@ -1308,7 +1936,7 @@ function applyUpdateInfoText(doc, text) {
1308
1936
  }
1309
1937
  const infoDict = doc.cos.infoRef ? doc.cos.resolveDict(doc.cos.infoRef) : void 0;
1310
1938
  if (infoDict) {
1311
- dictSet(infoDict, curKey, cosString(val));
1939
+ dictSet2(infoDict, curKey, cosString3(val));
1312
1940
  }
1313
1941
  }
1314
1942
  mode = "none";
@@ -1355,7 +1983,7 @@ function applyUpdateInfoText(doc, text) {
1355
1983
  const existing1 = doc.cos.idArray?.items[1] && doc.cos.resolve(doc.cos.idArray.items[1])?.kind === "string" ? doc.cos.resolve(doc.cos.idArray.items[1]).bytes : existing0;
1356
1984
  const b0 = pdfId0Hex !== void 0 ? hexToBytes(pdfId0Hex) : existing0;
1357
1985
  const b1 = pdfId1Hex !== void 0 ? hexToBytes(pdfId1Hex) : existing1;
1358
- doc.cos.idArray = cosArray([cosHexString(b0), cosHexString(b1)]);
1986
+ doc.cos.idArray = cosArray3([cosHexString(b0), cosHexString(b1)]);
1359
1987
  }
1360
1988
  for (const [pageNum, rot] of pageRotations.entries()) {
1361
1989
  if (pageNum >= 1 && pageNum <= doc.pageCount) {
@@ -1364,28 +1992,28 @@ function applyUpdateInfoText(doc, text) {
1364
1992
  }
1365
1993
  for (const [pageNum, [w, h]] of pageDimensions.entries()) {
1366
1994
  if (pageNum >= 1 && pageNum <= doc.pageCount) {
1367
- dictSet(
1995
+ dictSet2(
1368
1996
  doc.getPage(pageNum - 1).pageDict,
1369
1997
  "MediaBox",
1370
- cosArray([cosNumber(0), cosNumber(0), cosNumber(w), cosNumber(h)])
1998
+ cosArray3([cosNumber3(0), cosNumber3(0), cosNumber3(w), cosNumber3(h)])
1371
1999
  );
1372
2000
  }
1373
2001
  }
1374
2002
  for (const [pageNum, [x0, y0, x1, y1]] of pageMediaRects.entries()) {
1375
2003
  if (pageNum >= 1 && pageNum <= doc.pageCount) {
1376
- dictSet(
2004
+ dictSet2(
1377
2005
  doc.getPage(pageNum - 1).pageDict,
1378
2006
  "MediaBox",
1379
- cosArray([cosNumber(x0), cosNumber(y0), cosNumber(x1), cosNumber(y1)])
2007
+ cosArray3([cosNumber3(x0), cosNumber3(y0), cosNumber3(x1), cosNumber3(y1)])
1380
2008
  );
1381
2009
  }
1382
2010
  }
1383
2011
  for (const [pageNum, [x0, y0, x1, y1]] of pageCropBoxes.entries()) {
1384
2012
  if (pageNum >= 1 && pageNum <= doc.pageCount) {
1385
- dictSet(
2013
+ dictSet2(
1386
2014
  doc.getPage(pageNum - 1).pageDict,
1387
2015
  "CropBox",
1388
- cosArray([cosNumber(x0), cosNumber(y0), cosNumber(x1), cosNumber(y1)])
2016
+ cosArray3([cosNumber3(x0), cosNumber3(y0), cosNumber3(x1), cosNumber3(y1)])
1389
2017
  );
1390
2018
  }
1391
2019
  }
@@ -1394,21 +2022,21 @@ function applyUpdateInfoText(doc, text) {
1394
2022
  if (catalog) {
1395
2023
  const numsItems = [];
1396
2024
  for (const pl of pageLabels) {
1397
- numsItems.push(cosNumber(Math.max(0, pl.newIndex - 1)));
2025
+ numsItems.push(cosNumber3(Math.max(0, pl.newIndex - 1)));
1398
2026
  const lblEntries = {
1399
- St: cosNumber(pl.start)
2027
+ St: cosNumber3(pl.start)
1400
2028
  };
1401
2029
  if (pl.prefix) {
1402
- lblEntries.P = cosString(pl.prefix);
2030
+ lblEntries.P = cosString3(pl.prefix);
1403
2031
  }
1404
2032
  const pdfStyle = PAGE_LABEL_STYLE_TO_PDF[pl.style];
1405
2033
  if (pdfStyle) {
1406
2034
  lblEntries.S = cosName(pdfStyle);
1407
2035
  }
1408
- numsItems.push(cosDict(lblEntries));
2036
+ numsItems.push(cosDict3(lblEntries));
1409
2037
  }
1410
- const plDict = cosDict({ Nums: cosArray(numsItems) });
1411
- dictSet(catalog, "PageLabels", doc.cos.allocateObject(plDict));
2038
+ const plDict = cosDict3({ Nums: cosArray3(numsItems) });
2039
+ dictSet2(catalog, "PageLabels", doc.cos.allocateObject(plDict));
1412
2040
  }
1413
2041
  }
1414
2042
  setDocumentBookmarks(doc, bookmarks);
@@ -1416,20 +2044,20 @@ function applyUpdateInfoText(doc, text) {
1416
2044
  function attachFilesToDocument(doc, filePaths, files, toPageSpec) {
1417
2045
  const catalog = doc.cos.resolveDict(doc.cos.rootRef);
1418
2046
  if (!catalog) return;
1419
- let namesDict = doc.cos.resolveDict(dictGet2(catalog, "Names"));
2047
+ let namesDict = doc.cos.resolveDict(dictGet5(catalog, "Names"));
1420
2048
  if (!namesDict) {
1421
- namesDict = cosDict({});
1422
- dictSet(catalog, "Names", doc.cos.allocateObject(namesDict));
2049
+ namesDict = cosDict3({});
2050
+ dictSet2(catalog, "Names", doc.cos.allocateObject(namesDict));
1423
2051
  }
1424
- let efTree = doc.cos.resolveDict(dictGet2(namesDict, "EmbeddedFiles"));
2052
+ let efTree = doc.cos.resolveDict(dictGet5(namesDict, "EmbeddedFiles"));
1425
2053
  if (!efTree) {
1426
- efTree = cosDict({ Names: cosArray([]) });
1427
- dictSet(namesDict, "EmbeddedFiles", doc.cos.allocateObject(efTree));
2054
+ efTree = cosDict3({ Names: cosArray3([]) });
2055
+ dictSet2(namesDict, "EmbeddedFiles", doc.cos.allocateObject(efTree));
1428
2056
  }
1429
- let namesArr = doc.cos.resolveArray(dictGet2(efTree, "Names"));
2057
+ let namesArr = doc.cos.resolveArray(dictGet5(efTree, "Names"));
1430
2058
  if (!namesArr) {
1431
- namesArr = cosArray([]);
1432
- dictSet(efTree, "Names", namesArr);
2059
+ namesArr = cosArray3([]);
2060
+ dictSet2(efTree, "Names", namesArr);
1433
2061
  }
1434
2062
  const targetPageIdx = toPageSpec !== void 0 && doc.pageCount > 0 ? toPageSpec.toLowerCase() === "end" ? doc.pageCount - 1 : Math.max(0, Math.min(doc.pageCount - 1, (Number.parseInt(toPageSpec, 10) || 1) - 1)) : void 0;
1435
2063
  for (const fp of filePaths) {
@@ -1438,34 +2066,34 @@ function attachFilesToDocument(doc, filePaths, files, toPageSpec) {
1438
2066
  const baseName = fp.slice(fp.lastIndexOf("/") + 1);
1439
2067
  const efStreamRef = doc.cos.allocateObject(
1440
2068
  cosStream(bytes, {
1441
- dict: cosDict({ Type: cosName("EmbeddedFile") }),
2069
+ dict: cosDict3({ Type: cosName("EmbeddedFile") }),
1442
2070
  compress: true
1443
2071
  })
1444
2072
  );
1445
2073
  const filespecRef = doc.cos.allocateObject(
1446
- cosDict({
2074
+ cosDict3({
1447
2075
  Type: cosName("Filespec"),
1448
- F: cosString(baseName),
1449
- UF: cosString(baseName),
1450
- EF: cosDict({ F: efStreamRef })
2076
+ F: cosString3(baseName),
2077
+ UF: cosString3(baseName),
2078
+ EF: cosDict3({ F: efStreamRef })
1451
2079
  })
1452
2080
  );
1453
- namesArr.items.push(cosString(baseName), filespecRef);
2081
+ namesArr.items.push(cosString3(baseName), filespecRef);
1454
2082
  if (targetPageIdx !== void 0) {
1455
2083
  const pageDict = doc.getPage(targetPageIdx).pageDict;
1456
- let annotsArr = doc.cos.resolveArray(dictGet2(pageDict, "Annots"));
2084
+ let annotsArr = doc.cos.resolveArray(dictGet5(pageDict, "Annots"));
1457
2085
  if (!annotsArr) {
1458
- annotsArr = cosArray([]);
1459
- dictSet(pageDict, "Annots", annotsArr);
2086
+ annotsArr = cosArray3([]);
2087
+ dictSet2(pageDict, "Annots", annotsArr);
1460
2088
  }
1461
2089
  const annotRef = doc.cos.allocateObject(
1462
- cosDict({
2090
+ cosDict3({
1463
2091
  Type: cosName("Annot"),
1464
2092
  Subtype: cosName("FileAttachment"),
1465
2093
  Name: cosName("PushPin"),
1466
- Contents: cosString(baseName),
2094
+ Contents: cosString3(baseName),
1467
2095
  FS: filespecRef,
1468
- Rect: cosArray([cosNumber(20), cosNumber(20), cosNumber(40), cosNumber(40)])
2096
+ Rect: cosArray3([cosNumber3(20), cosNumber3(20), cosNumber3(40), cosNumber3(40)])
1469
2097
  })
1470
2098
  );
1471
2099
  annotsArr.items.push(annotRef);
@@ -1482,11 +2110,11 @@ function attachmentBasename(name) {
1482
2110
  function unpackFilesFromDocument(doc, outDir, files) {
1483
2111
  const cleanDir = outDir.endsWith("/") ? outDir.slice(0, -1) : outDir;
1484
2112
  const writeSpecDict = (specDict, fallbackName = "attachment.bin") => {
1485
- const ufNode = doc.cos.resolve(dictGet2(specDict, "UF") ?? dictGet2(specDict, "F"));
1486
- const fileName = attachmentBasename(ufNode?.kind === "string" ? decodePdfString2(ufNode) : fallbackName);
1487
- const efDict = doc.cos.resolveDict(dictGet2(specDict, "EF"));
2113
+ const ufNode = doc.cos.resolve(dictGet5(specDict, "UF") ?? dictGet5(specDict, "F"));
2114
+ const fileName = attachmentBasename(ufNode?.kind === "string" ? decodePdfString4(ufNode) : fallbackName);
2115
+ const efDict = doc.cos.resolveDict(dictGet5(specDict, "EF"));
1488
2116
  const fStream = efDict ? doc.cos.resolve(
1489
- dictGet2(efDict, "UF") ?? dictGet2(efDict, "F") ?? dictGet2(efDict, "DOS") ?? dictGet2(efDict, "Mac") ?? dictGet2(efDict, "Unix")
2117
+ dictGet5(efDict, "UF") ?? dictGet5(efDict, "F") ?? dictGet5(efDict, "DOS") ?? dictGet5(efDict, "Mac") ?? dictGet5(efDict, "Unix")
1490
2118
  ) : void 0;
1491
2119
  if (fStream?.kind === "stream") {
1492
2120
  const decoded = doc.cos.decodeStream(fStream);
@@ -1496,10 +2124,10 @@ function unpackFilesFromDocument(doc, outDir, files) {
1496
2124
  };
1497
2125
  const catalog = doc.cos.resolveDict(doc.cos.rootRef);
1498
2126
  if (catalog) {
1499
- const namesDict = doc.cos.resolveDict(dictGet2(catalog, "Names"));
2127
+ const namesDict = doc.cos.resolveDict(dictGet5(catalog, "Names"));
1500
2128
  const efPairs = [];
1501
2129
  if (namesDict) {
1502
- collectNameTreePairs(doc, dictGet2(namesDict, "EmbeddedFiles"), efPairs);
2130
+ collectNameTreePairs(doc, dictGet5(namesDict, "EmbeddedFiles"), efPairs);
1503
2131
  }
1504
2132
  for (const pair of efPairs) {
1505
2133
  const specDict = doc.cos.resolveDict(pair.value);
@@ -1507,7 +2135,7 @@ function unpackFilesFromDocument(doc, outDir, files) {
1507
2135
  writeSpecDict(specDict, pair.name);
1508
2136
  }
1509
2137
  }
1510
- const rootAfArr = doc.cos.resolveArray(dictGet2(catalog, "AF"));
2138
+ const rootAfArr = doc.cos.resolveArray(dictGet5(catalog, "AF"));
1511
2139
  if (rootAfArr) {
1512
2140
  for (const item of rootAfArr.items) {
1513
2141
  const specDict = doc.cos.resolveDict(item);
@@ -1516,69 +2144,32 @@ function unpackFilesFromDocument(doc, outDir, files) {
1516
2144
  }
1517
2145
  }
1518
2146
  for (let p = 0; p < doc.pageCount; p++) {
1519
- const pageAfArr = doc.cos.resolveArray(dictGet2(doc.getPage(p).pageDict, "AF"));
2147
+ const pageAfArr = doc.cos.resolveArray(dictGet5(doc.getPage(p).pageDict, "AF"));
1520
2148
  if (pageAfArr) {
1521
2149
  for (const item of pageAfArr.items) {
1522
2150
  const specDict = doc.cos.resolveDict(item);
1523
2151
  if (specDict) writeSpecDict(specDict);
1524
2152
  }
1525
2153
  }
1526
- const annotsArr = doc.cos.resolveArray(dictGet2(doc.getPage(p).pageDict, "Annots"));
2154
+ const annotsArr = doc.cos.resolveArray(dictGet5(doc.getPage(p).pageDict, "Annots"));
1527
2155
  if (!annotsArr) continue;
1528
2156
  for (const item of annotsArr.items) {
1529
2157
  const annotDict = doc.cos.resolveDict(item);
1530
2158
  if (!annotDict) continue;
1531
- const subNode = doc.cos.resolve(dictGet2(annotDict, "Subtype"));
2159
+ const subNode = doc.cos.resolve(dictGet5(annotDict, "Subtype"));
1532
2160
  if (subNode?.kind === "name" && subNode.decoded === "FileAttachment") {
1533
- const specDict = doc.cos.resolveDict(dictGet2(annotDict, "FS"));
2161
+ const specDict = doc.cos.resolveDict(dictGet5(annotDict, "FS"));
1534
2162
  if (specDict) writeSpecDict(specDict);
1535
2163
  }
1536
2164
  }
1537
2165
  }
1538
2166
  }
1539
- function formatBurstFilename(pattern, pageNum) {
1540
- let out = "";
1541
- let replaced = false;
1542
- for (let i = 0; i < pattern.length; i++) {
1543
- if (pattern[i] !== "%") {
1544
- out += pattern[i];
1545
- continue;
1546
- }
1547
- if (pattern[i + 1] === "%") {
1548
- out += "%";
1549
- i++;
1550
- continue;
1551
- }
1552
- if (!replaced) {
1553
- let j = i + 1;
1554
- let zeroPad = false;
1555
- if (pattern[j] === "0") {
1556
- zeroPad = true;
1557
- j++;
1558
- }
1559
- let widthStr = "";
1560
- while (j < pattern.length && pattern[j] >= "0" && pattern[j] <= "9") {
1561
- widthStr += pattern[j];
1562
- j++;
1563
- }
1564
- if (pattern[j] === "d") {
1565
- const width = widthStr ? Number.parseInt(widthStr, 10) : 1;
1566
- out += zeroPad ? String(pageNum).padStart(width, "0") : String(pageNum);
1567
- replaced = true;
1568
- i = j;
1569
- continue;
1570
- }
1571
- }
1572
- out += "%";
1573
- }
1574
- return out;
1575
- }
1576
2167
  function cloneCosSubgraphInto(srcDoc, dstDoc, node, memo = /* @__PURE__ */ new Map()) {
1577
2168
  if (!node) return void 0;
1578
2169
  if (node.kind === "ref") {
1579
2170
  const cached = memo.get(node.objectNumber);
1580
2171
  if (cached) return cached;
1581
- const placeholder = dstDoc.cos.allocateObject(cosDict({}));
2172
+ const placeholder = dstDoc.cos.allocateObject(cosDict3({}));
1582
2173
  memo.set(node.objectNumber, placeholder);
1583
2174
  const resolved = srcDoc.cos.resolve(node);
1584
2175
  const cloned = cloneCosSubgraphInto(srcDoc, dstDoc, resolved, memo);
@@ -1592,14 +2183,14 @@ function cloneCosSubgraphInto(srcDoc, dstDoc, node, memo = /* @__PURE__ */ new M
1592
2183
  return placeholder;
1593
2184
  }
1594
2185
  if (node.kind === "array") {
1595
- return cosArray(node.items.map((it) => cloneCosSubgraphInto(srcDoc, dstDoc, it, memo)).filter(Boolean));
2186
+ return cosArray3(node.items.map((it) => cloneCosSubgraphInto(srcDoc, dstDoc, it, memo)).filter(Boolean));
1596
2187
  }
1597
2188
  if (node.kind === "dict") {
1598
- const next = cosDict({});
2189
+ const next = cosDict3({});
1599
2190
  for (const entry of node.entries) {
1600
2191
  if (entry.key.decoded === "Parent") continue;
1601
2192
  const clonedVal = cloneCosSubgraphInto(srcDoc, dstDoc, entry.value, memo);
1602
- if (clonedVal) dictSet(next, entry.key.decoded, clonedVal);
2193
+ if (clonedVal) dictSet2(next, entry.key.decoded, clonedVal);
1603
2194
  }
1604
2195
  return next;
1605
2196
  }
@@ -1664,31 +2255,31 @@ function applyOverlayToDocument(targetDoc, overlayDoc, mode, multi) {
1664
2255
  const srcRes = srcPage.getResourcesDict();
1665
2256
  const renamedResources = /* @__PURE__ */ new Map();
1666
2257
  for (const subKey of ["Font", "XObject", "ExtGState", "ColorSpace", "Pattern", "Shading", "Properties"]) {
1667
- const srcSub = overlayDoc.cos.resolveDict(dictGet2(srcRes, subKey));
2258
+ const srcSub = overlayDoc.cos.resolveDict(dictGet5(srcRes, subKey));
1668
2259
  if (!srcSub) continue;
1669
- let dstSub = targetDoc.cos.resolveDict(dictGet2(dstRes, subKey));
2260
+ let dstSub = targetDoc.cos.resolveDict(dictGet5(dstRes, subKey));
1670
2261
  if (!dstSub) {
1671
- dstSub = cosDict({});
1672
- dictSet(dstRes, subKey, dstSub);
2262
+ dstSub = cosDict3({});
2263
+ dictSet2(dstRes, subKey, dstSub);
1673
2264
  }
1674
2265
  for (const entry of srcSub.entries) {
1675
2266
  const origKey = entry.key.decoded;
1676
2267
  const cloned = cloneCosSubgraphInto(overlayDoc, targetDoc, entry.value, memo);
1677
2268
  if (!cloned) continue;
1678
- if (!dictGet2(dstSub, origKey)) {
1679
- dictSet(dstSub, origKey, cloned);
2269
+ if (!dictGet5(dstSub, origKey)) {
2270
+ dictSet2(dstSub, origKey, cloned);
1680
2271
  } else {
1681
2272
  let newKey = `Ov_${i}_${origKey}`;
1682
2273
  let suffix = 1;
1683
- while (dictGet2(dstSub, newKey)) {
2274
+ while (dictGet5(dstSub, newKey)) {
1684
2275
  newKey = `Ov_${i}_${suffix++}_${origKey}`;
1685
2276
  }
1686
- dictSet(dstSub, newKey, cloned);
2277
+ dictSet2(dstSub, newKey, cloned);
1687
2278
  renamedResources.set(origKey, newKey);
1688
2279
  }
1689
2280
  }
1690
2281
  }
1691
- const srcContents = dictGet2(srcPage.pageDict, "Contents");
2282
+ const srcContents = dictGet5(srcPage.pageDict, "Contents");
1692
2283
  if (!srcContents) continue;
1693
2284
  const rawSrcNodes = [];
1694
2285
  const resolvedSrcContents = overlayDoc.cos.resolve(srcContents);
@@ -1714,7 +2305,7 @@ function applyOverlayToDocument(targetDoc, overlayDoc, mode, multi) {
1714
2305
  }
1715
2306
  }
1716
2307
  if (srcList.length === 0) continue;
1717
- const dstContents = dictGet2(dstPage.pageDict, "Contents");
2308
+ const dstContents = dictGet5(dstPage.pageDict, "Contents");
1718
2309
  const toStreamList = (c) => {
1719
2310
  if (!c) return [];
1720
2311
  const r = targetDoc.cos.resolve(c);
@@ -1763,7 +2354,7 @@ ${fmt6(s)} 0 0 ${fmt6(s)} ${fmt4(tx)} ${fmt4(ty)} cm
1763
2354
  const qOpenSrc = targetDoc.cos.allocateObject(cosStream(new TextEncoder().encode(srcOpenCmd), { compress: false }));
1764
2355
  const qClose = targetDoc.cos.allocateObject(cosStream(new TextEncoder().encode("\nQ\n"), { compress: false }));
1765
2356
  const combined = mode === "background" ? [qOpenSrc, ...srcList, qClose, qOpenDst, ...dstList, qClose] : [qOpenDst, ...dstList, qClose, qOpenSrc, ...srcList, qClose];
1766
- dictSet(dstPage.pageDict, "Contents", cosArray(combined));
2357
+ dictSet2(dstPage.pageDict, "Contents", cosArray3(combined));
1767
2358
  }
1768
2359
  }
1769
2360
  function normalizeQuarterTurn(degrees) {
@@ -1837,8 +2428,8 @@ function* runPdftkCliSteps(argv, files, signal) {
1837
2428
  if (obj.value.kind !== "stream")
1838
2429
  continue;
1839
2430
  const raw = singleDoc.cos.decodeStream(obj.value);
1840
- dictDelete(obj.value.dict, "Filter");
1841
- dictDelete(obj.value.dict, "DecodeParms");
2431
+ dictDelete2(obj.value.dict, "Filter");
2432
+ dictDelete2(obj.value.dict, "DecodeParms");
1842
2433
  singleDoc.cos.objects.set(obj.objectNumber, {
1843
2434
  ...obj,
1844
2435
  value: cosStream(raw, {
@@ -1947,9 +2538,9 @@ function* runPdftkCliSteps(argv, files, signal) {
1947
2538
  if (!cached) {
1948
2539
  cached = [];
1949
2540
  const cat = d.cos.resolveDict(d.cos.rootRef);
1950
- const outDict = cat ? d.cos.resolveDict(dictGet2(cat, "Outlines")) : void 0;
2541
+ const outDict = cat ? d.cos.resolveDict(dictGet5(cat, "Outlines")) : void 0;
1951
2542
  if (outDict) {
1952
- collectOutlineBookmarks(d, dictGet2(outDict, "First"), 1, cached);
2543
+ collectOutlineBookmarks(d, dictGet5(outDict, "First"), 1, cached);
1953
2544
  }
1954
2545
  bookmarksByDoc.set(d, cached);
1955
2546
  }
@@ -2039,14 +2630,14 @@ function* runPdftkCliSteps(argv, files, signal) {
2039
2630
  }
2040
2631
  if (dropXfa) {
2041
2632
  const root = resultDoc.cos.resolveDict(resultDoc.cos.rootRef);
2042
- const acroForm = root ? resultDoc.cos.resolveDict(dictGet2(root, "AcroForm")) : void 0;
2633
+ const acroForm = root ? resultDoc.cos.resolveDict(dictGet5(root, "AcroForm")) : void 0;
2043
2634
  if (acroForm)
2044
- dictDelete(acroForm, "XFA");
2635
+ dictDelete2(acroForm, "XFA");
2045
2636
  }
2046
2637
  if (dropXmp) {
2047
2638
  const root = resultDoc.cos.resolveDict(resultDoc.cos.rootRef);
2048
2639
  if (root)
2049
- dictDelete(root, "Metadata");
2640
+ dictDelete2(root, "Metadata");
2050
2641
  }
2051
2642
  if (replacementFont && operation === "fill_form") {
2052
2643
  const cleanFontName = replacementFont.startsWith("/") ? replacementFont.slice(1) : replacementFont;
@@ -2054,28 +2645,28 @@ function* runPdftkCliSteps(argv, files, signal) {
2054
2645
  if (++cooperativeWork % 64 === 0)
2055
2646
  yield;
2056
2647
  if (obj.value.kind === "dict") {
2057
- const stNode = dictGet2(obj.value, "Subtype");
2058
- const bfNode = dictGet2(obj.value, "BaseFont");
2648
+ const stNode = dictGet5(obj.value, "Subtype");
2649
+ const bfNode = dictGet5(obj.value, "BaseFont");
2059
2650
  const subtype = stNode?.kind === "name" ? stNode.decoded : void 0;
2060
2651
  const baseFont = bfNode?.kind === "name" ? bfNode.decoded : void 0;
2061
2652
  if (subtype === "Type1" && baseFont === "Helvetica") {
2062
- dictSet(obj.value, "BaseFont", cosName(cleanFontName));
2653
+ dictSet2(obj.value, "BaseFont", cosName(cleanFontName));
2063
2654
  }
2064
2655
  }
2065
2656
  }
2066
2657
  }
2067
2658
  if (operation === "fill_form" && !shouldFlatten) {
2068
2659
  const root = resultDoc.cos.resolveDict(resultDoc.cos.rootRef);
2069
- const acroForm = root ? resultDoc.cos.resolveDict(dictGet2(root, "AcroForm")) : void 0;
2660
+ const acroForm = root ? resultDoc.cos.resolveDict(dictGet5(root, "AcroForm")) : void 0;
2070
2661
  if (acroForm) {
2071
- dictSet(acroForm, "NeedAppearances", { kind: "boolean", value: needAppearances });
2662
+ dictSet2(acroForm, "NeedAppearances", { kind: "boolean", value: needAppearances });
2072
2663
  }
2073
2664
  } else if (needAppearances && !shouldFlatten) {
2074
2665
  const root = resultDoc.cos.resolveDict(resultDoc.cos.rootRef);
2075
2666
  if (root) {
2076
- const acroForm = resultDoc.cos.resolveDict(dictGet2(root, "AcroForm"));
2667
+ const acroForm = resultDoc.cos.resolveDict(dictGet5(root, "AcroForm"));
2077
2668
  if (acroForm) {
2078
- dictSet(acroForm, "NeedAppearances", { kind: "boolean", value: true });
2669
+ dictSet2(acroForm, "NeedAppearances", { kind: "boolean", value: true });
2079
2670
  }
2080
2671
  }
2081
2672
  }
@@ -2083,12 +2674,12 @@ function* runPdftkCliSteps(argv, files, signal) {
2083
2674
  if (keepFinalId) {
2084
2675
  const lastInput = handleDocs[handleDocs.length - 1];
2085
2676
  if (lastInput?.cos.idArray) {
2086
- resultDoc.cos.idArray = cosArray([...lastInput.cos.idArray.items]);
2677
+ resultDoc.cos.idArray = cosArray3([...lastInput.cos.idArray.items]);
2087
2678
  }
2088
2679
  } else if (keepFirstId || !resultDoc.cos.idArray) {
2089
2680
  const firstInput = handleDocs[0];
2090
2681
  if (firstInput?.cos.idArray) {
2091
- resultDoc.cos.idArray = cosArray([...firstInput.cos.idArray.items]);
2682
+ resultDoc.cos.idArray = cosArray3([...firstInput.cos.idArray.items]);
2092
2683
  }
2093
2684
  }
2094
2685
  if (uncompressStreams || compressStreams) {
@@ -2098,8 +2689,8 @@ function* runPdftkCliSteps(argv, files, signal) {
2098
2689
  if (obj.value.kind !== "stream")
2099
2690
  continue;
2100
2691
  const raw = resultDoc.cos.decodeStream(obj.value);
2101
- dictDelete(obj.value.dict, "Filter");
2102
- dictDelete(obj.value.dict, "DecodeParms");
2692
+ dictDelete2(obj.value.dict, "Filter");
2693
+ dictDelete2(obj.value.dict, "DecodeParms");
2103
2694
  resultDoc.cos.objects.set(obj.objectNumber, {
2104
2695
  ...obj,
2105
2696
  value: cosStream(raw, {
@@ -2147,7 +2738,7 @@ function runPdftkCliSync(argv, files, signal) {
2147
2738
  }
2148
2739
  return next.value;
2149
2740
  }
2150
- async function executePdftk(context) {
2741
+ async function executePdftk(context, retainedContext = context) {
2151
2742
  let cooperativeWork = 63;
2152
2743
  const invocation = createOutputOperation(context, { write: async () => {
2153
2744
  } });
@@ -2155,8 +2746,8 @@ async function executePdftk(context) {
2155
2746
  const carrier = getCommandArguments(context);
2156
2747
  const argv = [...carrier.args];
2157
2748
  const parsed = await drainSteps(parsePdftkArgumentsSteps(argv), invocation.signal);
2158
- if (parsed.options && ["dump_data_annots", "dump_data_annots_utf8"].includes(parsed.options.operation)) {
2159
- return await executeRetainedPdftk({ ...context, signal: invocation.signal, stdout: invocation.child(context.stdout).output }, parsed.options);
2749
+ if (parsed.options && (["output", "rotate", "attach_files", "stamp", "multistamp", "background", "multibackground", "burst"].includes(parsed.options.operation) && !parsed.options.shouldFlatten || ["dump_data", "dump_data_utf8", "dump_data_annots", "dump_data_annots_utf8", "dump_data_fields", "dump_data_fields_utf8", "generate_fdf", "unpack_files"].includes(parsed.options.operation))) {
2750
+ return await executeRetainedPdftk({ ...retainedContext, signal: invocation.signal, stdout: invocation.child(context.stdout).output }, parsed.options);
2160
2751
  }
2161
2752
  const vfsFiles = /* @__PURE__ */ new Map();
2162
2753
  let accountedBytes = 0;
@@ -2257,7 +2848,7 @@ function createPdftkCommand(options = {}) {
2257
2848
  runtimeIdentity: commandRuntimeIdentity,
2258
2849
  description: "Manipulate PDF documents, fill/flatten AcroForms, and assemble pages via @poe-code/pdf-ast",
2259
2850
  execute(context) {
2260
- return new InputByteBudget(maxInputBytes).run(context, executePdftk);
2851
+ return new InputByteBudget(maxInputBytes).run(context, (limited) => executePdftk(limited, { ...context, inputBudget: limited.inputBudget }));
2261
2852
  }
2262
2853
  });
2263
2854
  }
@@ -2279,6 +2870,7 @@ function createPdftkCommands(options = {}) {
2279
2870
  export {
2280
2871
  createPdftkCommand,
2281
2872
  createPdftkCommands,
2873
+ iteratePdftkRangeToken,
2282
2874
  parsePdftkRangeToken,
2283
2875
  pdftkCommand,
2284
2876
  pdftkCommands,