@poe-platform/safe-bash 0.1.802 → 0.1.804

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 (748) hide show
  1. package/README.md +60 -33
  2. package/dist/image-ast/ast.d.ts +1 -0
  3. package/dist/image-ast/browser/ast.d.ts +1 -0
  4. package/dist/image-ast/browser/codecs/jpeg.d.ts +2 -2
  5. package/dist/image-ast/codecs/jpeg.d.ts +2 -2
  6. package/dist/image-ast/index.browser.js +692 -8355
  7. package/dist/image-ast/index.js +692 -8355
  8. package/dist/mp4-ast/codecs.d.ts +7 -2
  9. package/dist/safe-bash/chunks/{chunk-CHYGPFVM.js → chunk-22SX3F2R.js} +1 -1
  10. package/dist/safe-bash/chunks/{chunk-FBUCWVTE.js → chunk-2IVBJTBD.js} +1 -1
  11. package/dist/safe-bash/chunks/chunk-2POETUMB.js +190 -0
  12. package/dist/safe-bash/chunks/{chunk-XVOSKJE2.js → chunk-47D7WBJK.js} +1 -1
  13. package/dist/safe-bash/chunks/{chunk-VKNVHEX3.js → chunk-4ESI236Y.js} +1 -1
  14. package/dist/safe-bash/chunks/{chunk-74GHTNJA.js → chunk-4KTMKD5W.js} +1 -1
  15. package/dist/safe-bash/chunks/{chunk-55YJASTN.js → chunk-4T53AERN.js} +1 -1
  16. package/dist/safe-bash/chunks/{chunk-DQP3VHSB.js → chunk-5XIFJVOO.js} +1 -1
  17. package/dist/safe-bash/chunks/{chunk-NZQXYWA3.js → chunk-62BOHHJT.js} +1 -2
  18. package/dist/safe-bash/chunks/{chunk-HZAMGT5I.js → chunk-67WIFM3N.js} +17 -6
  19. package/dist/safe-bash/chunks/{chunk-4D4N7IU2.js → chunk-6LNFRPW5.js} +2 -2
  20. package/dist/safe-bash/chunks/{chunk-6O77NL2S.js → chunk-6SMICPI3.js} +1 -1
  21. package/dist/safe-bash/chunks/{chunk-4BSJLKNM.js → chunk-7O76UFQD.js} +1 -1
  22. package/dist/safe-bash/chunks/{chunk-44ALJ4QG.js → chunk-AW5KIT6V.js} +3549 -84
  23. package/dist/safe-bash/chunks/{chunk-RSTHLAF3.js → chunk-B2Z73HTZ.js} +52 -28
  24. package/dist/safe-bash/chunks/chunk-B3ZMOJVM.js +319 -0
  25. package/dist/safe-bash/chunks/{chunk-7ZBU7KYV.js → chunk-CFAWS3O4.js} +1 -1
  26. package/dist/safe-bash/chunks/{chunk-I5HZ4FGE.js → chunk-CL2FCTTO.js} +1 -1
  27. package/dist/safe-bash/chunks/{chunk-KDNSPLII.js → chunk-CTXNARJH.js} +2 -1
  28. package/dist/safe-bash/chunks/{chunk-TFIBK2GI.js → chunk-D5Q7NFWI.js} +1 -1
  29. package/dist/safe-bash/chunks/{chunk-OQRVVGR6.js → chunk-DSOOVZ6Q.js} +1 -1
  30. package/dist/safe-bash/chunks/{chunk-VTH3MLDU.js → chunk-DUTAG6ZD.js} +1 -1
  31. package/dist/safe-bash/chunks/{chunk-XAQMU6OY.js → chunk-EE5YGFIZ.js} +1 -1
  32. package/dist/safe-bash/chunks/{chunk-FZE4HW6G.js → chunk-EJOYT2ME.js} +1 -1
  33. package/dist/safe-bash/chunks/chunk-FAAIR6EJ.js +887 -0
  34. package/dist/safe-bash/chunks/{chunk-OV6IHKO6.js → chunk-FOB2FZR4.js} +2 -2
  35. package/dist/safe-bash/chunks/chunk-G6V4RRSQ.js +14 -0
  36. package/dist/safe-bash/chunks/{chunk-UTBUUFDM.js → chunk-GGQAGQXQ.js} +1 -1
  37. package/dist/safe-bash/chunks/{chunk-K6VCD7IY.js → chunk-HIIYIJ5G.js} +2 -4
  38. package/dist/safe-bash/chunks/chunk-IOHH2GTI.js +56 -0
  39. package/dist/safe-bash/chunks/{chunk-CTVWDACF.js → chunk-IQW34XQT.js} +1 -1
  40. package/dist/safe-bash/chunks/{chunk-HZ7BWKQ3.js → chunk-IS572AAT.js} +1 -1
  41. package/dist/safe-bash/chunks/{chunk-AUSNDQTJ.js → chunk-JPSUHHOA.js} +1 -1
  42. package/dist/safe-bash/chunks/{chunk-ZVD5IS4V.js → chunk-KBZ4UB2O.js} +2 -2
  43. package/dist/safe-bash/chunks/{chunk-AM5ESLPH.js → chunk-KU5CVWKA.js} +1 -1
  44. package/dist/safe-bash/chunks/{chunk-NQCM3TYR.js → chunk-LPOVNKNB.js} +225 -176
  45. package/dist/safe-bash/chunks/{chunk-46Z5E5EV.js → chunk-MBOC3LZ4.js} +1 -1
  46. package/dist/safe-bash/chunks/{chunk-6PAVEFT3.js → chunk-N4BQFD3P.js} +1 -1
  47. package/dist/safe-bash/chunks/{chunk-CS4MNM6I.js → chunk-NGKCVNWS.js} +1 -1
  48. package/dist/safe-bash/chunks/{chunk-7R5BDCG7.js → chunk-OHML2BEU.js} +1 -1
  49. package/dist/safe-bash/chunks/{chunk-C5OWC2TL.js → chunk-OQ3AGYCZ.js} +1 -1
  50. package/dist/safe-bash/chunks/{chunk-B7TAL7S5.js → chunk-PTAEWLSE.js} +0 -2
  51. package/dist/safe-bash/chunks/{chunk-LVOBFF4D.js → chunk-Q4FNLOTI.js} +1 -1
  52. package/dist/safe-bash/chunks/chunk-Q5XO3NAS.js +1036 -0
  53. package/dist/safe-bash/chunks/{chunk-GEG3BWGE.js → chunk-RHFRJIWQ.js} +1 -1
  54. package/dist/safe-bash/chunks/chunk-RUR6J33T.js +11 -0
  55. package/dist/safe-bash/chunks/{chunk-WDLGKIHD.js → chunk-S4RFUUXO.js} +841 -26
  56. package/dist/safe-bash/chunks/{chunk-RRR7AQ24.js → chunk-SD2ISU5L.js} +1 -1
  57. package/dist/safe-bash/chunks/{chunk-3NDIFSNM.js → chunk-SUJ3NTMH.js} +3 -3
  58. package/dist/safe-bash/chunks/{chunk-R3NAKOED.js → chunk-SZRUU5HS.js} +2 -2
  59. package/dist/safe-bash/chunks/{chunk-PH63PLPZ.js → chunk-TC3F4UFF.js} +1 -1
  60. package/dist/safe-bash/chunks/{chunk-3R3AANOR.js → chunk-TCKYOLUE.js} +1 -1
  61. package/dist/safe-bash/chunks/{chunk-D3ANYGMC.js → chunk-UV4X32QU.js} +1 -1
  62. package/dist/safe-bash/chunks/{chunk-E7OYNDGL.js → chunk-V7QT2RWC.js} +1 -1
  63. package/dist/safe-bash/chunks/{chunk-SHEMU2Z7.js → chunk-W2IYOVHK.js} +839 -1211
  64. package/dist/safe-bash/chunks/{chunk-3HQU4OJO.js → chunk-XNGVOSGI.js} +1 -1
  65. package/dist/safe-bash/chunks/{chunk-J42RIHHJ.js → chunk-XQWCQSRN.js} +1 -1
  66. package/dist/safe-bash/chunks/{chunk-BJA5XNP6.js → chunk-Y7FW6GLT.js} +6 -6
  67. package/dist/safe-bash/chunks/{chunk-QGUV42T5.js → chunk-YL3GBUG4.js} +1 -1
  68. package/dist/safe-bash/chunks/chunk-YOXUCJER.js +389 -0
  69. package/dist/safe-bash/chunks/{chunk-HBCN24ZA.js → chunk-Z2AAYYJN.js} +2 -2
  70. package/dist/safe-bash/chunks/chunk-ZKYKJCZZ.js +30 -0
  71. package/dist/safe-bash/chunks/core-IE3AFIDX.js +85806 -0
  72. package/dist/safe-bash/chunks/{ffmpeg-WTC3TEFI.js → ffmpeg-YANDK6HU.js} +2 -2
  73. package/dist/safe-bash/chunks/{gh-6WU6PXL4.js → gh-4MBJ2S5V.js} +2 -2
  74. package/dist/safe-bash/chunks/{git-EFZIGJW4.js → git-2QONJNRQ.js} +2 -2
  75. package/dist/safe-bash/chunks/{imagemagick-EIEYGWPF.js → imagemagick-JLEHGYSN.js} +2 -2
  76. package/dist/safe-bash/chunks/{mmdc-ROQJT5HQ.js → mmdc-6LD7A6ND.js} +2 -2
  77. package/dist/safe-bash/chunks/{pdfimages-DW7LWXFI.js → pdfimages-RSHL7LOP.js} +2 -2
  78. package/dist/safe-bash/chunks/{pdfinfo-TIP6XLUQ.js → pdfinfo-L3SGWPNG.js} +2 -2
  79. package/dist/safe-bash/chunks/{pdftk-DMG22ITZ.js → pdftk-LFBJNU5A.js} +2 -2
  80. package/dist/safe-bash/chunks/{pdftoppm-WNDYR72T.js → pdftoppm-NXXFUIHG.js} +2 -2
  81. package/dist/safe-bash/chunks/{pdftotext-5IPZ4NI7.js → pdftotext-4IHNWT6F.js} +2 -2
  82. package/dist/safe-bash/chunks/{qpdf-TTX2DIUA.js → qpdf-ZEIREV63.js} +2 -2
  83. package/dist/safe-bash/chunks/read-builtin-A4QKAT45.js +9 -0
  84. package/dist/safe-bash/chunks/{sips-XYS46JPJ.js → sips-D5YBG2V3.js} +2 -2
  85. package/dist/safe-bash/chunks/{soffice-TU73E5KL.js → soffice-RAJU3JUT.js} +2 -2
  86. package/dist/safe-bash/chunks/source-files-3XWRRHFA.js +7 -0
  87. package/dist/safe-bash/chunks/{wkhtmltopdf-FSZ2CHGE.js → wkhtmltopdf-7UE4FORZ.js} +2 -2
  88. package/dist/safe-bash/command-chunks/{chunk-7KWZXKY6.js → chunk-26RTBV2I.js} +1 -0
  89. package/dist/safe-bash/command-chunks/{chunk-AQJ2ROJO.js → chunk-2WYNMZR2.js} +10 -8
  90. package/dist/safe-bash/command-chunks/{chunk-BDSMROQZ.js → chunk-36GFRF2N.js} +2 -1
  91. package/dist/safe-bash/command-chunks/{chunk-GC5TJZOF.js → chunk-3VIA2IA7.js} +114 -31
  92. package/dist/safe-bash/command-chunks/{chunk-NKFYQSES.js → chunk-4CTI3ZTX.js} +1 -0
  93. package/dist/safe-bash/command-chunks/{chunk-WH627NJL.js → chunk-4MYP2FX4.js} +2 -1
  94. package/dist/safe-bash/command-chunks/chunk-4R5ADJM5.js +178 -0
  95. package/dist/safe-bash/command-chunks/{chunk-P2N33UMN.js → chunk-5MIKM54M.js} +4 -4
  96. package/dist/safe-bash/command-chunks/{chunk-DB453IE6.js → chunk-6FZQUOSJ.js} +1 -1
  97. package/dist/safe-bash/command-chunks/{chunk-WPYIOKE3.js → chunk-6GKYHPJG.js} +2 -2
  98. package/dist/safe-bash/command-chunks/{chunk-7K6JYKPJ.js → chunk-6M2ELGEN.js} +17 -15
  99. package/dist/safe-bash/command-chunks/{chunk-PXEIT2O4.js → chunk-6UR7V3ET.js} +8 -1
  100. package/dist/safe-bash/command-chunks/{chunk-6KJ3LPI2.js → chunk-6XBS5B46.js} +26 -3
  101. package/dist/safe-bash/command-chunks/{chunk-5PWJG2UK.js → chunk-6YXLZX7L.js} +2 -2
  102. package/dist/safe-bash/command-chunks/{chunk-EK6YNAXT.js → chunk-753YOR54.js} +31 -5
  103. package/dist/safe-bash/command-chunks/{chunk-RMWQAAO5.js → chunk-7IR4NRNE.js} +2 -2
  104. package/dist/safe-bash/command-chunks/{chunk-FZTK4MFI.js → chunk-7NM73SVK.js} +8 -8
  105. package/dist/safe-bash/command-chunks/{chunk-NXEQ3ESQ.js → chunk-7QD5YY4F.js} +6 -11
  106. package/dist/safe-bash/command-chunks/{chunk-EMPU65ZK.js → chunk-A5LBSJGH.js} +1 -0
  107. package/dist/safe-bash/command-chunks/chunk-A7MU7762.js +200 -0
  108. package/dist/safe-bash/command-chunks/{chunk-ORYGZYKW.js → chunk-ARZMP2L2.js} +3 -3
  109. package/dist/safe-bash/command-chunks/{chunk-OQKC5ZU2.js → chunk-BAKFZ477.js} +62 -20
  110. package/dist/safe-bash/command-chunks/{chunk-QRRYN2KO.js → chunk-BC7BK6R6.js} +0 -2424
  111. package/dist/safe-bash/command-chunks/{chunk-F4TEEZTL.js → chunk-BOEOJS2Q.js} +1 -1
  112. package/dist/safe-bash/command-chunks/{chunk-XS72HTMA.js → chunk-BWGGLYEB.js} +5 -22
  113. package/dist/safe-bash/command-chunks/{chunk-PMBFZXTK.js → chunk-C5ZZKP7V.js} +1 -1
  114. package/dist/safe-bash/command-chunks/{chunk-LHIOAFWW.js → chunk-C7SEB6WU.js} +1 -1
  115. package/dist/safe-bash/command-chunks/{chunk-XPT2UGBF.js → chunk-CHJKFRT7.js} +1 -1
  116. package/dist/safe-bash/command-chunks/{chunk-TIOCQVUQ.js → chunk-CON26Q2O.js} +1 -1
  117. package/dist/safe-bash/command-chunks/{chunk-E55UKBIE.js → chunk-DBAT3IK2.js} +1 -1
  118. package/dist/safe-bash/command-chunks/{chunk-Z45N42QC.js → chunk-DPAYAVMS.js} +15 -1
  119. package/dist/safe-bash/command-chunks/chunk-DS3NXVUM.js +368 -0
  120. package/dist/safe-bash/command-chunks/{chunk-5ZMZ573Q.js → chunk-DSJ3VRL3.js} +16 -4
  121. package/dist/safe-bash/command-chunks/{chunk-K2GDEMEU.js → chunk-EFRCFWVR.js} +4 -4
  122. package/dist/safe-bash/command-chunks/{chunk-DZCY63VJ.js → chunk-EV6HIJ5H.js} +6 -5
  123. package/dist/safe-bash/command-chunks/{chunk-JDYXY44P.js → chunk-FJURV46Y.js} +3 -3
  124. package/dist/safe-bash/command-chunks/{chunk-TZZ4WUKH.js → chunk-FZAWGKSE.js} +6 -4
  125. package/dist/safe-bash/command-chunks/{chunk-YHFXOX6U.js → chunk-GOCFQ6XV.js} +4 -4
  126. package/dist/safe-bash/command-chunks/{chunk-YOFC45RK.js → chunk-HH5O7DJI.js} +1 -1
  127. package/dist/safe-bash/command-chunks/{chunk-3HHCU5YU.js → chunk-HK7F5SDC.js} +13 -0
  128. package/dist/safe-bash/command-chunks/{chunk-JNZ3CVAE.js → chunk-HQBXIZC7.js} +8 -3
  129. package/dist/safe-bash/command-chunks/{chunk-2JRBIDAD.js → chunk-I63DBZXZ.js} +2 -2
  130. package/dist/safe-bash/command-chunks/{chunk-WNE7FPVR.js → chunk-I64TLTIW.js} +24 -16
  131. package/dist/safe-bash/command-chunks/{chunk-QKFSRZGQ.js → chunk-ICANWOXH.js} +7 -31
  132. package/dist/safe-bash/command-chunks/{chunk-SQRQW3CT.js → chunk-IJ6LGLXM.js} +1 -1
  133. package/dist/safe-bash/command-chunks/{chunk-5E4WAO4O.js → chunk-JD5QNRNO.js} +3 -3
  134. package/dist/safe-bash/command-chunks/{chunk-KJIMDLBB.js → chunk-JNANXVJV.js} +1 -1
  135. package/dist/safe-bash/command-chunks/{chunk-TGSNCQSR.js → chunk-JT4RYCA6.js} +1771 -1663
  136. package/dist/safe-bash/command-chunks/{chunk-II77KPZN.js → chunk-JWW6FYBN.js} +2 -2
  137. package/dist/safe-bash/command-chunks/{chunk-ZYXH3B66.js → chunk-LCJWKTCJ.js} +250 -203
  138. package/dist/safe-bash/command-chunks/{chunk-I237SNW5.js → chunk-LFJJQQND.js} +1 -1
  139. package/dist/safe-bash/command-chunks/chunk-LU4HBPP2.js +97 -0
  140. package/dist/safe-bash/command-chunks/{chunk-XJXU3VVH.js → chunk-LWOE65OE.js} +20 -5
  141. package/dist/safe-bash/command-chunks/{chunk-GMIHJYDG.js → chunk-M32HFSX7.js} +22 -6
  142. package/dist/safe-bash/command-chunks/{chunk-YG4EPFWC.js → chunk-M3NINRDU.js} +2880 -172
  143. package/dist/safe-bash/command-chunks/chunk-MQREDAL6.js +164 -0
  144. package/dist/safe-bash/command-chunks/{chunk-LWS62ISU.js → chunk-N6DIASO2.js} +1 -1
  145. package/dist/safe-bash/command-chunks/chunk-NGL7YK7O.js +188 -0
  146. package/dist/safe-bash/command-chunks/{chunk-PEF7K3UQ.js → chunk-NJYHWKIL.js} +40 -10
  147. package/dist/safe-bash/command-chunks/{chunk-VXSLJH7G.js → chunk-OJQRSCBP.js} +27 -7
  148. package/dist/safe-bash/command-chunks/{chunk-OQU6UT6X.js → chunk-OV3XREFN.js} +11 -0
  149. package/dist/safe-bash/command-chunks/{chunk-MIXBO6U7.js → chunk-PTZLF456.js} +2 -2
  150. package/dist/safe-bash/command-chunks/{chunk-ALDC4XP4.js → chunk-QILLRNES.js} +34 -10
  151. package/dist/safe-bash/command-chunks/{chunk-L22T3H7L.js → chunk-QR25JLKO.js} +1 -1
  152. package/dist/safe-bash/command-chunks/{chunk-7U7EXOXX.js → chunk-R7C4MGZ5.js} +17 -223
  153. package/dist/safe-bash/command-chunks/{chunk-LCF3OB7P.js → chunk-RBME3JEH.js} +1 -1
  154. package/dist/safe-bash/command-chunks/{chunk-2KG2QLJE.js → chunk-RFWGYT7G.js} +3 -0
  155. package/dist/safe-bash/command-chunks/{chunk-5TBUOBDE.js → chunk-RZMVRT26.js} +27 -13
  156. package/dist/safe-bash/command-chunks/chunk-TFR6B3WB.js +44 -0
  157. package/dist/safe-bash/command-chunks/chunk-TOH3OF3O.js +179 -0
  158. package/dist/safe-bash/command-chunks/{chunk-VGG2DL5Q.js → chunk-TRR4MYWF.js} +4 -0
  159. package/dist/safe-bash/command-chunks/chunk-TT4DAFBT.js +13621 -0
  160. package/dist/safe-bash/command-chunks/{chunk-LWSBAWLT.js → chunk-TXI64OAG.js} +1 -1
  161. package/dist/safe-bash/command-chunks/chunk-TZRI7BJZ.js +496 -0
  162. package/dist/safe-bash/command-chunks/{chunk-QOKBZFFD.js → chunk-U3MMODA5.js} +2 -7
  163. package/dist/safe-bash/command-chunks/{chunk-ZYHTWNAE.js → chunk-UAW423ZL.js} +11 -11
  164. package/dist/safe-bash/command-chunks/{chunk-C5YYCQHW.js → chunk-UXEEUGOV.js} +222 -12
  165. package/dist/safe-bash/command-chunks/{chunk-GY3BWK7K.js → chunk-VOZPMJRX.js} +87 -80
  166. package/dist/safe-bash/command-chunks/{chunk-MQFIPHIQ.js → chunk-WPANOB4A.js} +38 -35
  167. package/dist/safe-bash/command-chunks/{chunk-Y2WBSJG6.js → chunk-X4QZQI5Q.js} +65 -64
  168. package/dist/safe-bash/command-chunks/{chunk-FPVUD6TH.js → chunk-XGI57GCN.js} +10 -8
  169. package/dist/safe-bash/command-chunks/{chunk-5UBXNSFZ.js → chunk-XUCU7QQT.js} +1281 -1278
  170. package/dist/safe-bash/command-chunks/chunk-Y22VXJBD.js +296 -0
  171. package/dist/safe-bash/command-chunks/{chunk-WVHONVZ4.js → chunk-YMFUUPDX.js} +5 -3
  172. package/dist/safe-bash/command-chunks/{chunk-IR2BY7EL.js → chunk-YYGIBXFZ.js} +2 -2
  173. package/dist/safe-bash/command-chunks/{chunk-MSFXC3OC.js → chunk-Z4FO6OHE.js} +2 -2
  174. package/dist/safe-bash/command-chunks/{chunk-6GWJUQAV.js → chunk-Z5ZZVDUD.js} +181 -133
  175. package/dist/safe-bash/command-chunks/{chunk-W5DNF4JH.js → chunk-ZHN3QDCI.js} +1 -1
  176. package/dist/safe-bash/commands/alias/index.d.ts +2 -0
  177. package/dist/safe-bash/commands/alias/index.js +2 -0
  178. package/dist/safe-bash/commands/apply-patch/index.browser.js +2 -3
  179. package/dist/safe-bash/commands/apply-patch/index.d.ts +0 -1
  180. package/dist/safe-bash/commands/apply-patch/index.js +0 -1
  181. package/dist/safe-bash/commands/archive/index.browser.js +2 -3
  182. package/dist/safe-bash/commands/archive/index.d.ts +0 -1
  183. package/dist/safe-bash/commands/archive/index.js +0 -1
  184. package/dist/safe-bash/commands/bytes/compression/index.js +54 -51
  185. package/dist/safe-bash/commands/bytes/index.js +2 -1
  186. package/dist/safe-bash/commands/chmod/index.browser.js +14 -0
  187. package/dist/safe-bash/commands/chmod/index.d.ts +2 -0
  188. package/dist/safe-bash/commands/chmod/index.js +2 -0
  189. package/dist/safe-bash/commands/column/index.browser.js +2 -3
  190. package/dist/safe-bash/commands/column/index.d.ts +0 -1
  191. package/dist/safe-bash/commands/column/index.js +0 -1
  192. package/dist/safe-bash/commands/copy-source.js +1 -0
  193. package/dist/safe-bash/commands/csplit/index.browser.js +2 -2
  194. package/dist/safe-bash/commands/csvkit/index.browser.js +72 -0
  195. package/dist/safe-bash/commands/csvkit/index.d.ts +0 -5
  196. package/dist/safe-bash/commands/csvkit/index.js +0 -50
  197. package/dist/safe-bash/commands/docx/index.browser.js +5 -7
  198. package/dist/safe-bash/commands/du/index.browser.js +2 -3
  199. package/dist/safe-bash/commands/du/index.d.ts +0 -1
  200. package/dist/safe-bash/commands/du/index.js +0 -1
  201. package/dist/safe-bash/commands/expr/index.browser.js +2 -3
  202. package/dist/safe-bash/commands/expr/index.d.ts +0 -1
  203. package/dist/safe-bash/commands/expr/index.js +0 -1
  204. package/dist/safe-bash/commands/factor/index.browser.js +2 -2
  205. package/dist/safe-bash/commands/file/index.browser.js +2 -3
  206. package/dist/safe-bash/commands/file/index.d.ts +0 -1
  207. package/dist/safe-bash/commands/file/index.js +0 -1
  208. package/dist/safe-bash/commands/filesystem.js +1 -1
  209. package/dist/safe-bash/commands/getopt/index.browser.js +2 -2
  210. package/dist/safe-bash/commands/grep-aliases/index.browser.js +3 -3
  211. package/dist/safe-bash/commands/hexdump/index.browser.js +2 -2
  212. package/dist/safe-bash/commands/html-to-markdown/index.browser.js +2 -3
  213. package/dist/safe-bash/commands/html-to-markdown/index.d.ts +0 -1
  214. package/dist/safe-bash/commands/html-to-markdown/index.js +0 -1
  215. package/dist/safe-bash/commands/htmlq/index.d.ts +1 -5
  216. package/dist/safe-bash/commands/htmlq/index.js +1 -143
  217. package/dist/safe-bash/commands/iconv/index.browser.js +2 -2
  218. package/dist/safe-bash/commands/line-endings/index.browser.js +2 -2
  219. package/dist/safe-bash/commands/llm/index.browser.js +2 -2
  220. package/dist/safe-bash/commands/llm/providers/index.browser.js +1 -1
  221. package/dist/safe-bash/commands/mdq/index.browser.js +3 -3
  222. package/dist/safe-bash/commands/media/index.browser.js +4 -16314
  223. package/dist/safe-bash/commands/media/index.d.ts +1 -5
  224. package/dist/safe-bash/commands/media/index.js +1 -3
  225. package/dist/safe-bash/commands/media/plugin.d.ts +1 -18
  226. package/dist/safe-bash/commands/media/plugin.js +1 -90
  227. package/dist/safe-bash/commands/media/remote.d.ts +1 -63
  228. package/dist/safe-bash/commands/media/remote.js +1 -405
  229. package/dist/safe-bash/commands/media/settings.d.ts +1 -4
  230. package/dist/safe-bash/commands/media/settings.js +1 -26
  231. package/dist/safe-bash/commands/metadata/chmod.d.ts +1 -7
  232. package/dist/safe-bash/commands/metadata/chmod.js +1 -204
  233. package/dist/safe-bash/commands/metadata/index.browser.js +3 -8
  234. package/dist/safe-bash/commands/metadata/index.d.ts +0 -1
  235. package/dist/safe-bash/commands/metadata/index.js +2 -2
  236. package/dist/safe-bash/commands/metadata/internal.d.ts +1 -30
  237. package/dist/safe-bash/commands/metadata/internal.js +1 -76
  238. package/dist/safe-bash/commands/metadata/mktemp.d.ts +1 -3
  239. package/dist/safe-bash/commands/metadata/mktemp.js +1 -202
  240. package/dist/safe-bash/commands/metadata/stat.d.ts +1 -7
  241. package/dist/safe-bash/commands/metadata/stat.js +1 -530
  242. package/dist/safe-bash/commands/mktemp/index.browser.js +13 -0
  243. package/dist/safe-bash/commands/mktemp/index.d.ts +2 -0
  244. package/dist/safe-bash/commands/mktemp/index.js +2 -0
  245. package/dist/safe-bash/commands/network/curl.js +1 -3
  246. package/dist/safe-bash/commands/network/index.browser.js +3 -4
  247. package/dist/safe-bash/commands/network/public.d.ts +0 -1
  248. package/dist/safe-bash/commands/network/public.js +0 -1
  249. package/dist/safe-bash/commands/network/transport.js +2 -1
  250. package/dist/safe-bash/commands/network/wget.js +1 -3
  251. package/dist/safe-bash/commands/node/browser.d.ts +0 -1
  252. package/dist/safe-bash/commands/node/browser.js +0 -1
  253. package/dist/safe-bash/commands/node/default-runtime.d.ts +3 -0
  254. package/dist/safe-bash/commands/node/default-runtime.js +15 -0
  255. package/dist/safe-bash/commands/node/index.browser.js +7 -8
  256. package/dist/safe-bash/commands/node/index.js +3 -3
  257. package/dist/safe-bash/commands/node/path.js +1 -1
  258. package/dist/safe-bash/commands/node/preload.d.ts +1 -1
  259. package/dist/safe-bash/commands/node/preload.js +4 -1
  260. package/dist/safe-bash/commands/node/quickjs.d.ts +2 -0
  261. package/dist/safe-bash/commands/node/quickjs.js +2 -0
  262. package/dist/safe-bash/commands/node/safejs.js +26 -12
  263. package/dist/safe-bash/commands/op/index.browser.js +2 -3
  264. package/dist/safe-bash/commands/op/index.d.ts +0 -11
  265. package/dist/safe-bash/commands/op/index.js +0 -84
  266. package/dist/safe-bash/commands/pandoc/index.browser.js +44 -0
  267. package/dist/safe-bash/commands/pandoc/index.d.ts +0 -1
  268. package/dist/safe-bash/commands/pandoc/index.js +0 -1
  269. package/dist/safe-bash/commands/portable-random.d.ts +1 -1
  270. package/dist/safe-bash/commands/portable-random.js +1 -12
  271. package/dist/safe-bash/commands/pr/index.browser.js +2 -2
  272. package/dist/safe-bash/commands/python/docker-runner.js +4 -3
  273. package/dist/safe-bash/commands/python/docker.d.ts +1 -0
  274. package/dist/safe-bash/commands/python/docker.js +5 -2
  275. package/dist/safe-bash/commands/python/index.browser.js +17 -13
  276. package/dist/safe-bash/commands/python/index.d.ts +2 -1
  277. package/dist/safe-bash/commands/python/index.js +10 -8
  278. package/dist/safe-bash/commands/python/llm-capability.js +65 -2
  279. package/dist/safe-bash/commands/python/llm-dependencies.d.ts +27 -0
  280. package/dist/safe-bash/commands/python/llm-dependencies.js +66 -0
  281. package/dist/safe-bash/commands/python/llm-module.js +6 -4
  282. package/dist/safe-bash/commands/python/llm-reference-module.d.ts +3 -0
  283. package/dist/safe-bash/commands/python/llm-reference-module.js +690 -0
  284. package/dist/safe-bash/commands/python/worker.browser.js +2 -3
  285. package/dist/safe-bash/commands/python/worker.d.ts +0 -1
  286. package/dist/safe-bash/commands/python/worker.js +0 -1
  287. package/dist/safe-bash/commands/regex-execution/ere/transport/wire-engine.d.ts +1 -1
  288. package/dist/safe-bash/commands/regex-execution/ere/transport/wire-engine.js +3 -3
  289. package/dist/safe-bash/commands/regex-execution/public.browser.js +7 -7
  290. package/dist/safe-bash/commands/safejs/options.js +5 -1
  291. package/dist/safe-bash/commands/safejs/runtime.d.ts +1 -0
  292. package/dist/safe-bash/commands/safejs/runtime.js +1 -1
  293. package/dist/safe-bash/commands/split/index.browser.js +2 -3
  294. package/dist/safe-bash/commands/split/index.d.ts +0 -1
  295. package/dist/safe-bash/commands/split/index.js +0 -1
  296. package/dist/safe-bash/commands/ssconvert/index.browser.js +98 -0
  297. package/dist/safe-bash/commands/stat/index.browser.js +13 -0
  298. package/dist/safe-bash/commands/stat/index.d.ts +2 -0
  299. package/dist/safe-bash/commands/stat/index.js +2 -0
  300. package/dist/safe-bash/commands/stream-format/index.browser.js +3 -4
  301. package/dist/safe-bash/commands/stream-format/index.d.ts +0 -1
  302. package/dist/safe-bash/commands/stream-format/index.js +0 -1
  303. package/dist/safe-bash/commands/stream-inspection/index.browser.js +3 -4
  304. package/dist/safe-bash/commands/stream-inspection/index.d.ts +0 -1
  305. package/dist/safe-bash/commands/stream-inspection/index.js +0 -1
  306. package/dist/safe-bash/commands/streams.js +2 -1
  307. package/dist/safe-bash/commands/table-text/index.browser.js +3 -4
  308. package/dist/safe-bash/commands/table-text/index.d.ts +0 -1
  309. package/dist/safe-bash/commands/table-text/index.js +0 -1
  310. package/dist/safe-bash/commands/text.js +74 -34
  311. package/dist/safe-bash/commands/time-env/index.browser.js +3 -4
  312. package/dist/safe-bash/commands/time-env/index.d.ts +0 -1
  313. package/dist/safe-bash/commands/time-env/index.js +0 -1
  314. package/dist/safe-bash/commands/tree/index.browser.js +2 -3
  315. package/dist/safe-bash/commands/tree/index.d.ts +0 -1
  316. package/dist/safe-bash/commands/tree/index.js +0 -1
  317. package/dist/safe-bash/commands/tsort/index.browser.js +2 -2
  318. package/dist/safe-bash/commands/unalias/index.d.ts +2 -0
  319. package/dist/safe-bash/commands/unalias/index.js +2 -0
  320. package/dist/safe-bash/commands/xml/index.browser.js +2 -2
  321. package/dist/safe-bash/commands/yq/index.browser.js +2 -2
  322. package/dist/safe-bash/core.browser.js +2 -2
  323. package/dist/safe-bash/core.d.ts +7 -1
  324. package/dist/safe-bash/core.js +7 -1
  325. package/dist/safe-bash/execution-runtime.js +2 -1
  326. package/dist/safe-bash/fs/s3/http/index.d.ts +2 -2
  327. package/dist/safe-bash/fs/s3/http/index.js +1 -1
  328. package/dist/safe-bash/full-core.browser.js +254 -916
  329. package/dist/safe-bash/internal/op/types.d.ts +1 -0
  330. package/dist/safe-bash/jobs.browser.js +5 -5
  331. package/dist/safe-bash/lazy-optional.d.ts +3 -3
  332. package/dist/safe-bash/lazy-optional.js +1 -1
  333. package/dist/safe-bash/opt-in/commands/cmp/index.js +7 -6
  334. package/dist/safe-bash/opt-in/commands/dd/index.js +1 -1
  335. package/dist/safe-bash/opt-in/commands/dd/io.js +51 -5
  336. package/dist/safe-bash/opt-in/commands/truncate/index.js +2 -2
  337. package/dist/safe-bash/opt-in/commands/yq/native-work.js +3 -0
  338. package/dist/safe-bash/opt-in/optional/commands/shuf/input.js +2 -1
  339. package/dist/safe-bash/opt-in/optional/commands/shuf/shuf.js +4 -2
  340. package/dist/safe-bash/opt-in/optional.d.ts +1 -1
  341. package/dist/safe-bash/opt-in/optional.js +1 -1
  342. package/dist/safe-bash/opt-in/shell/extensions/read/index.js +2 -344
  343. package/dist/safe-bash/optional-host.browser.js +19 -14
  344. package/dist/safe-bash/optional-host.d.ts +1 -0
  345. package/dist/safe-bash/optional-host.js +1 -0
  346. package/dist/safe-bash/playwright/controller.js +41 -3
  347. package/dist/safe-bash/playwright/native-storage-targets.js +4 -2
  348. package/dist/safe-bash/plugins/base.d.ts +1 -1
  349. package/dist/safe-bash/plugins/base.js +3 -3
  350. package/dist/safe-bash/plugins/composition.d.ts +5 -2
  351. package/dist/safe-bash/plugins/composition.js +10 -7
  352. package/dist/safe-bash/plugins/index.browser.js +44 -41
  353. package/dist/safe-bash/plugins/index.js +3 -2
  354. package/dist/safe-bash/plugins/portable-commands.d.ts +3 -0
  355. package/dist/safe-bash/plugins/portable-commands.js +31 -0
  356. package/dist/safe-bash/registry-entry.browser.js +41 -42
  357. package/dist/safe-bash/search.browser.js +32 -33
  358. package/dist/safe-bash/shell/arithmetic.js +19 -6
  359. package/dist/safe-bash/shell/arrays/state.js +1 -1
  360. package/dist/safe-bash/shell/arrays/syntax.js +4 -3
  361. package/dist/safe-bash/shell/index.d.ts +0 -1
  362. package/dist/safe-bash/shell/index.js +0 -1
  363. package/dist/safe-bash/shell/parser.d.ts +2 -2
  364. package/dist/safe-bash/shell/parser.js +268 -64
  365. package/dist/safe-bash/shell/read-builtin.d.ts +3 -0
  366. package/dist/safe-bash/shell/read-builtin.js +344 -0
  367. package/dist/safe-bash/shell/runtime.d.ts +24 -4
  368. package/dist/safe-bash/shell/runtime.js +392 -414
  369. package/dist/safe-bash/shell/session-state.js +25 -0
  370. package/dist/safe-bash/shell/shell.js +76 -154
  371. package/dist/safe-bash/shell/tilde-expansion.d.ts +1 -1
  372. package/dist/safe-bash/shell/tilde-expansion.js +2 -2
  373. package/dist/safe-bash/shell/types.d.ts +7 -0
  374. package/dist/safe-bash/shell/value-state.js +1 -1
  375. package/dist/safe-bash/shell/worker-limits.js +1 -0
  376. package/dist/safe-bash/shell-entry.browser.js +32 -33
  377. package/dist/safe-bash/trap.browser.js +4 -4
  378. package/dist/safe-bash/worker/host.js +1 -1
  379. package/dist/safe-bash/yq-browser/index.js +1 -1
  380. package/dist/safe-bash-calendar-engine/time-env/calendar.d.ts +1 -1
  381. package/dist/safe-bash-calendar-engine/time-env/calendar.js +1 -1
  382. package/dist/safe-bash-calendar-engine/time-env/format.js +1 -1
  383. package/dist/safe-bash-command-alias/index.d.ts +13 -0
  384. package/dist/safe-bash-command-alias/index.js +88 -0
  385. package/dist/safe-bash-command-apply-patch/apply.js +3 -3
  386. package/dist/safe-bash-command-apply-patch/index.js +3 -3
  387. package/dist/safe-bash-command-apply-patch/matcher.js +1 -1
  388. package/dist/safe-bash-command-apply-patch/parser.js +1 -1
  389. package/dist/safe-bash-command-awk/awk-pipes.js +2 -2
  390. package/dist/safe-bash-command-awk/awk-reader.js +1 -1
  391. package/dist/safe-bash-command-awk/awk-runtime.js +3 -3
  392. package/dist/safe-bash-command-awk/awk.js +5 -5
  393. package/dist/safe-bash-command-awk/index.js +5 -5
  394. package/dist/safe-bash-command-bc/index.js +218 -65
  395. package/dist/safe-bash-command-bzip2/index.js +4 -3
  396. package/dist/safe-bash-command-chmod/LICENSE +21 -0
  397. package/dist/safe-bash-command-chmod/command.d.ts +7 -0
  398. package/dist/safe-bash-command-chmod/command.js +11 -0
  399. package/dist/safe-bash-command-chmod/index.d.ts +6 -0
  400. package/dist/safe-bash-command-chmod/index.js +27 -0
  401. package/dist/safe-bash-command-cmp/index.js +7 -6
  402. package/dist/safe-bash-command-column/column.js +3 -3
  403. package/dist/safe-bash-command-column/index.js +3 -3
  404. package/dist/safe-bash-command-column/layout.js +2 -2
  405. package/dist/safe-bash-command-csvkit/index.d.ts +1 -0
  406. package/dist/safe-bash-command-csvkit/index.js +1505 -7
  407. package/dist/safe-bash-command-csvkit/sync-support.js +2 -7
  408. package/dist/safe-bash-command-curl/curl.js +1 -1
  409. package/dist/safe-bash-command-curl/index.js +1 -1
  410. package/dist/safe-bash-command-date/date.js +1 -1
  411. package/dist/safe-bash-command-date/index.js +1 -1
  412. package/dist/safe-bash-command-dd/index.js +1 -1
  413. package/dist/safe-bash-command-dd/io.js +51 -5
  414. package/dist/safe-bash-command-diff/diff.js +1 -1
  415. package/dist/safe-bash-command-diff/index.js +1 -1
  416. package/dist/safe-bash-command-diff3/index.js +10 -13
  417. package/dist/safe-bash-command-exiftool/index.js +283 -55
  418. package/dist/safe-bash-command-exiftool/registry.d.ts +4 -2
  419. package/dist/safe-bash-command-factor/command.js +2 -2
  420. package/dist/safe-bash-command-factor/index.js +2 -2
  421. package/dist/safe-bash-command-fd/arguments.d.ts +2 -0
  422. package/dist/safe-bash-command-fd/index.js +42 -12
  423. package/dist/safe-bash-command-ffmpeg/index.js +356 -66
  424. package/dist/safe-bash-command-find/find-format.d.ts +3 -0
  425. package/dist/safe-bash-command-find/find-format.js +1 -1
  426. package/dist/safe-bash-command-find/find.js +2 -2
  427. package/dist/safe-bash-command-find/index.js +2 -2
  428. package/dist/safe-bash-command-fmt/index.js +10 -6
  429. package/dist/safe-bash-command-fold/engine.d.ts +1 -1
  430. package/dist/safe-bash-command-fold/family.js +2 -2
  431. package/dist/safe-bash-command-fold/index.js +1 -1
  432. package/dist/safe-bash-command-gzip/index.js +45 -42
  433. package/dist/safe-bash-command-hexdump/command.js +2 -2
  434. package/dist/safe-bash-command-hexdump/index.js +2 -2
  435. package/dist/safe-bash-command-html-to-markdown/entities.js +1 -1
  436. package/dist/safe-bash-command-html-to-markdown/index.js +4 -4
  437. package/dist/safe-bash-command-html-to-markdown/input.js +3 -3
  438. package/dist/safe-bash-command-html-to-markdown/parser.js +2 -2
  439. package/dist/safe-bash-command-html-to-markdown/render.js +3 -3
  440. package/dist/safe-bash-command-htmlq/contracts.d.ts +5 -2
  441. package/dist/safe-bash-command-htmlq/index.d.ts +2 -1
  442. package/dist/safe-bash-command-htmlq/index.js +175 -49
  443. package/dist/safe-bash-command-htmlq/sync.d.ts +1 -0
  444. package/dist/safe-bash-command-imagemagick/index.js +59 -7
  445. package/dist/safe-bash-command-install/arguments.d.ts +27 -0
  446. package/dist/safe-bash-command-install/arguments.js +224 -0
  447. package/dist/safe-bash-command-install/index.d.ts +7 -0
  448. package/dist/safe-bash-command-install/index.js +942 -0
  449. package/dist/safe-bash-command-install/mode.d.ts +6 -0
  450. package/dist/safe-bash-command-install/mode.js +71 -0
  451. package/dist/safe-bash-command-install/options.d.ts +40 -0
  452. package/dist/safe-bash-command-install/options.js +27 -0
  453. package/dist/safe-bash-command-jq/index.js +1 -1
  454. package/dist/safe-bash-command-jq/jq.js +1 -1
  455. package/dist/safe-bash-command-less/index.js +42 -57
  456. package/dist/safe-bash-command-llm/command.js +1 -1
  457. package/dist/safe-bash-command-llm/elevenlabs.js +2 -2
  458. package/dist/safe-bash-command-llm/index.js +4 -4
  459. package/dist/safe-bash-command-llm/openai.js +2 -2
  460. package/dist/safe-bash-command-llm/providers/elevenlabs.js +2 -2
  461. package/dist/safe-bash-command-llm/providers/index.js +3 -3
  462. package/dist/safe-bash-command-llm/providers/openai.js +2 -2
  463. package/dist/safe-bash-command-llm/providers/shared.js +1 -1
  464. package/dist/{safe-bash-mcp → safe-bash-command-mcp}/index.browser.d.ts +463 -46
  465. package/dist/safe-bash-command-mcp/index.browser.js +19308 -0
  466. package/dist/{safe-bash-mcp → safe-bash-command-mcp}/index.d.ts +15 -6
  467. package/dist/{safe-bash-mcp → safe-bash-command-mcp}/index.js +2835 -2783
  468. package/dist/safe-bash-command-media/LICENSE +21 -0
  469. package/dist/safe-bash-command-media/index.d.ts +6 -0
  470. package/dist/safe-bash-command-media/index.js +30 -0
  471. package/dist/safe-bash-command-media/plugin.d.ts +18 -0
  472. package/dist/safe-bash-command-media/plugin.js +11 -0
  473. package/dist/safe-bash-command-media/remote.d.ts +63 -0
  474. package/dist/safe-bash-command-media/remote.js +11 -0
  475. package/dist/safe-bash-command-media/settings.d.ts +4 -0
  476. package/dist/safe-bash-command-media/settings.js +41 -0
  477. package/dist/safe-bash-command-mktemp/LICENSE +21 -0
  478. package/dist/safe-bash-command-mktemp/command.d.ts +3 -0
  479. package/dist/safe-bash-command-mktemp/command.js +9 -0
  480. package/dist/safe-bash-command-mktemp/index.d.ts +6 -0
  481. package/dist/safe-bash-command-mktemp/index.js +25 -0
  482. package/dist/safe-bash-command-mmdc/arguments.d.ts +1 -0
  483. package/dist/safe-bash-command-mmdc/command.d.ts +2 -0
  484. package/dist/safe-bash-command-mmdc/contracts.d.ts +8 -1
  485. package/dist/safe-bash-command-mmdc/index.js +359 -7
  486. package/dist/safe-bash-command-nl/index.js +1 -1
  487. package/dist/safe-bash-command-nl/nl.js +1 -1
  488. package/dist/safe-bash-command-node/LICENSE +21 -0
  489. package/dist/safe-bash-command-node/index.d.ts +17 -0
  490. package/dist/safe-bash-command-node/index.js +328 -0
  491. package/dist/safe-bash-command-numfmt/index.js +1 -0
  492. package/dist/safe-bash-command-od/index.js +16 -8
  493. package/dist/safe-bash-command-op/index.js +62 -36
  494. package/dist/safe-bash-command-op/types.d.ts +1 -0
  495. package/dist/safe-bash-command-pandoc/command.js +3 -3
  496. package/dist/safe-bash-command-pandoc/index.d.ts +1 -0
  497. package/dist/safe-bash-command-pandoc/index.js +5 -3
  498. package/dist/safe-bash-command-pandoc/sync.d.ts +1 -0
  499. package/dist/safe-bash-command-patch/index.js +4 -4
  500. package/dist/safe-bash-command-patch/patch.js +4 -4
  501. package/dist/safe-bash-command-pdfimages/index.js +1 -1
  502. package/dist/safe-bash-command-pdfinfo/index.js +30 -5
  503. package/dist/safe-bash-command-pdftk/index.js +21 -23
  504. package/dist/safe-bash-command-pdftoppm/index.js +17 -4
  505. package/dist/safe-bash-command-pdftotext/index.js +11 -14
  506. package/dist/safe-bash-command-qpdf/index.d.ts +1 -0
  507. package/dist/safe-bash-command-qpdf/index.js +9 -6
  508. package/dist/safe-bash-command-rg/index.js +1 -1
  509. package/dist/safe-bash-command-rg/rg-command.js +1 -1
  510. package/dist/safe-bash-command-sed/index.js +1 -1
  511. package/dist/safe-bash-command-sed/sed.js +1 -1
  512. package/dist/safe-bash-command-shuf/input.d.ts +2 -2
  513. package/dist/safe-bash-command-shuf/input.js +2 -1
  514. package/dist/safe-bash-command-shuf/shuf.js +4 -2
  515. package/dist/safe-bash-command-sips/index.js +15 -7
  516. package/dist/safe-bash-command-soffice/index.js +97 -12
  517. package/dist/safe-bash-command-sponge/index.js +13 -3
  518. package/dist/safe-bash-command-sqlite3/engine.d.ts +1 -0
  519. package/dist/safe-bash-command-sqlite3/index.js +510 -70
  520. package/dist/safe-bash-command-ssconvert/formats/xlsx.js +2 -2
  521. package/dist/safe-bash-command-ssconvert/index.js +44 -22
  522. package/dist/safe-bash-command-stat/LICENSE +21 -0
  523. package/dist/safe-bash-command-stat/command.d.ts +7 -0
  524. package/dist/safe-bash-command-stat/command.js +9 -0
  525. package/dist/safe-bash-command-stat/index.d.ts +6 -0
  526. package/dist/safe-bash-command-stat/index.js +25 -0
  527. package/dist/safe-bash-command-tar/create.d.ts +1 -0
  528. package/dist/safe-bash-command-tar/create.js +2 -2
  529. package/dist/safe-bash-command-tar/extract.js +2 -2
  530. package/dist/safe-bash-command-tar/index.js +4 -4
  531. package/dist/safe-bash-command-tar/modes.js +4 -4
  532. package/dist/safe-bash-command-tar/options.js +1 -1
  533. package/dist/safe-bash-command-truncate/index.js +2 -2
  534. package/dist/safe-bash-command-tsort/command.js +2 -2
  535. package/dist/safe-bash-command-tsort/index.js +2 -2
  536. package/dist/safe-bash-command-unalias/index.d.ts +12 -0
  537. package/dist/safe-bash-command-unalias/index.js +67 -0
  538. package/dist/safe-bash-command-unrtf/index.js +37 -5
  539. package/dist/safe-bash-command-xan/argv.d.ts +1 -1
  540. package/dist/safe-bash-command-xan/argv.js +2 -2
  541. package/dist/safe-bash-command-xan/budget.d.ts +0 -1
  542. package/dist/safe-bash-command-xan/budget.js +1 -1
  543. package/dist/safe-bash-command-xan/commands.js +6 -6
  544. package/dist/safe-bash-command-xan/csv.js +2 -2
  545. package/dist/safe-bash-command-xan/index.js +8 -9
  546. package/dist/safe-bash-command-xan/io.js +4 -4
  547. package/dist/safe-bash-command-xan/options.js +1 -1
  548. package/dist/safe-bash-command-xan/selector.js +2 -2
  549. package/dist/safe-bash-command-xmllint/index.js +45 -23
  550. package/dist/safe-bash-command-xxd/index.js +47 -12
  551. package/dist/safe-bash-command-xz/command.d.ts +1 -1
  552. package/dist/safe-bash-command-xz/index.js +3 -2
  553. package/dist/safe-bash-command-yq/accounting.js +1 -1
  554. package/dist/safe-bash-command-yq/index.js +4 -2
  555. package/dist/safe-bash-command-yq/native-work.js +3 -0
  556. package/dist/safe-bash-command-yq/parser.js +2 -2
  557. package/dist/safe-bash-command-yq/query.js +8 -5
  558. package/dist/safe-bash-command-yq/toml.js +2 -2
  559. package/dist/safe-bash-command-zip/index.js +3 -3
  560. package/dist/safe-bash-compression-engine/bounded-codec.js +3 -3
  561. package/dist/safe-bash-compression-engine/codec-loader.js +2 -2
  562. package/dist/safe-bash-compression-engine/files.js +6 -6
  563. package/dist/safe-bash-compression-engine/index.js +5 -5
  564. package/dist/safe-bash-compression-engine/operand.js +6 -6
  565. package/dist/safe-bash-compression-engine/options.js +1 -1
  566. package/dist/safe-bash-compression-engine/stream.js +5 -5
  567. package/dist/safe-bash-compression-engine/zstd-decode.js +4 -4
  568. package/dist/safe-bash-contracts/command.js +3 -3
  569. package/dist/safe-bash-contracts/default-executor.js +2 -2
  570. package/dist/safe-bash-contracts/diagnostics.js +3 -3
  571. package/dist/safe-bash-contracts/escaping.js +6 -6
  572. package/dist/safe-bash-contracts/filesystem-descriptor.js +3 -3
  573. package/dist/safe-bash-contracts/filesystem-output.js +5 -5
  574. package/dist/safe-bash-contracts/http.d.ts +7 -0
  575. package/dist/safe-bash-contracts/index.js +8 -8
  576. package/dist/safe-bash-contracts/io.d.ts +2 -0
  577. package/dist/safe-bash-contracts/io.js +2 -2
  578. package/dist/safe-bash-contracts/output.js +3 -3
  579. package/dist/safe-bash-contracts/runtime-control.d.ts +2 -2
  580. package/dist/safe-bash-contracts/runtime-control.js +4 -2
  581. package/dist/safe-bash-contracts/signals.d.ts +2 -0
  582. package/dist/safe-bash-contracts/signals.js +3 -1
  583. package/dist/safe-bash-contracts/yield.js +1 -1
  584. package/dist/safe-bash-csv-engine/index.d.ts +2 -1
  585. package/dist/safe-bash-csv-engine/index.js +21 -15
  586. package/dist/safe-bash-io-engine/commands/search/requirements.js +2 -2
  587. package/dist/safe-bash-io-engine/commands/text-programs/shared.js +6 -6
  588. package/dist/safe-bash-io-engine/internal.js +1 -1
  589. package/dist/safe-bash-io-engine/shell/pattern.js +38 -18
  590. package/dist/safe-bash-line-ending-engine/convert.js +9 -204
  591. package/dist/safe-bash-line-ending-engine/encoding.js +9 -42
  592. package/dist/safe-bash-line-ending-engine/index.js +48 -0
  593. package/dist/safe-bash-line-ending-engine/info.js +9 -90
  594. package/dist/safe-bash-line-ending-engine/internal.js +15 -160
  595. package/dist/safe-bash-line-ending-engine/io.js +12 -289
  596. package/dist/safe-bash-line-ending-engine/stage.js +10 -160
  597. package/dist/safe-bash-markdown-engine/index.js +3 -3
  598. package/dist/safe-bash-metadata-engine/LICENSE +21 -0
  599. package/dist/safe-bash-metadata-engine/index.d.ts +30 -0
  600. package/dist/safe-bash-metadata-engine/index.js +82 -0
  601. package/dist/safe-bash-metadata-engine/random.d.ts +1 -0
  602. package/dist/safe-bash-metadata-engine/random.js +21 -0
  603. package/dist/safe-bash-network-engine/args.d.ts +6 -0
  604. package/dist/safe-bash-network-engine/args.js +4 -2
  605. package/dist/safe-bash-network-engine/body.js +1 -1
  606. package/dist/safe-bash-network-engine/fetch-transport.js +3 -1
  607. package/dist/safe-bash-network-engine/index.js +3 -1
  608. package/dist/safe-bash-network-engine/input.js +2 -2
  609. package/dist/safe-bash-network-engine/platform-portable.js +3 -1
  610. package/dist/safe-bash-query-engine/dates.d.ts +1 -1
  611. package/dist/safe-bash-query-engine/dates.js +1 -1
  612. package/dist/safe-bash-query-engine/index.js +6 -6
  613. package/dist/safe-bash-query-engine/interpreter.js +4 -4
  614. package/dist/safe-bash-query-engine/parser.js +1 -1
  615. package/dist/safe-bash-query-engine/query-core.js +6 -6
  616. package/dist/safe-bash-regex-engine/execution/bounded-provider.js +10 -0
  617. package/dist/safe-bash-regex-engine/index.js +1 -1
  618. package/dist/safe-bash-regex-engine/text/regex.d.ts +1 -1
  619. package/dist/safe-bash-regex-engine/text/regex.js +1 -1
  620. package/dist/safe-bash-search-engine/ergonomic-regex.d.ts +1 -0
  621. package/dist/safe-bash-search-engine/ergonomic-regex.js +2 -2
  622. package/dist/safe-bash-search-engine/glob.js +2 -2
  623. package/dist/safe-bash-search-engine/grep.js +17 -10
  624. package/dist/safe-bash-search-engine/matcher.d.ts +2 -2
  625. package/dist/safe-bash-search-engine/matcher.js +13 -9
  626. package/dist/safe-bash-search-engine/options.d.ts +2 -0
  627. package/dist/safe-bash-search-engine/options.js +1 -1
  628. package/dist/safe-bash-search-engine/output.js +1 -1
  629. package/dist/safe-bash-search-engine/shared.js +2 -2
  630. package/dist/safe-bash-search-engine/walk.js +15 -3
  631. package/dist/safe-bash-text-stream-engine/stream-format/shared.d.ts +1 -1
  632. package/dist/safe-bash-text-stream-engine/stream-format/shared.js +2 -1
  633. package/dist/safe-bash-xml-engine/document.js +3 -3
  634. package/dist/safe-bash-xml-engine/evaluate.js +2 -2
  635. package/dist/safe-bash-xml-engine/index.js +4 -4
  636. package/dist/safe-bash-xml-engine/io.js +7 -2
  637. package/dist/safe-bash-xml-engine/limits.d.ts +0 -2
  638. package/dist/safe-bash-xml-engine/limits.js +1 -1
  639. package/dist/safe-bash-xml-engine/query.js +3 -3
  640. package/dist/safe-bash-zip-engine/index.js +3 -3
  641. package/dist/safe-bash-zip-engine/zip/repair.js +3 -3
  642. package/dist/safe-bash-zip-engine/zip/safety.js +1 -1
  643. package/dist/safe-bash-zip-engine/zip/sfx.js +3 -3
  644. package/dist/safe-bash-zip-engine/zip/volumes.js +1 -1
  645. package/dist/safe-bash-zip-engine/zip-format.js +3 -3
  646. package/dist/safe-playwright-cloudflare/browser-snapshot-json.js +2 -2
  647. package/dist/safe-playwright-cloudflare/browser-snapshot-references.js +1 -1
  648. package/dist/safe-playwright-cloudflare/browser-socket-closure.js +18 -3
  649. package/dist/safe-playwright-cloudflare/shell-browser-resource.js +1 -1
  650. package/dist/xlsx-ast/xlsx.js +6 -5
  651. package/package.json +112 -98
  652. package/dist/media-cli/bytes.d.ts +0 -8
  653. package/dist/media-cli/bytes.js +0 -40
  654. package/dist/media-cli/concat.d.ts +0 -30
  655. package/dist/media-cli/concat.js +0 -197
  656. package/dist/media-cli/content.js +0 -66
  657. package/dist/media-cli/dependency-grammars.d.ts +0 -12
  658. package/dist/media-cli/dependency-grammars.js +0 -557
  659. package/dist/media-cli/discover.js +0 -286
  660. package/dist/media-cli/engine.js +0 -190
  661. package/dist/media-cli/filename-expression.js +0 -147
  662. package/dist/media-cli/filesystem.js +0 -35
  663. package/dist/media-cli/frontend-contract.js +0 -8
  664. package/dist/media-cli/frontend-issues.d.ts +0 -6
  665. package/dist/media-cli/frontend-issues.js +0 -9
  666. package/dist/media-cli/imagemagick-operand.d.ts +0 -42
  667. package/dist/media-cli/imagemagick-operand.js +0 -229
  668. package/dist/media-cli/imagemagick-references.d.ts +0 -7
  669. package/dist/media-cli/imagemagick-references.js +0 -42
  670. package/dist/media-cli/imagemagick.generated.js +0 -3254
  671. package/dist/media-cli/imagemagick.js +0 -615
  672. package/dist/media-cli/index.js +0 -12
  673. package/dist/media-cli/mvg.d.ts +0 -10
  674. package/dist/media-cli/mvg.js +0 -102
  675. package/dist/media-cli/network.js +0 -78
  676. package/dist/media-cli/options.generated.js +0 -3312
  677. package/dist/media-cli/preset.d.ts +0 -11
  678. package/dist/media-cli/preset.js +0 -57
  679. package/dist/media-cli/resolution-path.d.ts +0 -23
  680. package/dist/media-cli/resolution-path.js +0 -217
  681. package/dist/media-cli/resolver.js +0 -494
  682. package/dist/media-cli/resources.d.ts +0 -16
  683. package/dist/media-cli/resources.js +0 -187
  684. package/dist/media-cli/shim.js +0 -52
  685. package/dist/media-cli/tee.d.ts +0 -6
  686. package/dist/media-cli/tee.js +0 -38
  687. package/dist/office-package/zip-sync.js +0 -111
  688. package/dist/remote-execution/binary.js +0 -178
  689. package/dist/remote-execution/callback-result.js +0 -26
  690. package/dist/remote-execution/canonical-capabilities.d.ts +0 -5
  691. package/dist/remote-execution/canonical-capabilities.js +0 -45
  692. package/dist/remote-execution/canonical-metadata.d.ts +0 -4
  693. package/dist/remote-execution/canonical-metadata.js +0 -32
  694. package/dist/remote-execution/client.js +0 -824
  695. package/dist/remote-execution/deployment.js +0 -131
  696. package/dist/remote-execution/descriptors.js +0 -267
  697. package/dist/remote-execution/effects.js +0 -357
  698. package/dist/remote-execution/endpoint.js +0 -224
  699. package/dist/remote-execution/files.js +0 -291
  700. package/dist/remote-execution/hosting-operation.js +0 -26
  701. package/dist/remote-execution/hosting-request.d.ts +0 -4
  702. package/dist/remote-execution/hosting-request.js +0 -12
  703. package/dist/remote-execution/hosting-stream.d.ts +0 -8
  704. package/dist/remote-execution/hosting-stream.js +0 -64
  705. package/dist/remote-execution/index.js +0 -18
  706. package/dist/remote-execution/invocation-admission.d.ts +0 -3
  707. package/dist/remote-execution/invocation-admission.js +0 -17
  708. package/dist/remote-execution/job-binding.js +0 -1269
  709. package/dist/remote-execution/materializations.js +0 -284
  710. package/dist/remote-execution/modal-driver.js +0 -90
  711. package/dist/remote-execution/native-result.d.ts +0 -3
  712. package/dist/remote-execution/native-result.js +0 -16
  713. package/dist/remote-execution/output-freshness.d.ts +0 -4
  714. package/dist/remote-execution/output-freshness.js +0 -19
  715. package/dist/remote-execution/output-retrieval.js +0 -474
  716. package/dist/remote-execution/process-http.js +0 -607
  717. package/dist/remote-execution/process.js +0 -577
  718. package/dist/remote-execution/protocol.js +0 -208
  719. package/dist/remote-execution/relay.js +0 -91
  720. package/dist/remote-execution/rest-driver.js +0 -93
  721. package/dist/remote-execution/upload-descriptor.js +0 -201
  722. package/dist/remote-execution/upload-protocol.js +0 -62
  723. package/dist/remote-execution/uploads.js +0 -324
  724. package/dist/remote-execution/wire-json.d.ts +0 -4
  725. package/dist/remote-execution/wire-json.js +0 -44
  726. package/dist/remote-execution/wire-validation.js +0 -131
  727. package/dist/remote-execution/wire.generated.js +0 -4224
  728. package/dist/safe-bash/chunks/chunk-GETUOD5D.js +0 -161
  729. package/dist/safe-bash/chunks/chunk-IWDICZVK.js +0 -20
  730. package/dist/safe-bash/chunks/chunk-MHMMRCYC.js +0 -3464
  731. package/dist/safe-bash/chunks/chunk-UE5KZDEK.js +0 -77
  732. package/dist/safe-bash/chunks/chunk-VSAJ4OTM.js +0 -962
  733. package/dist/safe-bash/chunks/csvkit-TACDU7FC.js +0 -1618
  734. package/dist/safe-bash/chunks/implementation-MLFHUQ5M.js +0 -133
  735. package/dist/safe-bash/commands/csvkit/sync.js +0 -1639
  736. package/dist/safe-bash/commands/node/unconfigured.d.ts +0 -3
  737. package/dist/safe-bash/commands/node/unconfigured.js +0 -10
  738. package/dist/safe-bash/commands/pandoc/implementation.d.ts +0 -8
  739. package/dist/safe-bash/commands/pandoc/implementation.js +0 -94
  740. package/dist/safe-bash-mcp/index.browser.js +0 -9157
  741. package/dist/safe-bash/command-chunks/{chunk-ZRRBXU3M.js → chunk-GIN5GUDP.js} +4 -4
  742. package/dist/safe-bash/command-chunks/{chunk-LAOM65EE.js → chunk-IEO4XVN6.js} +3 -3
  743. package/dist/safe-bash/command-chunks/{chunk-364TMWBT.js → chunk-MWREVL44.js} +6 -6
  744. package/dist/safe-bash/command-chunks/{chunk-464RVBGB.js → chunk-Q5TDKFHK.js} +3 -3
  745. package/dist/safe-bash/command-chunks/{chunk-AJR3AQYA.js → chunk-UKX3LZHR.js} +0 -0
  746. package/dist/safe-bash/command-chunks/{chunk-XIIBTGC5.js → chunk-XPXEQKRW.js} +9 -9
  747. package/dist/safe-bash/command-chunks/{chunk-FDBUV4HJ.js → chunk-Y4HGTG3E.js} +3 -3
  748. /package/dist/{safe-bash/commands/csvkit → safe-bash-command-csvkit}/sync.d.ts +0 -0
@@ -1282,35 +1282,183 @@ function buildHuffmanTree(counts, symbols) {
1282
1282
  }
1283
1283
  level = nextLevel.slice(count);
1284
1284
  }
1285
+ const fastLut = new Int32Array(256).fill(-1);
1286
+ for (let byte = 0; byte < 256; byte++) {
1287
+ let node = root;
1288
+ for (let bitIdx = 7; bitIdx >= 0; bitIdx--) {
1289
+ node = node?.children?.[byte >>> bitIdx & 1];
1290
+ if (!node) break;
1291
+ if (node.symbol !== void 0) {
1292
+ const len = 8 - bitIdx;
1293
+ fastLut[byte] = len << 8 | node.symbol;
1294
+ break;
1295
+ }
1296
+ }
1297
+ }
1298
+ root.fastLut = fastLut;
1285
1299
  return root;
1286
1300
  }
1287
- function idct8x8(coeffs, quant, out) {
1288
- const dequant = new Float64Array(64);
1289
- for (let i = 0; i < 64; i++) {
1290
- dequant[ZIGZAG[i]] = coeffs[i] * quant[i];
1301
+ var IDCT_DEQUANT = new Float64Array(64);
1302
+ var IDCT_TEMP = new Float64Array(64);
1303
+ var SCRATCH_COEFFS = new Int32Array(64);
1304
+ var BOX4_TABLE = (() => {
1305
+ const table = new Float64Array(32);
1306
+ for (let q = 0; q < 4; q++) {
1307
+ for (let u = 0; u < 8; u++) {
1308
+ table[q * 8 + u] = 0.25 * (COS_TABLE[u * 8 + 2 * q] + COS_TABLE[u * 8 + 2 * q + 1]);
1309
+ }
1310
+ }
1311
+ return table;
1312
+ })();
1313
+ var BOX2_TABLE = (() => {
1314
+ const table = new Float64Array(16);
1315
+ for (let q = 0; q < 2; q++) {
1316
+ for (let u = 0; u < 8; u++) {
1317
+ table[q * 8 + u] = 0.125 * (COS_TABLE[u * 8 + 4 * q] + COS_TABLE[u * 8 + 4 * q + 1] + COS_TABLE[u * 8 + 4 * q + 2] + COS_TABLE[u * 8 + 4 * q + 3]);
1318
+ }
1319
+ }
1320
+ return table;
1321
+ })();
1322
+ function idct8x8(coeffs, quant, out, maxK = 63) {
1323
+ if (maxK === 0) {
1324
+ const dcVal = Math.round(coeffs[0] * quant[0] * 0.125 + 128);
1325
+ const clamped = dcVal < 0 ? 0 : dcVal > 255 ? 255 : dcVal;
1326
+ out.fill(clamped, 0, 64);
1327
+ return;
1328
+ }
1329
+ IDCT_DEQUANT.fill(0);
1330
+ for (let i = 0; i <= maxK; i++) {
1331
+ const c = coeffs[i];
1332
+ if (c !== 0) {
1333
+ IDCT_DEQUANT[ZIGZAG[i]] = c * quant[i];
1334
+ }
1291
1335
  }
1292
- const temp = new Float64Array(64);
1293
1336
  for (let y = 0; y < 8; y++) {
1337
+ const rowOff = y * 8;
1338
+ const d0 = IDCT_DEQUANT[rowOff];
1339
+ const d1 = IDCT_DEQUANT[rowOff + 1];
1340
+ const d2 = IDCT_DEQUANT[rowOff + 2];
1341
+ const d3 = IDCT_DEQUANT[rowOff + 3];
1342
+ const d4 = IDCT_DEQUANT[rowOff + 4];
1343
+ const d5 = IDCT_DEQUANT[rowOff + 5];
1344
+ const d6 = IDCT_DEQUANT[rowOff + 6];
1345
+ const d7 = IDCT_DEQUANT[rowOff + 7];
1346
+ if (d1 === 0 && d2 === 0 && d3 === 0 && d4 === 0 && d5 === 0 && d6 === 0 && d7 === 0) {
1347
+ const v = d0 * COS_TABLE[0] * 0.5;
1348
+ IDCT_TEMP[rowOff] = v;
1349
+ IDCT_TEMP[rowOff + 1] = v;
1350
+ IDCT_TEMP[rowOff + 2] = v;
1351
+ IDCT_TEMP[rowOff + 3] = v;
1352
+ IDCT_TEMP[rowOff + 4] = v;
1353
+ IDCT_TEMP[rowOff + 5] = v;
1354
+ IDCT_TEMP[rowOff + 6] = v;
1355
+ IDCT_TEMP[rowOff + 7] = v;
1356
+ continue;
1357
+ }
1294
1358
  for (let x = 0; x < 8; x++) {
1295
- let sum = 0;
1296
- for (let u = 0; u < 8; u++) {
1297
- sum += dequant[y * 8 + u] * COS_TABLE[u * 8 + x];
1298
- }
1299
- temp[y * 8 + x] = sum * 0.5;
1359
+ const sum = d0 * COS_TABLE[x] + d1 * COS_TABLE[8 + x] + d2 * COS_TABLE[16 + x] + d3 * COS_TABLE[24 + x] + d4 * COS_TABLE[32 + x] + d5 * COS_TABLE[40 + x] + d6 * COS_TABLE[48 + x] + d7 * COS_TABLE[56 + x];
1360
+ IDCT_TEMP[rowOff + x] = sum * 0.5;
1300
1361
  }
1301
1362
  }
1302
1363
  for (let x = 0; x < 8; x++) {
1364
+ const t0 = IDCT_TEMP[x];
1365
+ const t1 = IDCT_TEMP[8 + x];
1366
+ const t2 = IDCT_TEMP[16 + x];
1367
+ const t3 = IDCT_TEMP[24 + x];
1368
+ const t4 = IDCT_TEMP[32 + x];
1369
+ const t5 = IDCT_TEMP[40 + x];
1370
+ const t6 = IDCT_TEMP[48 + x];
1371
+ const t7 = IDCT_TEMP[56 + x];
1303
1372
  for (let y = 0; y < 8; y++) {
1304
- let sum = 0;
1305
- for (let v = 0; v < 8; v++) {
1306
- sum += temp[v * 8 + x] * COS_TABLE[v * 8 + y];
1307
- }
1373
+ const sum = t0 * COS_TABLE[y] + t1 * COS_TABLE[8 + y] + t2 * COS_TABLE[16 + y] + t3 * COS_TABLE[24 + y] + t4 * COS_TABLE[32 + y] + t5 * COS_TABLE[40 + y] + t6 * COS_TABLE[48 + y] + t7 * COS_TABLE[56 + y];
1308
1374
  const val = Math.round(sum * 0.5 + 128);
1309
1375
  out[y * 8 + x] = val < 0 ? 0 : val > 255 ? 255 : val;
1310
1376
  }
1311
1377
  }
1312
1378
  }
1313
- function decodeJpegImage(bytes) {
1379
+ function idctScaledBlock(coeffs, quant, out, maxK, step) {
1380
+ if (step === 8) {
1381
+ idct8x8(coeffs, quant, out, maxK);
1382
+ return;
1383
+ }
1384
+ if (maxK === 0) {
1385
+ const dcVal = Math.round(coeffs[0] * quant[0] * 0.125 + 128);
1386
+ const clamped = dcVal < 0 ? 0 : dcVal > 255 ? 255 : dcVal;
1387
+ out.fill(clamped, 0, step * step);
1388
+ return;
1389
+ }
1390
+ IDCT_DEQUANT.fill(0);
1391
+ for (let i = 0; i <= maxK; i++) {
1392
+ const c = coeffs[i];
1393
+ if (c !== 0) {
1394
+ IDCT_DEQUANT[ZIGZAG[i]] = c * quant[i];
1395
+ }
1396
+ }
1397
+ if (step === 4) {
1398
+ for (let y = 0; y < 8; y++) {
1399
+ const rowOff = y * 8;
1400
+ const d0 = IDCT_DEQUANT[rowOff];
1401
+ const d1 = IDCT_DEQUANT[rowOff + 1];
1402
+ const d2 = IDCT_DEQUANT[rowOff + 2];
1403
+ const d3 = IDCT_DEQUANT[rowOff + 3];
1404
+ const d4 = IDCT_DEQUANT[rowOff + 4];
1405
+ const d5 = IDCT_DEQUANT[rowOff + 5];
1406
+ const d6 = IDCT_DEQUANT[rowOff + 6];
1407
+ const d7 = IDCT_DEQUANT[rowOff + 7];
1408
+ const dstOff = y * 4;
1409
+ if (d1 === 0 && d2 === 0 && d3 === 0 && d4 === 0 && d5 === 0 && d6 === 0 && d7 === 0) {
1410
+ const v = d0 * BOX4_TABLE[0];
1411
+ IDCT_TEMP[dstOff] = v;
1412
+ IDCT_TEMP[dstOff + 1] = v;
1413
+ IDCT_TEMP[dstOff + 2] = v;
1414
+ IDCT_TEMP[dstOff + 3] = v;
1415
+ continue;
1416
+ }
1417
+ for (let qx = 0; qx < 4; qx++) {
1418
+ const bOff = qx * 8;
1419
+ IDCT_TEMP[dstOff + qx] = d0 * BOX4_TABLE[bOff] + d1 * BOX4_TABLE[bOff + 1] + d2 * BOX4_TABLE[bOff + 2] + d3 * BOX4_TABLE[bOff + 3] + d4 * BOX4_TABLE[bOff + 4] + d5 * BOX4_TABLE[bOff + 5] + d6 * BOX4_TABLE[bOff + 6] + d7 * BOX4_TABLE[bOff + 7];
1420
+ }
1421
+ }
1422
+ for (let qx = 0; qx < 4; qx++) {
1423
+ const t0 = IDCT_TEMP[qx];
1424
+ const t1 = IDCT_TEMP[4 + qx];
1425
+ const t2 = IDCT_TEMP[8 + qx];
1426
+ const t3 = IDCT_TEMP[12 + qx];
1427
+ const t4 = IDCT_TEMP[16 + qx];
1428
+ const t5 = IDCT_TEMP[20 + qx];
1429
+ const t6 = IDCT_TEMP[24 + qx];
1430
+ const t7 = IDCT_TEMP[28 + qx];
1431
+ for (let qy = 0; qy < 4; qy++) {
1432
+ const bOff = qy * 8;
1433
+ const sum = t0 * BOX4_TABLE[bOff] + t1 * BOX4_TABLE[bOff + 1] + t2 * BOX4_TABLE[bOff + 2] + t3 * BOX4_TABLE[bOff + 3] + t4 * BOX4_TABLE[bOff + 4] + t5 * BOX4_TABLE[bOff + 5] + t6 * BOX4_TABLE[bOff + 6] + t7 * BOX4_TABLE[bOff + 7];
1434
+ const val = Math.round(sum + 128);
1435
+ out[qy * 4 + qx] = val < 0 ? 0 : val > 255 ? 255 : val;
1436
+ }
1437
+ }
1438
+ } else {
1439
+ for (let y = 0; y < 8; y++) {
1440
+ const rowOff = y * 8;
1441
+ const d0 = IDCT_DEQUANT[rowOff];
1442
+ const d1 = IDCT_DEQUANT[rowOff + 1];
1443
+ const d3 = IDCT_DEQUANT[rowOff + 3];
1444
+ const d5 = IDCT_DEQUANT[rowOff + 5];
1445
+ const d7 = IDCT_DEQUANT[rowOff + 7];
1446
+ const evenTerm = d0 * BOX2_TABLE[0];
1447
+ const oddTerm = d1 * BOX2_TABLE[1] + d3 * BOX2_TABLE[3] + d5 * BOX2_TABLE[5] + d7 * BOX2_TABLE[7];
1448
+ IDCT_TEMP[y * 2] = evenTerm + oddTerm;
1449
+ IDCT_TEMP[y * 2 + 1] = evenTerm - oddTerm;
1450
+ }
1451
+ for (let qx = 0; qx < 2; qx++) {
1452
+ const evenCol = (IDCT_TEMP[qx] + IDCT_TEMP[2 + qx] + IDCT_TEMP[4 + qx] + IDCT_TEMP[6 + qx] + IDCT_TEMP[8 + qx] + IDCT_TEMP[10 + qx] + IDCT_TEMP[12 + qx] + IDCT_TEMP[14 + qx]) * BOX2_TABLE[0];
1453
+ const oddCol = (IDCT_TEMP[qx] - IDCT_TEMP[14 + qx]) * BOX2_TABLE[1] + (IDCT_TEMP[2 + qx] - IDCT_TEMP[12 + qx]) * BOX2_TABLE[3] + (IDCT_TEMP[4 + qx] - IDCT_TEMP[10 + qx]) * BOX2_TABLE[5] + (IDCT_TEMP[6 + qx] - IDCT_TEMP[8 + qx]) * BOX2_TABLE[7];
1454
+ const v0 = Math.round(evenCol + oddCol + 128);
1455
+ const v1 = Math.round(evenCol - oddCol + 128);
1456
+ out[qx] = v0 < 0 ? 0 : v0 > 255 ? 255 : v0;
1457
+ out[2 + qx] = v1 < 0 ? 0 : v1 > 255 ? 255 : v1;
1458
+ }
1459
+ }
1460
+ }
1461
+ function decodeJpegImage(bytes, options) {
1314
1462
  const meta = readJpegMetadata(bytes);
1315
1463
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1316
1464
  const quantTables = [];
@@ -1318,6 +1466,12 @@ function decodeJpegImage(bytes) {
1318
1466
  const acTrees = [];
1319
1467
  let width = 0;
1320
1468
  let height = 0;
1469
+ let scaleDenom = 1;
1470
+ let blockStep = 8;
1471
+ let outWidth = 0;
1472
+ let outHeight = 0;
1473
+ let useStripDecode = false;
1474
+ let outRgba;
1321
1475
  let maxH = 1;
1322
1476
  let maxV = 1;
1323
1477
  let mcusX = 0;
@@ -1373,6 +1527,19 @@ function decodeJpegImage(bytes) {
1373
1527
  } else if (marker === 192 || marker === 193 || marker === 194) {
1374
1528
  height = payload[1] << 8 | payload[2];
1375
1529
  width = payload[3] << 8 | payload[4];
1530
+ if (!meta.isProgressive && options?.maxDecodeDimension && options.maxDecodeDimension > 0) {
1531
+ const maxSide = Math.max(width, height);
1532
+ const minSide = Math.min(width, height);
1533
+ if (maxSide >= options.maxDecodeDimension * 4 && minSide >= options.maxDecodeDimension * 2) {
1534
+ scaleDenom = 4;
1535
+ blockStep = 2;
1536
+ } else if (maxSide >= options.maxDecodeDimension * 2) {
1537
+ scaleDenom = 2;
1538
+ blockStep = 4;
1539
+ }
1540
+ }
1541
+ outWidth = Math.max(1, Math.ceil(width / scaleDenom));
1542
+ outHeight = Math.max(1, Math.ceil(height / scaleDenom));
1376
1543
  const numComps = payload[5];
1377
1544
  components.length = 0;
1378
1545
  maxH = 1;
@@ -1394,16 +1561,22 @@ function decodeJpegImage(bytes) {
1394
1561
  acId: 0,
1395
1562
  dcPred: 0,
1396
1563
  blocksX: 0,
1397
- blocksY: 0,
1398
- blocks: []
1564
+ blocksY: 0
1399
1565
  });
1400
1566
  }
1401
1567
  mcusX = Math.ceil(width / (maxH * 8));
1402
1568
  mcusY = Math.ceil(height / (maxV * 8));
1569
+ useStripDecode = !meta.isProgressive && (scaleDenom > 1 || width * height > 512 * 512);
1403
1570
  for (const comp of components) {
1404
1571
  comp.blocksX = mcusX * comp.h;
1405
1572
  comp.blocksY = mcusY * comp.v;
1406
- comp.blocks = Array.from({ length: comp.blocksX * comp.blocksY }, () => new Int32Array(64));
1573
+ if (meta.isProgressive) {
1574
+ comp.blocksFlat = new Int16Array(comp.blocksX * comp.blocksY * 64);
1575
+ } else if (useStripDecode) {
1576
+ comp.stripPixels = new Uint8Array(comp.blocksX * blockStep * comp.v * blockStep);
1577
+ } else {
1578
+ comp.pixels = new Uint8Array(comp.blocksX * blockStep * comp.blocksY * blockStep);
1579
+ }
1407
1580
  }
1408
1581
  } else if (marker === 218) {
1409
1582
  const scanCompsCount = payload[0];
@@ -1417,6 +1590,17 @@ function decodeJpegImage(bytes) {
1417
1590
  comp.acId = tdta & 15;
1418
1591
  scanComps.push(comp);
1419
1592
  }
1593
+ if (!meta.isProgressive && scanCompsCount < components.length) {
1594
+ useStripDecode = false;
1595
+ for (const comp of components) {
1596
+ if (!comp.pixels) {
1597
+ comp.pixels = new Uint8Array(comp.blocksX * blockStep * comp.blocksY * blockStep);
1598
+ }
1599
+ }
1600
+ }
1601
+ if (useStripDecode && !outRgba) {
1602
+ outRgba = new Uint8Array(outWidth * outHeight * 4);
1603
+ }
1420
1604
  const ssPos = 1 + scanCompsCount * 2;
1421
1605
  const spectralStart = payload[ssPos] ?? 0;
1422
1606
  const spectralEnd = payload[ssPos + 1] ?? 63;
@@ -1427,6 +1611,23 @@ function decodeJpegImage(bytes) {
1427
1611
  let bitBuf = 0;
1428
1612
  let bitCount = 0;
1429
1613
  let eobRun = 0;
1614
+ const refillBits = () => {
1615
+ while (bitCount <= 16 && scanPos < bytes.length) {
1616
+ const b = bytes[scanPos];
1617
+ if (b === 255) {
1618
+ if (scanPos + 1 >= bytes.length || bytes[scanPos + 1] !== 0) {
1619
+ break;
1620
+ }
1621
+ scanPos += 2;
1622
+ bitBuf = (bitBuf << 8 | 255) >>> 0;
1623
+ bitCount += 8;
1624
+ } else {
1625
+ scanPos++;
1626
+ bitBuf = (bitBuf << 8 | b) >>> 0;
1627
+ bitCount += 8;
1628
+ }
1629
+ }
1630
+ };
1430
1631
  const readBit = () => {
1431
1632
  if (bitCount === 0) {
1432
1633
  if (scanPos >= bytes.length) throw new Error("Truncated JPEG entropy data");
@@ -1443,6 +1644,13 @@ function decodeJpegImage(bytes) {
1443
1644
  return bit;
1444
1645
  };
1445
1646
  const readBits = (n) => {
1647
+ if (n === 0) return 0;
1648
+ if (bitCount < n) refillBits();
1649
+ if (bitCount >= n) {
1650
+ const val2 = bitBuf >>> bitCount - n & (1 << n) - 1;
1651
+ bitCount -= n;
1652
+ return val2;
1653
+ }
1446
1654
  let val = 0;
1447
1655
  for (let i = 0; i < n; i++) {
1448
1656
  val = val << 1 | readBit();
@@ -1455,6 +1663,16 @@ function decodeJpegImage(bytes) {
1455
1663
  return v < 1 << n - 1 ? v + (-1 << n) + 1 : v;
1456
1664
  };
1457
1665
  const decodeSymbol = (tree) => {
1666
+ if (!tree) throw new Error("Invalid JPEG Huffman code");
1667
+ if (bitCount < 8) refillBits();
1668
+ if (bitCount >= 8 && tree.fastLut) {
1669
+ const peek = bitBuf >>> bitCount - 8 & 255;
1670
+ const fast = tree.fastLut[peek];
1671
+ if (fast >= 0) {
1672
+ bitCount -= fast >>> 8;
1673
+ return fast & 255;
1674
+ }
1675
+ }
1458
1676
  let node = tree;
1459
1677
  while (node && node.symbol === void 0) {
1460
1678
  const bit = readBit();
@@ -1464,12 +1682,14 @@ function decodeJpegImage(bytes) {
1464
1682
  return node.symbol;
1465
1683
  };
1466
1684
  const decodeBlockBaseline = (comp, block) => {
1685
+ block.fill(0);
1467
1686
  const dcTree = dcTrees[comp.dcId];
1468
1687
  const acTree = acTrees[comp.acId];
1469
1688
  const t = decodeSymbol(dcTree);
1470
1689
  const diff = receiveExtend(t);
1471
1690
  comp.dcPred += diff;
1472
1691
  block[0] = comp.dcPred;
1692
+ let maxK = 0;
1473
1693
  let k = 1;
1474
1694
  while (k < 64) {
1475
1695
  const rs = decodeSymbol(acTree);
@@ -1485,9 +1705,11 @@ function decodeJpegImage(bytes) {
1485
1705
  k += r;
1486
1706
  if (k < 64) {
1487
1707
  block[k] = receiveExtend(s);
1708
+ maxK = k;
1488
1709
  }
1489
1710
  k++;
1490
1711
  }
1712
+ return maxK;
1491
1713
  };
1492
1714
  const decodeBlockProgressive = (comp, block) => {
1493
1715
  if (spectralStart === 0) {
@@ -1562,6 +1784,24 @@ function decodeJpegImage(bytes) {
1562
1784
  }
1563
1785
  }
1564
1786
  };
1787
+ const blockOut = new Uint8Array(64);
1788
+ const decodeAndStoreBaselineBlock = (comp, bx, by, stripVy) => {
1789
+ const maxK = decodeBlockBaseline(comp, SCRATCH_COEFFS);
1790
+ const quant = quantTables[comp.qId];
1791
+ if (!quant) throw new Error("Missing JPEG quantization table");
1792
+ idctScaledBlock(SCRATCH_COEFFS, quant, blockOut, maxK, blockStep);
1793
+ const stride = comp.blocksX * blockStep;
1794
+ const dst = useStripDecode ? comp.stripPixels : comp.pixels;
1795
+ const baseRow = (useStripDecode ? stripVy : by) * blockStep;
1796
+ const baseCol = bx * blockStep;
1797
+ for (let y = 0; y < blockStep; y++) {
1798
+ const dstOff = (baseRow + y) * stride + baseCol;
1799
+ const srcOff = y * blockStep;
1800
+ for (let x = 0; x < blockStep; x++) {
1801
+ dst[dstOff + x] = blockOut[srcOff + x];
1802
+ }
1803
+ }
1804
+ };
1565
1805
  let mcuCounter = 0;
1566
1806
  let restartCounter = 0;
1567
1807
  const consumeRestart = () => {
@@ -1582,13 +1822,17 @@ function decodeJpegImage(bytes) {
1582
1822
  if (restartInterval > 0 && mcuCounter > 0 && mcuCounter % restartInterval === 0) {
1583
1823
  consumeRestart();
1584
1824
  }
1585
- const block = comp.blocks[by * comp.blocksX + bx];
1586
- if (meta.isProgressive) decodeBlockProgressive(comp, block);
1587
- else decodeBlockBaseline(comp, block);
1825
+ if (meta.isProgressive) {
1826
+ const off = (by * comp.blocksX + bx) * 64;
1827
+ decodeBlockProgressive(comp, comp.blocksFlat.subarray(off, off + 64));
1828
+ } else {
1829
+ decodeAndStoreBaselineBlock(comp, bx, by, by % comp.v);
1830
+ }
1588
1831
  mcuCounter++;
1589
1832
  }
1590
1833
  }
1591
1834
  } else {
1835
+ const mcuRowH = maxV * blockStep;
1592
1836
  for (let my = 0; my < mcusY; my++) {
1593
1837
  for (let mx = 0; mx < mcusX; mx++) {
1594
1838
  if (restartInterval > 0 && mcuCounter > 0 && mcuCounter % restartInterval === 0) {
@@ -1599,14 +1843,87 @@ function decodeJpegImage(bytes) {
1599
1843
  for (let hx = 0; hx < comp.h; hx++) {
1600
1844
  const bx = mx * comp.h + hx;
1601
1845
  const by = my * comp.v + vy;
1602
- const block = comp.blocks[by * comp.blocksX + bx];
1603
- if (meta.isProgressive) decodeBlockProgressive(comp, block);
1604
- else decodeBlockBaseline(comp, block);
1846
+ if (meta.isProgressive) {
1847
+ const off = (by * comp.blocksX + bx) * 64;
1848
+ decodeBlockProgressive(comp, comp.blocksFlat.subarray(off, off + 64));
1849
+ } else {
1850
+ decodeAndStoreBaselineBlock(comp, bx, by, vy);
1851
+ }
1605
1852
  }
1606
1853
  }
1607
1854
  }
1608
1855
  mcuCounter++;
1609
1856
  }
1857
+ if (useStripDecode && outRgba) {
1858
+ const yStart = my * mcuRowH;
1859
+ const yEnd = Math.min(outHeight, yStart + mcuRowH);
1860
+ const c0 = components[0];
1861
+ const s0 = c0.blocksX * blockStep;
1862
+ if (components.length === 1) {
1863
+ const p0 = c0.stripPixels;
1864
+ for (let y = yStart; y < yEnd; y++) {
1865
+ const ly = y - yStart;
1866
+ const rowIn = ly * s0;
1867
+ let outIdx = y * outWidth * 4;
1868
+ for (let x = 0; x < outWidth; x++) {
1869
+ const g = p0[rowIn + x];
1870
+ outRgba[outIdx] = g;
1871
+ outRgba[outIdx + 1] = g;
1872
+ outRgba[outIdx + 2] = g;
1873
+ outRgba[outIdx + 3] = 255;
1874
+ outIdx += 4;
1875
+ }
1876
+ }
1877
+ } else if (components.length >= 3) {
1878
+ const c1 = components[1];
1879
+ const c2 = components[2];
1880
+ const pY = c0.stripPixels;
1881
+ const pCb = c1.stripPixels;
1882
+ const pCr = c2.stripPixels;
1883
+ const sY = s0;
1884
+ const sCb = c1.blocksX * blockStep;
1885
+ const sCr = c2.blocksX * blockStep;
1886
+ const hY = c0.h, vY = c0.v;
1887
+ const hCb = c1.h, vCb = c1.v;
1888
+ const hCr = c2.h, vCr = c2.v;
1889
+ const hasK = components.length === 4;
1890
+ const c3 = hasK ? components[3] : void 0;
1891
+ const pK = c3?.stripPixels;
1892
+ const sK = c3 ? c3.blocksX * blockStep : 0;
1893
+ for (let y = yStart; y < yEnd; y++) {
1894
+ const ly = y - yStart;
1895
+ const yRow = (vY === maxV ? ly : Math.floor(ly * vY / maxV)) * sY;
1896
+ const cbRow = (vCb === maxV ? ly : Math.floor(ly * vCb / maxV)) * sCb;
1897
+ const crRow = (vCr === maxV ? ly : Math.floor(ly * vCr / maxV)) * sCr;
1898
+ const kRow = c3 ? (c3.v === maxV ? ly : Math.floor(ly * c3.v / maxV)) * sK : 0;
1899
+ let outIdx = y * outWidth * 4;
1900
+ for (let x = 0; x < outWidth; x++) {
1901
+ const yVal = pY[yRow + (hY === maxH ? x : Math.floor(x * hY / maxH))];
1902
+ const cbVal = pCb[cbRow + (hCb === maxH ? x : Math.floor(x * hCb / maxH))] - 128;
1903
+ const crVal = pCr[crRow + (hCr === maxH ? x : Math.floor(x * hCr / maxH))] - 128;
1904
+ let r = yVal + (91881 * crVal + 32768 >> 16);
1905
+ let g = yVal - (22554 * cbVal + 46802 * crVal + 32768 >> 16);
1906
+ let b = yVal + (116130 * cbVal + 32768 >> 16);
1907
+ r = r < 0 ? 0 : r > 255 ? 255 : r;
1908
+ g = g < 0 ? 0 : g > 255 ? 255 : g;
1909
+ b = b < 0 ? 0 : b > 255 ? 255 : b;
1910
+ if (hasK && pK && c3) {
1911
+ const kVal = pK[kRow + (c3.h === maxH ? x : Math.floor(x * c3.h / maxH))];
1912
+ outRgba[outIdx] = Math.round(r * kVal / 255);
1913
+ outRgba[outIdx + 1] = Math.round(g * kVal / 255);
1914
+ outRgba[outIdx + 2] = Math.round(b * kVal / 255);
1915
+ outRgba[outIdx + 3] = 255;
1916
+ } else {
1917
+ outRgba[outIdx] = r;
1918
+ outRgba[outIdx + 1] = g;
1919
+ outRgba[outIdx + 2] = b;
1920
+ outRgba[outIdx + 3] = 255;
1921
+ }
1922
+ outIdx += 4;
1923
+ }
1924
+ }
1925
+ }
1926
+ }
1610
1927
  }
1611
1928
  }
1612
1929
  pos = scanPos;
@@ -1614,14 +1931,34 @@ function decodeJpegImage(bytes) {
1614
1931
  }
1615
1932
  pos += segLen;
1616
1933
  }
1934
+ if (useStripDecode && outRgba) {
1935
+ return {
1936
+ width: outWidth,
1937
+ height: outHeight,
1938
+ data: outRgba,
1939
+ format: "jpeg",
1940
+ space: meta.space,
1941
+ channels: meta.channels,
1942
+ depth: "uchar",
1943
+ density: meta.density,
1944
+ hasAlpha: false,
1945
+ ...meta.orientation !== void 0 ? { orientation: meta.orientation } : {},
1946
+ ...meta.isProgressive !== void 0 ? { isProgressive: meta.isProgressive } : {}
1947
+ };
1948
+ }
1617
1949
  const compPixels = components.map((comp) => {
1950
+ if (!meta.isProgressive && comp.pixels) {
1951
+ return { comp, pixels: comp.pixels, stride: comp.blocksX * blockStep };
1952
+ }
1618
1953
  const pixels = new Uint8Array(comp.blocksX * 8 * comp.blocksY * 8);
1619
1954
  const blockOut = new Uint8Array(64);
1620
1955
  const quant = quantTables[comp.qId];
1621
1956
  if (!quant) throw new Error("Missing JPEG quantization table");
1957
+ const blocksFlat = comp.blocksFlat;
1622
1958
  for (let by = 0; by < comp.blocksY; by++) {
1623
1959
  for (let bx = 0; bx < comp.blocksX; bx++) {
1624
- idct8x8(comp.blocks[by * comp.blocksX + bx], quant, blockOut);
1960
+ const off = (by * comp.blocksX + bx) * 64;
1961
+ idct8x8(blocksFlat.subarray(off, off + 64), quant, blockOut, 63);
1625
1962
  for (let y = 0; y < 8; y++) {
1626
1963
  const dstOffset = (by * 8 + y) * (comp.blocksX * 8) + bx * 8;
1627
1964
  for (let x = 0; x < 8; x++) {
@@ -1733,28 +2070,36 @@ var ENC_DC_LUMA = buildEncodeTable(STD_DC_LUMA_NRCODES, STD_DC_LUMA_VALUES);
1733
2070
  var ENC_DC_CHROMA = buildEncodeTable(STD_DC_CHROMA_NRCODES, STD_DC_CHROMA_VALUES);
1734
2071
  var ENC_AC_LUMA = buildEncodeTable(STD_AC_LUMA_NRCODES, STD_AC_LUMA_VALUES);
1735
2072
  var ENC_AC_CHROMA = buildEncodeTable(STD_AC_CHROMA_NRCODES, STD_AC_CHROMA_VALUES);
2073
+ var INV_ZIGZAG = (() => {
2074
+ const inv = new Uint8Array(64);
2075
+ for (let i = 0; i < 64; i++) {
2076
+ inv[ZIGZAG[i]] = i;
2077
+ }
2078
+ return inv;
2079
+ })();
2080
+ var FDCT_TEMP = new Float64Array(64);
1736
2081
  function fdct8x8(block, quant, outZigZag) {
1737
- const temp = new Float64Array(64);
1738
2082
  for (let y = 0; y < 8; y++) {
2083
+ const rowOff = y * 8;
1739
2084
  for (let u = 0; u < 8; u++) {
2085
+ const cosOff = u * 8;
1740
2086
  let sum = 0;
1741
2087
  for (let x = 0; x < 8; x++) {
1742
- sum += block[y * 8 + x] * COS_TABLE[u * 8 + x];
2088
+ sum += block[rowOff + x] * COS_TABLE[cosOff + x];
1743
2089
  }
1744
- temp[y * 8 + u] = sum * 0.5;
2090
+ FDCT_TEMP[rowOff + u] = sum * 0.5;
1745
2091
  }
1746
2092
  }
1747
2093
  for (let v = 0; v < 8; v++) {
2094
+ const cosOff = v * 8;
2095
+ const vRow = v * 8;
1748
2096
  for (let u = 0; u < 8; u++) {
1749
2097
  let sum = 0;
1750
2098
  for (let y = 0; y < 8; y++) {
1751
- sum += temp[y * 8 + u] * COS_TABLE[v * 8 + y];
1752
- }
1753
- const coeff = sum * 0.5;
1754
- const zigIdx = ZIGZAG.indexOf(v * 8 + u);
1755
- if (zigIdx >= 0) {
1756
- outZigZag[zigIdx] = Math.round(coeff / (quant[zigIdx] ?? 1));
2099
+ sum += FDCT_TEMP[y * 8 + u] * COS_TABLE[cosOff + y];
1757
2100
  }
2101
+ const zigIdx = INV_ZIGZAG[vRow + u];
2102
+ outZigZag[zigIdx] = Math.round(sum * 0.5 / (quant[zigIdx] ?? 1));
1758
2103
  }
1759
2104
  }
1760
2105
  }
@@ -1858,29 +2203,26 @@ function encodeJpegImage(img, options) {
1858
2203
  let bitBuf = 0;
1859
2204
  let bitCnt = 0;
1860
2205
  const writeBits = (code, len) => {
1861
- for (let i = len - 1; i >= 0; i--) {
1862
- bitBuf = bitBuf << 1 | code >>> i & 1;
1863
- bitCnt++;
1864
- if (bitCnt === 8) {
1865
- bytes.push(bitBuf);
1866
- if (bitBuf === 255) bytes.push(0);
1867
- bitBuf = 0;
1868
- bitCnt = 0;
1869
- }
2206
+ bitBuf = bitBuf << len | code & (1 << len) - 1;
2207
+ bitCnt += len;
2208
+ while (bitCnt >= 8) {
2209
+ bitCnt -= 8;
2210
+ const b = bitBuf >>> bitCnt & 255;
2211
+ bytes.push(b);
2212
+ if (b === 255) bytes.push(0);
1870
2213
  }
1871
2214
  };
1872
- const encodeNumber = (val) => {
1873
- if (val === 0) return { category: 0, bits: 0 };
1874
- const abs = Math.abs(val);
1875
- const category = 32 - Math.clz32(abs);
1876
- const bits = val > 0 ? val : (1 << category) - 1 + val;
1877
- return { category, bits };
1878
- };
1879
2215
  const encodeBlock = (zz, prevDc, dcTab, acTab) => {
1880
2216
  const diff = zz[0] - prevDc;
1881
- const dcEnc = encodeNumber(diff);
1882
- writeBits(dcTab.code[dcEnc.category], dcTab.len[dcEnc.category]);
1883
- if (dcEnc.category > 0) writeBits(dcEnc.bits, dcEnc.category);
2217
+ if (diff === 0) {
2218
+ writeBits(dcTab.code[0], dcTab.len[0]);
2219
+ } else {
2220
+ const abs = diff < 0 ? -diff : diff;
2221
+ const cat = 32 - Math.clz32(abs);
2222
+ const bits = diff > 0 ? diff : (1 << cat) - 1 + diff;
2223
+ writeBits(dcTab.code[cat], dcTab.len[cat]);
2224
+ writeBits(bits, cat);
2225
+ }
1884
2226
  let zeroRun = 0;
1885
2227
  for (let k = 1; k < 64; k++) {
1886
2228
  const v = zz[k];
@@ -1891,10 +2233,12 @@ function encodeJpegImage(img, options) {
1891
2233
  writeBits(acTab.code[240], acTab.len[240]);
1892
2234
  zeroRun -= 16;
1893
2235
  }
1894
- const acEnc = encodeNumber(v);
1895
- const sym = zeroRun << 4 | acEnc.category;
2236
+ const abs = v < 0 ? -v : v;
2237
+ const cat = 32 - Math.clz32(abs);
2238
+ const bits = v > 0 ? v : (1 << cat) - 1 + v;
2239
+ const sym = zeroRun << 4 | cat;
1896
2240
  writeBits(acTab.code[sym], acTab.len[sym]);
1897
- writeBits(acEnc.bits, acEnc.category);
2241
+ writeBits(bits, cat);
1898
2242
  zeroRun = 0;
1899
2243
  }
1900
2244
  }
@@ -5130,14 +5474,12 @@ function decodeSvgImage(bytes, options) {
5130
5474
  }
5131
5475
 
5132
5476
  // packages/image-ast/src/codecs/index.ts
5133
- var DEFAULT_PIXEL_LIMIT = Infinity;
5134
5477
  function checkLimitInputPixels(width, height, options) {
5135
- const limit = options?.limitInputPixels === false || options?.limitInputPixels === 0 || options?.unlimited === true && options?.limitInputPixels === void 0 ? Infinity : typeof options?.limitInputPixels === "number" ? options.limitInputPixels : DEFAULT_PIXEL_LIMIT;
5478
+ const limit = options?.limitInputPixels === false || options?.limitInputPixels === 0 || options?.unlimited === true && options?.limitInputPixels === void 0 ? Infinity : typeof options?.limitInputPixels === "number" ? options.limitInputPixels : Infinity;
5136
5479
  if (width * height > limit) {
5137
5480
  throw new Error(`Input image exceeds pixel limit (${width}x${height} > ${limit})`);
5138
5481
  }
5139
5482
  }
5140
- var DECODE_CACHE = /* @__PURE__ */ new WeakMap();
5141
5483
  function detectImageFormat(bytes) {
5142
5484
  if (isPngBytes(bytes)) return "png";
5143
5485
  if (isJpegBytes(bytes)) return "jpeg";
@@ -5577,14 +5919,6 @@ function decodeImage(bytes, options) {
5577
5919
  if (!bytes || bytes.length === 0) {
5578
5920
  throw new Error(!bytes ? "Input file is missing:" : "Input buffer contains unsupported image format");
5579
5921
  }
5580
- const canCache = options?.density === void 0 && options?.page === void 0 && options?.pages === void 0 && options?.animated === void 0 && options?.raw === void 0 && options?.create === void 0;
5581
- if (canCache) {
5582
- const cached = DECODE_CACHE.get(bytes);
5583
- if (cached) {
5584
- checkLimitInputPixels(cached.width, cached.height, options);
5585
- return cached;
5586
- }
5587
- }
5588
5922
  const meta = readImageMetadata(bytes, options);
5589
5923
  let decoded;
5590
5924
  switch (meta.format) {
@@ -5592,7 +5926,7 @@ function decodeImage(bytes, options) {
5592
5926
  decoded = decodePngImage(bytes);
5593
5927
  break;
5594
5928
  case "jpeg":
5595
- decoded = decodeJpegImage(bytes);
5929
+ decoded = decodeJpegImage(bytes, options);
5596
5930
  break;
5597
5931
  case "webp":
5598
5932
  decoded = decodeWebpImage(bytes);
@@ -5625,9 +5959,6 @@ function decodeImage(bytes, options) {
5625
5959
  default:
5626
5960
  throw new Error(`Unsupported format: ${meta.format}`);
5627
5961
  }
5628
- if (canCache) {
5629
- DECODE_CACHE.set(bytes, decoded);
5630
- }
5631
5962
  return decoded;
5632
5963
  }
5633
5964
  function encodeImage(img, options) {
@@ -6244,19 +6575,22 @@ function* shrinkVBoxSteps(src, w, h, vshrink) {
6244
6575
  const out = new Uint8Array(w * outH * 4);
6245
6576
  const roundAdd = vshrink >> 1;
6246
6577
  for (let y = 0; y < outH; y++) {
6247
- if (++work % 16384 === 0) yield;
6248
6578
  for (let x = 0; x < w; x++) {
6249
6579
  if (++work % 16384 === 0) yield;
6250
- for (let c = 0; c < 4; c++) {
6251
- if (++work % 16384 === 0) yield;
6252
- let sum = 0;
6253
- for (let k = 0; k < vshrink; k++) {
6254
- if (++work % 16384 === 0) yield;
6255
- const sy = Math.min(h - 1, y * vshrink + k);
6256
- sum += src[(sy * w + x) * 4 + c];
6257
- }
6258
- out[(y * w + x) * 4 + c] = Math.floor((sum + roundAdd) / vshrink);
6580
+ let sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0;
6581
+ for (let k = 0; k < vshrink; k++) {
6582
+ const sy = Math.min(h - 1, y * vshrink + k);
6583
+ const sIdx = (sy * w + x) * 4;
6584
+ sum0 += src[sIdx];
6585
+ sum1 += src[sIdx + 1];
6586
+ sum2 += src[sIdx + 2];
6587
+ sum3 += src[sIdx + 3];
6259
6588
  }
6589
+ const dIdx = (y * w + x) * 4;
6590
+ out[dIdx] = Math.floor((sum0 + roundAdd) / vshrink);
6591
+ out[dIdx + 1] = Math.floor((sum1 + roundAdd) / vshrink);
6592
+ out[dIdx + 2] = Math.floor((sum2 + roundAdd) / vshrink);
6593
+ out[dIdx + 3] = Math.floor((sum3 + roundAdd) / vshrink);
6260
6594
  }
6261
6595
  }
6262
6596
  return { data: out, h: outH };
@@ -6267,19 +6601,24 @@ function* shrinkHBoxSteps(src, w, h, hshrink) {
6267
6601
  const out = new Uint8Array(outW * h * 4);
6268
6602
  const roundAdd = hshrink >> 1;
6269
6603
  for (let y = 0; y < h; y++) {
6270
- if (++work % 16384 === 0) yield;
6604
+ const rowOff = y * w * 4;
6605
+ const dstRowOff = y * outW * 4;
6271
6606
  for (let x = 0; x < outW; x++) {
6272
6607
  if (++work % 16384 === 0) yield;
6273
- for (let c = 0; c < 4; c++) {
6274
- if (++work % 16384 === 0) yield;
6275
- let sum = 0;
6276
- for (let k = 0; k < hshrink; k++) {
6277
- if (++work % 16384 === 0) yield;
6278
- const sx = Math.min(w - 1, x * hshrink + k);
6279
- sum += src[(y * w + sx) * 4 + c];
6280
- }
6281
- out[(y * outW + x) * 4 + c] = Math.floor((sum + roundAdd) / hshrink);
6282
- }
6608
+ let sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0;
6609
+ for (let k = 0; k < hshrink; k++) {
6610
+ const sx = Math.min(w - 1, x * hshrink + k);
6611
+ const sIdx = rowOff + sx * 4;
6612
+ sum0 += src[sIdx];
6613
+ sum1 += src[sIdx + 1];
6614
+ sum2 += src[sIdx + 2];
6615
+ sum3 += src[sIdx + 3];
6616
+ }
6617
+ const dIdx = dstRowOff + x * 4;
6618
+ out[dIdx] = Math.floor((sum0 + roundAdd) / hshrink);
6619
+ out[dIdx + 1] = Math.floor((sum1 + roundAdd) / hshrink);
6620
+ out[dIdx + 2] = Math.floor((sum2 + roundAdd) / hshrink);
6621
+ out[dIdx + 3] = Math.floor((sum3 + roundAdd) / hshrink);
6283
6622
  }
6284
6623
  }
6285
6624
  return { data: out, w: outW };
@@ -6356,23 +6695,32 @@ function* resampleRawBitmapSteps(src, srcW, srcH, dstW, dstH, kernel = "lanczos3
6356
6695
  const voffset = (extraPixels + 1) * 0.5 - 1;
6357
6696
  const out = new Uint8Array(w * targetH * 4);
6358
6697
  let Y = fmaDouble(0.5, vshrink, -0.5) - voffset;
6698
+ const rowOffsets = new Int32Array(nPoint);
6359
6699
  for (let y = 0; y < targetH; y++) {
6360
- if (++work % 16384 === 0) yield;
6361
6700
  const iy = Math.trunc(Y);
6362
6701
  const ty = (Math.trunc(Y * 128) & 127) + 1 >> 1;
6363
6702
  const wRow = ty * nPoint;
6703
+ for (let j = 0; j < nPoint; j++) {
6704
+ rowOffsets[j] = Math.max(0, Math.min(h - 1, iy + j - topPad)) * w * 4;
6705
+ }
6706
+ const dstRowOff = y * w * 4;
6364
6707
  for (let x = 0; x < w; x++) {
6365
6708
  if (++work % 16384 === 0) yield;
6366
- for (let c = 0; c < 4; c++) {
6367
- if (++work % 16384 === 0) yield;
6368
- let sum = 0;
6369
- for (let j = 0; j < nPoint; j++) {
6370
- if (++work % 16384 === 0) yield;
6371
- const sy = Math.max(0, Math.min(h - 1, iy + j - topPad));
6372
- sum += cur[(sy * w + x) * 4 + c] * table[wRow + j];
6373
- }
6374
- out[(y * w + x) * 4 + c] = Math.max(0, Math.min(255, sum + 2048 >> 12));
6709
+ const xOff = x * 4;
6710
+ let sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0;
6711
+ for (let j = 0; j < nPoint; j++) {
6712
+ const wt = table[wRow + j];
6713
+ const sIdx = rowOffsets[j] + xOff;
6714
+ sum0 += cur[sIdx] * wt;
6715
+ sum1 += cur[sIdx + 1] * wt;
6716
+ sum2 += cur[sIdx + 2] * wt;
6717
+ sum3 += cur[sIdx + 3] * wt;
6375
6718
  }
6719
+ const dIdx = dstRowOff + xOff;
6720
+ out[dIdx] = Math.max(0, Math.min(255, sum0 + 2048 >> 12));
6721
+ out[dIdx + 1] = Math.max(0, Math.min(255, sum1 + 2048 >> 12));
6722
+ out[dIdx + 2] = Math.max(0, Math.min(255, sum2 + 2048 >> 12));
6723
+ out[dIdx + 3] = Math.max(0, Math.min(255, sum3 + 2048 >> 12));
6376
6724
  }
6377
6725
  Y += vshrink;
6378
6726
  }
@@ -6398,24 +6746,33 @@ function* resampleRawBitmapSteps(src, srcW, srcH, dstW, dstH, kernel = "lanczos3
6398
6746
  const leftPad = Math.ceil(nPoint * 0.5) - 1;
6399
6747
  const hoffset = (extraPixels + 1) * 0.5 - 1;
6400
6748
  const out = new Uint8Array(targetW * h * 4);
6749
+ const colOffsets = new Int32Array(nPoint);
6401
6750
  let X = fmaDouble(0.5, hshrink, -0.5) - hoffset;
6402
6751
  for (let x = 0; x < targetW; x++) {
6403
- if (++work % 16384 === 0) yield;
6404
6752
  const ix = Math.trunc(X);
6405
6753
  const tx = (Math.trunc(X * 128) & 127) + 1 >> 1;
6406
6754
  const wRow = tx * nPoint;
6755
+ for (let j = 0; j < nPoint; j++) {
6756
+ colOffsets[j] = Math.max(0, Math.min(w - 1, ix + j - leftPad)) * 4;
6757
+ }
6758
+ const dstColOff = x * 4;
6407
6759
  for (let y = 0; y < h; y++) {
6408
6760
  if (++work % 16384 === 0) yield;
6409
- for (let c = 0; c < 4; c++) {
6410
- if (++work % 16384 === 0) yield;
6411
- let sum = 0;
6412
- for (let j = 0; j < nPoint; j++) {
6413
- if (++work % 16384 === 0) yield;
6414
- const sx = Math.max(0, Math.min(w - 1, ix + j - leftPad));
6415
- sum += cur[(y * w + sx) * 4 + c] * table[wRow + j];
6416
- }
6417
- out[(y * targetW + x) * 4 + c] = Math.max(0, Math.min(255, sum + 2048 >> 12));
6761
+ const srcRowOff = y * w * 4;
6762
+ let sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0;
6763
+ for (let j = 0; j < nPoint; j++) {
6764
+ const wt = table[wRow + j];
6765
+ const sIdx = srcRowOff + colOffsets[j];
6766
+ sum0 += cur[sIdx] * wt;
6767
+ sum1 += cur[sIdx + 1] * wt;
6768
+ sum2 += cur[sIdx + 2] * wt;
6769
+ sum3 += cur[sIdx + 3] * wt;
6418
6770
  }
6771
+ const dIdx = y * targetW * 4 + dstColOff;
6772
+ out[dIdx] = Math.max(0, Math.min(255, sum0 + 2048 >> 12));
6773
+ out[dIdx + 1] = Math.max(0, Math.min(255, sum1 + 2048 >> 12));
6774
+ out[dIdx + 2] = Math.max(0, Math.min(255, sum2 + 2048 >> 12));
6775
+ out[dIdx + 3] = Math.max(0, Math.min(255, sum3 + 2048 >> 12));
6419
6776
  }
6420
6777
  X += hshrink;
6421
6778
  }
@@ -8373,35 +8730,35 @@ function buildVipsGaussmat(sigma, minAmpl = 0.1) {
8373
8730
  }
8374
8731
  return { radius: maxX, weights, scale };
8375
8732
  }
8376
- function vipsSrgbToLabForSharpen(r, g, b) {
8733
+ var SHARPEN_LAB_OUT = new Float64Array(3);
8734
+ var SHARPEN_RGB_OUT = new Uint8Array(3);
8735
+ function vipsSrgbToLabForSharpenInto(r, g, b, out) {
8377
8736
  const rl = SRGB_TO_LINEAR_LUT[r];
8378
8737
  const gl = SRGB_TO_LINEAR_LUT[g];
8379
8738
  const bl = SRGB_TO_LINEAR_LUT[b];
8380
8739
  const X = (41.24 * rl + 35.76 * gl + 18.05 * bl) / 95.047;
8381
8740
  const Y = (21.26 * rl + 71.52 * gl + 7.22 * bl) / 100;
8382
8741
  const Z = (1.93 * rl + 11.92 * gl + 95.05 * bl) / 108.883;
8383
- const f = (t) => t > 8856e-6 ? Math.cbrt(t) : 7.787 * t + 16 / 116;
8384
- const fx = f(X);
8385
- const fy = f(Y);
8386
- const fz = f(Z);
8387
- return [
8388
- Math.fround(116 * fy - 16),
8389
- Math.fround(500 * (fx - fy)),
8390
- Math.fround(200 * (fy - fz))
8391
- ];
8392
- }
8393
- function vipsLabToSrgbForSharpen(L, a, b) {
8742
+ const fx = X > 8856e-6 ? Math.cbrt(X) : 7.787 * X + 16 / 116;
8743
+ const fy = Y > 8856e-6 ? Math.cbrt(Y) : 7.787 * Y + 16 / 116;
8744
+ const fz = Z > 8856e-6 ? Math.cbrt(Z) : 7.787 * Z + 16 / 116;
8745
+ out[0] = Math.fround(116 * fy - 16);
8746
+ out[1] = Math.fround(500 * (fx - fy));
8747
+ out[2] = Math.fround(200 * (fy - fz));
8748
+ }
8749
+ function vipsLabToSrgbForSharpenInto(L, a, b, out) {
8394
8750
  const fy = (L + 16) / 116;
8395
8751
  const fx = fy + a / 500;
8396
8752
  const fz = fy - b / 200;
8397
- const inv = (t) => t > 0.20689655172413793 ? t * t * t : (t - 16 / 116) / 7.787;
8398
- const X = inv(fx) * 0.95047;
8399
- const Y = inv(fy) * 1;
8400
- const Z = inv(fz) * 1.08883;
8753
+ const X = (fx > 0.20689655172413793 ? fx * fx * fx : (fx - 16 / 116) / 7.787) * 0.95047;
8754
+ const Y = (fy > 0.20689655172413793 ? fy * fy * fy : (fy - 16 / 116) / 7.787) * 1;
8755
+ const Z = (fz > 0.20689655172413793 ? fz * fz * fz : (fz - 16 / 116) / 7.787) * 1.08883;
8401
8756
  const rl = 3.2406 * X - 1.5372 * Y - 0.4986 * Z;
8402
8757
  const gl = -0.9689 * X + 1.8758 * Y + 0.0415 * Z;
8403
8758
  const bl = 0.0557 * X - 0.204 * Y + 1.057 * Z;
8404
- return [linearToSrgbByte(rl), linearToSrgbByte(gl), linearToSrgbByte(bl)];
8759
+ out[0] = linearToSrgbByte(rl);
8760
+ out[1] = linearToSrgbByte(gl);
8761
+ out[2] = linearToSrgbByte(bl);
8405
8762
  }
8406
8763
  function* sharpenImageSteps(img, sigma = 1, m1 = 1, m2 = 2, x1 = 2, y2 = 10, y3 = 20) {
8407
8764
  let work = 0;
@@ -8446,37 +8803,35 @@ function* sharpenImageSteps(img, sigma = 1, m1 = 1, m2 = 2, x1 = 2, y2 = 10, y3
8446
8803
  for (let i = 0; i < width * height; i++) {
8447
8804
  if (++work % 16384 === 0) yield;
8448
8805
  const idx = i * 4;
8449
- const [lVal, aVal, bVal] = vipsSrgbToLabForSharpen(cur[idx], cur[idx + 1], cur[idx + 2]);
8450
- Ls[i] = Math.trunc(lVal * 327.67);
8451
- As[i] = Math.trunc(aVal * 256);
8452
- Bs[i] = Math.trunc(bVal * 256);
8806
+ vipsSrgbToLabForSharpenInto(cur[idx], cur[idx + 1], cur[idx + 2], SHARPEN_LAB_OUT);
8807
+ Ls[i] = Math.trunc(SHARPEN_LAB_OUT[0] * 327.67);
8808
+ As[i] = Math.trunc(SHARPEN_LAB_OUT[1] * 256);
8809
+ Bs[i] = Math.trunc(SHARPEN_LAB_OUT[2] * 256);
8453
8810
  }
8454
8811
  const { radius, weights, scale } = buildVipsGaussmat(sigma, 0.1);
8455
8812
  const roundAdd = Math.trunc(scale) >> 1;
8456
8813
  const tmpL = new Int16Array(width * height);
8457
8814
  const blurL = new Int16Array(width * height);
8458
8815
  for (let y = 0; y < height; y++) {
8459
- if (++work % 16384 === 0) yield;
8816
+ const rowOff = y * width;
8460
8817
  for (let x = 0; x < width; x++) {
8461
8818
  if (++work % 16384 === 0) yield;
8462
8819
  let sum = 0;
8463
8820
  for (let k = -radius; k <= radius; k++) {
8464
- if (++work % 16384 === 0) yield;
8465
- sum += Ls[y * width + Math.max(0, Math.min(width - 1, x + k))] * weights[k + radius];
8821
+ sum += Ls[rowOff + Math.max(0, Math.min(width - 1, x + k))] * weights[k + radius];
8466
8822
  }
8467
- tmpL[y * width + x] = Math.floor((sum + roundAdd) / scale);
8823
+ tmpL[rowOff + x] = Math.floor((sum + roundAdd) / scale);
8468
8824
  }
8469
8825
  }
8470
8826
  for (let y = 0; y < height; y++) {
8471
- if (++work % 16384 === 0) yield;
8827
+ const rowOff = y * width;
8472
8828
  for (let x = 0; x < width; x++) {
8473
8829
  if (++work % 16384 === 0) yield;
8474
8830
  let sum = 0;
8475
8831
  for (let k = -radius; k <= radius; k++) {
8476
- if (++work % 16384 === 0) yield;
8477
8832
  sum += tmpL[Math.max(0, Math.min(height - 1, y + k)) * width + x] * weights[k + radius];
8478
8833
  }
8479
- blurL[y * width + x] = Math.floor((sum + roundAdd) / scale);
8834
+ blurL[rowOff + x] = Math.floor((sum + roundAdd) / scale);
8480
8835
  }
8481
8836
  }
8482
8837
  const out = new Uint8Array(img.data.length);
@@ -8493,7 +8848,10 @@ function* sharpenImageSteps(img, sigma = 1, m1 = 1, m2 = 2, x1 = 2, y2 = 10, y3
8493
8848
  if (v > y2) v = y2;
8494
8849
  const boostS = rintEven2(v * 327.67);
8495
8850
  const newLS = Math.max(0, Math.min(32767, Ls[i] + boostS));
8496
- const [nr, ng, nb] = vipsLabToSrgbForSharpen(newLS / 327.67, As[i] / 256, Bs[i] / 256);
8851
+ vipsLabToSrgbForSharpenInto(newLS / 327.67, As[i] / 256, Bs[i] / 256, SHARPEN_RGB_OUT);
8852
+ const nr = SHARPEN_RGB_OUT[0];
8853
+ const ng = SHARPEN_RGB_OUT[1];
8854
+ const nb = SHARPEN_RGB_OUT[2];
8497
8855
  if (hasSemiTransparentAlpha && !alreadyPremultiplied) {
8498
8856
  const a = cur[idx + 3];
8499
8857
  const factor = a === 0 ? 0 : Math.fround(255 / a);
@@ -9479,6 +9837,2386 @@ function erodeImage(img, width = 1) {
9479
9837
  return next.value;
9480
9838
  }
9481
9839
 
9840
+ // packages/image-ast/src/sharp.ts
9841
+ init_buffer();
9842
+
9843
+ // packages/image-ast/src/streams/web.ts
9844
+ init_buffer();
9845
+ var outputBytes = Uint8Array.from.bind(Uint8Array);
9846
+ var isBuffer = (_input) => false;
9847
+ var EventEmitter = class {
9848
+ listeners = /* @__PURE__ */ new Map();
9849
+ on(event, listener) {
9850
+ let listeners = this.listeners.get(event);
9851
+ if (!listeners) this.listeners.set(event, listeners = /* @__PURE__ */ new Set());
9852
+ listeners.add(listener);
9853
+ return this;
9854
+ }
9855
+ once(event, listener) {
9856
+ const once = (...args) => {
9857
+ this.removeListener(event, once);
9858
+ listener(...args);
9859
+ };
9860
+ return this.on(event, once);
9861
+ }
9862
+ removeListener(event, listener) {
9863
+ this.listeners.get(event)?.delete(listener);
9864
+ return this;
9865
+ }
9866
+ emit(event, ...args) {
9867
+ const listeners = [...this.listeners.get(event) ?? []];
9868
+ for (const listener of listeners) listener(...args);
9869
+ return listeners.length > 0;
9870
+ }
9871
+ };
9872
+ var Duplex = class extends EventEmitter {
9873
+ readable;
9874
+ writable;
9875
+ writableFinished = false;
9876
+ controller;
9877
+ closed = false;
9878
+ constructor() {
9879
+ super();
9880
+ this.readable = new ReadableStream({
9881
+ start: (controller) => {
9882
+ this.controller = controller;
9883
+ },
9884
+ pull: () => {
9885
+ this._read();
9886
+ },
9887
+ cancel: (reason) => {
9888
+ this.destroy(reason instanceof Error ? reason : void 0);
9889
+ }
9890
+ }, { highWaterMark: 0 });
9891
+ this.writable = new WritableStream({
9892
+ write: (chunk) => new Promise((resolve, reject) => {
9893
+ this._write(chunk, "utf8", (error) => {
9894
+ if (error) {
9895
+ this.destroy(error);
9896
+ reject(error);
9897
+ } else resolve();
9898
+ });
9899
+ }),
9900
+ close: () => {
9901
+ this.writableFinished = true;
9902
+ this.emit("finish");
9903
+ },
9904
+ abort: (reason) => {
9905
+ this.destroy(reason instanceof Error ? reason : void 0);
9906
+ }
9907
+ });
9908
+ }
9909
+ _write(_chunk, _encoding, callback) {
9910
+ callback(new Error("Writable operation is not implemented"));
9911
+ }
9912
+ _read() {
9913
+ throw new Error("Readable operation is not implemented");
9914
+ }
9915
+ push(chunk) {
9916
+ if (this.closed) return false;
9917
+ if (chunk === null) {
9918
+ this.closed = true;
9919
+ this.controller.close();
9920
+ } else this.controller.enqueue(new Uint8Array(chunk));
9921
+ return (this.controller.desiredSize ?? 0) > 0;
9922
+ }
9923
+ destroy(error) {
9924
+ if (!this.closed) {
9925
+ this.closed = true;
9926
+ this.controller.error(error ?? new Error("Stream cancelled"));
9927
+ this.emit("error", error ?? new Error("Stream cancelled"));
9928
+ }
9929
+ return this;
9930
+ }
9931
+ async *[Symbol.asyncIterator]() {
9932
+ const reader = this.readable.getReader();
9933
+ try {
9934
+ while (true) {
9935
+ const result = await reader.read();
9936
+ if (result.done) return;
9937
+ yield result.value;
9938
+ }
9939
+ } finally {
9940
+ await reader.cancel();
9941
+ reader.releaseLock();
9942
+ }
9943
+ }
9944
+ };
9945
+
9946
+ // packages/image-ast/src/sharp.ts
9947
+ import { extname, normalizePath } from "@poe-platform/safe-fs/contracts";
9948
+ function inferTypedArrayDepth(input) {
9949
+ if (!input || !ArrayBuffer.isView(input)) return void 0;
9950
+ if (input instanceof Int8Array) return "char";
9951
+ if (input instanceof Uint16Array) return "ushort";
9952
+ if (input instanceof Int16Array) return "short";
9953
+ if (input instanceof Uint32Array) return "uint";
9954
+ if (input instanceof Int32Array) return "int";
9955
+ if (input instanceof Float32Array) return "float";
9956
+ if (input instanceof Float64Array) return "double";
9957
+ return "uchar";
9958
+ }
9959
+ function validateInputOptions(opts) {
9960
+ if (!opts || typeof opts !== "object") return;
9961
+ const anyOpts = opts;
9962
+ if (anyOpts.failOnError !== void 0 && typeof anyOpts.failOnError !== "boolean") {
9963
+ throw new Error(`Expected boolean for failOnError but received ${anyOpts.failOnError} of type ${typeof anyOpts.failOnError}`);
9964
+ }
9965
+ if (opts.failOn !== void 0 && !["none", "truncated", "error", "warning"].includes(opts.failOn)) {
9966
+ throw new Error(`Expected one of: none, truncated, error, warning for failOn but received ${opts.failOn} of type ${typeof opts.failOn}`);
9967
+ }
9968
+ for (const boolKey of ["animated", "autoOrient", "sequentialRead", "unlimited", "ignoreIcc"]) {
9969
+ if (anyOpts[boolKey] !== void 0 && typeof anyOpts[boolKey] !== "boolean") {
9970
+ throw new Error(`Expected boolean for ${boolKey} but received ${anyOpts[boolKey]} of type ${typeof anyOpts[boolKey]}`);
9971
+ }
9972
+ }
9973
+ if (opts.density !== void 0 && (typeof opts.density !== "number" || Number.isNaN(opts.density) || opts.density < 1 || opts.density > 1e5)) {
9974
+ throw new Error(`Expected number between 1 and 100000 for density but received ${opts.density} of type ${typeof opts.density}`);
9975
+ }
9976
+ if (opts.limitInputPixels !== void 0 && typeof opts.limitInputPixels !== "boolean" && (!Number.isInteger(opts.limitInputPixels) || opts.limitInputPixels < 0 || opts.limitInputPixels > Number.MAX_SAFE_INTEGER)) {
9977
+ throw new Error(
9978
+ `Expected positive integer for limitInputPixels but received ${opts.limitInputPixels} of type ${typeof opts.limitInputPixels}`
9979
+ );
9980
+ }
9981
+ if (opts.page !== void 0 && (!Number.isInteger(opts.page) || opts.page < 0 || opts.page > 1e5)) {
9982
+ throw new Error(`Expected integer between 0 and 100000 for page but received ${opts.page} of type ${typeof opts.page}`);
9983
+ }
9984
+ if (opts.pages !== void 0 && (!Number.isInteger(opts.pages) || opts.pages < -1 || opts.pages > 1e5)) {
9985
+ throw new Error(`Expected integer between -1 and 100000 for pages but received ${opts.pages} of type ${typeof opts.pages}`);
9986
+ }
9987
+ if (opts.raw !== void 0) {
9988
+ const raw = opts.raw;
9989
+ if (!raw || typeof raw !== "object" || !Number.isInteger(raw.width) || raw.width <= 0 || !Number.isInteger(raw.height) || raw.height <= 0 || !Number.isInteger(raw.channels) || raw.channels < 1 || raw.channels > 4) {
9990
+ throw new Error("Expected width, height and channels for raw pixel input");
9991
+ }
9992
+ if (raw.premultiplied !== void 0 && typeof raw.premultiplied !== "boolean") {
9993
+ throw new Error(`Expected boolean for raw.premultiplied but received ${raw.premultiplied}`);
9994
+ }
9995
+ if (raw.pageHeight !== void 0) {
9996
+ if (!Number.isInteger(raw.pageHeight) || raw.pageHeight <= 0 || raw.pageHeight > raw.height) {
9997
+ throw new Error(`Expected positive integer for raw.pageHeight but received ${raw.pageHeight}`);
9998
+ }
9999
+ if (raw.height % raw.pageHeight !== 0) {
10000
+ throw new Error(`Expected raw.height ${raw.height} to be a multiple of raw.pageHeight ${raw.pageHeight}`);
10001
+ }
10002
+ }
10003
+ }
10004
+ const validAlignments = ["left", "top", "low", "center", "centre", "right", "bottom", "high"];
10005
+ if (opts.join !== void 0) {
10006
+ const join = opts.join;
10007
+ if (join && typeof join === "object") {
10008
+ if (join.across !== void 0 && (!Number.isInteger(join.across) || join.across < 1 || join.across > 1e5)) {
10009
+ throw new Error(`Expected integer between 1 and 100000 for join.across but received ${join.across} of type ${typeof join.across}`);
10010
+ }
10011
+ if (join.shim !== void 0 && (!Number.isInteger(join.shim) || join.shim < 0 || join.shim > 1e5)) {
10012
+ throw new Error(`Expected integer between 0 and 100000 for join.shim but received ${join.shim} of type ${typeof join.shim}`);
10013
+ }
10014
+ if (join.halign !== void 0 && !validAlignments.includes(join.halign)) {
10015
+ throw new Error(`Expected valid alignment for join.halign but received ${join.halign} of type ${typeof join.halign}`);
10016
+ }
10017
+ if (join.valign !== void 0 && !validAlignments.includes(join.valign)) {
10018
+ throw new Error(`Expected valid alignment for join.valign but received ${join.valign} of type ${typeof join.valign}`);
10019
+ }
10020
+ if (join.animated !== void 0 && typeof join.animated !== "boolean") {
10021
+ throw new Error(`Expected boolean for join.animated but received ${join.animated} of type ${typeof join.animated}`);
10022
+ }
10023
+ if (join.background !== void 0) {
10024
+ parseColor(join.background, 255);
10025
+ }
10026
+ }
10027
+ }
10028
+ if (opts.text !== void 0) {
10029
+ const text = opts.text;
10030
+ if (!text || typeof text !== "object" || typeof text.text !== "string" || text.text.trim().length === 0) {
10031
+ throw new Error("Expected a valid string to create an image with text.");
10032
+ }
10033
+ if (text.width !== void 0 && (!Number.isInteger(text.width) || text.width <= 0)) {
10034
+ throw new Error(`Expected positive integer for text.width but received ${text.width} of type ${typeof text.width}`);
10035
+ }
10036
+ if (text.height !== void 0 && (!Number.isInteger(text.height) || text.height <= 0)) {
10037
+ throw new Error(`Expected positive integer for text.height but received ${text.height} of type ${typeof text.height}`);
10038
+ }
10039
+ if (text.dpi !== void 0 && (!Number.isInteger(text.dpi) || text.dpi < 1 || text.dpi > 1e6)) {
10040
+ throw new Error(`Expected integer between 1 and 1000000 for text.dpi but received ${text.dpi} of type ${typeof text.dpi}`);
10041
+ }
10042
+ if (text.align !== void 0 && !validAlignments.includes(text.align)) {
10043
+ throw new Error(`Expected valid alignment for text.align but received ${text.align} of type ${typeof text.align}`);
10044
+ }
10045
+ if (text.justify !== void 0 && typeof text.justify !== "boolean") {
10046
+ throw new Error(`Expected boolean for text.justify but received ${text.justify} of type ${typeof text.justify}`);
10047
+ }
10048
+ if (text.rgba !== void 0 && typeof text.rgba !== "boolean") {
10049
+ throw new Error(`Expected bool for text.rgba but received ${text.rgba} of type ${typeof text.rgba}`);
10050
+ }
10051
+ if (text.wrap !== void 0 && !["word", "char", "word-char", "none"].includes(text.wrap)) {
10052
+ throw new Error(`Expected one of: word, char, word-char, none for text.wrap but received ${text.wrap} of type ${typeof text.wrap}`);
10053
+ }
10054
+ }
10055
+ if (opts.create !== void 0) {
10056
+ const create = opts.create;
10057
+ if (!create || typeof create !== "object" || !Number.isInteger(create.width) || create.width <= 0 || !Number.isInteger(create.height) || create.height <= 0 || !Number.isInteger(create.channels)) {
10058
+ throw new Error("Expected valid width, height and channels to create a new input image");
10059
+ }
10060
+ if (create.pageHeight !== void 0) {
10061
+ if (!Number.isInteger(create.pageHeight) || create.pageHeight <= 0 || create.pageHeight > create.height) {
10062
+ throw new Error(`Expected positive integer for create.pageHeight but received ${create.pageHeight}`);
10063
+ }
10064
+ if (create.height % create.pageHeight !== 0) {
10065
+ throw new Error(`Expected create.height ${create.height} to be a multiple of create.pageHeight ${create.pageHeight}`);
10066
+ }
10067
+ }
10068
+ if (create.noise !== void 0) {
10069
+ if (!create.noise || typeof create.noise !== "object") {
10070
+ throw new Error("Expected noise to be an object");
10071
+ }
10072
+ if (create.noise.type !== "gaussian") {
10073
+ throw new Error("Only gaussian noise is supported at the moment");
10074
+ }
10075
+ if (create.channels < 1 || create.channels > 4) {
10076
+ throw new Error(
10077
+ `Expected number between 1 and 4 for create.channels but received ${create.channels} of type ${typeof create.channels}`
10078
+ );
10079
+ }
10080
+ } else if (create.background !== void 0) {
10081
+ if (create.channels < 3 || create.channels > 4) {
10082
+ throw new Error(
10083
+ `Expected number between 3 and 4 for create.channels but received ${create.channels} of type ${typeof create.channels}`
10084
+ );
10085
+ }
10086
+ } else {
10087
+ throw new Error("Expected valid noise or background to create a new input image");
10088
+ }
10089
+ }
10090
+ }
10091
+ function toBytes(input, readFile) {
10092
+ if (!input) return void 0;
10093
+ if (isBuffer(input)) {
10094
+ const bytes = input;
10095
+ if (bytes.length === 0) {
10096
+ throw new Error("Input Buffer is empty");
10097
+ }
10098
+ return bytes;
10099
+ }
10100
+ if (ArrayBuffer.isView(input)) {
10101
+ if (input.byteLength === 0) {
10102
+ throw new Error("Input Bit Array is empty");
10103
+ }
10104
+ return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
10105
+ }
10106
+ if (input instanceof ArrayBuffer) {
10107
+ if (input.byteLength === 0) {
10108
+ throw new Error("Input bit Array is empty");
10109
+ }
10110
+ return new Uint8Array(input);
10111
+ }
10112
+ if (typeof input === "string") {
10113
+ if (input.trimStart().startsWith("<")) {
10114
+ return new TextEncoder().encode(input);
10115
+ }
10116
+ if (!readFile) throw new Error("File inputs require an explicit filesystem and an asynchronous output method");
10117
+ return readFile(input);
10118
+ }
10119
+ return void 0;
10120
+ }
10121
+ function inferFormatFromPath(fileOut) {
10122
+ const ext = extname(fileOut).toLowerCase().slice(1);
10123
+ switch (ext) {
10124
+ case "png":
10125
+ return "png";
10126
+ case "jpg":
10127
+ case "jpeg":
10128
+ case "jpe":
10129
+ return "jpeg";
10130
+ case "webp":
10131
+ return "webp";
10132
+ case "gif":
10133
+ return "gif";
10134
+ case "tif":
10135
+ case "tiff":
10136
+ return "tiff";
10137
+ case "avif":
10138
+ return "avif";
10139
+ case "heic":
10140
+ return "heic";
10141
+ case "heif":
10142
+ return "heif";
10143
+ case "pdf":
10144
+ return "pdf";
10145
+ case "ppm":
10146
+ return "ppm";
10147
+ case "pgm":
10148
+ return "pgm";
10149
+ case "pbm":
10150
+ return "pbm";
10151
+ case "bmp":
10152
+ return "bmp";
10153
+ case "raw":
10154
+ return "raw";
10155
+ default:
10156
+ return void 0;
10157
+ }
10158
+ }
10159
+ var SharpInstance = class _SharpInstance extends Duplex {
10160
+ inputBytes;
10161
+ inputFilePath;
10162
+ joinInputs;
10163
+ inputOptions;
10164
+ nodes = [];
10165
+ outputOptions = {};
10166
+ streamIn = false;
10167
+ streamInFinished = false;
10168
+ streamFailure;
10169
+ streamChunks = [];
10170
+ fileInputs = /* @__PURE__ */ new Map();
10171
+ fileLoads = /* @__PURE__ */ new Map();
10172
+ clonedStreams = [];
10173
+ streamOutStarted = false;
10174
+ constructor(input, options) {
10175
+ super();
10176
+ if (Array.isArray(input)) {
10177
+ if (input.length < 2) {
10178
+ throw new Error("Expected at least two images to join");
10179
+ }
10180
+ if (input.some((item) => Array.isArray(item))) {
10181
+ throw new Error("Recursive join is unsupported");
10182
+ }
10183
+ this.inputBytes = void 0;
10184
+ this.joinInputs = input;
10185
+ this.inputOptions = options;
10186
+ } else if (input && typeof input === "object" && !ArrayBuffer.isView(input) && !(input instanceof ArrayBuffer)) {
10187
+ this.inputBytes = void 0;
10188
+ this.joinInputs = void 0;
10189
+ this.inputOptions = input;
10190
+ if (this.inputOptions.join !== void 0) {
10191
+ throw new Error("Expected input to be an array of images to join");
10192
+ }
10193
+ validateInputOptions(this.inputOptions);
10194
+ if (!this.inputOptions.create && !this.inputOptions.text && Object.keys(this.inputOptions).length > 0) {
10195
+ this.streamIn = true;
10196
+ }
10197
+ } else {
10198
+ if (options?.join !== void 0) {
10199
+ throw new Error("Expected input to be an array of images to join");
10200
+ }
10201
+ this.inputFilePath = typeof input === "string" && !input.trimStart().startsWith("<") ? input : void 0;
10202
+ const inferredDepth = inferTypedArrayDepth(input);
10203
+ let effectiveOptions = options;
10204
+ if (effectiveOptions?.raw && inferredDepth && !effectiveOptions.raw.depth) {
10205
+ effectiveOptions = {
10206
+ ...effectiveOptions,
10207
+ raw: {
10208
+ ...effectiveOptions.raw,
10209
+ depth: inferredDepth
10210
+ }
10211
+ };
10212
+ }
10213
+ validateInputOptions(effectiveOptions);
10214
+ this.inputBytes = this.inputFilePath ? void 0 : toBytes(input);
10215
+ this.joinInputs = void 0;
10216
+ this.inputOptions = effectiveOptions;
10217
+ if (input === void 0 && (!effectiveOptions || !effectiveOptions.create && !effectiveOptions.text)) {
10218
+ this.streamIn = true;
10219
+ }
10220
+ }
10221
+ validateInputOptions(this.inputOptions);
10222
+ this.on("error", (error) => {
10223
+ this.streamFailure = error;
10224
+ for (const child of this.clonedStreams) {
10225
+ child.streamFailure = error;
10226
+ child.destroy(error);
10227
+ }
10228
+ });
10229
+ if (this.streamIn) {
10230
+ this.on("finish", () => {
10231
+ this.flattenStreamInput();
10232
+ });
10233
+ }
10234
+ if (this.inputOptions?.autoOrient) {
10235
+ this.nodes.push({ kind: "autoOrient" });
10236
+ }
10237
+ }
10238
+ flattenStreamInput() {
10239
+ if (this.streamIn && !this.streamInFinished) {
10240
+ const merged = new Uint8Array(this.streamChunks.reduce((total, bytes) => total + bytes.length, 0));
10241
+ let offset = 0;
10242
+ for (const bytes of this.streamChunks) {
10243
+ merged.set(bytes, offset);
10244
+ offset += bytes.length;
10245
+ }
10246
+ this.receiveStreamInput(merged);
10247
+ }
10248
+ }
10249
+ receiveStreamInput(merged) {
10250
+ this.inputBytes = merged;
10251
+ this.streamInFinished = true;
10252
+ for (const child of this.clonedStreams) {
10253
+ child.receiveStreamInput(merged);
10254
+ }
10255
+ this.emit("streamReady");
10256
+ }
10257
+ async waitForStreamInput() {
10258
+ if (this.streamFailure) throw this.streamFailure;
10259
+ await this.loadFileInputs();
10260
+ if (this.streamFailure) throw this.streamFailure;
10261
+ if (!this.streamIn || this.streamInFinished) {
10262
+ return;
10263
+ }
10264
+ if (this.writableFinished) {
10265
+ this.flattenStreamInput();
10266
+ if (this.streamInFinished) return;
10267
+ }
10268
+ await new Promise((resolve, reject) => {
10269
+ const onReady = () => {
10270
+ this.removeListener("finish", onReady);
10271
+ this.removeListener("streamReady", onReady);
10272
+ this.removeListener("error", onError);
10273
+ this.flattenStreamInput();
10274
+ resolve();
10275
+ };
10276
+ const onError = (err) => {
10277
+ this.removeListener("finish", onReady);
10278
+ this.removeListener("streamReady", onReady);
10279
+ reject(err);
10280
+ };
10281
+ this.once("finish", onReady);
10282
+ this.once("streamReady", onReady);
10283
+ this.once("error", onError);
10284
+ });
10285
+ }
10286
+ operationInput(input) {
10287
+ if (typeof input !== "string" || input.trimStart().startsWith("<")) return toBytes(input);
10288
+ return input;
10289
+ }
10290
+ loadedFile(path) {
10291
+ const bytes = this.fileInputs.get(path);
10292
+ if (!bytes) throw new Error("File inputs require an explicit filesystem and an asynchronous output method");
10293
+ return bytes;
10294
+ }
10295
+ async loadFileInputs() {
10296
+ const paths = /* @__PURE__ */ new Set();
10297
+ if (this.inputFilePath) paths.add(this.inputFilePath);
10298
+ for (const input of this.joinInputs ?? []) {
10299
+ if (typeof input === "string" && !input.trimStart().startsWith("<")) paths.add(input);
10300
+ }
10301
+ for (const node of this.nodes) {
10302
+ if (node.kind === "boolean" && typeof node.operand === "string") paths.add(node.operand);
10303
+ if (node.kind === "joinChannel") {
10304
+ for (const input of node.inputs) if (typeof input.data === "string") paths.add(input.data);
10305
+ }
10306
+ if (node.kind !== "composite") continue;
10307
+ for (const layer of node.layers) {
10308
+ if (typeof layer.input === "string" && !layer.input.trimStart().startsWith("<")) paths.add(layer.input);
10309
+ }
10310
+ }
10311
+ await Promise.all([...paths].map((path) => {
10312
+ if (this.fileInputs.has(path)) return;
10313
+ let pending = this.fileLoads.get(path);
10314
+ if (!pending) {
10315
+ if (!this.inputOptions?.filesystem) throw new Error("File inputs require an explicit filesystem");
10316
+ pending = this.inputOptions.filesystem.readFile(path).then((bytes) => {
10317
+ this.fileInputs.set(path, new Uint8Array(bytes));
10318
+ });
10319
+ this.fileLoads.set(path, pending);
10320
+ }
10321
+ return pending;
10322
+ }));
10323
+ if (this.inputFilePath) this.inputBytes = this.loadedFile(this.inputFilePath);
10324
+ }
10325
+ _write(chunk, _encoding, callback) {
10326
+ if (this.streamIn && !this.streamInFinished) {
10327
+ if (chunk instanceof Uint8Array) {
10328
+ this.streamChunks.push(new Uint8Array(chunk));
10329
+ callback();
10330
+ } else {
10331
+ callback(new Error("Non-Buffer data on Writable Stream"));
10332
+ }
10333
+ } else {
10334
+ callback(new Error("Unexpected data on Writable Stream"));
10335
+ }
10336
+ }
10337
+ _read() {
10338
+ if (!this.streamOutStarted) {
10339
+ this.streamOutStarted = true;
10340
+ this.waitForStreamInput().then(() => {
10341
+ const res = this.toBufferWithObjectSync();
10342
+ this.emit("info", res.info);
10343
+ this.push(res.data);
10344
+ this.push(null);
10345
+ }).catch((err) => {
10346
+ this.destroy(err);
10347
+ });
10348
+ }
10349
+ }
10350
+ clone() {
10351
+ if (this.streamIn && !this.streamInFinished) {
10352
+ const copy2 = new _SharpInstance(void 0, this.inputOptions);
10353
+ copy2.nodes.length = 0;
10354
+ copy2.nodes.push(...this.nodes);
10355
+ copy2.outputOptions = { ...this.outputOptions };
10356
+ this.clonedStreams.push(copy2);
10357
+ if (this.streamFailure) {
10358
+ copy2.streamFailure = this.streamFailure;
10359
+ copy2.destroy(this.streamFailure);
10360
+ }
10361
+ return copy2;
10362
+ }
10363
+ const copy = this.joinInputs !== void 0 ? new _SharpInstance(this.joinInputs, this.inputOptions) : this.inputFilePath !== void 0 ? new _SharpInstance(this.inputFilePath, this.inputOptions) : this.inputBytes !== void 0 ? new _SharpInstance(this.inputBytes, this.inputOptions) : new _SharpInstance(this.inputOptions);
10364
+ copy.inputFilePath = this.inputFilePath;
10365
+ for (const [path, bytes] of this.fileInputs) copy.fileInputs.set(path, bytes);
10366
+ copy.nodes.length = 0;
10367
+ copy.nodes.push(...this.nodes);
10368
+ copy.outputOptions = { ...this.outputOptions };
10369
+ return copy;
10370
+ }
10371
+ decodeInitialImage() {
10372
+ if (!this.joinInputs) {
10373
+ return decodeImage(this.inputFilePath ? this.loadedFile(this.inputFilePath) : this.inputBytes, this.inputOptions);
10374
+ }
10375
+ const imgs = this.joinInputs.map((item) => {
10376
+ if (item && typeof item === "object" && !(item instanceof Uint8Array) && !(item instanceof ArrayBuffer)) {
10377
+ return decodeImage(void 0, item);
10378
+ }
10379
+ return decodeImage(toBytes(item, (path) => this.loadedFile(path)), this.inputOptions);
10380
+ });
10381
+ const n = imgs.length;
10382
+ const cellW = Math.max(...imgs.map((i) => i.width));
10383
+ const cellH = Math.max(...imgs.map((i) => i.height));
10384
+ const joinOpts = this.inputOptions?.join;
10385
+ const animated = Boolean(joinOpts?.animated);
10386
+ const across = Math.max(1, joinOpts?.across ?? 1);
10387
+ const cols = Math.min(n, across);
10388
+ const rows = Math.ceil(n / cols);
10389
+ const shim = Math.max(0, joinOpts?.shim ?? 0);
10390
+ const outW = cols * cellW + (cols - 1) * shim;
10391
+ const outH = rows * cellH + (rows - 1) * shim;
10392
+ const anyAlpha = imgs.some((i) => i.hasAlpha);
10393
+ const bg = parseColor(joinOpts?.background ?? { r: 0, g: 0, b: 0, alpha: 1 }, 255);
10394
+ const hasAlpha = anyAlpha || bg.a < 255;
10395
+ const channels = hasAlpha ? 4 : 3;
10396
+ const out = new Uint8Array(outW * outH * 4);
10397
+ const bgA = hasAlpha ? bg.a : 255;
10398
+ const bgWord = (bgA << 24 | bg.b << 16 | bg.g << 8 | bg.r) >>> 0;
10399
+ new Uint32Array(out.buffer, out.byteOffset, outW * outH).fill(bgWord);
10400
+ const halign = joinOpts?.halign ?? "left";
10401
+ const valign = joinOpts?.valign ?? "top";
10402
+ for (let k = 0; k < n; k++) {
10403
+ const im = imgs[k];
10404
+ const col = k % cols;
10405
+ const row = Math.floor(k / cols);
10406
+ const cellX = col * (cellW + shim);
10407
+ const cellY = row * (cellH + shim);
10408
+ const dx = halign === "centre" || halign === "center" ? Math.floor((cellW - im.width) / 2) : halign === "right" || halign === "high" ? cellW - im.width : 0;
10409
+ const dy = valign === "centre" || valign === "center" ? Math.floor((cellH - im.height) / 2) : valign === "bottom" || valign === "high" ? cellH - im.height : 0;
10410
+ for (let y = 0; y < im.height; y++) {
10411
+ const dstY = cellY + dy + y;
10412
+ const sRow = y * im.width * 4;
10413
+ const dRow = (dstY * outW + cellX + dx) * 4;
10414
+ out.set(im.data.subarray(sRow, sRow + im.width * 4), dRow);
10415
+ }
10416
+ }
10417
+ const animPageHeight = animated && n > 0 ? Math.floor(outH / n) : 0;
10418
+ const validAnim = animated && animPageHeight > 0 && outH % animPageHeight === 0 && outH / animPageHeight === n;
10419
+ return {
10420
+ width: outW,
10421
+ height: outH,
10422
+ data: out,
10423
+ format: "raw",
10424
+ space: "srgb",
10425
+ channels,
10426
+ depth: "uchar",
10427
+ density: this.inputOptions?.density ?? 72,
10428
+ hasAlpha,
10429
+ ...validAnim ? { pages: n, pageHeight: animPageHeight } : {}
10430
+ };
10431
+ }
10432
+ getAst() {
10433
+ return this.nodes;
10434
+ }
10435
+ upsertNode(nextNode, beforeGrayscale = false) {
10436
+ const idx = this.nodes.findIndex((n) => n.kind === nextNode.kind);
10437
+ if (idx !== -1) {
10438
+ this.nodes[idx] = nextNode;
10439
+ return;
10440
+ }
10441
+ if (nextNode.kind === "removeAlpha" || nextNode.kind === "flatten") {
10442
+ const ensureIdx = this.nodes.findIndex((n) => n.kind === "ensureAlpha");
10443
+ if (ensureIdx !== -1) {
10444
+ this.nodes.splice(ensureIdx, 0, nextNode);
10445
+ return;
10446
+ }
10447
+ }
10448
+ if (beforeGrayscale) {
10449
+ const grayIdx = this.nodes.findIndex((n) => n.kind === "grayscale");
10450
+ if (grayIdx !== -1) {
10451
+ this.nodes.splice(grayIdx, 0, nextNode);
10452
+ return;
10453
+ }
10454
+ }
10455
+ this.nodes.push(nextNode);
10456
+ }
10457
+ evaluateImage() {
10458
+ let img = this.decodeInitialImage();
10459
+ const resizeIdx = this.nodes.findIndex((n) => n.kind === "resize");
10460
+ const postScaleIndices = /* @__PURE__ */ new Set();
10461
+ if (resizeIdx !== -1) {
10462
+ for (let i = resizeIdx + 1; i < this.nodes.length; i++) {
10463
+ const n = this.nodes[i];
10464
+ if (n.kind === "flip" || n.kind === "flop" || n.kind === "rotate" && n.angle % 90 === 0) {
10465
+ postScaleIndices.add(i);
10466
+ }
10467
+ }
10468
+ }
10469
+ const postScaleNodes = this.nodes.filter((_, idx) => postScaleIndices.has(idx));
10470
+ const postScaleTransform = postScaleNodes.length > 0 ? (scaled) => {
10471
+ let cur = scaled;
10472
+ for (const pNode of postScaleNodes) {
10473
+ if (pNode.kind === "rotate") {
10474
+ cur = rotateImage(cur, pNode.angle, pNode.background);
10475
+ } else if (pNode.kind === "flip") {
10476
+ cur = flipImage(cur);
10477
+ } else if (pNode.kind === "flop") {
10478
+ cur = flopImage(cur);
10479
+ }
10480
+ }
10481
+ return cur;
10482
+ } : void 0;
10483
+ const gammaNode = this.nodes.find((n) => n.kind === "gamma");
10484
+ const splitGamma = gammaNode !== void 0 && this.nodes.some(
10485
+ (n) => n.kind === "resize" || n.kind === "blur" || n.kind === "convolve" || n.kind === "recomb" || n.kind === "modulate" || n.kind === "sharpen" || n.kind === "composite"
10486
+ );
10487
+ const postStageRank = {
10488
+ extend: 10,
10489
+ median: 20,
10490
+ threshold: 30,
10491
+ dilate: 40,
10492
+ erode: 50,
10493
+ blur: 60,
10494
+ unflatten: 70,
10495
+ convolve: 80,
10496
+ recomb: 90,
10497
+ modulate: 100,
10498
+ sharpen: 110,
10499
+ composite: 120,
10500
+ gamma: 130,
10501
+ linear: 140,
10502
+ normalize: 150,
10503
+ clahe: 160,
10504
+ negate: 170,
10505
+ tint: 180,
10506
+ grayscale: 190,
10507
+ toColorspace: 200,
10508
+ bandbool: 210,
10509
+ boolean: 220,
10510
+ joinChannel: 230,
10511
+ extractChannel: 240,
10512
+ withMetadata: 250
10513
+ };
10514
+ const activeNodes = this.nodes.filter((_, idx) => !postScaleIndices.has(idx));
10515
+ const preNodes = activeNodes.filter((n) => !(n.kind in postStageRank));
10516
+ const postNodes = activeNodes.filter((n) => n.kind in postStageRank).sort((a, b) => (postStageRank[a.kind] ?? 999) - (postStageRank[b.kind] ?? 999));
10517
+ const orderedNodes = [...preNodes, ...postNodes];
10518
+ const isPremulStageKind = (kind) => kind === "resize" || kind === "blur" || kind === "convolve" || kind === "sharpen";
10519
+ const premulStageCount = orderedNodes.filter((n) => isPremulStageKind(n.kind)).length;
10520
+ const firstPremulIdx = orderedNodes.findIndex((n) => isPremulStageKind(n.kind));
10521
+ let lastPremulIdx = -1;
10522
+ for (let i = orderedNodes.length - 1; i >= 0; i--) {
10523
+ if (isPremulStageKind(orderedNodes[i].kind)) {
10524
+ lastPremulIdx = i;
10525
+ break;
10526
+ }
10527
+ }
10528
+ let gammaInApplied = false;
10529
+ let gammaOutApplied = false;
10530
+ for (let i = 0; i < orderedNodes.length; i++) {
10531
+ const node = orderedNodes[i];
10532
+ if (splitGamma && gammaNode && !gammaInApplied && (i === firstPremulIdx || node.kind === "recomb" || node.kind === "modulate" || node.kind === "composite")) {
10533
+ img = gammaImage(img, gammaNode.gamma, 1);
10534
+ gammaInApplied = true;
10535
+ }
10536
+ if (i === firstPremulIdx && img.hasAlpha) {
10537
+ if (premulStageCount > 1) {
10538
+ img = premultiplyRgbaImage(img);
10539
+ } else {
10540
+ img = { ...img, wasPremultiplied: true };
10541
+ }
10542
+ }
10543
+ switch (node.kind) {
10544
+ case "autoOrient":
10545
+ img = applyExifOrientation(img);
10546
+ break;
10547
+ case "rotate":
10548
+ img = rotateImage(img, node.angle, node.background);
10549
+ break;
10550
+ case "flip":
10551
+ img = flipImage(img);
10552
+ break;
10553
+ case "flop":
10554
+ img = flopImage(img);
10555
+ break;
10556
+ case "extract":
10557
+ img = extractImage(img, node);
10558
+ break;
10559
+ case "trim":
10560
+ img = trimImage(img, {
10561
+ threshold: node.threshold,
10562
+ ...node.background !== void 0 ? { background: node.background } : {},
10563
+ ...node.lineArt !== void 0 ? { lineArt: node.lineArt } : {}
10564
+ });
10565
+ break;
10566
+ case "resize":
10567
+ img = resizeImage(img, node, postScaleTransform);
10568
+ if (img.hasAlpha && !img.isPremultiplied) {
10569
+ if (i < lastPremulIdx) {
10570
+ img = premultiplyRgbaImage(img);
10571
+ } else {
10572
+ img = { ...img, wasPremultiplied: true };
10573
+ }
10574
+ }
10575
+ break;
10576
+ case "extend":
10577
+ img = extendImage(img, node);
10578
+ break;
10579
+ case "composite":
10580
+ img = compositeImage(img, node.layers, (path) => this.loadedFile(path));
10581
+ break;
10582
+ case "grayscale":
10583
+ img = grayscaleImage(img);
10584
+ break;
10585
+ case "flatten":
10586
+ img = flattenImage(img, node.background);
10587
+ break;
10588
+ case "unflatten":
10589
+ img = unflattenImage(img);
10590
+ break;
10591
+ case "negate":
10592
+ img = negateImage(img, { alpha: node.alpha });
10593
+ break;
10594
+ case "modulate":
10595
+ img = modulateImage(img, node);
10596
+ break;
10597
+ case "tint":
10598
+ img = tintImage(img, node.color);
10599
+ break;
10600
+ case "gamma":
10601
+ if (splitGamma) {
10602
+ img = gammaImage(img, 1, node.gammaOut);
10603
+ gammaOutApplied = true;
10604
+ } else {
10605
+ img = gammaImage(img, node.gamma, node.gammaOut);
10606
+ }
10607
+ break;
10608
+ case "linear":
10609
+ img = linearImage(img, node.a, node.b);
10610
+ break;
10611
+ case "normalize":
10612
+ img = normalizeImage(img, { lower: node.lower, upper: node.upper });
10613
+ break;
10614
+ case "threshold":
10615
+ img = thresholdImage(img, node.value, node.grayscale);
10616
+ break;
10617
+ case "blur":
10618
+ img = blurImage(img, node.sigma, node.minAmplitude, node.precision);
10619
+ break;
10620
+ case "sharpen":
10621
+ img = sharpenImage(img, node.sigma, node.m1, node.m2, node.x1, node.y2, node.y3);
10622
+ break;
10623
+ case "median":
10624
+ img = medianImage(img, node.size);
10625
+ break;
10626
+ case "dilate":
10627
+ img = dilateImage(img, node.width);
10628
+ break;
10629
+ case "erode":
10630
+ img = erodeImage(img, node.width);
10631
+ break;
10632
+ case "convolve":
10633
+ img = convolveImage(img, node);
10634
+ break;
10635
+ case "ensureAlpha":
10636
+ img = ensureAlphaImage(img, node.alpha);
10637
+ break;
10638
+ case "removeAlpha":
10639
+ img = removeAlphaImage(img);
10640
+ break;
10641
+ case "extractChannel":
10642
+ img = extractChannelImage(img, node.channel);
10643
+ break;
10644
+ case "recomb":
10645
+ img = recombImage(img, node.matrix);
10646
+ break;
10647
+ case "toColorspace":
10648
+ img = toColorspaceImage(img, node.space);
10649
+ break;
10650
+ case "bandbool":
10651
+ img = bandboolImage(img, node.op);
10652
+ break;
10653
+ case "boolean": {
10654
+ const opImg = decodeImage(typeof node.operand === "string" ? this.loadedFile(node.operand) : node.operand, node.options);
10655
+ img = booleanImage(img, opImg, node.op);
10656
+ break;
10657
+ }
10658
+ case "joinChannel": {
10659
+ const extras = node.inputs.map((item) => decodeImage(typeof item.data === "string" ? this.loadedFile(item.data) : item.data, item.options));
10660
+ img = joinChannelImage(img, extras);
10661
+ break;
10662
+ }
10663
+ case "clahe": {
10664
+ const explicitBw = this.nodes.some(
10665
+ (n) => n.kind === "grayscale" || n.kind === "toColorspace" && (n.space === "b-w" || n.space === "grey16")
10666
+ );
10667
+ if (!explicitBw && (img.channels === 1 || img.channels === 2)) {
10668
+ img = {
10669
+ ...img,
10670
+ channels: img.channels === 2 ? 4 : 3,
10671
+ space: "srgb",
10672
+ hasAlpha: img.channels === 2
10673
+ };
10674
+ }
10675
+ img = claheImage(img, node);
10676
+ break;
10677
+ }
10678
+ case "affine":
10679
+ img = affineImage(img, node);
10680
+ break;
10681
+ case "withMetadata":
10682
+ img = {
10683
+ ...img,
10684
+ ...node.density !== void 0 ? { density: node.density } : {},
10685
+ ...node.orientation !== void 0 ? { orientation: node.orientation } : {}
10686
+ };
10687
+ break;
10688
+ }
10689
+ if (i === lastPremulIdx && img.isPremultiplied) {
10690
+ img = unpremultiplyRgbaImage(img);
10691
+ }
10692
+ }
10693
+ if (splitGamma && gammaNode && gammaInApplied && !gammaOutApplied) {
10694
+ img = gammaImage(img, 1, gammaNode.gammaOut);
10695
+ }
10696
+ return img;
10697
+ }
10698
+ metadataSync() {
10699
+ const computeAutoOrient = (w, h, orient) => orient !== void 0 && orient >= 5 && orient <= 8 ? { width: h, height: w } : { width: w, height: h };
10700
+ const rawMeta = this.joinInputs ? (() => {
10701
+ const joined = this.decodeInitialImage();
10702
+ return {
10703
+ format: joined.format,
10704
+ width: joined.width,
10705
+ height: joined.height,
10706
+ space: joined.space,
10707
+ channels: joined.channels,
10708
+ depth: joined.depth,
10709
+ density: joined.density,
10710
+ hasAlpha: joined.hasAlpha,
10711
+ ...joined.pages !== void 0 ? { pages: joined.pages } : {},
10712
+ ...joined.pageHeight !== void 0 ? { pageHeight: joined.pageHeight } : {},
10713
+ size: joined.data.byteLength
10714
+ };
10715
+ })() : readImageMetadata(this.inputFilePath ? this.loadedFile(this.inputFilePath) : this.inputBytes, this.inputOptions);
10716
+ if (this.nodes.length === 0) {
10717
+ return {
10718
+ ...rawMeta,
10719
+ autoOrient: computeAutoOrient(rawMeta.width, rawMeta.height, rawMeta.orientation)
10720
+ };
10721
+ }
10722
+ const evaluated = this.evaluateImage();
10723
+ return {
10724
+ format: this.outputOptions.format ?? evaluated.format,
10725
+ width: evaluated.width,
10726
+ height: evaluated.height,
10727
+ space: evaluated.space,
10728
+ channels: evaluated.channels,
10729
+ depth: evaluated.depth,
10730
+ density: this.outputOptions.density ?? evaluated.density,
10731
+ hasAlpha: evaluated.hasAlpha,
10732
+ autoOrient: computeAutoOrient(evaluated.width, evaluated.height, evaluated.orientation),
10733
+ ...evaluated.orientation !== void 0 ? { orientation: evaluated.orientation } : {},
10734
+ ...rawMeta.pages !== void 0 ? { pages: rawMeta.pages } : {},
10735
+ ...rawMeta.pagePrimary !== void 0 ? { pagePrimary: rawMeta.pagePrimary } : {},
10736
+ ...rawMeta.isProgressive !== void 0 ? { isProgressive: rawMeta.isProgressive } : {},
10737
+ ...rawMeta.size !== void 0 ? { size: rawMeta.size } : {}
10738
+ };
10739
+ }
10740
+ async metadata(callback) {
10741
+ try {
10742
+ await this.waitForStreamInput();
10743
+ const res = this.metadataSync();
10744
+ if (callback) callback(null, res);
10745
+ return res;
10746
+ } catch (err) {
10747
+ if (callback) callback(err);
10748
+ throw err;
10749
+ }
10750
+ }
10751
+ statsSync() {
10752
+ const img = this.evaluateImage();
10753
+ return computeImageStats(img);
10754
+ }
10755
+ async stats(callback) {
10756
+ try {
10757
+ await this.waitForStreamInput();
10758
+ const res = this.statsSync();
10759
+ if (callback) callback(null, res);
10760
+ return res;
10761
+ } catch (err) {
10762
+ if (callback) callback(err);
10763
+ throw err;
10764
+ }
10765
+ }
10766
+ autoOrient() {
10767
+ return this.rotate();
10768
+ }
10769
+ rotate(angle, options) {
10770
+ if (angle === void 0) {
10771
+ if (!this.nodes.some((n) => n.kind === "autoOrient")) {
10772
+ const insertIdx = this.nodes.findIndex(
10773
+ (n) => n.kind === "rotate" || n.kind === "flip" || n.kind === "flop" || n.kind === "resize"
10774
+ );
10775
+ if (insertIdx !== -1) {
10776
+ this.nodes.splice(insertIdx, 0, { kind: "autoOrient" });
10777
+ } else {
10778
+ this.nodes.push({ kind: "autoOrient" });
10779
+ }
10780
+ }
10781
+ } else {
10782
+ if (typeof angle !== "number" || Number.isNaN(angle)) {
10783
+ throw new Error(`Expected numeric for angle but received ${angle} of type ${typeof angle}`);
10784
+ }
10785
+ const isOrthogonal = Number.isInteger(angle) && angle % 90 === 0;
10786
+ const nextNode = {
10787
+ kind: "rotate",
10788
+ angle,
10789
+ background: isOrthogonal ? { r: 0, g: 0, b: 0, a: 255 } : parseColor(options?.background, 255)
10790
+ };
10791
+ const existingIdx = this.nodes.findIndex((n) => n.kind === "rotate");
10792
+ if (existingIdx !== -1) {
10793
+ this.nodes[existingIdx] = nextNode;
10794
+ } else {
10795
+ this.nodes.push(nextNode);
10796
+ }
10797
+ }
10798
+ return this;
10799
+ }
10800
+ flip(flip = true) {
10801
+ const existingIdx = this.nodes.findIndex((n) => n.kind === "flip");
10802
+ if (flip) {
10803
+ if (existingIdx !== -1) return this;
10804
+ const rotIdx = this.nodes.findIndex((n) => n.kind === "rotate");
10805
+ if (rotIdx !== -1) this.nodes.splice(rotIdx, 0, { kind: "flip" });
10806
+ else this.nodes.push({ kind: "flip" });
10807
+ } else if (existingIdx !== -1) {
10808
+ this.nodes.splice(existingIdx, 1);
10809
+ }
10810
+ return this;
10811
+ }
10812
+ flop(flop = true) {
10813
+ const existingIdx = this.nodes.findIndex((n) => n.kind === "flop");
10814
+ if (flop) {
10815
+ if (existingIdx !== -1) return this;
10816
+ const rotIdx = this.nodes.findIndex((n) => n.kind === "rotate");
10817
+ if (rotIdx !== -1) this.nodes.splice(rotIdx, 0, { kind: "flop" });
10818
+ else this.nodes.push({ kind: "flop" });
10819
+ } else if (existingIdx !== -1) {
10820
+ this.nodes.splice(existingIdx, 1);
10821
+ }
10822
+ return this;
10823
+ }
10824
+ extract(region) {
10825
+ if (!region || typeof region !== "object") {
10826
+ throw new Error("Expected object for extract region");
10827
+ }
10828
+ for (const name of ["left", "top", "width", "height"]) {
10829
+ const val = region[name];
10830
+ if (!Number.isInteger(val) || val < 0) {
10831
+ throw new Error(`Expected integer for ${name} but received ${val}`);
10832
+ }
10833
+ }
10834
+ const nextNode = {
10835
+ kind: "extract",
10836
+ left: region.left,
10837
+ top: region.top,
10838
+ width: region.width,
10839
+ height: region.height
10840
+ };
10841
+ const resizeIdx = this.nodes.findIndex((n) => n.kind === "resize");
10842
+ const extractIndices = [];
10843
+ for (let i = 0; i < this.nodes.length; i++) {
10844
+ if (this.nodes[i].kind === "extract") extractIndices.push(i);
10845
+ }
10846
+ if (resizeIdx !== -1) {
10847
+ const postIdx = extractIndices.find((idx) => idx > resizeIdx);
10848
+ if (postIdx !== void 0) {
10849
+ this.nodes[postIdx] = nextNode;
10850
+ return this;
10851
+ }
10852
+ } else if (extractIndices.length >= 2) {
10853
+ this.nodes[extractIndices[1]] = nextNode;
10854
+ return this;
10855
+ }
10856
+ const extIdx = this.nodes.findIndex((n) => n.kind === "extend");
10857
+ if (extIdx !== -1) this.nodes.splice(extIdx, 0, nextNode);
10858
+ else this.nodes.push(nextNode);
10859
+ return this;
10860
+ }
10861
+ trim(options) {
10862
+ if (options !== void 0 && typeof options !== "number" && (typeof options !== "object" || options === null || Array.isArray(options))) {
10863
+ throw new Error(`Expected object or number for trim but received ${options} of type ${typeof options}`);
10864
+ }
10865
+ if (typeof options === "object" && options !== null && options.lineArt !== void 0 && typeof options.lineArt !== "boolean") {
10866
+ throw new Error(
10867
+ `Expected boolean for trimLineArt but received ${options.lineArt} of type ${typeof options.lineArt}`
10868
+ );
10869
+ }
10870
+ const threshold = typeof options === "number" ? options : options?.threshold ?? 10;
10871
+ if (typeof threshold !== "number" || Number.isNaN(threshold) || threshold < 0) {
10872
+ throw new Error(`Expected positive number for threshold but received ${threshold} of type ${typeof threshold}`);
10873
+ }
10874
+ const background = typeof options === "object" && options?.background ? parseColor(options.background) : void 0;
10875
+ const lineArt = typeof options === "object" && typeof options?.lineArt === "boolean" ? options.lineArt : void 0;
10876
+ const nextNode = {
10877
+ kind: "trim",
10878
+ threshold,
10879
+ ...background ? { background } : {},
10880
+ ...lineArt !== void 0 ? { lineArt } : {}
10881
+ };
10882
+ const existingIdx = this.nodes.findIndex((n) => n.kind === "trim");
10883
+ if (existingIdx !== -1) {
10884
+ this.nodes[existingIdx] = nextNode;
10885
+ return this;
10886
+ }
10887
+ const geomIdx = this.nodes.findIndex(
10888
+ (n) => n.kind === "resize" || n.kind === "extend" || n.kind === "extract" || n.kind === "rotate"
10889
+ );
10890
+ if (geomIdx !== -1) this.nodes.splice(geomIdx, 0, nextNode);
10891
+ else this.nodes.push(nextNode);
10892
+ return this;
10893
+ }
10894
+ resize(widthOrOptions, height, options) {
10895
+ let w = null;
10896
+ let h = null;
10897
+ let wProvided = false;
10898
+ let hProvided = false;
10899
+ let opts = {};
10900
+ if (typeof widthOrOptions === "object" && widthOrOptions !== null) {
10901
+ opts = widthOrOptions;
10902
+ w = opts.width ?? null;
10903
+ h = opts.height ?? null;
10904
+ wProvided = opts.width !== void 0;
10905
+ hProvided = true;
10906
+ } else {
10907
+ opts = options ?? {};
10908
+ w = widthOrOptions !== void 0 ? widthOrOptions : opts.width ?? null;
10909
+ h = height !== void 0 ? height : opts.height ?? null;
10910
+ wProvided = true;
10911
+ hProvided = true;
10912
+ }
10913
+ if (w !== null && (!Number.isInteger(w) || w <= 0)) {
10914
+ throw new Error(`Expected positive integer for width but received ${w}`);
10915
+ }
10916
+ if (h !== null && (!Number.isInteger(h) || h <= 0)) {
10917
+ throw new Error(`Expected positive integer for height but received ${h}`);
10918
+ }
10919
+ if (opts.fit !== void 0 && !["contain", "cover", "fill", "inside", "outside"].includes(opts.fit)) {
10920
+ throw new Error(`Expected valid fit for fit but received ${opts.fit} of type ${typeof opts.fit}`);
10921
+ }
10922
+ if (opts.kernel !== void 0 && !["nearest", "linear", "cubic", "mitchell", "lanczos2", "lanczos3", "mks2013", "mks2021"].includes(opts.kernel)) {
10923
+ throw new Error(`Expected valid kernel name for kernel but received ${opts.kernel} of type ${typeof opts.kernel}`);
10924
+ }
10925
+ if (opts.position !== void 0) {
10926
+ const validPosStrings = [
10927
+ "top",
10928
+ "right",
10929
+ "bottom",
10930
+ "left",
10931
+ "right top",
10932
+ "right bottom",
10933
+ "left bottom",
10934
+ "left top",
10935
+ "north",
10936
+ "northeast",
10937
+ "east",
10938
+ "southeast",
10939
+ "south",
10940
+ "southwest",
10941
+ "west",
10942
+ "northwest",
10943
+ "center",
10944
+ "centre",
10945
+ "entropy",
10946
+ "attention"
10947
+ ];
10948
+ const isValidPos = typeof opts.position === "string" ? validPosStrings.includes(opts.position) : typeof opts.position === "number" && Number.isInteger(opts.position) && (opts.position >= 0 && opts.position <= 8 || opts.position === 16 || opts.position === 17);
10949
+ if (!isValidPos) {
10950
+ throw new Error(
10951
+ `Expected valid position/gravity/strategy for position but received ${opts.position} of type ${typeof opts.position}`
10952
+ );
10953
+ }
10954
+ }
10955
+ const anyResizeOpts = opts;
10956
+ for (const boolKey of ["withoutEnlargement", "withoutReduction", "fastShrinkOnLoad"]) {
10957
+ if (anyResizeOpts[boolKey] !== void 0 && typeof anyResizeOpts[boolKey] !== "boolean") {
10958
+ throw new Error(
10959
+ `Expected boolean for ${boolKey} but received ${anyResizeOpts[boolKey]} of type ${typeof anyResizeOpts[boolKey]}`
10960
+ );
10961
+ }
10962
+ }
10963
+ const existingIdx = this.nodes.findIndex((n) => n.kind === "resize");
10964
+ if (existingIdx !== -1) {
10965
+ const prev = this.nodes[existingIdx];
10966
+ this.nodes[existingIdx] = {
10967
+ kind: "resize",
10968
+ width: wProvided ? w : prev.width,
10969
+ height: hProvided ? h : prev.height,
10970
+ fit: opts.fit ?? prev.fit,
10971
+ position: opts.position ?? prev.position,
10972
+ kernel: opts.kernel ?? prev.kernel,
10973
+ background: opts.background !== void 0 ? parseColor(opts.background, 255) : prev.background,
10974
+ withoutEnlargement: opts.withoutEnlargement ?? prev.withoutEnlargement,
10975
+ withoutReduction: opts.withoutReduction ?? prev.withoutReduction
10976
+ };
10977
+ return this;
10978
+ }
10979
+ const nextResizeNode = {
10980
+ kind: "resize",
10981
+ width: w,
10982
+ height: h,
10983
+ fit: opts.fit ?? "cover",
10984
+ position: opts.position ?? "centre",
10985
+ kernel: opts.kernel ?? "lanczos3",
10986
+ background: parseColor(opts.background, 255),
10987
+ withoutEnlargement: opts.withoutEnlargement ?? false,
10988
+ withoutReduction: opts.withoutReduction ?? false
10989
+ };
10990
+ const extIdx = this.nodes.findIndex((n) => n.kind === "extend");
10991
+ if (extIdx !== -1) this.nodes.splice(extIdx, 0, nextResizeNode);
10992
+ else this.nodes.push(nextResizeNode);
10993
+ return this;
10994
+ }
10995
+ extend(edges) {
10996
+ if (typeof edges === "number") {
10997
+ if (!Number.isInteger(edges) || edges <= 0) {
10998
+ throw new Error(`Expected positive integer for extend but received ${edges}`);
10999
+ }
11000
+ } else if (edges && typeof edges === "object") {
11001
+ for (const side of ["top", "bottom", "left", "right"]) {
11002
+ const val = edges[side];
11003
+ if (val !== void 0 && (!Number.isInteger(val) || val < 0)) {
11004
+ throw new Error(`Expected positive integer for ${side} but received ${val}`);
11005
+ }
11006
+ }
11007
+ if (edges.extendWith !== void 0 && edges.extendWith !== "background" && edges.extendWith !== "copy" && edges.extendWith !== "repeat" && edges.extendWith !== "mirror") {
11008
+ throw new Error(`Expected one of: background, copy, repeat, mirror for extendWith but received ${edges.extendWith}`);
11009
+ }
11010
+ } else {
11011
+ throw new Error(`Expected integer or object for extend but received ${edges}`);
11012
+ }
11013
+ const nextNode = typeof edges === "number" ? {
11014
+ kind: "extend",
11015
+ top: edges,
11016
+ bottom: edges,
11017
+ left: edges,
11018
+ right: edges,
11019
+ background: { r: 0, g: 0, b: 0, a: 255 },
11020
+ extendWith: "background"
11021
+ } : {
11022
+ kind: "extend",
11023
+ top: edges.top ?? 0,
11024
+ bottom: edges.bottom ?? 0,
11025
+ left: edges.left ?? 0,
11026
+ right: edges.right ?? 0,
11027
+ background: parseColor(edges.background, 255),
11028
+ extendWith: edges.extendWith ?? "background"
11029
+ };
11030
+ const existingIdx = this.nodes.findIndex((n) => n.kind === "extend");
11031
+ if (existingIdx !== -1) {
11032
+ this.nodes[existingIdx] = nextNode;
11033
+ } else {
11034
+ this.nodes.push(nextNode);
11035
+ }
11036
+ return this;
11037
+ }
11038
+ composite(images) {
11039
+ if (!Array.isArray(images)) {
11040
+ throw new Error("Expected array for images to composite");
11041
+ }
11042
+ const validBlends = [
11043
+ "clear",
11044
+ "source",
11045
+ "over",
11046
+ "in",
11047
+ "out",
11048
+ "atop",
11049
+ "dest",
11050
+ "dest-over",
11051
+ "dest-in",
11052
+ "dest-out",
11053
+ "dest-atop",
11054
+ "xor",
11055
+ "add",
11056
+ "saturate",
11057
+ "multiply",
11058
+ "screen",
11059
+ "overlay",
11060
+ "darken",
11061
+ "lighten",
11062
+ "colour-dodge",
11063
+ "color-dodge",
11064
+ "colour-burn",
11065
+ "color-burn",
11066
+ "hard-light",
11067
+ "soft-light",
11068
+ "difference",
11069
+ "exclusion"
11070
+ ];
11071
+ const validGravities = [
11072
+ "center",
11073
+ "centre",
11074
+ "north",
11075
+ "east",
11076
+ "south",
11077
+ "west",
11078
+ "northeast",
11079
+ "southeast",
11080
+ "southwest",
11081
+ "northwest"
11082
+ ];
11083
+ for (const img of images) {
11084
+ if (!img || typeof img !== "object") {
11085
+ throw new Error("Expected object for image to composite");
11086
+ }
11087
+ if (img.input === void 0) {
11088
+ throw new Error(`Unsupported input '${img.input}' of type ${typeof img.input}`);
11089
+ }
11090
+ validateInputOptions(img);
11091
+ if (img.blend !== void 0 && !validBlends.includes(img.blend)) {
11092
+ throw new Error(`Expected valid blend name for blend but received ${img.blend} of type ${typeof img.blend}`);
11093
+ }
11094
+ if (img.tile !== void 0 && typeof img.tile !== "boolean") {
11095
+ throw new Error(`Expected boolean for tile but received ${img.tile} of type ${typeof img.tile}`);
11096
+ }
11097
+ if (img.premultiplied !== void 0 && typeof img.premultiplied !== "boolean") {
11098
+ throw new Error(`Expected boolean for premultiplied but received ${img.premultiplied} of type ${typeof img.premultiplied}`);
11099
+ }
11100
+ if (img.gravity !== void 0) {
11101
+ const validG = typeof img.gravity === "string" ? validGravities.includes(img.gravity) : typeof img.gravity === "number" && Number.isInteger(img.gravity) && img.gravity >= 0 && img.gravity <= 8;
11102
+ if (!validG) {
11103
+ throw new Error(`Expected valid gravity for gravity but received ${img.gravity} of type ${typeof img.gravity}`);
11104
+ }
11105
+ }
11106
+ if (img.top !== void 0 !== (img.left !== void 0)) {
11107
+ throw new Error("Expected both left and top to be set");
11108
+ }
11109
+ if (img.top !== void 0 && !Number.isInteger(img.top)) {
11110
+ throw new Error(`Expected integer for top but received ${img.top}`);
11111
+ }
11112
+ if (img.left !== void 0 && !Number.isInteger(img.left)) {
11113
+ throw new Error(`Expected integer for left but received ${img.left}`);
11114
+ }
11115
+ }
11116
+ const existingIdx = this.nodes.findIndex((n) => n.kind === "composite");
11117
+ if (existingIdx !== -1) {
11118
+ this.nodes[existingIdx] = { kind: "composite", layers: [...images] };
11119
+ } else {
11120
+ this.nodes.push({ kind: "composite", layers: [...images] });
11121
+ }
11122
+ return this;
11123
+ }
11124
+ grayscale(grayscale = true) {
11125
+ if (grayscale === false) {
11126
+ const idx = this.nodes.findIndex((n) => n.kind === "grayscale");
11127
+ if (idx !== -1) this.nodes.splice(idx, 1);
11128
+ return this;
11129
+ }
11130
+ this.upsertNode({ kind: "grayscale" });
11131
+ return this;
11132
+ }
11133
+ greyscale(greyscale = true) {
11134
+ return this.grayscale(greyscale);
11135
+ }
11136
+ flatten(options) {
11137
+ if (options === false) {
11138
+ const idx = this.nodes.findIndex((n) => n.kind === "flatten");
11139
+ if (idx !== -1) this.nodes.splice(idx, 1);
11140
+ return this;
11141
+ }
11142
+ const bg = typeof options === "object" ? options?.background : void 0;
11143
+ this.upsertNode({
11144
+ kind: "flatten",
11145
+ background: parseColor(bg ?? "#000000", 255)
11146
+ });
11147
+ return this;
11148
+ }
11149
+ unflatten() {
11150
+ this.upsertNode({ kind: "unflatten" }, true);
11151
+ return this;
11152
+ }
11153
+ negate(options) {
11154
+ if (options === false) {
11155
+ const idx = this.nodes.findIndex((n) => n.kind === "negate");
11156
+ if (idx !== -1) this.nodes.splice(idx, 1);
11157
+ return this;
11158
+ }
11159
+ if (typeof options === "object" && options !== null && options.alpha !== void 0 && typeof options.alpha !== "boolean") {
11160
+ throw new Error(`Expected should be boolean value for alpha but received ${options.alpha} of type ${typeof options.alpha}`);
11161
+ }
11162
+ const alpha = typeof options === "object" ? options.alpha ?? true : true;
11163
+ this.upsertNode({ kind: "negate", alpha });
11164
+ return this;
11165
+ }
11166
+ modulate(options) {
11167
+ if (!options || typeof options !== "object") {
11168
+ throw new Error(`Expected plain object for modulate options but received ${options}`);
11169
+ }
11170
+ if (options.brightness !== void 0 && (typeof options.brightness !== "number" || Number.isNaN(options.brightness) || options.brightness < 0)) {
11171
+ throw new Error(`Expected number above zero for brightness but received ${options.brightness} of type ${typeof options.brightness}`);
11172
+ }
11173
+ if (options.saturation !== void 0 && (typeof options.saturation !== "number" || Number.isNaN(options.saturation) || options.saturation < 0)) {
11174
+ throw new Error(`Expected number above zero for saturation but received ${options.saturation} of type ${typeof options.saturation}`);
11175
+ }
11176
+ if (options.hue !== void 0 && (typeof options.hue !== "number" || Number.isNaN(options.hue))) {
11177
+ throw new Error(`Expected number for hue but received ${options.hue} of type ${typeof options.hue}`);
11178
+ }
11179
+ if (options.lightness !== void 0 && (typeof options.lightness !== "number" || Number.isNaN(options.lightness))) {
11180
+ throw new Error(`Expected number for lightness but received ${options.lightness} of type ${typeof options.lightness}`);
11181
+ }
11182
+ const idx = this.nodes.findIndex((n) => n.kind === "modulate");
11183
+ if (idx !== -1) {
11184
+ const prev = this.nodes[idx];
11185
+ this.nodes[idx] = {
11186
+ kind: "modulate",
11187
+ brightness: options.brightness ?? prev.brightness,
11188
+ saturation: options.saturation ?? prev.saturation,
11189
+ hue: options.hue ?? prev.hue,
11190
+ lightness: options.lightness ?? prev.lightness
11191
+ };
11192
+ return this;
11193
+ }
11194
+ this.nodes.push({
11195
+ kind: "modulate",
11196
+ brightness: options.brightness ?? 1,
11197
+ saturation: options.saturation ?? 1,
11198
+ hue: options.hue ?? 0,
11199
+ lightness: options.lightness ?? 0
11200
+ });
11201
+ return this;
11202
+ }
11203
+ tint(rgb) {
11204
+ this.upsertNode({ kind: "tint", color: parseColor(rgb, 255) }, true);
11205
+ return this;
11206
+ }
11207
+ gamma(gamma = 2.2, gammaOut = gamma) {
11208
+ if (typeof gamma !== "number" || Number.isNaN(gamma) || gamma < 1 || gamma > 3) {
11209
+ throw new Error(`Expected number between 1.0 and 3.0 for gamma but received ${gamma}`);
11210
+ }
11211
+ if (typeof gammaOut !== "number" || Number.isNaN(gammaOut) || gammaOut < 1 || gammaOut > 3) {
11212
+ throw new Error(`Expected number between 1.0 and 3.0 for gammaOut but received ${gammaOut}`);
11213
+ }
11214
+ this.upsertNode({ kind: "gamma", gamma, gammaOut });
11215
+ return this;
11216
+ }
11217
+ linear(a, b) {
11218
+ if (a == null && b == null) {
11219
+ const idx = this.nodes.findIndex((n) => n.kind === "linear");
11220
+ if (idx !== -1) this.nodes.splice(idx, 1);
11221
+ return this;
11222
+ }
11223
+ let effA = a;
11224
+ let effB = b;
11225
+ if (effA == null && typeof effB === "number") {
11226
+ effA = 1;
11227
+ } else if (typeof effA === "number" && effB == null) {
11228
+ effB = 0;
11229
+ }
11230
+ const aArr = effA == null ? [] : typeof effA === "number" ? [effA] : Array.isArray(effA) ? [...effA] : [];
11231
+ const bArr = effB == null ? [] : typeof effB === "number" ? [effB] : Array.isArray(effB) ? [...effB] : [];
11232
+ if (aArr.length !== bArr.length) {
11233
+ throw new Error("Expected a and b to be arrays of the same length");
11234
+ }
11235
+ this.upsertNode({ kind: "linear", a: aArr, b: bArr });
11236
+ return this;
11237
+ }
11238
+ normalize(lowerOrOptions, upperArg) {
11239
+ if (lowerOrOptions === false) {
11240
+ const idx = this.nodes.findIndex((n) => n.kind === "normalize");
11241
+ if (idx !== -1) this.nodes.splice(idx, 1);
11242
+ return this;
11243
+ }
11244
+ if (lowerOrOptions === true) {
11245
+ this.upsertNode({ kind: "normalize", lower: 1, upper: 99 });
11246
+ return this;
11247
+ }
11248
+ const lower = typeof lowerOrOptions === "number" ? lowerOrOptions : lowerOrOptions?.lower ?? 1;
11249
+ const upper = typeof lowerOrOptions === "number" ? upperArg ?? 99 : lowerOrOptions?.upper ?? 99;
11250
+ if (typeof lower !== "number" || Number.isNaN(lower) || lower < 0 || lower > 99) {
11251
+ throw new Error(`Expected number between 0 and 99 for lower but received ${lower} of type ${typeof lower}`);
11252
+ }
11253
+ if (typeof upper !== "number" || Number.isNaN(upper) || upper < 1 || upper > 100) {
11254
+ throw new Error(`Expected number between 1 and 100 for upper but received ${upper} of type ${typeof upper}`);
11255
+ }
11256
+ if (lower >= upper) {
11257
+ throw new Error(`Expected lower to be less than upper for range but received ${lower} >= ${upper} of type string`);
11258
+ }
11259
+ this.upsertNode({ kind: "normalize", lower, upper });
11260
+ return this;
11261
+ }
11262
+ normalise(lowerOrOptions, upperArg) {
11263
+ return this.normalize(lowerOrOptions, upperArg);
11264
+ }
11265
+ threshold(threshold = 128, options) {
11266
+ if (threshold === false || threshold === 0) {
11267
+ const idx = this.nodes.findIndex((n) => n.kind === "threshold");
11268
+ if (idx !== -1) this.nodes.splice(idx, 1);
11269
+ return this;
11270
+ }
11271
+ if (typeof threshold === "number" && (!Number.isInteger(threshold) || threshold < 0 || threshold > 255)) {
11272
+ throw new Error(`Expected integer between 0 and 255 for threshold but received ${threshold}`);
11273
+ }
11274
+ const val = typeof threshold === "number" ? threshold : 128;
11275
+ const gs = options?.grayscale ?? options?.greyscale ?? true;
11276
+ this.upsertNode({ kind: "threshold", value: val, grayscale: gs });
11277
+ return this;
11278
+ }
11279
+ blur(options) {
11280
+ if (options === false) {
11281
+ const idx = this.nodes.findIndex((n) => n.kind === "blur");
11282
+ if (idx !== -1) this.nodes.splice(idx, 1);
11283
+ return this;
11284
+ }
11285
+ let sigma;
11286
+ let precision;
11287
+ let minAmplitude;
11288
+ if (typeof options === "number") {
11289
+ sigma = options;
11290
+ } else if (options !== null && typeof options === "object" && !Array.isArray(options)) {
11291
+ if (typeof options.sigma !== "number" || Number.isNaN(options.sigma)) {
11292
+ throw new Error(
11293
+ `Expected number between 0.3 and 1000 for options.sigma but received ${options.sigma} of type ${typeof options.sigma}`
11294
+ );
11295
+ }
11296
+ sigma = options.sigma;
11297
+ if ("precision" in options && options.precision !== void 0) {
11298
+ if (options.precision !== "integer" && options.precision !== "float" && options.precision !== "approximate") {
11299
+ throw new Error(
11300
+ `Expected one of: integer, float, approximate for precision but received ${options.precision} of type ${typeof options.precision}`
11301
+ );
11302
+ }
11303
+ precision = options.precision;
11304
+ }
11305
+ if ("minAmplitude" in options && options.minAmplitude !== void 0) {
11306
+ if (typeof options.minAmplitude !== "number" || Number.isNaN(options.minAmplitude) || options.minAmplitude < 1e-3 || options.minAmplitude > 1) {
11307
+ throw new Error(
11308
+ `Expected number between 0.001 and 1 for minAmplitude but received ${options.minAmplitude} of type ${typeof options.minAmplitude}`
11309
+ );
11310
+ }
11311
+ minAmplitude = options.minAmplitude;
11312
+ }
11313
+ }
11314
+ if (options === void 0 || options === true) {
11315
+ this.upsertNode({ kind: "blur", sigma: -1 });
11316
+ return this;
11317
+ }
11318
+ if (typeof sigma !== "number" || Number.isNaN(sigma) || sigma < 0.3 || sigma > 1e3) {
11319
+ throw new Error(
11320
+ `Expected number between 0.3 and 1000 for sigma but received ${sigma} of type ${typeof sigma}`
11321
+ );
11322
+ }
11323
+ this.upsertNode({
11324
+ kind: "blur",
11325
+ sigma,
11326
+ ...precision ? { precision } : {},
11327
+ ...minAmplitude !== void 0 ? { minAmplitude } : {}
11328
+ });
11329
+ return this;
11330
+ }
11331
+ sharpen(options, flat, jagged) {
11332
+ if (options === false) {
11333
+ const idx = this.nodes.findIndex((n) => n.kind === "sharpen");
11334
+ if (idx !== -1) this.nodes.splice(idx, 1);
11335
+ return this;
11336
+ }
11337
+ if (options === void 0 || options === true) {
11338
+ this.upsertNode({ kind: "sharpen", sigma: -1, m1: 1, m2: 2, x1: 2, y2: 10, y3: 20 });
11339
+ return this;
11340
+ }
11341
+ if (typeof options === "number") {
11342
+ if (Number.isNaN(options) || options < 0.01 || options > 1e4) {
11343
+ throw new Error(`Expected number between 0.01 and 10000 for sigma but received ${options}`);
11344
+ }
11345
+ this.upsertNode({
11346
+ kind: "sharpen",
11347
+ sigma: options,
11348
+ m1: flat ?? 1,
11349
+ m2: jagged ?? 2,
11350
+ x1: 2,
11351
+ y2: 10,
11352
+ y3: 20
11353
+ });
11354
+ return this;
11355
+ }
11356
+ if (options.sigma !== void 0 && (typeof options.sigma !== "number" || Number.isNaN(options.sigma) || options.sigma < 1e-6 || options.sigma > 10)) {
11357
+ throw new Error(`Expected number between 0.000001 and 10 for options.sigma but received ${options.sigma}`);
11358
+ }
11359
+ this.upsertNode({
11360
+ kind: "sharpen",
11361
+ sigma: options.sigma ?? -1,
11362
+ m1: options.m1 ?? 1,
11363
+ m2: options.m2 ?? 2,
11364
+ x1: options.x1 ?? 2,
11365
+ y2: options.y2 ?? 10,
11366
+ y3: options.y3 ?? 20
11367
+ });
11368
+ return this;
11369
+ }
11370
+ median(size = 3) {
11371
+ if (size === false) {
11372
+ const idx = this.nodes.findIndex((n) => n.kind === "median");
11373
+ if (idx !== -1) this.nodes.splice(idx, 1);
11374
+ return this;
11375
+ }
11376
+ const effSize = size === true ? 3 : size;
11377
+ if (!Number.isInteger(effSize) || effSize < 1 || effSize > 1e3) {
11378
+ throw new Error(`Expected integer between 1 and 1000 for size but received ${size}`);
11379
+ }
11380
+ this.upsertNode({ kind: "median", size: effSize });
11381
+ return this;
11382
+ }
11383
+ dilate(width = 1) {
11384
+ if (!Number.isInteger(width) || width <= 0) {
11385
+ throw new Error(`Expected positive integer for dilate but received ${width}`);
11386
+ }
11387
+ this.upsertNode({ kind: "dilate", width });
11388
+ return this;
11389
+ }
11390
+ erode(width = 1) {
11391
+ if (!Number.isInteger(width) || width <= 0) {
11392
+ throw new Error(`Expected positive integer for erode but received ${width}`);
11393
+ }
11394
+ this.upsertNode({ kind: "erode", width });
11395
+ return this;
11396
+ }
11397
+ convolve(kernelSpec) {
11398
+ if (!kernelSpec || typeof kernelSpec !== "object" || !Array.isArray(kernelSpec.kernel) || !Number.isInteger(kernelSpec.width) || !Number.isInteger(kernelSpec.height) || kernelSpec.width < 3 || kernelSpec.width > 1001 || kernelSpec.height < 3 || kernelSpec.height > 1001 || kernelSpec.width * kernelSpec.height !== kernelSpec.kernel.length) {
11399
+ throw new Error("Invalid convolution kernel");
11400
+ }
11401
+ const defaultScale = kernelSpec.kernel.reduce((s, v) => s + v, 0) || 1;
11402
+ this.upsertNode({
11403
+ kind: "convolve",
11404
+ width: kernelSpec.width,
11405
+ height: kernelSpec.height,
11406
+ kernel: [...kernelSpec.kernel],
11407
+ scale: kernelSpec.scale ?? defaultScale,
11408
+ offset: kernelSpec.offset ?? 0
11409
+ });
11410
+ return this;
11411
+ }
11412
+ ensureAlpha(alpha = 1) {
11413
+ if (typeof alpha !== "number" || Number.isNaN(alpha) || alpha < 0 || alpha > 1) {
11414
+ throw new Error(`Expected number between 0 and 1 for alpha but received ${alpha}`);
11415
+ }
11416
+ this.upsertNode({ kind: "ensureAlpha", alpha }, true);
11417
+ return this;
11418
+ }
11419
+ removeAlpha() {
11420
+ this.upsertNode({ kind: "removeAlpha" }, true);
11421
+ return this;
11422
+ }
11423
+ extractChannel(channel) {
11424
+ const ch = channel === "red" ? 0 : channel === "green" ? 1 : channel === "blue" ? 2 : channel === "alpha" ? 3 : channel;
11425
+ if (!Number.isInteger(ch) || ch < 0 || ch > 3) {
11426
+ throw new Error(`Expected integer or one of: red, green, blue, alpha for channel but received ${channel}`);
11427
+ }
11428
+ this.upsertNode({ kind: "extractChannel", channel: ch });
11429
+ return this;
11430
+ }
11431
+ recomb(matrix) {
11432
+ if (!Array.isArray(matrix) || matrix.length !== 3 && matrix.length !== 4) {
11433
+ throw new Error(`Expected 3x3 or 4x4 array for inputMatrix but received ${matrix?.length}`);
11434
+ }
11435
+ const flatLen = matrix.reduce((acc, row) => acc + (Array.isArray(row) ? row.length : 0), 0);
11436
+ if (flatLen !== 9 && flatLen !== 16) {
11437
+ throw new Error(`Expected 3x3 or 4x4 array with cardinality of 9 or 16 for inputMatrix`);
11438
+ }
11439
+ this.upsertNode({
11440
+ kind: "recomb",
11441
+ matrix: matrix.map((row) => [...row])
11442
+ });
11443
+ return this;
11444
+ }
11445
+ toColorspace(colorspace) {
11446
+ if (typeof colorspace !== "string") {
11447
+ throw new Error(`Expected string for colourspace but received ${colorspace}`);
11448
+ }
11449
+ const norm = colorspace.toLowerCase();
11450
+ const space = norm === "grey16" ? "grey16" : norm === "rgb16" ? "rgb16" : norm === "b-w" || norm === "bw" || norm === "gray" ? "b-w" : norm === "cmyk" ? "cmyk" : "srgb";
11451
+ if (space === "srgb" && this.nodes.some((n) => n.kind === "grayscale")) {
11452
+ const idx = this.nodes.findIndex((n) => n.kind === "toColorspace");
11453
+ if (idx !== -1) this.nodes.splice(idx, 1);
11454
+ return this;
11455
+ }
11456
+ this.upsertNode({ kind: "toColorspace", space });
11457
+ return this;
11458
+ }
11459
+ toColourspace(colourspace) {
11460
+ return this.toColorspace(colourspace);
11461
+ }
11462
+ pipelineColorspace(colorspace) {
11463
+ return this.toColorspace(colorspace);
11464
+ }
11465
+ pipelineColourspace(colourspace) {
11466
+ return this.toColorspace(colourspace);
11467
+ }
11468
+ bandbool(boolOp) {
11469
+ if (boolOp !== "and" && boolOp !== "or" && boolOp !== "eor") {
11470
+ throw new Error(`Expected one of: and, or, eor for boolOp but received ${boolOp}`);
11471
+ }
11472
+ this.upsertNode({ kind: "bandbool", op: boolOp });
11473
+ return this;
11474
+ }
11475
+ boolean(operand, op, options) {
11476
+ if (op !== "and" && op !== "or" && op !== "eor") {
11477
+ throw new Error(`Expected one of: and, or, eor for operator but received ${op}`);
11478
+ }
11479
+ const data = this.operationInput(operand);
11480
+ if (data) {
11481
+ this.nodes.push({
11482
+ kind: "boolean",
11483
+ operand: data,
11484
+ op,
11485
+ ...options?.raw !== void 0 ? { options: { raw: options.raw } } : {}
11486
+ });
11487
+ }
11488
+ return this;
11489
+ }
11490
+ joinChannel(images, options) {
11491
+ const list = Array.isArray(images) ? images : [images];
11492
+ this.nodes.push({
11493
+ kind: "joinChannel",
11494
+ inputs: list.map((buf) => {
11495
+ const data = this.operationInput(buf);
11496
+ if (!data) {
11497
+ throw new Error(`Unsupported joinChannel input: ${typeof buf}`);
11498
+ }
11499
+ return {
11500
+ data,
11501
+ ...options !== void 0 ? { options } : {}
11502
+ };
11503
+ })
11504
+ });
11505
+ return this;
11506
+ }
11507
+ clahe(options) {
11508
+ if (!options || typeof options !== "object") {
11509
+ throw new Error("Expected plain object for clahe options");
11510
+ }
11511
+ if (!Number.isInteger(options.width) || options.width <= 0) {
11512
+ throw new Error(`Expected integer greater than zero for width but received ${options.width}`);
11513
+ }
11514
+ if (!Number.isInteger(options.height) || options.height <= 0) {
11515
+ throw new Error(`Expected integer greater than zero for height but received ${options.height}`);
11516
+ }
11517
+ if (options.maxSlope !== void 0 && (!Number.isInteger(options.maxSlope) || options.maxSlope < 0 || options.maxSlope > 100)) {
11518
+ throw new Error(`Expected integer between 0 and 100 for maxSlope but received ${options.maxSlope}`);
11519
+ }
11520
+ this.upsertNode({
11521
+ kind: "clahe",
11522
+ width: options.width,
11523
+ height: options.height,
11524
+ maxSlope: options.maxSlope ?? 3
11525
+ });
11526
+ return this;
11527
+ }
11528
+ affine(matrix, options) {
11529
+ const rawFlat = Array.isArray(matrix) ? Array.isArray(matrix[0]) ? [...matrix[0], ...matrix[1] ?? []] : [...matrix] : [];
11530
+ if (rawFlat.length !== 4 || rawFlat.some((v) => typeof v !== "number" || Number.isNaN(v))) {
11531
+ throw new Error(`Expected 1x4 or 2x2 array for matrix but received ${matrix} of type ${typeof matrix}`);
11532
+ }
11533
+ if (options?.interpolator !== void 0 && !["nearest", "bilinear", "bicubic", "lbb", "nohalo", "vsqbs"].includes(options.interpolator)) {
11534
+ throw new Error(
11535
+ `Expected valid interpolator name for options.interpolator but received ${options.interpolator} of type ${typeof options.interpolator}`
11536
+ );
11537
+ }
11538
+ for (const key of ["idx", "idy", "odx", "ody"]) {
11539
+ const val = options?.[key];
11540
+ if (val !== void 0 && (typeof val !== "number" || Number.isNaN(val))) {
11541
+ throw new Error(`Expected number for options.${key} but received ${val} of type ${typeof val}`);
11542
+ }
11543
+ }
11544
+ const flat = [rawFlat[0], rawFlat[1], rawFlat[2], rawFlat[3]];
11545
+ this.upsertNode({
11546
+ kind: "affine",
11547
+ matrix: flat,
11548
+ background: parseColor(options?.background ?? "#000000", 255),
11549
+ idx: options?.idx ?? 0,
11550
+ idy: options?.idy ?? 0,
11551
+ odx: options?.odx ?? 0,
11552
+ ody: options?.ody ?? 0,
11553
+ ...options?.interpolator !== void 0 ? { interpolator: options.interpolator } : {}
11554
+ });
11555
+ return this;
11556
+ }
11557
+ withMetadata(options) {
11558
+ if (options && typeof options === "object") {
11559
+ if (options.orientation !== void 0 && (!Number.isInteger(options.orientation) || options.orientation < 1 || options.orientation > 8)) {
11560
+ throw new Error(`Expected integer between 1 and 8 for orientation but received ${options.orientation}`);
11561
+ }
11562
+ if (options.density !== void 0 && (typeof options.density !== "number" || Number.isNaN(options.density) || options.density <= 0)) {
11563
+ throw new Error(`Expected positive number for density but received ${options.density}`);
11564
+ }
11565
+ }
11566
+ const existingIdx = this.nodes.findIndex((n) => n.kind === "withMetadata");
11567
+ const prev = existingIdx !== -1 ? this.nodes[existingIdx] : void 0;
11568
+ const density = options?.density ?? prev?.density;
11569
+ const orientation = options?.orientation ?? prev?.orientation;
11570
+ this.upsertNode({
11571
+ kind: "withMetadata",
11572
+ ...density !== void 0 ? { density } : {},
11573
+ ...orientation !== void 0 ? { orientation } : {}
11574
+ });
11575
+ this.outputOptions = {
11576
+ ...this.outputOptions,
11577
+ ...density !== void 0 ? { density } : {},
11578
+ ...orientation !== void 0 ? { orientation } : {}
11579
+ };
11580
+ return this;
11581
+ }
11582
+ keepExif() {
11583
+ return this.withMetadata();
11584
+ }
11585
+ withExif(exif) {
11586
+ if (!exif || typeof exif !== "object" || Array.isArray(exif)) {
11587
+ throw new Error(`Expected object for exif but received ${exif}`);
11588
+ }
11589
+ const orientStr = exif?.IFD0?.Orientation;
11590
+ const orientNum = orientStr !== void 0 ? Number(orientStr) : void 0;
11591
+ return this.withMetadata(orientNum !== void 0 && Number.isFinite(orientNum) ? { orientation: orientNum } : void 0);
11592
+ }
11593
+ withExifMerge(exif) {
11594
+ return this.withExif(exif);
11595
+ }
11596
+ keepIccProfile() {
11597
+ return this;
11598
+ }
11599
+ withIccProfile(profile, _options) {
11600
+ if (typeof profile !== "string") {
11601
+ throw new Error(`Expected string for icc but received ${profile}`);
11602
+ }
11603
+ return this;
11604
+ }
11605
+ timeout(options) {
11606
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
11607
+ throw new Error(`Expected object for options but received ${options}`);
11608
+ }
11609
+ if (!Number.isInteger(options.seconds) || options.seconds < 0 || options.seconds > 3600) {
11610
+ throw new Error(`Expected integer between 0 and 3600 for seconds but received ${options.seconds}`);
11611
+ }
11612
+ return this;
11613
+ }
11614
+ keepXmp() {
11615
+ return this;
11616
+ }
11617
+ withXmp(xmp) {
11618
+ if (typeof xmp !== "string" || xmp.length === 0) {
11619
+ throw new Error(`Expected non-empty string for xmp but received ${xmp}`);
11620
+ }
11621
+ return this;
11622
+ }
11623
+ keepMetadata() {
11624
+ return this.withMetadata();
11625
+ }
11626
+ validateQuality(q) {
11627
+ if (q !== void 0 && (!Number.isInteger(q) || q < 1 || q > 100)) {
11628
+ throw new Error(`Expected integer between 1 and 100 for quality but received ${q}`);
11629
+ }
11630
+ }
11631
+ validateCompressionLevel(level) {
11632
+ if (level !== void 0 && (!Number.isInteger(level) || level < 0 || level > 9)) {
11633
+ throw new Error(`Expected integer between 0 and 9 for compressionLevel but received ${level}`);
11634
+ }
11635
+ }
11636
+ jp2(options) {
11637
+ this.validateQuality(options?.quality);
11638
+ return this.png(options);
11639
+ }
11640
+ jxl(options) {
11641
+ this.validateQuality(options?.quality);
11642
+ return this.png(options);
11643
+ }
11644
+ tile(_options) {
11645
+ return this;
11646
+ }
11647
+ png(options) {
11648
+ this.validateCompressionLevel(options?.compressionLevel);
11649
+ this.validateQuality(options?.quality);
11650
+ const anyOpts = options;
11651
+ for (const [k, label] of [
11652
+ ["progressive", "pngProgressive"],
11653
+ ["adaptiveFiltering", "pngAdaptiveFiltering"],
11654
+ ["palette", "pngPalette"]
11655
+ ]) {
11656
+ if (anyOpts?.[k] !== void 0 && typeof anyOpts[k] !== "boolean") {
11657
+ throw new Error(`Expected boolean for ${label} but received ${anyOpts[k]} of type ${typeof anyOpts[k]}`);
11658
+ }
11659
+ }
11660
+ if (anyOpts?.effort !== void 0 && (!Number.isInteger(anyOpts.effort) || anyOpts.effort < 1 || anyOpts.effort > 10)) {
11661
+ throw new Error(`Expected integer between 1 and 10 for effort but received ${anyOpts.effort} of type ${typeof anyOpts.effort}`);
11662
+ }
11663
+ const colours = anyOpts?.colours ?? anyOpts?.colors;
11664
+ if (colours !== void 0 && (!Number.isInteger(colours) || colours < 2 || colours > 256)) {
11665
+ throw new Error(`Expected integer between 2 and 256 for colours but received ${colours} of type ${typeof colours}`);
11666
+ }
11667
+ if (anyOpts?.dither !== void 0 && (typeof anyOpts.dither !== "number" || Number.isNaN(anyOpts.dither) || anyOpts.dither < 0 || anyOpts.dither > 1)) {
11668
+ throw new Error(`Expected number between 0.0 and 1.0 for dither but received ${anyOpts.dither} of type ${typeof anyOpts.dither}`);
11669
+ }
11670
+ if (anyOpts?.bitdepth !== void 0 && ![1, 2, 4, 8, 16].includes(anyOpts.bitdepth)) {
11671
+ throw new Error(`Expected 1, 2, 4, 8 or 16 for bitdepth but received ${anyOpts.bitdepth} of type ${typeof anyOpts.bitdepth}`);
11672
+ }
11673
+ this.outputOptions = {
11674
+ ...this.outputOptions,
11675
+ ...options?.force === false ? {} : { format: "png" },
11676
+ ...options?.compressionLevel !== void 0 ? { compressionLevel: options.compressionLevel } : {},
11677
+ ...options?.palette !== void 0 ? { palette: options.palette } : {}
11678
+ };
11679
+ return this;
11680
+ }
11681
+ jpeg(options) {
11682
+ this.validateQuality(options?.quality);
11683
+ const anyOpts = options;
11684
+ for (const [k, label] of [
11685
+ ["progressive", "jpegProgressive"],
11686
+ ["trellisQuantisation", "jpegTrellisQuantisation"],
11687
+ ["overshootDeringing", "jpegOvershootDeringing"],
11688
+ ["optimiseScans", "jpegOptimiseScans"],
11689
+ ["optimiseCoding", "jpegOptimiseCoding"],
11690
+ ["mozjpeg", "mozjpeg"]
11691
+ ]) {
11692
+ if (anyOpts?.[k] !== void 0 && typeof anyOpts[k] !== "boolean") {
11693
+ throw new Error(`Expected boolean for ${label} but received ${anyOpts[k]} of type ${typeof anyOpts[k]}`);
11694
+ }
11695
+ }
11696
+ if (anyOpts?.chromaSubsampling !== void 0 && typeof anyOpts.chromaSubsampling !== "string") {
11697
+ throw new Error(`Expected one of: 4:2:0, 4:4:4 for chromaSubsampling but received ${anyOpts.chromaSubsampling} of type ${typeof anyOpts.chromaSubsampling}`);
11698
+ }
11699
+ const qTable = anyOpts?.quantisationTable ?? anyOpts?.quantizationTable;
11700
+ if (qTable !== void 0 && (!Number.isInteger(qTable) || qTable < 0 || qTable > 8)) {
11701
+ throw new Error(`Expected integer between 0 and 8 for quantisationTable but received ${qTable} of type ${typeof qTable}`);
11702
+ }
11703
+ this.outputOptions = {
11704
+ ...this.outputOptions,
11705
+ ...options?.force === false ? {} : { format: "jpeg" },
11706
+ ...options?.quality !== void 0 ? { quality: options.quality } : {}
11707
+ };
11708
+ return this;
11709
+ }
11710
+ webp(options) {
11711
+ this.validateQuality(options?.quality);
11712
+ const anyOpts = options;
11713
+ for (const [k, label] of [
11714
+ ["lossless", "webpLossless"],
11715
+ ["nearLossless", "webpNearLossless"],
11716
+ ["smartSubsample", "webpSmartSubsample"],
11717
+ ["smartDeblock", "webpSmartDeblock"],
11718
+ ["minSize", "webpMinSize"],
11719
+ ["mixed", "webpMixed"]
11720
+ ]) {
11721
+ if (anyOpts?.[k] !== void 0 && typeof anyOpts[k] !== "boolean") {
11722
+ throw new Error(`Expected boolean for ${label} but received ${anyOpts[k]} of type ${typeof anyOpts[k]}`);
11723
+ }
11724
+ }
11725
+ if (anyOpts?.alphaQuality !== void 0 && (!Number.isInteger(anyOpts.alphaQuality) || anyOpts.alphaQuality < 0 || anyOpts.alphaQuality > 100)) {
11726
+ throw new Error(
11727
+ `Expected integer between 0 and 100 for alphaQuality but received ${anyOpts.alphaQuality} of type ${typeof anyOpts.alphaQuality}`
11728
+ );
11729
+ }
11730
+ if (anyOpts?.effort !== void 0 && (!Number.isInteger(anyOpts.effort) || anyOpts.effort < 0 || anyOpts.effort > 6)) {
11731
+ throw new Error(`Expected integer between 0 and 6 for effort but received ${anyOpts.effort} of type ${typeof anyOpts.effort}`);
11732
+ }
11733
+ if (anyOpts?.preset !== void 0 && !["default", "photo", "picture", "drawing", "icon", "text"].includes(anyOpts.preset)) {
11734
+ throw new Error(
11735
+ `Expected one of: default, photo, picture, drawing, icon, text for preset but received ${anyOpts.preset} of type ${typeof anyOpts.preset}`
11736
+ );
11737
+ }
11738
+ this.outputOptions = {
11739
+ ...this.outputOptions,
11740
+ ...options?.force === false ? {} : { format: "webp" },
11741
+ ...options?.quality !== void 0 ? { quality: options.quality } : {},
11742
+ ...options?.lossless !== void 0 ? { lossless: options.lossless } : {}
11743
+ };
11744
+ return this;
11745
+ }
11746
+ heif(options) {
11747
+ this.validateQuality(options?.quality);
11748
+ if (options?.compression !== void 0 && !["av1", "hevc"].includes(options.compression)) {
11749
+ throw new Error(`Expected one of: av1, hevc for compression but received ${options.compression} of type ${typeof options.compression}`);
11750
+ }
11751
+ const anyOpts = options;
11752
+ if (anyOpts?.lossless !== void 0 && typeof anyOpts.lossless !== "boolean") {
11753
+ throw new Error(`Expected boolean for lossless but received ${anyOpts.lossless} of type ${typeof anyOpts.lossless}`);
11754
+ }
11755
+ if (anyOpts?.chromaSubsampling !== void 0 && typeof anyOpts.chromaSubsampling !== "string") {
11756
+ throw new Error(`Expected one of: 4:2:0, 4:4:4 for chromaSubsampling but received ${anyOpts.chromaSubsampling} of type ${typeof anyOpts.chromaSubsampling}`);
11757
+ }
11758
+ if (anyOpts?.bitdepth !== void 0 && ![8, 10, 12].includes(anyOpts.bitdepth)) {
11759
+ throw new Error(`Expected 8, 10 or 12 for bitdepth but received ${anyOpts.bitdepth} of type ${typeof anyOpts.bitdepth}`);
11760
+ }
11761
+ if (anyOpts?.effort !== void 0 && (!Number.isInteger(anyOpts.effort) || anyOpts.effort < 0 || anyOpts.effort > 9)) {
11762
+ throw new Error(`Expected integer between 0 and 9 for effort but received ${anyOpts.effort} of type ${typeof anyOpts.effort}`);
11763
+ }
11764
+ this.outputOptions = {
11765
+ ...this.outputOptions,
11766
+ ...options?.force === false ? {} : { format: "heif" },
11767
+ ...options?.quality !== void 0 ? { quality: options.quality } : {},
11768
+ ...options?.compression !== void 0 ? { compression: options.compression } : {},
11769
+ ...options?.lossless !== void 0 ? { lossless: options.lossless } : {}
11770
+ };
11771
+ return this;
11772
+ }
11773
+ heic(options) {
11774
+ this.validateQuality(options?.quality);
11775
+ this.outputOptions = {
11776
+ ...this.outputOptions,
11777
+ ...options?.force === false ? {} : { format: "heic" },
11778
+ compression: options?.compression ?? "hevc",
11779
+ ...options?.quality !== void 0 ? { quality: options.quality } : {},
11780
+ ...options?.lossless !== void 0 ? { lossless: options.lossless } : {}
11781
+ };
11782
+ return this;
11783
+ }
11784
+ avif(options) {
11785
+ this.validateQuality(options?.quality);
11786
+ const anyOpts = options;
11787
+ if (anyOpts?.lossless !== void 0 && typeof anyOpts.lossless !== "boolean") {
11788
+ throw new Error(`Expected boolean for lossless but received ${anyOpts.lossless} of type ${typeof anyOpts.lossless}`);
11789
+ }
11790
+ if (anyOpts?.chromaSubsampling !== void 0 && typeof anyOpts.chromaSubsampling !== "string") {
11791
+ throw new Error(`Expected one of: 4:2:0, 4:4:4 for chromaSubsampling but received ${anyOpts.chromaSubsampling} of type ${typeof anyOpts.chromaSubsampling}`);
11792
+ }
11793
+ if (anyOpts?.bitdepth !== void 0 && ![8, 10, 12].includes(anyOpts.bitdepth)) {
11794
+ throw new Error(`Expected 8, 10 or 12 for bitdepth but received ${anyOpts.bitdepth} of type ${typeof anyOpts.bitdepth}`);
11795
+ }
11796
+ if (anyOpts?.effort !== void 0 && (!Number.isInteger(anyOpts.effort) || anyOpts.effort < 0 || anyOpts.effort > 9)) {
11797
+ throw new Error(`Expected integer between 0 and 9 for effort but received ${anyOpts.effort} of type ${typeof anyOpts.effort}`);
11798
+ }
11799
+ this.outputOptions = {
11800
+ ...this.outputOptions,
11801
+ ...options?.force === false ? {} : { format: "avif" },
11802
+ compression: "av1",
11803
+ ...options?.quality !== void 0 ? { quality: options.quality } : {},
11804
+ ...options?.lossless !== void 0 ? { lossless: options.lossless } : {}
11805
+ };
11806
+ return this;
11807
+ }
11808
+ gif(options) {
11809
+ const anyOpts = options;
11810
+ if (anyOpts?.reuse !== void 0 && typeof anyOpts.reuse !== "boolean") {
11811
+ throw new Error(`Expected boolean for gifReuse but received ${anyOpts.reuse} of type ${typeof anyOpts.reuse}`);
11812
+ }
11813
+ const prog = anyOpts?.progressive;
11814
+ if (prog !== void 0 && typeof prog !== "boolean") {
11815
+ throw new Error(`Expected boolean for gifProgressive but received ${prog} of type ${typeof prog}`);
11816
+ }
11817
+ const colours = anyOpts?.colours ?? anyOpts?.colors;
11818
+ if (colours !== void 0 && (!Number.isInteger(colours) || colours < 2 || colours > 256)) {
11819
+ throw new Error(`Expected integer between 2 and 256 for colours but received ${colours} of type ${typeof colours}`);
11820
+ }
11821
+ if (anyOpts?.effort !== void 0 && (!Number.isInteger(anyOpts.effort) || anyOpts.effort < 1 || anyOpts.effort > 10)) {
11822
+ throw new Error(`Expected integer between 1 and 10 for effort but received ${anyOpts.effort} of type ${typeof anyOpts.effort}`);
11823
+ }
11824
+ if (anyOpts?.dither !== void 0 && (typeof anyOpts.dither !== "number" || Number.isNaN(anyOpts.dither) || anyOpts.dither < 0 || anyOpts.dither > 1)) {
11825
+ throw new Error(`Expected number between 0.0 and 1.0 for dither but received ${anyOpts.dither} of type ${typeof anyOpts.dither}`);
11826
+ }
11827
+ if (anyOpts?.interFrameMaxError !== void 0 && (typeof anyOpts.interFrameMaxError !== "number" || Number.isNaN(anyOpts.interFrameMaxError) || anyOpts.interFrameMaxError < 0 || anyOpts.interFrameMaxError > 32)) {
11828
+ throw new Error(`Expected number between 0.0 and 32.0 for interFrameMaxError but received ${anyOpts.interFrameMaxError} of type ${typeof anyOpts.interFrameMaxError}`);
11829
+ }
11830
+ if (anyOpts?.interPaletteMaxError !== void 0 && (typeof anyOpts.interPaletteMaxError !== "number" || Number.isNaN(anyOpts.interPaletteMaxError) || anyOpts.interPaletteMaxError < 0 || anyOpts.interPaletteMaxError > 256)) {
11831
+ throw new Error(`Expected number between 0.0 and 256.0 for interPaletteMaxError but received ${anyOpts.interPaletteMaxError} of type ${typeof anyOpts.interPaletteMaxError}`);
11832
+ }
11833
+ if (options?.loop !== void 0 && (!Number.isInteger(options.loop) || options.loop < 0 || options.loop > 65535)) {
11834
+ throw new Error(`Expected integer between 0 and 65535 for loop but received ${options.loop} of type ${typeof options.loop}`);
11835
+ }
11836
+ if (options?.delay !== void 0) {
11837
+ const isValidDelay = Number.isInteger(options.delay) && options.delay >= 0 && options.delay <= 65535 || Array.isArray(options.delay) && options.delay.every((d) => Number.isInteger(d) && d >= 0 && d <= 65535);
11838
+ if (!isValidDelay) {
11839
+ throw new Error(
11840
+ `Expected integer or an array of integers between 0 and 65535 for delay but received ${options.delay} of type ${typeof options.delay}`
11841
+ );
11842
+ }
11843
+ }
11844
+ this.outputOptions = {
11845
+ ...this.outputOptions,
11846
+ ...options?.force === false ? {} : { format: "gif" },
11847
+ ...options?.pageHeight !== void 0 ? { pageHeight: options.pageHeight } : {},
11848
+ ...options?.delay !== void 0 ? { delay: options.delay } : {},
11849
+ ...options?.loop !== void 0 ? { loop: options.loop } : {}
11850
+ };
11851
+ return this;
11852
+ }
11853
+ ppm() {
11854
+ this.outputOptions = { ...this.outputOptions, format: "ppm" };
11855
+ return this;
11856
+ }
11857
+ pgm() {
11858
+ this.outputOptions = { ...this.outputOptions, format: "pgm" };
11859
+ return this;
11860
+ }
11861
+ pbm() {
11862
+ this.outputOptions = { ...this.outputOptions, format: "pbm" };
11863
+ return this;
11864
+ }
11865
+ bmp() {
11866
+ this.outputOptions = { ...this.outputOptions, format: "bmp" };
11867
+ return this;
11868
+ }
11869
+ tiff(options) {
11870
+ this.validateQuality(options?.quality);
11871
+ const anyOpts = options;
11872
+ if (anyOpts?.predictor !== void 0 && !["none", "horizontal", "float"].includes(anyOpts.predictor)) {
11873
+ throw new Error(`Expected one of: none, horizontal, float for predictor but received ${anyOpts.predictor} of type ${typeof anyOpts.predictor}`);
11874
+ }
11875
+ for (const [k, label] of [
11876
+ ["pyramid", "tiffPyramid"],
11877
+ ["tile", "tiffTile"],
11878
+ ["miniswhite", "tiffMiniswhite"]
11879
+ ]) {
11880
+ if (anyOpts?.[k] !== void 0 && typeof anyOpts[k] !== "boolean") {
11881
+ throw new Error(`Expected boolean for ${label} but received ${anyOpts[k]} of type ${typeof anyOpts[k]}`);
11882
+ }
11883
+ }
11884
+ if (anyOpts?.tileWidth !== void 0 && (!Number.isInteger(anyOpts.tileWidth) || anyOpts.tileWidth <= 0)) {
11885
+ throw new Error(`Expected integer greater than zero for tileWidth but received ${anyOpts.tileWidth} of type ${typeof anyOpts.tileWidth}`);
11886
+ }
11887
+ if (anyOpts?.tileHeight !== void 0 && (!Number.isInteger(anyOpts.tileHeight) || anyOpts.tileHeight <= 0)) {
11888
+ throw new Error(`Expected integer greater than zero for tileHeight but received ${anyOpts.tileHeight} of type ${typeof anyOpts.tileHeight}`);
11889
+ }
11890
+ if (anyOpts?.xres !== void 0 && (typeof anyOpts.xres !== "number" || Number.isNaN(anyOpts.xres) || anyOpts.xres <= 0)) {
11891
+ throw new Error(`Expected number greater than zero for xres but received ${anyOpts.xres} of type ${typeof anyOpts.xres}`);
11892
+ }
11893
+ if (anyOpts?.yres !== void 0 && (typeof anyOpts.yres !== "number" || Number.isNaN(anyOpts.yres) || anyOpts.yres <= 0)) {
11894
+ throw new Error(`Expected number greater than zero for yres but received ${anyOpts.yres} of type ${typeof anyOpts.yres}`);
11895
+ }
11896
+ if (anyOpts?.resolutionUnit !== void 0 && !["inch", "cm"].includes(anyOpts.resolutionUnit)) {
11897
+ throw new Error(`Expected one of: inch, cm for resolutionUnit but received ${anyOpts.resolutionUnit} of type ${typeof anyOpts.resolutionUnit}`);
11898
+ }
11899
+ if (anyOpts?.compression !== void 0 && !["none", "jpeg", "deflate", "packbits", "ccittfax4", "lzw", "webp", "zstd", "jp2k"].includes(anyOpts.compression)) {
11900
+ throw new Error(
11901
+ `Expected one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k for compression but received ${anyOpts.compression} of type ${typeof anyOpts.compression}`
11902
+ );
11903
+ }
11904
+ if (anyOpts?.bitdepth !== void 0 && ![1, 2, 4, 8].includes(anyOpts.bitdepth)) {
11905
+ throw new Error(`Expected 1, 2, 4 or 8 for bitdepth but received ${anyOpts.bitdepth} of type ${typeof anyOpts.bitdepth}`);
11906
+ }
11907
+ this.outputOptions = {
11908
+ ...this.outputOptions,
11909
+ ...options?.force === false ? {} : { format: "tiff" },
11910
+ ...options?.quality !== void 0 ? { quality: options.quality } : {}
11911
+ };
11912
+ return this;
11913
+ }
11914
+ raw(options) {
11915
+ if (options?.depth !== void 0 && !["char", "uchar", "short", "ushort", "int", "uint", "float", "complex", "double", "dpcomplex"].includes(options.depth)) {
11916
+ throw new Error(
11917
+ `Expected one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex for depth but received ${options.depth} of type ${typeof options.depth}`
11918
+ );
11919
+ }
11920
+ this.outputOptions = {
11921
+ ...this.outputOptions,
11922
+ format: "raw",
11923
+ ...options?.depth !== void 0 ? { rawDepth: options.depth } : {}
11924
+ };
11925
+ return this;
11926
+ }
11927
+ toFormat(format, options) {
11928
+ const rawFmt = typeof format === "object" && format !== null ? format.id : String(format);
11929
+ const lower = rawFmt.toLowerCase();
11930
+ const norm = lower === "jpg" || lower === "jpe" ? "jpeg" : lower === "tif" ? "tiff" : lower;
11931
+ const validFormats = [
11932
+ "jpeg",
11933
+ "png",
11934
+ "webp",
11935
+ "tiff",
11936
+ "heif",
11937
+ "heic",
11938
+ "avif",
11939
+ "gif",
11940
+ "svg",
11941
+ "pdf",
11942
+ "ppm",
11943
+ "pgm",
11944
+ "pbm",
11945
+ "bmp",
11946
+ "raw",
11947
+ "jp2",
11948
+ "jxl"
11949
+ ];
11950
+ if (!validFormats.includes(norm)) {
11951
+ throw new Error(`Expected one of: ${validFormats.join(", ")} for format but received ${rawFmt}`);
11952
+ }
11953
+ this.validateQuality(options?.quality);
11954
+ this.validateCompressionLevel(options?.compressionLevel);
11955
+ this.outputOptions = {
11956
+ ...this.outputOptions,
11957
+ ...options?.force === false ? {} : { format: norm },
11958
+ ...options?.quality !== void 0 ? { quality: options.quality } : {},
11959
+ ...options?.compression !== void 0 ? { compression: options.compression } : {},
11960
+ ...options?.compressionLevel !== void 0 ? { compressionLevel: options.compressionLevel } : {},
11961
+ ...options?.lossless !== void 0 ? { lossless: options.lossless } : {}
11962
+ };
11963
+ return this;
11964
+ }
11965
+ toBufferWithObjectSync() {
11966
+ let img = this.evaluateImage();
11967
+ if (this.outputOptions.format === "raw" && (img.channels === 2 || img.channels === 1 && this.nodes.some((n) => n.kind === "removeAlpha" || n.kind === "flatten")) && !this.nodes.some(
11968
+ (n) => n.kind === "toColorspace" && n.space === "b-w" || n.kind === "grayscale" || n.kind === "joinChannel" || n.kind === "extractChannel"
11969
+ )) {
11970
+ img = { ...img, space: "srgb", channels: img.hasAlpha ? 4 : 3 };
11971
+ }
11972
+ const encoded = encodeImage(img, this.outputOptions);
11973
+ const outBuf = outputBytes(encoded.data);
11974
+ return {
11975
+ data: outBuf,
11976
+ info: {
11977
+ format: encoded.format,
11978
+ width: img.width,
11979
+ height: img.height,
11980
+ channels: encoded.channels,
11981
+ ...encoded.format === "raw" ? { depth: this.outputOptions.rawDepth ?? img.depth } : {},
11982
+ premultiplied: Boolean(img.wasPremultiplied),
11983
+ ...img.pageHeight !== void 0 ? { pageHeight: img.pageHeight } : {},
11984
+ ...img.pageHeight !== void 0 && (img.sourcePages ?? img.pages) !== void 0 ? { pages: img.sourcePages ?? img.pages } : {},
11985
+ ...img.trimOffsetLeft !== void 0 ? { trimOffsetLeft: img.trimOffsetLeft } : {},
11986
+ ...img.trimOffsetTop !== void 0 ? { trimOffsetTop: img.trimOffsetTop } : {},
11987
+ ...img.textAutofitDpi !== void 0 ? { textAutofitDpi: img.textAutofitDpi } : {},
11988
+ size: encoded.data.byteLength
11989
+ }
11990
+ };
11991
+ }
11992
+ toBufferSync() {
11993
+ return this.toBufferWithObjectSync().data;
11994
+ }
11995
+ async toFile(fileOut, callback) {
11996
+ try {
11997
+ if (!fileOut || typeof fileOut !== "string") {
11998
+ throw new Error("Missing output file path");
11999
+ }
12000
+ if (this.inputFilePath && normalizePath(fileOut) === normalizePath(this.inputFilePath)) {
12001
+ throw new Error("Cannot use same file for input and output");
12002
+ }
12003
+ const filesystem = this.inputOptions?.filesystem;
12004
+ if (!filesystem) throw new Error("File outputs require an explicit filesystem");
12005
+ const prevFormat = this.outputOptions.format;
12006
+ const inferred = prevFormat ?? inferFormatFromPath(fileOut);
12007
+ if (!prevFormat && inferred) {
12008
+ this.outputOptions = { ...this.outputOptions, format: inferred };
12009
+ }
12010
+ try {
12011
+ await this.waitForStreamInput();
12012
+ const res = this.toBufferWithObjectSync();
12013
+ await filesystem.writeFile(fileOut, res.data);
12014
+ if (callback) callback(null, res.info);
12015
+ return res.info;
12016
+ } finally {
12017
+ if (!prevFormat && inferred) {
12018
+ const { format: _omit, ...rest } = this.outputOptions;
12019
+ this.outputOptions = rest;
12020
+ }
12021
+ }
12022
+ } catch (err) {
12023
+ if (callback) callback(err);
12024
+ throw err;
12025
+ }
12026
+ }
12027
+ async toBuffer(optionsOrCallback) {
12028
+ const cb = typeof optionsOrCallback === "function" ? optionsOrCallback : void 0;
12029
+ const options = typeof optionsOrCallback === "object" && optionsOrCallback !== null ? optionsOrCallback : void 0;
12030
+ try {
12031
+ await this.waitForStreamInput();
12032
+ const res = this.toBufferWithObjectSync();
12033
+ if (cb) cb(null, res.data, res.info);
12034
+ if (options?.resolveWithObject) {
12035
+ return res;
12036
+ }
12037
+ return res.data;
12038
+ } catch (err) {
12039
+ if (cb) cb(err);
12040
+ throw err;
12041
+ }
12042
+ }
12043
+ };
12044
+ function sharp(input, options) {
12045
+ return new SharpInstance(input, options);
12046
+ }
12047
+ Object.assign(sharp, {
12048
+ align: {
12049
+ left: "low",
12050
+ top: "low",
12051
+ low: "low",
12052
+ center: "centre",
12053
+ centre: "centre",
12054
+ right: "high",
12055
+ bottom: "high",
12056
+ high: "high"
12057
+ },
12058
+ position: {
12059
+ top: 1,
12060
+ right: 2,
12061
+ bottom: 3,
12062
+ left: 4,
12063
+ "right top": 5,
12064
+ "right bottom": 6,
12065
+ "left bottom": 7,
12066
+ "left top": 8
12067
+ },
12068
+ blend: {
12069
+ clear: "clear",
12070
+ source: "source",
12071
+ over: "over",
12072
+ in: "in",
12073
+ out: "out",
12074
+ atop: "atop",
12075
+ dest: "dest",
12076
+ "dest-over": "dest-over",
12077
+ "dest-in": "dest-in",
12078
+ "dest-out": "dest-out",
12079
+ "dest-atop": "dest-atop",
12080
+ xor: "xor",
12081
+ add: "add",
12082
+ saturate: "saturate",
12083
+ multiply: "multiply",
12084
+ screen: "screen",
12085
+ overlay: "overlay",
12086
+ darken: "darken",
12087
+ lighten: "lighten",
12088
+ "colour-dodge": "colour-dodge",
12089
+ "color-dodge": "colour-dodge",
12090
+ "colour-burn": "colour-burn",
12091
+ "color-burn": "colour-burn",
12092
+ "hard-light": "hard-light",
12093
+ "soft-light": "soft-light",
12094
+ difference: "difference",
12095
+ exclusion: "exclusion"
12096
+ },
12097
+ queue: new EventEmitter(),
12098
+ gravity: {
12099
+ center: 0,
12100
+ centre: 0,
12101
+ north: 1,
12102
+ east: 2,
12103
+ south: 3,
12104
+ west: 4,
12105
+ northeast: 5,
12106
+ southeast: 6,
12107
+ southwest: 7,
12108
+ northwest: 8
12109
+ },
12110
+ fit: {
12111
+ contain: "contain",
12112
+ cover: "cover",
12113
+ fill: "fill",
12114
+ inside: "inside",
12115
+ outside: "outside"
12116
+ },
12117
+ kernel: {
12118
+ nearest: "nearest",
12119
+ linear: "linear",
12120
+ cubic: "cubic",
12121
+ mitchell: "mitchell",
12122
+ lanczos2: "lanczos2",
12123
+ lanczos3: "lanczos3",
12124
+ mks2013: "mks2013",
12125
+ mks2021: "mks2021"
12126
+ },
12127
+ bool: {
12128
+ and: "and",
12129
+ or: "or",
12130
+ eor: "eor"
12131
+ },
12132
+ strategy: {
12133
+ entropy: 16,
12134
+ attention: 17
12135
+ },
12136
+ colourspace: {
12137
+ multiband: "multiband",
12138
+ "b-w": "b-w",
12139
+ bw: "b-w",
12140
+ cmyk: "cmyk",
12141
+ srgb: "srgb"
12142
+ },
12143
+ colorspace: {
12144
+ multiband: "multiband",
12145
+ "b-w": "b-w",
12146
+ bw: "b-w",
12147
+ cmyk: "cmyk",
12148
+ srgb: "srgb"
12149
+ },
12150
+ interpolators: {
12151
+ nearest: "nearest",
12152
+ bilinear: "bilinear",
12153
+ bicubic: "bicubic",
12154
+ locallyBoundedBicubic: "lbb",
12155
+ nohalo: "nohalo",
12156
+ vertexSplitQuadraticBasisSpline: "vsqbs"
12157
+ },
12158
+ format: Object.fromEntries(
12159
+ ["jpeg", "png", "webp", "tiff", "heif", "heic", "avif", "gif", "svg", "pdf", "ppm", "pgm", "pbm", "bmp", "raw"].map(
12160
+ (id) => [
12161
+ id,
12162
+ {
12163
+ id,
12164
+ input: { file: true, buffer: true, stream: true },
12165
+ output: { file: true, buffer: true, stream: true }
12166
+ }
12167
+ ]
12168
+ )
12169
+ ),
12170
+ cache: /* @__PURE__ */ (() => {
12171
+ let memMax = 50;
12172
+ let filesMax = 20;
12173
+ let itemsMax = 100;
12174
+ return (options) => {
12175
+ if (options === false) {
12176
+ memMax = 0;
12177
+ filesMax = 0;
12178
+ itemsMax = 0;
12179
+ } else if (options === true) {
12180
+ memMax = 50;
12181
+ filesMax = 20;
12182
+ itemsMax = 100;
12183
+ } else if (options && typeof options === "object") {
12184
+ if (typeof options.memory === "number") memMax = options.memory;
12185
+ if (typeof options.files === "number") filesMax = options.files;
12186
+ if (typeof options.items === "number") itemsMax = options.items;
12187
+ }
12188
+ return {
12189
+ memory: { current: 0, high: 0, max: memMax },
12190
+ files: { current: 0, max: filesMax },
12191
+ items: { current: 0, max: itemsMax }
12192
+ };
12193
+ };
12194
+ })(),
12195
+ concurrency: /* @__PURE__ */ (() => {
12196
+ let threads = 4;
12197
+ return (n) => {
12198
+ if (typeof n === "number" && n > 0) threads = Math.floor(n);
12199
+ return threads;
12200
+ };
12201
+ })(),
12202
+ counters: () => ({ queue: 0, process: 0 }),
12203
+ simd: /* @__PURE__ */ (() => {
12204
+ let enabled = true;
12205
+ return (enable) => {
12206
+ if (typeof enable === "boolean") enabled = enable;
12207
+ return enabled;
12208
+ };
12209
+ })(),
12210
+ block: (_options) => {
12211
+ },
12212
+ unblock: (_options) => {
12213
+ },
12214
+ versions: {
12215
+ vips: "8.16.1",
12216
+ sharp: "0.34.5"
12217
+ }
12218
+ });
12219
+
9482
12220
  export {
9483
12221
  parseColor,
9484
12222
  decodeJpegImage,
@@ -9513,39 +12251,9 @@ export {
9513
12251
  computeImageStatsSteps,
9514
12252
  flipImage,
9515
12253
  flopImage,
9516
- applyExifOrientation,
9517
12254
  rotateImage,
9518
12255
  extractImage,
9519
- trimImage,
9520
12256
  extendImage,
9521
- compositeImage,
9522
- booleanImage,
9523
12257
  grayscaleImage,
9524
- flattenImage,
9525
- unflattenImage,
9526
- negateImage,
9527
- modulateImage,
9528
- tintImage,
9529
- gammaImage,
9530
- linearImage,
9531
- normalizeImage,
9532
- thresholdImage,
9533
- premultiplyRgbaImage,
9534
- unpremultiplyRgbaImage,
9535
- blurImage,
9536
- sharpenImage,
9537
- medianImage,
9538
- convolveImage,
9539
- ensureAlphaImage,
9540
- removeAlphaImage,
9541
- extractChannelImage,
9542
- recombImage,
9543
- toColorspaceImage,
9544
- bandboolImage,
9545
- joinChannelImage,
9546
- claheImage,
9547
- affineImage,
9548
- computeImageStats,
9549
- dilateImage,
9550
- erodeImage
12258
+ negateImage
9551
12259
  };