@rowsncolumns/toolkit 24.4.1

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 (456) hide show
  1. package/LICENSE.md +100 -0
  2. package/Readme.md +27 -0
  3. package/dist/cjs/autofilter-condition.d.ts +43 -0
  4. package/dist/cjs/autofilter-condition.d.ts.map +1 -0
  5. package/dist/cjs/autofilter-condition.js +155 -0
  6. package/dist/cjs/csv-export.d.ts +49 -0
  7. package/dist/cjs/csv-export.d.ts.map +1 -0
  8. package/dist/cjs/csv-export.js +142 -0
  9. package/dist/cjs/csv-import-worker.d.ts +16 -0
  10. package/dist/cjs/csv-import-worker.d.ts.map +1 -0
  11. package/dist/cjs/csv-import-worker.js +60 -0
  12. package/dist/cjs/csv-import.d.ts +38 -0
  13. package/dist/cjs/csv-import.d.ts.map +1 -0
  14. package/dist/cjs/csv-import.js +166 -0
  15. package/dist/cjs/csv-parser/helpers.d.ts +14 -0
  16. package/dist/cjs/csv-parser/helpers.d.ts.map +1 -0
  17. package/dist/cjs/csv-parser/helpers.js +145 -0
  18. package/dist/cjs/csv-parser/types.d.ts +66 -0
  19. package/dist/cjs/csv-parser/types.d.ts.map +1 -0
  20. package/dist/cjs/csv-parser/types.js +14 -0
  21. package/dist/cjs/csv-parser/worker.d.ts +2 -0
  22. package/dist/cjs/csv-parser/worker.d.ts.map +1 -0
  23. package/dist/cjs/csv-parser/worker.js +200 -0
  24. package/dist/cjs/excel-export.d.ts +11 -0
  25. package/dist/cjs/excel-export.d.ts.map +1 -0
  26. package/dist/cjs/excel-export.js +22 -0
  27. package/dist/cjs/excel-import-session.d.ts +51 -0
  28. package/dist/cjs/excel-import-session.d.ts.map +1 -0
  29. package/dist/cjs/excel-import-session.js +307 -0
  30. package/dist/cjs/excel-import-worker.d.ts +7 -0
  31. package/dist/cjs/excel-import-worker.d.ts.map +1 -0
  32. package/dist/cjs/excel-import-worker.js +119 -0
  33. package/dist/cjs/excel-parser/builtin-numfmts.d.ts +24 -0
  34. package/dist/cjs/excel-parser/builtin-numfmts.d.ts.map +1 -0
  35. package/dist/cjs/excel-parser/builtin-numfmts.js +63 -0
  36. package/dist/cjs/excel-parser/cfb-decryptor.d.ts +53 -0
  37. package/dist/cjs/excel-parser/cfb-decryptor.d.ts.map +1 -0
  38. package/dist/cjs/excel-parser/cfb-decryptor.js +553 -0
  39. package/dist/cjs/excel-parser/cfb-encryptor.d.ts +23 -0
  40. package/dist/cjs/excel-parser/cfb-encryptor.d.ts.map +1 -0
  41. package/dist/cjs/excel-parser/cfb-encryptor.js +200 -0
  42. package/dist/cjs/excel-parser/dv-cell-stamp.d.ts +29 -0
  43. package/dist/cjs/excel-parser/dv-cell-stamp.d.ts.map +1 -0
  44. package/dist/cjs/excel-parser/dv-cell-stamp.js +239 -0
  45. package/dist/cjs/excel-parser/helpers.d.ts +28 -0
  46. package/dist/cjs/excel-parser/helpers.d.ts.map +1 -0
  47. package/dist/cjs/excel-parser/helpers.js +188 -0
  48. package/dist/cjs/excel-parser/interface.d.ts +179 -0
  49. package/dist/cjs/excel-parser/interface.d.ts.map +1 -0
  50. package/dist/cjs/excel-parser/interface.js +1 -0
  51. package/dist/cjs/excel-parser/plugins/base/index.d.ts +31 -0
  52. package/dist/cjs/excel-parser/plugins/base/index.d.ts.map +1 -0
  53. package/dist/cjs/excel-parser/plugins/base/index.js +101 -0
  54. package/dist/cjs/excel-parser/plugins/ods/conditional-formatting.d.ts +16 -0
  55. package/dist/cjs/excel-parser/plugins/ods/conditional-formatting.d.ts.map +1 -0
  56. package/dist/cjs/excel-parser/plugins/ods/conditional-formatting.js +488 -0
  57. package/dist/cjs/excel-parser/plugins/ods/data-validations.d.ts +15 -0
  58. package/dist/cjs/excel-parser/plugins/ods/data-validations.d.ts.map +1 -0
  59. package/dist/cjs/excel-parser/plugins/ods/data-validations.js +353 -0
  60. package/dist/cjs/excel-parser/plugins/ods/formula.d.ts +8 -0
  61. package/dist/cjs/excel-parser/plugins/ods/formula.d.ts.map +1 -0
  62. package/dist/cjs/excel-parser/plugins/ods/formula.js +82 -0
  63. package/dist/cjs/excel-parser/plugins/ods/index.d.ts +122 -0
  64. package/dist/cjs/excel-parser/plugins/ods/index.d.ts.map +1 -0
  65. package/dist/cjs/excel-parser/plugins/ods/index.js +3642 -0
  66. package/dist/cjs/excel-parser/plugins/ods/sparklines.d.ts +25 -0
  67. package/dist/cjs/excel-parser/plugins/ods/sparklines.d.ts.map +1 -0
  68. package/dist/cjs/excel-parser/plugins/ods/sparklines.js +221 -0
  69. package/dist/cjs/excel-parser/plugins/ods/styles.d.ts +60 -0
  70. package/dist/cjs/excel-parser/plugins/ods/styles.d.ts.map +1 -0
  71. package/dist/cjs/excel-parser/plugins/ods/styles.js +808 -0
  72. package/dist/cjs/excel-parser/plugins/ods/types.d.ts +7 -0
  73. package/dist/cjs/excel-parser/plugins/ods/types.d.ts.map +1 -0
  74. package/dist/cjs/excel-parser/plugins/ods/types.js +1 -0
  75. package/dist/cjs/excel-parser/plugins/xls/index.d.ts +5 -0
  76. package/dist/cjs/excel-parser/plugins/xls/index.d.ts.map +1 -0
  77. package/dist/cjs/excel-parser/plugins/xls/index.js +19 -0
  78. package/dist/cjs/excel-parser/plugins/xlsb/biff-record-reader.d.ts +13 -0
  79. package/dist/cjs/excel-parser/plugins/xlsb/biff-record-reader.d.ts.map +1 -0
  80. package/dist/cjs/excel-parser/plugins/xlsb/biff-record-reader.js +49 -0
  81. package/dist/cjs/excel-parser/plugins/xlsb/index.d.ts +117 -0
  82. package/dist/cjs/excel-parser/plugins/xlsb/index.d.ts.map +1 -0
  83. package/dist/cjs/excel-parser/plugins/xlsb/index.js +2972 -0
  84. package/dist/cjs/excel-parser/plugins/xlsb/rgce-parser.d.ts +18 -0
  85. package/dist/cjs/excel-parser/plugins/xlsb/rgce-parser.d.ts.map +1 -0
  86. package/dist/cjs/excel-parser/plugins/xlsb/rgce-parser.js +527 -0
  87. package/dist/cjs/excel-parser/plugins/xlsm/index.d.ts +5 -0
  88. package/dist/cjs/excel-parser/plugins/xlsm/index.d.ts.map +1 -0
  89. package/dist/cjs/excel-parser/plugins/xlsm/index.js +10 -0
  90. package/dist/cjs/excel-parser/plugins/xlsx/charts.d.ts +60 -0
  91. package/dist/cjs/excel-parser/plugins/xlsx/charts.d.ts.map +1 -0
  92. package/dist/cjs/excel-parser/plugins/xlsx/charts.js +2178 -0
  93. package/dist/cjs/excel-parser/plugins/xlsx/conditional-formatting.d.ts +18 -0
  94. package/dist/cjs/excel-parser/plugins/xlsx/conditional-formatting.d.ts.map +1 -0
  95. package/dist/cjs/excel-parser/plugins/xlsx/conditional-formatting.js +620 -0
  96. package/dist/cjs/excel-parser/plugins/xlsx/data-validations.d.ts +4 -0
  97. package/dist/cjs/excel-parser/plugins/xlsx/data-validations.d.ts.map +1 -0
  98. package/dist/cjs/excel-parser/plugins/xlsx/data-validations.js +515 -0
  99. package/dist/cjs/excel-parser/plugins/xlsx/drawing.d.ts +39 -0
  100. package/dist/cjs/excel-parser/plugins/xlsx/drawing.d.ts.map +1 -0
  101. package/dist/cjs/excel-parser/plugins/xlsx/drawing.js +941 -0
  102. package/dist/cjs/excel-parser/plugins/xlsx/index.d.ts +320 -0
  103. package/dist/cjs/excel-parser/plugins/xlsx/index.d.ts.map +1 -0
  104. package/dist/cjs/excel-parser/plugins/xlsx/index.js +6056 -0
  105. package/dist/cjs/excel-parser/plugins/xlsx/numfmt.d.ts +2 -0
  106. package/dist/cjs/excel-parser/plugins/xlsx/numfmt.d.ts.map +1 -0
  107. package/dist/cjs/excel-parser/plugins/xlsx/numfmt.js +3 -0
  108. package/dist/cjs/excel-parser/plugins/xlsx/pivots.d.ts +40 -0
  109. package/dist/cjs/excel-parser/plugins/xlsx/pivots.d.ts.map +1 -0
  110. package/dist/cjs/excel-parser/plugins/xlsx/pivots.js +342 -0
  111. package/dist/cjs/excel-parser/plugins/xlsx/relationships.d.ts +8 -0
  112. package/dist/cjs/excel-parser/plugins/xlsx/relationships.d.ts.map +1 -0
  113. package/dist/cjs/excel-parser/plugins/xlsx/relationships.js +26 -0
  114. package/dist/cjs/excel-parser/plugins/xlsx/sheet-views.d.ts +26 -0
  115. package/dist/cjs/excel-parser/plugins/xlsx/sheet-views.d.ts.map +1 -0
  116. package/dist/cjs/excel-parser/plugins/xlsx/sheet-views.js +59 -0
  117. package/dist/cjs/excel-parser/plugins/xlsx/styles.d.ts +44 -0
  118. package/dist/cjs/excel-parser/plugins/xlsx/styles.d.ts.map +1 -0
  119. package/dist/cjs/excel-parser/plugins/xlsx/styles.js +1377 -0
  120. package/dist/cjs/excel-parser/plugins/xlsx/theme.d.ts +50 -0
  121. package/dist/cjs/excel-parser/plugins/xlsx/theme.d.ts.map +1 -0
  122. package/dist/cjs/excel-parser/plugins/xlsx/theme.js +150 -0
  123. package/dist/cjs/excel-parser/plugins/xlsx/threaded-comments.d.ts +47 -0
  124. package/dist/cjs/excel-parser/plugins/xlsx/threaded-comments.d.ts.map +1 -0
  125. package/dist/cjs/excel-parser/plugins/xlsx/threaded-comments.js +141 -0
  126. package/dist/cjs/excel-parser/plugins/xlsx/value-type-detection.d.ts +44 -0
  127. package/dist/cjs/excel-parser/plugins/xlsx/value-type-detection.d.ts.map +1 -0
  128. package/dist/cjs/excel-parser/plugins/xlsx/value-type-detection.js +407 -0
  129. package/dist/cjs/excel-parser/registry.d.ts +5 -0
  130. package/dist/cjs/excel-parser/registry.d.ts.map +1 -0
  131. package/dist/cjs/excel-parser/registry.js +21 -0
  132. package/dist/cjs/excel-parser/style-registry.d.ts +51 -0
  133. package/dist/cjs/excel-parser/style-registry.d.ts.map +1 -0
  134. package/dist/cjs/excel-parser/style-registry.js +175 -0
  135. package/dist/cjs/excel-parser/theme-default.d.ts +3 -0
  136. package/dist/cjs/excel-parser/theme-default.d.ts.map +1 -0
  137. package/dist/cjs/excel-parser/theme-default.js +19 -0
  138. package/dist/cjs/excel-parser/types.d.ts +365 -0
  139. package/dist/cjs/excel-parser/types.d.ts.map +1 -0
  140. package/dist/cjs/excel-parser/types.js +59 -0
  141. package/dist/cjs/excel-parser/utils.d.ts +6 -0
  142. package/dist/cjs/excel-parser/utils.d.ts.map +1 -0
  143. package/dist/cjs/excel-parser/utils.js +30 -0
  144. package/dist/cjs/excel-parser/workbook.d.ts +51 -0
  145. package/dist/cjs/excel-parser/workbook.d.ts.map +1 -0
  146. package/dist/cjs/excel-parser/workbook.js +317 -0
  147. package/dist/cjs/excel-parser/worker.d.ts +2 -0
  148. package/dist/cjs/excel-parser/worker.d.ts.map +1 -0
  149. package/dist/cjs/excel-parser/worker.js +1149 -0
  150. package/dist/cjs/excel-parser/zip-parser-streaming.d.ts +13 -0
  151. package/dist/cjs/excel-parser/zip-parser-streaming.d.ts.map +1 -0
  152. package/dist/cjs/excel-parser/zip-parser-streaming.js +200 -0
  153. package/dist/cjs/excel-parser/zip-parser.d.ts +11 -0
  154. package/dist/cjs/excel-parser/zip-parser.d.ts.map +1 -0
  155. package/dist/cjs/excel-parser/zip-parser.js +49 -0
  156. package/dist/cjs/exporter/invalid-data-validation.d.ts +19 -0
  157. package/dist/cjs/exporter/invalid-data-validation.d.ts.map +1 -0
  158. package/dist/cjs/exporter/invalid-data-validation.js +39 -0
  159. package/dist/cjs/exporter/ods/ods-export.d.ts +26 -0
  160. package/dist/cjs/exporter/ods/ods-export.d.ts.map +1 -0
  161. package/dist/cjs/exporter/ods/ods-export.js +3714 -0
  162. package/dist/cjs/exporter/ods/sparkline-builder.d.ts +33 -0
  163. package/dist/cjs/exporter/ods/sparkline-builder.d.ts.map +1 -0
  164. package/dist/cjs/exporter/ods/sparkline-builder.js +221 -0
  165. package/dist/cjs/exporter/xlsx/chart-builder.d.ts +3 -0
  166. package/dist/cjs/exporter/xlsx/chart-builder.d.ts.map +1 -0
  167. package/dist/cjs/exporter/xlsx/chart-builder.js +1901 -0
  168. package/dist/cjs/exporter/xlsx/chart-templates.d.ts +1781 -0
  169. package/dist/cjs/exporter/xlsx/chart-templates.d.ts.map +1 -0
  170. package/dist/cjs/exporter/xlsx/chart-templates.js +1798 -0
  171. package/dist/cjs/exporter/xlsx/future-functions.d.ts +10 -0
  172. package/dist/cjs/exporter/xlsx/future-functions.d.ts.map +1 -0
  173. package/dist/cjs/exporter/xlsx/future-functions.js +264 -0
  174. package/dist/cjs/exporter/xlsx/pivot-builder.d.ts +58 -0
  175. package/dist/cjs/exporter/xlsx/pivot-builder.d.ts.map +1 -0
  176. package/dist/cjs/exporter/xlsx/pivot-builder.js +277 -0
  177. package/dist/cjs/exporter/xlsx/power-query-builder.d.ts +26 -0
  178. package/dist/cjs/exporter/xlsx/power-query-builder.d.ts.map +1 -0
  179. package/dist/cjs/exporter/xlsx/power-query-builder.js +306 -0
  180. package/dist/cjs/exporter/xlsx/slicer-builder.d.ts +11 -0
  181. package/dist/cjs/exporter/xlsx/slicer-builder.d.ts.map +1 -0
  182. package/dist/cjs/exporter/xlsx/slicer-builder.js +87 -0
  183. package/dist/cjs/exporter/xlsx/sparkline-builder.d.ts +61 -0
  184. package/dist/cjs/exporter/xlsx/sparkline-builder.d.ts.map +1 -0
  185. package/dist/cjs/exporter/xlsx/sparkline-builder.js +489 -0
  186. package/dist/cjs/exporter/xlsx/style-builder.d.ts +93 -0
  187. package/dist/cjs/exporter/xlsx/style-builder.d.ts.map +1 -0
  188. package/dist/cjs/exporter/xlsx/style-builder.js +813 -0
  189. package/dist/cjs/exporter/xlsx/threaded-comments-builder.d.ts +58 -0
  190. package/dist/cjs/exporter/xlsx/threaded-comments-builder.d.ts.map +1 -0
  191. package/dist/cjs/exporter/xlsx/threaded-comments-builder.js +189 -0
  192. package/dist/cjs/exporter/xlsx/xlsx-export.d.ts +121 -0
  193. package/dist/cjs/exporter/xlsx/xlsx-export.d.ts.map +1 -0
  194. package/dist/cjs/exporter/xlsx/xlsx-export.js +4596 -0
  195. package/dist/cjs/helpers/theme-xml-generator.d.ts +8 -0
  196. package/dist/cjs/helpers/theme-xml-generator.d.ts.map +1 -0
  197. package/dist/cjs/helpers/theme-xml-generator.js +33 -0
  198. package/dist/cjs/helpers.d.ts +34 -0
  199. package/dist/cjs/helpers.d.ts.map +1 -0
  200. package/dist/cjs/helpers.js +189 -0
  201. package/dist/cjs/index.d.ts +16 -0
  202. package/dist/cjs/index.d.ts.map +1 -0
  203. package/dist/cjs/index.js +15 -0
  204. package/dist/cjs/indexed-colors.d.ts +2 -0
  205. package/dist/cjs/indexed-colors.d.ts.map +1 -0
  206. package/dist/cjs/indexed-colors.js +75 -0
  207. package/dist/cjs/ods-export.d.ts +24 -0
  208. package/dist/cjs/ods-export.d.ts.map +1 -0
  209. package/dist/cjs/ods-export.js +23 -0
  210. package/dist/cjs/parse.d.ts +24 -0
  211. package/dist/cjs/parse.d.ts.map +1 -0
  212. package/dist/cjs/parse.js +68 -0
  213. package/dist/cjs/power-query.d.ts +41 -0
  214. package/dist/cjs/power-query.d.ts.map +1 -0
  215. package/dist/cjs/power-query.js +22 -0
  216. package/dist/cjs/server.d.ts +9 -0
  217. package/dist/cjs/server.d.ts.map +1 -0
  218. package/dist/cjs/server.js +8 -0
  219. package/dist/cjs/theme1.d.ts +3 -0
  220. package/dist/cjs/theme1.d.ts.map +1 -0
  221. package/dist/cjs/theme1.js +2 -0
  222. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -0
  223. package/dist/cjs/types.d.ts +14 -0
  224. package/dist/cjs/types.d.ts.map +1 -0
  225. package/dist/cjs/types.js +14 -0
  226. package/dist/cjs/vitest.config.d.ts +3 -0
  227. package/dist/cjs/vitest.config.d.ts.map +1 -0
  228. package/dist/cjs/vitest.config.js +16 -0
  229. package/dist/esm/autofilter-condition.d.ts +43 -0
  230. package/dist/esm/autofilter-condition.d.ts.map +1 -0
  231. package/dist/esm/autofilter-condition.js +145 -0
  232. package/dist/esm/csv-export.d.ts +49 -0
  233. package/dist/esm/csv-export.d.ts.map +1 -0
  234. package/dist/esm/csv-export.js +126 -0
  235. package/dist/esm/csv-import-worker.d.ts +16 -0
  236. package/dist/esm/csv-import-worker.d.ts.map +1 -0
  237. package/dist/esm/csv-import-worker.js +60 -0
  238. package/dist/esm/csv-import.d.ts +38 -0
  239. package/dist/esm/csv-import.d.ts.map +1 -0
  240. package/dist/esm/csv-import.js +132 -0
  241. package/dist/esm/csv-parser/helpers.d.ts +14 -0
  242. package/dist/esm/csv-parser/helpers.d.ts.map +1 -0
  243. package/dist/esm/csv-parser/helpers.js +0 -0
  244. package/dist/esm/csv-parser/types.d.ts +66 -0
  245. package/dist/esm/csv-parser/types.d.ts.map +1 -0
  246. package/dist/esm/csv-parser/types.js +14 -0
  247. package/dist/esm/csv-parser/worker.d.ts +2 -0
  248. package/dist/esm/csv-parser/worker.d.ts.map +1 -0
  249. package/dist/esm/csv-parser/worker.js +154 -0
  250. package/dist/esm/excel-export.d.ts +11 -0
  251. package/dist/esm/excel-export.d.ts.map +1 -0
  252. package/dist/esm/excel-export.js +13 -0
  253. package/dist/esm/excel-import-session.d.ts +51 -0
  254. package/dist/esm/excel-import-session.d.ts.map +1 -0
  255. package/dist/esm/excel-import-session.js +255 -0
  256. package/dist/esm/excel-import-worker.d.ts +7 -0
  257. package/dist/esm/excel-import-worker.d.ts.map +1 -0
  258. package/dist/esm/excel-import-worker.js +116 -0
  259. package/dist/esm/excel-parser/builtin-numfmts.d.ts +24 -0
  260. package/dist/esm/excel-parser/builtin-numfmts.d.ts.map +1 -0
  261. package/dist/esm/excel-parser/builtin-numfmts.js +59 -0
  262. package/dist/esm/excel-parser/cfb-decryptor.d.ts +53 -0
  263. package/dist/esm/excel-parser/cfb-decryptor.d.ts.map +1 -0
  264. package/dist/esm/excel-parser/cfb-decryptor.js +493 -0
  265. package/dist/esm/excel-parser/cfb-encryptor.d.ts +23 -0
  266. package/dist/esm/excel-parser/cfb-encryptor.d.ts.map +1 -0
  267. package/dist/esm/excel-parser/cfb-encryptor.js +181 -0
  268. package/dist/esm/excel-parser/dv-cell-stamp.d.ts +29 -0
  269. package/dist/esm/excel-parser/dv-cell-stamp.d.ts.map +1 -0
  270. package/dist/esm/excel-parser/dv-cell-stamp.js +155 -0
  271. package/dist/esm/excel-parser/helpers.d.ts +28 -0
  272. package/dist/esm/excel-parser/helpers.d.ts.map +1 -0
  273. package/dist/esm/excel-parser/helpers.js +160 -0
  274. package/dist/esm/excel-parser/interface.d.ts +179 -0
  275. package/dist/esm/excel-parser/interface.d.ts.map +1 -0
  276. package/dist/esm/excel-parser/interface.js +1 -0
  277. package/dist/esm/excel-parser/plugins/base/index.d.ts +31 -0
  278. package/dist/esm/excel-parser/plugins/base/index.d.ts.map +1 -0
  279. package/dist/esm/excel-parser/plugins/base/index.js +64 -0
  280. package/dist/esm/excel-parser/plugins/ods/conditional-formatting.d.ts +16 -0
  281. package/dist/esm/excel-parser/plugins/ods/conditional-formatting.d.ts.map +1 -0
  282. package/dist/esm/excel-parser/plugins/ods/conditional-formatting.js +405 -0
  283. package/dist/esm/excel-parser/plugins/ods/data-validations.d.ts +15 -0
  284. package/dist/esm/excel-parser/plugins/ods/data-validations.d.ts.map +1 -0
  285. package/dist/esm/excel-parser/plugins/ods/data-validations.js +331 -0
  286. package/dist/esm/excel-parser/plugins/ods/formula.d.ts +8 -0
  287. package/dist/esm/excel-parser/plugins/ods/formula.d.ts.map +1 -0
  288. package/dist/esm/excel-parser/plugins/ods/formula.js +82 -0
  289. package/dist/esm/excel-parser/plugins/ods/index.d.ts +122 -0
  290. package/dist/esm/excel-parser/plugins/ods/index.d.ts.map +1 -0
  291. package/dist/esm/excel-parser/plugins/ods/index.js +2896 -0
  292. package/dist/esm/excel-parser/plugins/ods/sparklines.d.ts +25 -0
  293. package/dist/esm/excel-parser/plugins/ods/sparklines.d.ts.map +1 -0
  294. package/dist/esm/excel-parser/plugins/ods/sparklines.js +188 -0
  295. package/dist/esm/excel-parser/plugins/ods/styles.d.ts +60 -0
  296. package/dist/esm/excel-parser/plugins/ods/styles.d.ts.map +1 -0
  297. package/dist/esm/excel-parser/plugins/ods/styles.js +732 -0
  298. package/dist/esm/excel-parser/plugins/ods/types.d.ts +7 -0
  299. package/dist/esm/excel-parser/plugins/ods/types.d.ts.map +1 -0
  300. package/dist/esm/excel-parser/plugins/ods/types.js +1 -0
  301. package/dist/esm/excel-parser/plugins/xls/index.d.ts +5 -0
  302. package/dist/esm/excel-parser/plugins/xls/index.d.ts.map +1 -0
  303. package/dist/esm/excel-parser/plugins/xls/index.js +7 -0
  304. package/dist/esm/excel-parser/plugins/xlsb/biff-record-reader.d.ts +13 -0
  305. package/dist/esm/excel-parser/plugins/xlsb/biff-record-reader.d.ts.map +1 -0
  306. package/dist/esm/excel-parser/plugins/xlsb/biff-record-reader.js +48 -0
  307. package/dist/esm/excel-parser/plugins/xlsb/index.d.ts +117 -0
  308. package/dist/esm/excel-parser/plugins/xlsb/index.d.ts.map +1 -0
  309. package/dist/esm/excel-parser/plugins/xlsb/index.js +2339 -0
  310. package/dist/esm/excel-parser/plugins/xlsb/rgce-parser.d.ts +18 -0
  311. package/dist/esm/excel-parser/plugins/xlsb/rgce-parser.d.ts.map +1 -0
  312. package/dist/esm/excel-parser/plugins/xlsb/rgce-parser.js +522 -0
  313. package/dist/esm/excel-parser/plugins/xlsm/index.d.ts +5 -0
  314. package/dist/esm/excel-parser/plugins/xlsm/index.d.ts.map +1 -0
  315. package/dist/esm/excel-parser/plugins/xlsm/index.js +6 -0
  316. package/dist/esm/excel-parser/plugins/xlsx/charts.d.ts +60 -0
  317. package/dist/esm/excel-parser/plugins/xlsx/charts.d.ts.map +1 -0
  318. package/dist/esm/excel-parser/plugins/xlsx/charts.js +2036 -0
  319. package/dist/esm/excel-parser/plugins/xlsx/conditional-formatting.d.ts +18 -0
  320. package/dist/esm/excel-parser/plugins/xlsx/conditional-formatting.d.ts.map +1 -0
  321. package/dist/esm/excel-parser/plugins/xlsx/conditional-formatting.js +621 -0
  322. package/dist/esm/excel-parser/plugins/xlsx/data-validations.d.ts +4 -0
  323. package/dist/esm/excel-parser/plugins/xlsx/data-validations.d.ts.map +1 -0
  324. package/dist/esm/excel-parser/plugins/xlsx/data-validations.js +493 -0
  325. package/dist/esm/excel-parser/plugins/xlsx/drawing.d.ts +39 -0
  326. package/dist/esm/excel-parser/plugins/xlsx/drawing.d.ts.map +1 -0
  327. package/dist/esm/excel-parser/plugins/xlsx/drawing.js +905 -0
  328. package/dist/esm/excel-parser/plugins/xlsx/index.d.ts +320 -0
  329. package/dist/esm/excel-parser/plugins/xlsx/index.d.ts.map +1 -0
  330. package/dist/esm/excel-parser/plugins/xlsx/index.js +4654 -0
  331. package/dist/esm/excel-parser/plugins/xlsx/numfmt.d.ts +2 -0
  332. package/dist/esm/excel-parser/plugins/xlsx/numfmt.d.ts.map +1 -0
  333. package/dist/esm/excel-parser/plugins/xlsx/numfmt.js +3 -0
  334. package/dist/esm/excel-parser/plugins/xlsx/pivots.d.ts +40 -0
  335. package/dist/esm/excel-parser/plugins/xlsx/pivots.d.ts.map +1 -0
  336. package/dist/esm/excel-parser/plugins/xlsx/pivots.js +254 -0
  337. package/dist/esm/excel-parser/plugins/xlsx/relationships.d.ts +8 -0
  338. package/dist/esm/excel-parser/plugins/xlsx/relationships.d.ts.map +1 -0
  339. package/dist/esm/excel-parser/plugins/xlsx/relationships.js +13 -0
  340. package/dist/esm/excel-parser/plugins/xlsx/sheet-views.d.ts +26 -0
  341. package/dist/esm/excel-parser/plugins/xlsx/sheet-views.d.ts.map +1 -0
  342. package/dist/esm/excel-parser/plugins/xlsx/sheet-views.js +64 -0
  343. package/dist/esm/excel-parser/plugins/xlsx/styles.d.ts +44 -0
  344. package/dist/esm/excel-parser/plugins/xlsx/styles.d.ts.map +1 -0
  345. package/dist/esm/excel-parser/plugins/xlsx/styles.js +1365 -0
  346. package/dist/esm/excel-parser/plugins/xlsx/theme.d.ts +50 -0
  347. package/dist/esm/excel-parser/plugins/xlsx/theme.d.ts.map +1 -0
  348. package/dist/esm/excel-parser/plugins/xlsx/theme.js +127 -0
  349. package/dist/esm/excel-parser/plugins/xlsx/threaded-comments.d.ts +47 -0
  350. package/dist/esm/excel-parser/plugins/xlsx/threaded-comments.d.ts.map +1 -0
  351. package/dist/esm/excel-parser/plugins/xlsx/threaded-comments.js +103 -0
  352. package/dist/esm/excel-parser/plugins/xlsx/value-type-detection.d.ts +44 -0
  353. package/dist/esm/excel-parser/plugins/xlsx/value-type-detection.d.ts.map +1 -0
  354. package/dist/esm/excel-parser/plugins/xlsx/value-type-detection.js +399 -0
  355. package/dist/esm/excel-parser/registry.d.ts +5 -0
  356. package/dist/esm/excel-parser/registry.d.ts.map +1 -0
  357. package/dist/esm/excel-parser/registry.js +20 -0
  358. package/dist/esm/excel-parser/style-registry.d.ts +51 -0
  359. package/dist/esm/excel-parser/style-registry.d.ts.map +1 -0
  360. package/dist/esm/excel-parser/style-registry.js +163 -0
  361. package/dist/esm/excel-parser/theme-default.d.ts +3 -0
  362. package/dist/esm/excel-parser/theme-default.d.ts.map +1 -0
  363. package/dist/esm/excel-parser/theme-default.js +19 -0
  364. package/dist/esm/excel-parser/types.d.ts +365 -0
  365. package/dist/esm/excel-parser/types.d.ts.map +1 -0
  366. package/dist/esm/excel-parser/types.js +59 -0
  367. package/dist/esm/excel-parser/utils.d.ts +6 -0
  368. package/dist/esm/excel-parser/utils.d.ts.map +1 -0
  369. package/dist/esm/excel-parser/utils.js +25 -0
  370. package/dist/esm/excel-parser/workbook.d.ts +51 -0
  371. package/dist/esm/excel-parser/workbook.d.ts.map +1 -0
  372. package/dist/esm/excel-parser/workbook.js +192 -0
  373. package/dist/esm/excel-parser/worker.d.ts +2 -0
  374. package/dist/esm/excel-parser/worker.d.ts.map +1 -0
  375. package/dist/esm/excel-parser/worker.js +862 -0
  376. package/dist/esm/excel-parser/zip-parser-streaming.d.ts +13 -0
  377. package/dist/esm/excel-parser/zip-parser-streaming.d.ts.map +1 -0
  378. package/dist/esm/excel-parser/zip-parser-streaming.js +119 -0
  379. package/dist/esm/excel-parser/zip-parser.d.ts +11 -0
  380. package/dist/esm/excel-parser/zip-parser.d.ts.map +1 -0
  381. package/dist/esm/excel-parser/zip-parser.js +43 -0
  382. package/dist/esm/exporter/invalid-data-validation.d.ts +19 -0
  383. package/dist/esm/exporter/invalid-data-validation.d.ts.map +1 -0
  384. package/dist/esm/exporter/invalid-data-validation.js +37 -0
  385. package/dist/esm/exporter/ods/ods-export.d.ts +26 -0
  386. package/dist/esm/exporter/ods/ods-export.d.ts.map +1 -0
  387. package/dist/esm/exporter/ods/ods-export.js +3238 -0
  388. package/dist/esm/exporter/ods/sparkline-builder.d.ts +33 -0
  389. package/dist/esm/exporter/ods/sparkline-builder.d.ts.map +1 -0
  390. package/dist/esm/exporter/ods/sparkline-builder.js +165 -0
  391. package/dist/esm/exporter/xlsx/chart-builder.d.ts +3 -0
  392. package/dist/esm/exporter/xlsx/chart-builder.d.ts.map +1 -0
  393. package/dist/esm/exporter/xlsx/chart-builder.js +1805 -0
  394. package/dist/esm/exporter/xlsx/chart-templates.d.ts +1781 -0
  395. package/dist/esm/exporter/xlsx/chart-templates.d.ts.map +1 -0
  396. package/dist/esm/exporter/xlsx/chart-templates.js +1798 -0
  397. package/dist/esm/exporter/xlsx/future-functions.d.ts +10 -0
  398. package/dist/esm/exporter/xlsx/future-functions.d.ts.map +1 -0
  399. package/dist/esm/exporter/xlsx/future-functions.js +264 -0
  400. package/dist/esm/exporter/xlsx/pivot-builder.d.ts +58 -0
  401. package/dist/esm/exporter/xlsx/pivot-builder.d.ts.map +1 -0
  402. package/dist/esm/exporter/xlsx/pivot-builder.js +230 -0
  403. package/dist/esm/exporter/xlsx/power-query-builder.d.ts +26 -0
  404. package/dist/esm/exporter/xlsx/power-query-builder.d.ts.map +1 -0
  405. package/dist/esm/exporter/xlsx/power-query-builder.js +257 -0
  406. package/dist/esm/exporter/xlsx/slicer-builder.d.ts +11 -0
  407. package/dist/esm/exporter/xlsx/slicer-builder.d.ts.map +1 -0
  408. package/dist/esm/exporter/xlsx/slicer-builder.js +84 -0
  409. package/dist/esm/exporter/xlsx/sparkline-builder.d.ts +61 -0
  410. package/dist/esm/exporter/xlsx/sparkline-builder.d.ts.map +1 -0
  411. package/dist/esm/exporter/xlsx/sparkline-builder.js +437 -0
  412. package/dist/esm/exporter/xlsx/style-builder.d.ts +93 -0
  413. package/dist/esm/exporter/xlsx/style-builder.d.ts.map +1 -0
  414. package/dist/esm/exporter/xlsx/style-builder.js +795 -0
  415. package/dist/esm/exporter/xlsx/threaded-comments-builder.d.ts +58 -0
  416. package/dist/esm/exporter/xlsx/threaded-comments-builder.d.ts.map +1 -0
  417. package/dist/esm/exporter/xlsx/threaded-comments-builder.js +175 -0
  418. package/dist/esm/exporter/xlsx/xlsx-export.d.ts +121 -0
  419. package/dist/esm/exporter/xlsx/xlsx-export.d.ts.map +1 -0
  420. package/dist/esm/exporter/xlsx/xlsx-export.js +4062 -0
  421. package/dist/esm/helpers/theme-xml-generator.d.ts +8 -0
  422. package/dist/esm/helpers/theme-xml-generator.d.ts.map +1 -0
  423. package/dist/esm/helpers/theme-xml-generator.js +33 -0
  424. package/dist/esm/helpers.d.ts +34 -0
  425. package/dist/esm/helpers.d.ts.map +1 -0
  426. package/dist/esm/helpers.js +182 -0
  427. package/dist/esm/index.d.ts +16 -0
  428. package/dist/esm/index.d.ts.map +1 -0
  429. package/dist/esm/index.js +15 -0
  430. package/dist/esm/indexed-colors.d.ts +2 -0
  431. package/dist/esm/indexed-colors.d.ts.map +1 -0
  432. package/dist/esm/indexed-colors.js +75 -0
  433. package/dist/esm/ods-export.d.ts +24 -0
  434. package/dist/esm/ods-export.d.ts.map +1 -0
  435. package/dist/esm/ods-export.js +12 -0
  436. package/dist/esm/parse.d.ts +24 -0
  437. package/dist/esm/parse.d.ts.map +1 -0
  438. package/dist/esm/parse.js +55 -0
  439. package/dist/esm/power-query.d.ts +41 -0
  440. package/dist/esm/power-query.d.ts.map +1 -0
  441. package/dist/esm/power-query.js +19 -0
  442. package/dist/esm/server.d.ts +9 -0
  443. package/dist/esm/server.d.ts.map +1 -0
  444. package/dist/esm/server.js +8 -0
  445. package/dist/esm/theme1.d.ts +3 -0
  446. package/dist/esm/theme1.d.ts.map +1 -0
  447. package/dist/esm/theme1.js +2 -0
  448. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -0
  449. package/dist/esm/types.d.ts +14 -0
  450. package/dist/esm/types.d.ts.map +1 -0
  451. package/dist/esm/types.js +14 -0
  452. package/dist/esm/vitest.config.d.ts +3 -0
  453. package/dist/esm/vitest.config.d.ts.map +1 -0
  454. package/dist/esm/vitest.config.js +16 -0
  455. package/package.json +62 -0
  456. package/xlsx.d.ts +52 -0
@@ -0,0 +1,3714 @@
1
+ import { __assign, __awaiter, __generator, __read, __spreadArray, __values } from "tslib";
2
+ import { tokenize as defaultTokenizer } from "@rowsncolumns/calculator";
3
+ import { CellXfsRegistry, deriveEffectiveNumberFormatFromFormula, } from "@rowsncolumns/spreadsheet-state";
4
+ import { cellRangeToAddress, cellToAddress, getCellEffectiveFormat, getCellEffectiveValue, getCellFormattedValue, getCellUserEnteredFormat, getCellUserEnteredValue, getExtendedValueBool, getExtendedValueError, getExtendedValueFormula, getExtendedValueNumber, getExtendedValueString, escapeCharacters, isNil, sortSheetsByIndex, addressToSelection, } from "@rowsncolumns/utils";
5
+ import { defaultSpreadsheetTheme } from "../../excel-parser/theme-default";
6
+ import { imageUrlToBase64 } from "../../helpers";
7
+ import { omitInvalidDataValidationError } from "../invalid-data-validation";
8
+ import { buildOdsSparklineGroupsXml } from "./sparkline-builder";
9
+ var BLANK_LABEL = "(Blanks)";
10
+ var isStyleReference = function (value) {
11
+ return !!value && typeof value === "object" && "sid" in value;
12
+ };
13
+ /**
14
+ * Walk a sparse 1-indexed `DimensionProperties` array and return every
15
+ * outline group span. Mirrors the level-transition scan the gutter and
16
+ * collapse hooks use; the difference is that here we also resolve each
17
+ * group's `collapsed` state from its summary cell so the ODS exporter
18
+ * can emit `table:display="false"` on the wrapper.
19
+ *
20
+ * `summaryAfter` follows the sheet's `outlinePr.summaryBelow`/
21
+ * `summaryRight` setting — when true (Excel default), the summary cell
22
+ * sits at `endIndex + 1`; when false, at `startIndex - 1`.
23
+ */
24
+ var findOutlineGroupSpans = function (metadata, count, summaryAfter) {
25
+ var _a, _b;
26
+ var spans = [];
27
+ if (!(metadata === null || metadata === void 0 ? void 0 : metadata.length) || count <= 0)
28
+ return spans;
29
+ var levelAt = function (i) { var _a, _b; return i >= 1 && i <= count ? (_b = (_a = metadata[i]) === null || _a === void 0 ? void 0 : _a.outlineLevel) !== null && _b !== void 0 ? _b : 0 : 0; };
30
+ var openStarts = new Map();
31
+ var prevLevel = 0;
32
+ // Walk one past `count` so a group that runs to the last row/column
33
+ // still closes cleanly.
34
+ for (var i = 1; i <= count + 1; i++) {
35
+ var curr = levelAt(i);
36
+ if (curr > prevLevel) {
37
+ for (var level = prevLevel + 1; level <= curr; level++) {
38
+ openStarts.set(level, i);
39
+ }
40
+ }
41
+ else if (curr < prevLevel) {
42
+ for (var level = prevLevel; level > curr; level--) {
43
+ var startIndex = (_a = openStarts.get(level)) !== null && _a !== void 0 ? _a : i;
44
+ var endIndex = i - 1;
45
+ var summaryIndex = summaryAfter ? i : startIndex - 1;
46
+ var collapsed = !!((_b = metadata[summaryIndex]) === null || _b === void 0 ? void 0 : _b.collapsed);
47
+ spans.push({ level: level, startIndex: startIndex, endIndex: endIndex, collapsed: collapsed });
48
+ openStarts.delete(level);
49
+ }
50
+ }
51
+ prevLevel = curr;
52
+ }
53
+ return spans;
54
+ };
55
+ /**
56
+ * Build "opens-at" and "closes-at" indices for the group spans.
57
+ * Returns lookup maps the row/column emitter consults at each index to
58
+ * know how many group tags need to be opened or closed. Opens are
59
+ * sorted outermost-first (lower level number first); closes are sorted
60
+ * innermost-first (higher level number first) so the XML nests properly.
61
+ */
62
+ var buildOutlineGroupIndex = function (spans) {
63
+ var e_1, _a, e_2, _b, e_3, _c;
64
+ var _d, _e;
65
+ var opensAt = new Map();
66
+ var closesAt = new Map();
67
+ try {
68
+ for (var spans_1 = __values(spans), spans_1_1 = spans_1.next(); !spans_1_1.done; spans_1_1 = spans_1.next()) {
69
+ var span = spans_1_1.value;
70
+ var opens = (_d = opensAt.get(span.startIndex)) !== null && _d !== void 0 ? _d : [];
71
+ opens.push(span);
72
+ opensAt.set(span.startIndex, opens);
73
+ var closes = (_e = closesAt.get(span.endIndex)) !== null && _e !== void 0 ? _e : [];
74
+ closes.push(span);
75
+ closesAt.set(span.endIndex, closes);
76
+ }
77
+ }
78
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
79
+ finally {
80
+ try {
81
+ if (spans_1_1 && !spans_1_1.done && (_a = spans_1.return)) _a.call(spans_1);
82
+ }
83
+ finally { if (e_1) throw e_1.error; }
84
+ }
85
+ try {
86
+ for (var _f = __values(opensAt.values()), _g = _f.next(); !_g.done; _g = _f.next()) {
87
+ var opens = _g.value;
88
+ opens.sort(function (a, b) { return a.level - b.level; });
89
+ }
90
+ }
91
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
92
+ finally {
93
+ try {
94
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
95
+ }
96
+ finally { if (e_2) throw e_2.error; }
97
+ }
98
+ try {
99
+ for (var _h = __values(closesAt.values()), _j = _h.next(); !_j.done; _j = _h.next()) {
100
+ var closes = _j.value;
101
+ closes.sort(function (a, b) { return b.level - a.level; });
102
+ }
103
+ }
104
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
105
+ finally {
106
+ try {
107
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
108
+ }
109
+ finally { if (e_3) throw e_3.error; }
110
+ }
111
+ return { opensAt: opensAt, closesAt: closesAt };
112
+ };
113
+ var outlineGroupOpenTag = function (span, tag) {
114
+ var display = span.collapsed ? " table:display=\"false\"" : "";
115
+ return "<".concat(tag).concat(display, ">");
116
+ };
117
+ var XML_DECLARATION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
118
+ var ODS_MIMETYPE = "application/vnd.oasis.opendocument.spreadsheet";
119
+ var CREATOR = "Rows n Columns";
120
+ var PIXELS_PER_INCH = 96;
121
+ var CM_PER_INCH = 2.54;
122
+ var ODS_NS = {
123
+ office: "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
124
+ style: "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
125
+ text: "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
126
+ table: "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
127
+ draw: "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
128
+ fo: "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
129
+ xlink: "http://www.w3.org/1999/xlink",
130
+ svg: "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
131
+ number: "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
132
+ of: "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
133
+ config: "urn:oasis:names:tc:opendocument:xmlns:config:1.0",
134
+ chart: "urn:oasis:names:tc:opendocument:xmlns:chart:1.0",
135
+ calcext: "urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0",
136
+ dc: "http://purl.org/dc/elements/1.1/",
137
+ };
138
+ var INVALID_XML_CHAR_REGEX = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g;
139
+ var textEncoder = new TextEncoder();
140
+ var encodeXml = function (content) { return textEncoder.encode(content); };
141
+ var sanitizeXmlText = function (value) {
142
+ if (!value)
143
+ return value;
144
+ return value.replace(INVALID_XML_CHAR_REGEX, "");
145
+ };
146
+ var escapeXml = function (value) {
147
+ return sanitizeXmlText(value)
148
+ .replace(/&/g, "&amp;")
149
+ .replace(/</g, "&lt;")
150
+ .replace(/>/g, "&gt;")
151
+ .replace(/"/g, "&quot;")
152
+ .replace(/'/g, "&apos;");
153
+ };
154
+ var escapeXmlAddress = function (value) {
155
+ return sanitizeXmlText(value)
156
+ .replace(/&/g, "&amp;")
157
+ .replace(/</g, "&lt;")
158
+ .replace(/>/g, "&gt;")
159
+ .replace(/"/g, "&quot;");
160
+ };
161
+ var pxToCm = function (px) { return (px * CM_PER_INCH) / PIXELS_PER_INCH; };
162
+ var DEFAULT_COLUMN_WIDTH_PX = 100;
163
+ var DEFAULT_ROW_HEIGHT_PX = 21;
164
+ var OdsStyleBuilder = /** @class */ (function () {
165
+ function OdsStyleBuilder(theme) {
166
+ this.theme = theme;
167
+ this.cellStyles = new Map();
168
+ this.usedStyleNames = new Set();
169
+ this.rowStyles = new Map();
170
+ this.columnStyles = new Map();
171
+ this.textStyles = new Map();
172
+ this.numberStyles = new Map();
173
+ this.styleXmlChunks = [];
174
+ this.numberXmlChunks = [];
175
+ // NEW: separate storage for conditional format styles (go to styles.xml)
176
+ this.conditionalStyleXmlChunks = [];
177
+ this.styleIndex = 1;
178
+ this.numberIndex = 1;
179
+ }
180
+ OdsStyleBuilder.prototype.registerCell = function (format) {
181
+ if (!format)
182
+ return undefined;
183
+ var key = stableStringify(normalizeCellFormat(format));
184
+ var existing = this.cellStyles.get(key);
185
+ if (existing)
186
+ return existing;
187
+ return this.registerCellWithName(format, key);
188
+ };
189
+ OdsStyleBuilder.prototype.registerRow = function (heightPx, hidden) {
190
+ if (!heightPx && !hidden)
191
+ return undefined;
192
+ var key = stableStringify({ heightPx: heightPx, hidden: hidden });
193
+ var existing = this.rowStyles.get(key);
194
+ if (existing)
195
+ return existing;
196
+ var styleName = "ro".concat(this.styleIndex++);
197
+ var styleXml = buildRowStyleXml(styleName, heightPx, hidden);
198
+ this.rowStyles.set(key, styleName);
199
+ this.styleXmlChunks.push(styleXml);
200
+ return styleName;
201
+ };
202
+ OdsStyleBuilder.prototype.registerColumn = function (widthPx, hidden) {
203
+ if (!widthPx && !hidden)
204
+ return undefined;
205
+ var key = stableStringify({ widthPx: widthPx, hidden: hidden });
206
+ var existing = this.columnStyles.get(key);
207
+ if (existing)
208
+ return existing;
209
+ var styleName = "co".concat(this.styleIndex++);
210
+ var styleXml = buildColumnStyleXml(styleName, widthPx, hidden);
211
+ this.columnStyles.set(key, styleName);
212
+ this.styleXmlChunks.push(styleXml);
213
+ return styleName;
214
+ };
215
+ OdsStyleBuilder.prototype.registerText = function (format) {
216
+ if (!format || Object.keys(format).length === 0)
217
+ return undefined;
218
+ var key = "text_".concat(stableStringify(format));
219
+ var existing = this.textStyles.get(key);
220
+ if (existing)
221
+ return existing;
222
+ var styleName = "T".concat(this.styleIndex++);
223
+ var styleXml = buildTextStyleXml(styleName, format, this.theme);
224
+ this.textStyles.set(key, styleName);
225
+ this.styleXmlChunks.push(styleXml);
226
+ return styleName;
227
+ };
228
+ OdsStyleBuilder.prototype.registerConditionalFormat = function (format, nameHint) {
229
+ if (!format)
230
+ return undefined;
231
+ var key = "cf_".concat(stableStringify(normalizeCellFormat(format)));
232
+ var existing = this.cellStyles.get(key);
233
+ if (existing)
234
+ return existing;
235
+ var styleName = this.allocateStyleName(nameHint);
236
+ var styleXml = buildConditionalCellStyleXml(styleName, format, this.theme);
237
+ this.cellStyles.set(key, styleName);
238
+ // Store in separate array for styles.xml
239
+ this.conditionalStyleXmlChunks.push(styleXml);
240
+ return styleName;
241
+ };
242
+ OdsStyleBuilder.prototype.registerNumberStyle = function (numberFormat) {
243
+ if (!numberFormat)
244
+ return undefined;
245
+ var key = stableStringify(numberFormat);
246
+ var existing = this.numberStyles.get(key);
247
+ if (existing)
248
+ return existing;
249
+ var styleName = "N".concat(this.numberIndex++);
250
+ var xml = buildNumberStyleXml(styleName, numberFormat);
251
+ this.numberStyles.set(key, styleName);
252
+ this.numberXmlChunks.push(xml);
253
+ return styleName;
254
+ };
255
+ OdsStyleBuilder.prototype.toAutomaticStylesXml = function () {
256
+ return "".concat(this.numberXmlChunks.join("")).concat(this.styleXmlChunks.join(""));
257
+ };
258
+ // NEW: Get conditional styles for styles.xml
259
+ OdsStyleBuilder.prototype.toConditionalStylesXml = function () {
260
+ return this.conditionalStyleXmlChunks.join("");
261
+ };
262
+ OdsStyleBuilder.prototype.registerCellWithName = function (format, key, nameHint) {
263
+ var existing = this.cellStyles.get(key);
264
+ if (existing)
265
+ return existing;
266
+ var styleName = this.allocateStyleName(nameHint);
267
+ var numberStyleName = format.numberFormat
268
+ ? this.registerNumberStyle(format.numberFormat)
269
+ : undefined;
270
+ var styleXml = buildCellStyleXml(styleName, format, numberStyleName, this.theme);
271
+ this.cellStyles.set(key, styleName);
272
+ this.styleXmlChunks.push(styleXml);
273
+ return styleName;
274
+ };
275
+ OdsStyleBuilder.prototype.allocateStyleName = function (nameHint) {
276
+ if (nameHint && !this.usedStyleNames.has(nameHint)) {
277
+ this.usedStyleNames.add(nameHint);
278
+ return nameHint;
279
+ }
280
+ var name = "ce".concat(this.styleIndex++);
281
+ while (this.usedStyleNames.has(name)) {
282
+ name = "ce".concat(this.styleIndex++);
283
+ }
284
+ this.usedStyleNames.add(name);
285
+ return name;
286
+ };
287
+ return OdsStyleBuilder;
288
+ }());
289
+ // NEW: Build style for conditional formatting (different parent)
290
+ var buildConditionalCellStyleXml = function (name, format, theme) {
291
+ var _a, _b, _c;
292
+ var textProps = [];
293
+ var cellProps = [];
294
+ var textFormat = (_a = format.textFormat) !== null && _a !== void 0 ? _a : undefined;
295
+ if (textFormat === null || textFormat === void 0 ? void 0 : textFormat.bold) {
296
+ textProps.push("fo:font-weight=\"bold\"");
297
+ }
298
+ if (textFormat === null || textFormat === void 0 ? void 0 : textFormat.italic) {
299
+ textProps.push("fo:font-style=\"italic\"");
300
+ }
301
+ if (textFormat === null || textFormat === void 0 ? void 0 : textFormat.underline) {
302
+ textProps.push("style:text-underline-style=\"solid\"");
303
+ }
304
+ if (textFormat === null || textFormat === void 0 ? void 0 : textFormat.strikethrough) {
305
+ textProps.push("style:text-line-through-style=\"solid\"");
306
+ }
307
+ if ((textFormat === null || textFormat === void 0 ? void 0 : textFormat.baselineOffset) === "superscript") {
308
+ textProps.push("style:text-position=\"super 58%\"");
309
+ }
310
+ else if ((textFormat === null || textFormat === void 0 ? void 0 : textFormat.baselineOffset) === "subscript") {
311
+ textProps.push("style:text-position=\"sub 58%\"");
312
+ }
313
+ var textColor = normalizeColor((_b = textFormat === null || textFormat === void 0 ? void 0 : textFormat.color) !== null && _b !== void 0 ? _b : undefined, theme);
314
+ if (textColor) {
315
+ textProps.push("fo:color=\"".concat(textColor, "\""));
316
+ }
317
+ var background = normalizeColor((_c = format.backgroundColor) !== null && _c !== void 0 ? _c : undefined, theme);
318
+ if (background) {
319
+ cellProps.push("fo:background-color=\"".concat(background, "\""));
320
+ }
321
+ // Note: parent-style-name="Default" is crucial for LibreOffice to recognize it
322
+ return "<style:style style:name=\"".concat(name, "\" style:family=\"table-cell\" style:parent-style-name=\"Default\"><style:table-cell-properties").concat(cellProps.length ? " " + cellProps.join(" ") : "", "/><style:text-properties").concat(textProps.length ? " " + textProps.join(" ") : "", "/></style:style>");
323
+ };
324
+ export var createODSFile = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
325
+ var sortedSheets, styleBuilder, preparedTables, embedsBySheet, chartsBySheet, namedRangeNames, sheetNameById, dataValidationsById, mediaEntries, sheetXmlEntries, chartObjectIndex, _loop_1, sortedSheets_1, sortedSheets_1_1, sheet, e_4_1, validationEntries, contentValidationsXml, calculationSettingsXml, contentXml, stylesXml, metaXml, settingsXml, chartObjects, manifestXml, files, chartObjects_1, chartObjects_1_1, chartObject, mediaEntries_1, mediaEntries_1_1, entry, orderedEntries;
326
+ var e_4, _c, e_5, _d, e_6, _e;
327
+ var _f, _g, _h, _j, _k, _l;
328
+ var _conditionalFormats = _b.conditionalFormats, _dataValidations = _b.dataValidations, sheets = _b.sheets, sheetData = _b.sheetData, sourceSharedStrings = _b.sharedStrings, _m = _b.tables, _tables = _m === void 0 ? [] : _m, cellXfs = _b.cellXfs, _theme = _b.theme, _o = _b.embeds, embeds = _o === void 0 ? [] : _o, _p = _b.charts, charts = _p === void 0 ? [] : _p, _q = _b.namedRanges, namedRanges = _q === void 0 ? [] : _q, iterativeCalculationOptions = _b.iterativeCalculationOptions, ignoreFormulaPatterns = _b.ignoreFormulaPatterns, citations = _b.citations, locale = _b.locale;
329
+ return __generator(this, function (_r) {
330
+ switch (_r.label) {
331
+ case 0:
332
+ sortedSheets = sortSheetsByIndex(sheets, true);
333
+ styleBuilder = new OdsStyleBuilder(_theme !== null && _theme !== void 0 ? _theme : defaultSpreadsheetTheme);
334
+ preparedTables = prepareTables(_tables !== null && _tables !== void 0 ? _tables : []);
335
+ embedsBySheet = groupEmbedsBySheet(embeds !== null && embeds !== void 0 ? embeds : []);
336
+ chartsBySheet = groupChartsBySheet(charts !== null && charts !== void 0 ? charts : []);
337
+ namedRangeNames = new Set((namedRanges !== null && namedRanges !== void 0 ? namedRanges : [])
338
+ .map(function (range) { return range.name; })
339
+ .filter(function (name) {
340
+ return typeof name === "string" && isValidNamedRangeName(name);
341
+ })
342
+ .map(function (name) { return name.toUpperCase(); }));
343
+ sheetNameById = new Map();
344
+ sortedSheets.forEach(function (sheet, index) {
345
+ var _a, _b;
346
+ sheetNameById.set((_a = sheet.sheetId) !== null && _a !== void 0 ? _a : index + 1, (_b = sheet.title) !== null && _b !== void 0 ? _b : "Sheet".concat(index + 1));
347
+ });
348
+ dataValidationsById = (_f = _dataValidations === null || _dataValidations === void 0 ? void 0 : _dataValidations.reduce(function (acc, rule) {
349
+ if (rule.id != null) {
350
+ acc[String(rule.id)] = rule;
351
+ }
352
+ return acc;
353
+ }, {})) !== null && _f !== void 0 ? _f : undefined;
354
+ mediaEntries = [];
355
+ sheetXmlEntries = [];
356
+ chartObjectIndex = 1;
357
+ _loop_1 = function (sheet) {
358
+ var rows, sheetTables, sheetConditionalFormats, embedImages, sheetCharts, sheetName, sheetCitations, result;
359
+ return __generator(this, function (_s) {
360
+ switch (_s.label) {
361
+ case 0:
362
+ rows = getRowsForSheet(sheetData, sheet.sheetId);
363
+ sheetTables = preparedTables.filter(function (table) { return table.sheetId === sheet.sheetId; });
364
+ sheetConditionalFormats = (_conditionalFormats !== null && _conditionalFormats !== void 0 ? _conditionalFormats : []).filter(function (rule) { var _a; return (_a = rule.ranges) === null || _a === void 0 ? void 0 : _a.some(function (range) { return range.sheetId === sheet.sheetId; }); });
365
+ embedImages = (_g = embedsBySheet.get(sheet.sheetId)) !== null && _g !== void 0 ? _g : [];
366
+ sheetCharts = (_h = chartsBySheet.get(sheet.sheetId)) !== null && _h !== void 0 ? _h : [];
367
+ sheetName = (_l = (_k = sheetNameById.get((_j = sheet.sheetId) !== null && _j !== void 0 ? _j : 0)) !== null && _k !== void 0 ? _k : sheet.title) !== null && _l !== void 0 ? _l : "Sheet";
368
+ sheetCitations = citations === null || citations === void 0 ? void 0 : citations.filter(function (citation) { return citation.range.sheetId === sheet.sheetId; });
369
+ return [4 /*yield*/, buildWorksheetXml({
370
+ sheet: sheet,
371
+ sheetName: sheetName,
372
+ rows: rows,
373
+ sourceSharedStrings: sourceSharedStrings,
374
+ cellXfs: cellXfs,
375
+ styleBuilder: styleBuilder,
376
+ tables: sheetTables,
377
+ conditionalFormats: sheetConditionalFormats,
378
+ dataValidationsById: dataValidationsById,
379
+ embeds: embedImages,
380
+ charts: sheetCharts,
381
+ mediaEntries: mediaEntries,
382
+ namedRangeNames: namedRangeNames,
383
+ sheetNameById: sheetNameById,
384
+ chartObjectIndex: chartObjectIndex,
385
+ ignoreFormulaPatterns: ignoreFormulaPatterns,
386
+ citations: sheetCitations,
387
+ sheetData: sheetData,
388
+ sheets: sortedSheets,
389
+ locale: locale,
390
+ })];
391
+ case 1:
392
+ result = _s.sent();
393
+ chartObjectIndex = result.nextChartObjectIndex;
394
+ sheetXmlEntries.push({
395
+ xml: result.xml,
396
+ databaseRanges: result.databaseRanges,
397
+ chartObjects: result.chartObjects,
398
+ });
399
+ return [2 /*return*/];
400
+ }
401
+ });
402
+ };
403
+ _r.label = 1;
404
+ case 1:
405
+ _r.trys.push([1, 6, 7, 8]);
406
+ sortedSheets_1 = __values(sortedSheets), sortedSheets_1_1 = sortedSheets_1.next();
407
+ _r.label = 2;
408
+ case 2:
409
+ if (!!sortedSheets_1_1.done) return [3 /*break*/, 5];
410
+ sheet = sortedSheets_1_1.value;
411
+ return [5 /*yield**/, _loop_1(sheet)];
412
+ case 3:
413
+ _r.sent();
414
+ _r.label = 4;
415
+ case 4:
416
+ sortedSheets_1_1 = sortedSheets_1.next();
417
+ return [3 /*break*/, 2];
418
+ case 5: return [3 /*break*/, 8];
419
+ case 6:
420
+ e_4_1 = _r.sent();
421
+ e_4 = { error: e_4_1 };
422
+ return [3 /*break*/, 8];
423
+ case 7:
424
+ try {
425
+ if (sortedSheets_1_1 && !sortedSheets_1_1.done && (_c = sortedSheets_1.return)) _c.call(sortedSheets_1);
426
+ }
427
+ finally { if (e_4) throw e_4.error; }
428
+ return [7 /*endfinally*/];
429
+ case 8:
430
+ validationEntries = buildAllDataValidationEntries(_dataValidations !== null && _dataValidations !== void 0 ? _dataValidations : [], sheetNameById);
431
+ contentValidationsXml = validationEntries.length
432
+ ? "<table:content-validations>".concat(validationEntries.join(""), "</table:content-validations>")
433
+ : "";
434
+ calculationSettingsXml = buildCalculationSettingsXml(iterativeCalculationOptions);
435
+ contentXml = buildContentXml({
436
+ sheetsXml: sheetXmlEntries.map(function (entry) { return entry.xml; }).join(""),
437
+ databaseRangesXml: buildDatabaseRangesXml(sheetXmlEntries.flatMap(function (entry) { return entry.databaseRanges; })),
438
+ namedRangesXml: buildNamedRangesXml(namedRanges, sheetNameById, namedRangeNames),
439
+ contentValidationsXml: contentValidationsXml,
440
+ automaticStylesXml: styleBuilder.toAutomaticStylesXml(),
441
+ calculationSettingsXml: calculationSettingsXml,
442
+ });
443
+ stylesXml = buildStylesXml(styleBuilder.toConditionalStylesXml());
444
+ metaXml = buildMetaXml();
445
+ settingsXml = buildSettingsXml(sortedSheets, _theme !== null && _theme !== void 0 ? _theme : defaultSpreadsheetTheme);
446
+ chartObjects = sheetXmlEntries.flatMap(function (entry) { return entry.chartObjects; });
447
+ manifestXml = buildManifestXml(mediaEntries, chartObjects, Boolean(settingsXml));
448
+ files = {
449
+ "content.xml": encodeXml(contentXml),
450
+ "styles.xml": encodeXml(stylesXml),
451
+ "meta.xml": encodeXml(metaXml),
452
+ "META-INF/manifest.xml": encodeXml(manifestXml),
453
+ };
454
+ if (settingsXml) {
455
+ files["settings.xml"] = encodeXml(settingsXml);
456
+ }
457
+ try {
458
+ for (chartObjects_1 = __values(chartObjects), chartObjects_1_1 = chartObjects_1.next(); !chartObjects_1_1.done; chartObjects_1_1 = chartObjects_1.next()) {
459
+ chartObject = chartObjects_1_1.value;
460
+ files["".concat(chartObject.folder, "/content.xml")] = encodeXml(chartObject.contentXml);
461
+ }
462
+ }
463
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
464
+ finally {
465
+ try {
466
+ if (chartObjects_1_1 && !chartObjects_1_1.done && (_d = chartObjects_1.return)) _d.call(chartObjects_1);
467
+ }
468
+ finally { if (e_5) throw e_5.error; }
469
+ }
470
+ try {
471
+ for (mediaEntries_1 = __values(mediaEntries), mediaEntries_1_1 = mediaEntries_1.next(); !mediaEntries_1_1.done; mediaEntries_1_1 = mediaEntries_1.next()) {
472
+ entry = mediaEntries_1_1.value;
473
+ files[entry.path] = entry.data;
474
+ }
475
+ }
476
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
477
+ finally {
478
+ try {
479
+ if (mediaEntries_1_1 && !mediaEntries_1_1.done && (_e = mediaEntries_1.return)) _e.call(mediaEntries_1);
480
+ }
481
+ finally { if (e_6) throw e_6.error; }
482
+ }
483
+ orderedEntries = __spreadArray([
484
+ { name: "mimetype", data: new TextEncoder().encode(ODS_MIMETYPE) }
485
+ ], __read(Object.entries(files).map(function (_a) {
486
+ var _b = __read(_a, 2), name = _b[0], data = _b[1];
487
+ return ({ name: name, data: data });
488
+ })), false);
489
+ return [2 /*return*/, buildZipStore(orderedEntries)];
490
+ }
491
+ });
492
+ }); };
493
+ var getRowsForSheet = function (sheetData, sheetId) {
494
+ var _a, _b, _c;
495
+ return ((_c = (_b = (_a = sheetData[sheetId]) !== null && _a !== void 0 ? _a : sheetData[String(sheetId)]) !== null && _b !== void 0 ? _b : sheetData[Number(sheetId)]) !== null && _c !== void 0 ? _c : []);
496
+ };
497
+ var buildWorksheetXml = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
498
+ var bounds, rowMetadata, maxRows, rowXmlEntries, mergeState, annotationsMap, citations_1, citations_1_1, citation, rowIndex, colIndex, address, conditionalFormattingXml, rowDataMap, rowIndex, row, metadata, rowXml, rowValues, _c, _d, _e, colIndex, cell, maxRowIndex, summaryBelow, rowSpans, _f, rowOpensAt, rowClosesAt, rowXmlChunks, index, rowIndex, _g, _h, span, entry, repeat, nextRowIndex, lastInRepeat, _j, _k, _1, _l, _m, _2, embedFrames, _o, chartFramesResult, _p, shapesXml, columnsXml, sparklineXml, sheetXml;
499
+ var e_7, _q, e_8, _r, e_9, _s, e_10, _t, e_11, _u;
500
+ var _v, _w, _x, _y, _z, _0, _1;
501
+ var sheet = _b.sheet, sheetName = _b.sheetName, rows = _b.rows, sourceSharedStrings = _b.sourceSharedStrings, cellXfs = _b.cellXfs, styleBuilder = _b.styleBuilder, tables = _b.tables, conditionalFormats = _b.conditionalFormats, dataValidationsById = _b.dataValidationsById, embeds = _b.embeds, charts = _b.charts, mediaEntries = _b.mediaEntries, namedRangeNames = _b.namedRangeNames, sheetNameById = _b.sheetNameById, chartObjectIndex = _b.chartObjectIndex, ignoreFormulaPatterns = _b.ignoreFormulaPatterns, citations = _b.citations, sheetData = _b.sheetData, sheets = _b.sheets, locale = _b.locale;
502
+ return __generator(this, function (_3) {
503
+ switch (_3.label) {
504
+ case 0:
505
+ bounds = {
506
+ minRow: Number.POSITIVE_INFINITY,
507
+ maxRow: 0,
508
+ minColumn: Number.POSITIVE_INFINITY,
509
+ maxColumn: 0,
510
+ };
511
+ rowMetadata = (_v = sheet.rowMetadata) !== null && _v !== void 0 ? _v : [];
512
+ maxRows = Math.max(rows.length, rowMetadata.length);
513
+ rowXmlEntries = [];
514
+ mergeState = buildMergeState((_w = sheet.merges) !== null && _w !== void 0 ? _w : []);
515
+ annotationsMap = new Map();
516
+ if (citations) {
517
+ try {
518
+ for (citations_1 = __values(citations), citations_1_1 = citations_1.next(); !citations_1_1.done; citations_1_1 = citations_1.next()) {
519
+ citation = citations_1_1.value;
520
+ // Citation ranges are worksheet-based (1-based).
521
+ for (rowIndex = citation.range.startRowIndex; rowIndex <= citation.range.endRowIndex; rowIndex++) {
522
+ for (colIndex = citation.range.startColumnIndex; colIndex <= citation.range.endColumnIndex; colIndex++) {
523
+ address = cellToAddress({ rowIndex: rowIndex, columnIndex: colIndex });
524
+ if (address) {
525
+ annotationsMap.set(address, {
526
+ text: citation.citation_string,
527
+ author: citation.created_by || "System",
528
+ });
529
+ }
530
+ }
531
+ }
532
+ }
533
+ }
534
+ catch (e_7_1) { e_7 = { error: e_7_1 }; }
535
+ finally {
536
+ try {
537
+ if (citations_1_1 && !citations_1_1.done && (_q = citations_1.return)) _q.call(citations_1);
538
+ }
539
+ finally { if (e_7) throw e_7.error; }
540
+ }
541
+ }
542
+ conditionalFormattingXml = conditionalFormats.length
543
+ ? buildConditionalFormattingXml({
544
+ sheetName: sheetName,
545
+ conditionalFormats: conditionalFormats,
546
+ styleBuilder: styleBuilder,
547
+ namedRangeNames: namedRangeNames,
548
+ })
549
+ : "";
550
+ rowDataMap = {};
551
+ rowIndex = 1;
552
+ _3.label = 1;
553
+ case 1:
554
+ if (!(rowIndex < maxRows)) return [3 /*break*/, 4];
555
+ row = rows[rowIndex];
556
+ metadata = rowMetadata[rowIndex];
557
+ return [4 /*yield*/, buildWorksheetRow({
558
+ rowNumber: rowIndex,
559
+ row: row,
560
+ rowMetadata: metadata,
561
+ sourceSharedStrings: sourceSharedStrings,
562
+ cellXfs: cellXfs,
563
+ styleBuilder: styleBuilder,
564
+ mergeState: mergeState,
565
+ dataValidationsById: dataValidationsById,
566
+ mediaEntries: mediaEntries,
567
+ sheet: sheet,
568
+ namedRangeNames: namedRangeNames,
569
+ tables: tables,
570
+ ignoreFormulaPatterns: ignoreFormulaPatterns,
571
+ annotationsMap: annotationsMap,
572
+ sheetData: sheetData,
573
+ sheets: sheets,
574
+ locale: locale,
575
+ })];
576
+ case 2:
577
+ rowXml = _3.sent();
578
+ rowXmlEntries.push(rowXml);
579
+ // Collect row data for sparkline detection
580
+ if (row === null || row === void 0 ? void 0 : row.values) {
581
+ rowValues = {};
582
+ try {
583
+ for (_c = (e_8 = void 0, __values(Object.entries(row.values))), _d = _c.next(); !_d.done; _d = _c.next()) {
584
+ _e = __read(_d.value, 2), colIndex = _e[0], cell = _e[1];
585
+ if (cell) {
586
+ rowValues[parseInt(colIndex, 10)] = cell;
587
+ }
588
+ }
589
+ }
590
+ catch (e_8_1) { e_8 = { error: e_8_1 }; }
591
+ finally {
592
+ try {
593
+ if (_d && !_d.done && (_r = _c.return)) _r.call(_c);
594
+ }
595
+ finally { if (e_8) throw e_8.error; }
596
+ }
597
+ if (Object.keys(rowValues).length > 0) {
598
+ rowDataMap[rowIndex] = rowValues;
599
+ }
600
+ }
601
+ if (!rowXml)
602
+ return [3 /*break*/, 3];
603
+ if (rowXml.minColumn) {
604
+ bounds.minColumn = Math.min(bounds.minColumn, rowXml.minColumn);
605
+ }
606
+ if (rowXml.maxColumn) {
607
+ bounds.maxColumn = Math.max(bounds.maxColumn, rowXml.maxColumn);
608
+ }
609
+ bounds.minRow = Math.min(bounds.minRow, rowIndex);
610
+ bounds.maxRow = Math.max(bounds.maxRow, rowIndex);
611
+ _3.label = 3;
612
+ case 3:
613
+ rowIndex++;
614
+ return [3 /*break*/, 1];
615
+ case 4:
616
+ updateBoundsForMerges(bounds, mergeState);
617
+ maxRowIndex = rowXmlEntries.length;
618
+ summaryBelow = ((_x = sheet.outlinePr) === null || _x === void 0 ? void 0 : _x.summaryBelow) !== false;
619
+ rowSpans = findOutlineGroupSpans(rowMetadata, maxRowIndex, summaryBelow);
620
+ _f = buildOutlineGroupIndex(rowSpans), rowOpensAt = _f.opensAt, rowClosesAt = _f.closesAt;
621
+ rowXmlChunks = [];
622
+ for (index = 0; index < rowXmlEntries.length; index++) {
623
+ rowIndex = index + 1;
624
+ try {
625
+ for (_g = (e_9 = void 0, __values((_y = rowOpensAt.get(rowIndex)) !== null && _y !== void 0 ? _y : [])), _h = _g.next(); !_h.done; _h = _g.next()) {
626
+ span = _h.value;
627
+ rowXmlChunks.push(outlineGroupOpenTag(span, "table:table-row-group"));
628
+ }
629
+ }
630
+ catch (e_9_1) { e_9 = { error: e_9_1 }; }
631
+ finally {
632
+ try {
633
+ if (_h && !_h.done && (_s = _g.return)) _s.call(_g);
634
+ }
635
+ finally { if (e_9) throw e_9.error; }
636
+ }
637
+ entry = rowXmlEntries[index];
638
+ if (entry) {
639
+ rowXmlChunks.push(entry.xml);
640
+ }
641
+ else {
642
+ repeat = 1;
643
+ while (index + repeat < rowXmlEntries.length &&
644
+ !rowXmlEntries[index + repeat]) {
645
+ nextRowIndex = index + repeat + 1;
646
+ if (rowOpensAt.has(nextRowIndex) || rowClosesAt.has(nextRowIndex - 1)) {
647
+ break;
648
+ }
649
+ repeat += 1;
650
+ }
651
+ rowXmlChunks.push(repeat > 1
652
+ ? "<table:table-row table:number-rows-repeated=\"".concat(repeat, "\"/>")
653
+ : "<table:table-row/>");
654
+ lastInRepeat = rowIndex + repeat - 1;
655
+ try {
656
+ for (_j = (e_10 = void 0, __values((_z = rowClosesAt.get(lastInRepeat)) !== null && _z !== void 0 ? _z : [])), _k = _j.next(); !_k.done; _k = _j.next()) {
657
+ _1 = _k.value;
658
+ rowXmlChunks.push("</table:table-row-group>");
659
+ }
660
+ }
661
+ catch (e_10_1) { e_10 = { error: e_10_1 }; }
662
+ finally {
663
+ try {
664
+ if (_k && !_k.done && (_t = _j.return)) _t.call(_j);
665
+ }
666
+ finally { if (e_10) throw e_10.error; }
667
+ }
668
+ index += repeat - 1;
669
+ continue;
670
+ }
671
+ try {
672
+ for (_l = (e_11 = void 0, __values((_0 = rowClosesAt.get(rowIndex)) !== null && _0 !== void 0 ? _0 : [])), _m = _l.next(); !_m.done; _m = _l.next()) {
673
+ _2 = _m.value;
674
+ rowXmlChunks.push("</table:table-row-group>");
675
+ }
676
+ }
677
+ catch (e_11_1) { e_11 = { error: e_11_1 }; }
678
+ finally {
679
+ try {
680
+ if (_m && !_m.done && (_u = _l.return)) _u.call(_l);
681
+ }
682
+ finally { if (e_11) throw e_11.error; }
683
+ }
684
+ }
685
+ if (!embeds.length) return [3 /*break*/, 6];
686
+ return [4 /*yield*/, buildEmbedFramesXml({
687
+ embeds: embeds,
688
+ mediaEntries: mediaEntries,
689
+ sheetName: sheetName,
690
+ sheet: sheet,
691
+ })];
692
+ case 5:
693
+ _o = _3.sent();
694
+ return [3 /*break*/, 7];
695
+ case 6:
696
+ _o = [];
697
+ _3.label = 7;
698
+ case 7:
699
+ embedFrames = _o;
700
+ if (!charts.length) return [3 /*break*/, 9];
701
+ return [4 /*yield*/, buildChartFramesXml({
702
+ charts: charts,
703
+ sheet: sheet,
704
+ sheetName: sheetName,
705
+ sheetNameById: sheetNameById,
706
+ startIndex: chartObjectIndex,
707
+ })];
708
+ case 8:
709
+ _p = _3.sent();
710
+ return [3 /*break*/, 10];
711
+ case 9:
712
+ _p = { frames: [], chartObjects: [], nextIndex: chartObjectIndex };
713
+ _3.label = 10;
714
+ case 10:
715
+ chartFramesResult = _p;
716
+ shapesXml = embedFrames.length || chartFramesResult.frames.length
717
+ ? "<table:shapes>".concat(__spreadArray(__spreadArray([], __read(embedFrames), false), __read(chartFramesResult.frames), false).join(""), "</table:shapes>")
718
+ : "";
719
+ columnsXml = buildColumnsXml(sheet, styleBuilder, bounds);
720
+ sparklineXml = (_1 = buildOdsSparklineGroupsXml(sheet, sheetName, rowDataMap)) !== null && _1 !== void 0 ? _1 : "";
721
+ sheetXml = "<table:table table:name=\"".concat(escapeXml(sheetName), "\">").concat(shapesXml).concat(columnsXml).concat(rowXmlChunks.join("")).concat(conditionalFormattingXml).concat(sparklineXml, "</table:table>");
722
+ return [2 /*return*/, {
723
+ xml: sheetXml,
724
+ databaseRanges: buildDatabaseRangeEntries(tables, sheetName, sheet, rows),
725
+ chartObjects: chartFramesResult.chartObjects,
726
+ nextChartObjectIndex: chartFramesResult.nextIndex,
727
+ }];
728
+ }
729
+ });
730
+ }); };
731
+ var buildWorksheetRow = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
732
+ var values, cellXmlChunks, minColumn, maxColumn, hasHiddenFlag, defaultRowHeightPx, rowSize, hasExplicitHeight, hasCustomHeight, rowStyle, maxColumnIndex, columnIndex, cell, mergeSpan, cellXml, hasCells, needsMetadata, attrs, rowXml;
733
+ var _c, _d;
734
+ var rowNumber = _b.rowNumber, row = _b.row, rowMetadata = _b.rowMetadata, sourceSharedStrings = _b.sourceSharedStrings, cellXfs = _b.cellXfs, styleBuilder = _b.styleBuilder, mergeState = _b.mergeState, dataValidationsById = _b.dataValidationsById, mediaEntries = _b.mediaEntries, sheet = _b.sheet, namedRangeNames = _b.namedRangeNames, tables = _b.tables, ignoreFormulaPatterns = _b.ignoreFormulaPatterns, annotationsMap = _b.annotationsMap, sheetData = _b.sheetData, sheets = _b.sheets, locale = _b.locale;
735
+ return __generator(this, function (_e) {
736
+ switch (_e.label) {
737
+ case 0:
738
+ values = (_c = row === null || row === void 0 ? void 0 : row.values) !== null && _c !== void 0 ? _c : [];
739
+ cellXmlChunks = [];
740
+ minColumn = Number.POSITIVE_INFINITY;
741
+ maxColumn = 0;
742
+ hasHiddenFlag = Boolean((rowMetadata === null || rowMetadata === void 0 ? void 0 : rowMetadata.hiddenByUser) || (rowMetadata === null || rowMetadata === void 0 ? void 0 : rowMetadata.hiddenByFilter));
743
+ defaultRowHeightPx = getDefaultRowHeightPx(sheet);
744
+ rowSize = (rowMetadata === null || rowMetadata === void 0 ? void 0 : rowMetadata.size) && rowMetadata.size > 0 ? rowMetadata.size : undefined;
745
+ hasExplicitHeight = Boolean(rowSize && Math.abs(rowSize - defaultRowHeightPx) > 0.01);
746
+ hasCustomHeight = Boolean(rowSize && (rowMetadata === null || rowMetadata === void 0 ? void 0 : rowMetadata.resizedByUser));
747
+ rowStyle = styleBuilder.registerRow(rowSize && (hasExplicitHeight || hasCustomHeight) ? rowSize : undefined, hasHiddenFlag);
748
+ maxColumnIndex = Math.max(values.length - 1, (_d = mergeState.maxColumnByRow.get(rowNumber)) !== null && _d !== void 0 ? _d : 0);
749
+ columnIndex = 1;
750
+ _e.label = 1;
751
+ case 1:
752
+ if (!(columnIndex <= maxColumnIndex)) return [3 /*break*/, 4];
753
+ if (mergeState.coveredCells.has("".concat(rowNumber, ":").concat(columnIndex))) {
754
+ cellXmlChunks.push("<table:covered-table-cell/>");
755
+ return [3 /*break*/, 3];
756
+ }
757
+ cell = values[columnIndex];
758
+ mergeSpan = mergeState.anchorSpans.get("".concat(rowNumber, ":").concat(columnIndex));
759
+ return [4 /*yield*/, buildCellXml({
760
+ rowNumber: rowNumber,
761
+ columnIndex: columnIndex,
762
+ cell: cell,
763
+ sourceSharedStrings: sourceSharedStrings,
764
+ cellXfs: cellXfs,
765
+ styleBuilder: styleBuilder,
766
+ dataValidationsById: dataValidationsById,
767
+ mergeSpan: mergeSpan,
768
+ mediaEntries: mediaEntries,
769
+ sheet: sheet,
770
+ namedRangeNames: namedRangeNames,
771
+ tables: tables,
772
+ ignoreFormulaPatterns: ignoreFormulaPatterns,
773
+ annotationsMap: annotationsMap,
774
+ sheetData: sheetData,
775
+ sheets: sheets,
776
+ locale: locale,
777
+ })];
778
+ case 2:
779
+ cellXml = _e.sent();
780
+ if (!cellXml) {
781
+ cellXmlChunks.push("<table:table-cell/>");
782
+ return [3 /*break*/, 3];
783
+ }
784
+ cellXmlChunks.push(cellXml);
785
+ minColumn = Math.min(minColumn, columnIndex);
786
+ maxColumn = Math.max(maxColumn, columnIndex);
787
+ _e.label = 3;
788
+ case 3:
789
+ columnIndex++;
790
+ return [3 /*break*/, 1];
791
+ case 4:
792
+ hasCells = cellXmlChunks.length > 0;
793
+ needsMetadata = hasHiddenFlag || hasExplicitHeight || hasCustomHeight;
794
+ if (!hasCells && !needsMetadata) {
795
+ return [2 /*return*/, null];
796
+ }
797
+ attrs = [];
798
+ if (rowStyle) {
799
+ attrs.push("table:style-name=\"".concat(rowStyle, "\""));
800
+ }
801
+ rowXml = "<table:table-row".concat(attrs.length ? " " + attrs.join(" ") : "", ">").concat(cellXmlChunks.join(""), "</table:table-row>");
802
+ return [2 /*return*/, {
803
+ xml: rowXml,
804
+ minColumn: isFinite(minColumn) ? minColumn : undefined,
805
+ maxColumn: maxColumn || undefined,
806
+ }];
807
+ }
808
+ });
809
+ }); };
810
+ var buildCellXml = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
811
+ var normalizedCell, userEnteredValue, effectiveValue, resolveStyleRef, effectiveFormat, formattedValue, richTextRuns, valueSource, numberValue, boolValue, rawFormulaValue, formulaValue, errorValue, stringValue, sharedStringIndex, sharedStringValue, isDateLike, hasExplicitValue, formatForExport, sheetIdByName_1, sheets_1, sheets_1_1, s, cellXfsRegistry, derived, cellStyle, address, validationRule, validationId, validationAttr, attrs, valueAttr, textNode, errorText, text, resolvedFormula, formulaAttr, arrayRef, spill, cols, rows, hyperlinkValue, href, display, imageXml, annotationXml, annotation, now;
812
+ var e_12, _c;
813
+ var _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
814
+ var rowNumber = _b.rowNumber, columnIndex = _b.columnIndex, cell = _b.cell, sourceSharedStrings = _b.sourceSharedStrings, cellXfs = _b.cellXfs, styleBuilder = _b.styleBuilder, dataValidationsById = _b.dataValidationsById, mergeSpan = _b.mergeSpan, mediaEntries = _b.mediaEntries, sheet = _b.sheet, namedRangeNames = _b.namedRangeNames, tables = _b.tables, ignoreFormulaPatterns = _b.ignoreFormulaPatterns, annotationsMap = _b.annotationsMap, sheetData = _b.sheetData, sheets = _b.sheets, locale = _b.locale;
815
+ return __generator(this, function (_p) {
816
+ switch (_p.label) {
817
+ case 0:
818
+ normalizedCell = cell;
819
+ userEnteredValue = getCellUserEnteredValue(normalizedCell);
820
+ effectiveValue = (_d = getCellEffectiveValue(normalizedCell)) !== null && _d !== void 0 ? _d : userEnteredValue;
821
+ resolveStyleRef = function (fmt) {
822
+ var _a;
823
+ if (!fmt)
824
+ return undefined;
825
+ if (isStyleReference(fmt)) {
826
+ var styleId = (_a = fmt.sid) !== null && _a !== void 0 ? _a : fmt.styleId;
827
+ return styleId ? cellXfs === null || cellXfs === void 0 ? void 0 : cellXfs.get(styleId) : undefined;
828
+ }
829
+ return fmt;
830
+ };
831
+ effectiveFormat = (_e = resolveStyleRef(getCellUserEnteredFormat(normalizedCell))) !== null && _e !== void 0 ? _e : resolveStyleRef(getCellEffectiveFormat(normalizedCell));
832
+ formattedValue = getCellFormattedValue(normalizedCell);
833
+ valueSource = (_f = omitInvalidDataValidationError(effectiveValue)) !== null && _f !== void 0 ? _f : omitInvalidDataValidationError(userEnteredValue);
834
+ numberValue = getExtendedValueNumber(valueSource);
835
+ boolValue = getExtendedValueBool(valueSource);
836
+ rawFormulaValue = getExtendedValueFormula(userEnteredValue);
837
+ formulaValue = shouldIgnoreFormula(rawFormulaValue, ignoreFormulaPatterns)
838
+ ? undefined
839
+ : rawFormulaValue;
840
+ errorValue = getExtendedValueError(valueSource);
841
+ stringValue = getExtendedValueString(valueSource);
842
+ sharedStringIndex = normalizedCell === null || normalizedCell === void 0 ? void 0 : normalizedCell.ss;
843
+ sharedStringValue = sharedStringIndex != null && sourceSharedStrings
844
+ ? sourceSharedStrings.get(String(sharedStringIndex))
845
+ : null;
846
+ if (sharedStringValue != null) {
847
+ stringValue =
848
+ typeof sharedStringValue === "string"
849
+ ? sharedStringValue
850
+ : (_g = sharedStringValue.text) !== null && _g !== void 0 ? _g : "";
851
+ richTextRuns =
852
+ typeof sharedStringValue === "object" &&
853
+ Array.isArray(sharedStringValue.runs)
854
+ ? (sharedStringValue.runs)
855
+ : undefined;
856
+ formattedValue = undefined;
857
+ }
858
+ isDateLike = ((_h = effectiveFormat === null || effectiveFormat === void 0 ? void 0 : effectiveFormat.numberFormat) === null || _h === void 0 ? void 0 : _h.type) === "DATE" ||
859
+ ((_j = effectiveFormat === null || effectiveFormat === void 0 ? void 0 : effectiveFormat.numberFormat) === null || _j === void 0 ? void 0 : _j.type) === "DATE_TIME";
860
+ if (isDateLike && formattedValue) {
861
+ stringValue = formattedValue;
862
+ }
863
+ if (formulaValue &&
864
+ (stringValue != null || formattedValue != null) &&
865
+ stringValue == null) {
866
+ stringValue = String(formattedValue !== null && formattedValue !== void 0 ? formattedValue : "");
867
+ }
868
+ hasExplicitValue = !isNil(numberValue) ||
869
+ !isNil(boolValue) ||
870
+ !isNil(formulaValue) ||
871
+ !isNil(errorValue) ||
872
+ stringValue != null;
873
+ if (!hasExplicitValue && formattedValue === "") {
874
+ formattedValue = undefined;
875
+ }
876
+ formatForExport = effectiveFormat;
877
+ if (formulaValue &&
878
+ !(formatForExport === null || formatForExport === void 0 ? void 0 : formatForExport.numberFormat) &&
879
+ sheetData &&
880
+ sheets &&
881
+ (sheet === null || sheet === void 0 ? void 0 : sheet.sheetId) != null) {
882
+ sheetIdByName_1 = new Map();
883
+ try {
884
+ for (sheets_1 = __values(sheets), sheets_1_1 = sheets_1.next(); !sheets_1_1.done; sheets_1_1 = sheets_1.next()) {
885
+ s = sheets_1_1.value;
886
+ if (s === null || s === void 0 ? void 0 : s.title)
887
+ sheetIdByName_1.set(s.title, s.sheetId);
888
+ }
889
+ }
890
+ catch (e_12_1) { e_12 = { error: e_12_1 }; }
891
+ finally {
892
+ try {
893
+ if (sheets_1_1 && !sheets_1_1.done && (_c = sheets_1.return)) _c.call(sheets_1);
894
+ }
895
+ finally { if (e_12) throw e_12.error; }
896
+ }
897
+ cellXfsRegistry = cellXfs ? new CellXfsRegistry(cellXfs) : undefined;
898
+ derived = (_k = deriveEffectiveNumberFormatFromFormula(formulaValue, sheet.sheetId, rowNumber, columnIndex, sheetData, function (input) { return defaultTokenizer(input); }, function (name) { var _a; return (_a = sheetIdByName_1.get(name)) !== null && _a !== void 0 ? _a : sheet.sheetId; }, locale, cellXfsRegistry, undefined, typeof numberValue === "number" ? numberValue : null)) !== null && _k !== void 0 ? _k : undefined;
899
+ if (derived) {
900
+ formatForExport = __assign(__assign({}, (formatForExport !== null && formatForExport !== void 0 ? formatForExport : {})), { numberFormat: derived });
901
+ }
902
+ }
903
+ cellStyle = styleBuilder.registerCell(formatForExport);
904
+ address = cellToAddress({
905
+ rowIndex: rowNumber,
906
+ columnIndex: columnIndex,
907
+ });
908
+ if (!address)
909
+ return [2 /*return*/, undefined];
910
+ validationRule = resolveCellDataValidation(normalizedCell, dataValidationsById);
911
+ validationId = (validationRule === null || validationRule === void 0 ? void 0 : validationRule.id) != null ? String(validationRule.id) : "";
912
+ validationAttr = validationId
913
+ ? " table:content-validation-name=\"".concat(escapeXml(validationId), "\"")
914
+ : "";
915
+ attrs = [];
916
+ if (cellStyle) {
917
+ attrs.push("table:style-name=\"".concat(cellStyle, "\""));
918
+ }
919
+ if (mergeSpan) {
920
+ if (mergeSpan.columns > 1) {
921
+ attrs.push("table:number-columns-spanned=\"".concat(mergeSpan.columns, "\""));
922
+ }
923
+ if (mergeSpan.rows > 1) {
924
+ attrs.push("table:number-rows-spanned=\"".concat(mergeSpan.rows, "\""));
925
+ }
926
+ }
927
+ valueAttr = "";
928
+ textNode = "";
929
+ if (errorValue) {
930
+ errorText = typeof errorValue === "string"
931
+ ? errorValue
932
+ : (errorValue === null || errorValue === void 0 ? void 0 : errorValue.type) || (errorValue === null || errorValue === void 0 ? void 0 : errorValue.message) || "#VALUE!";
933
+ valueAttr = " office:value-type=\"string\" office:string-value=\"".concat(escapeXml(errorText), "\"");
934
+ textNode = "<text:p>".concat(escapeXml(errorText), "</text:p>");
935
+ }
936
+ else if (!isNil(numberValue)) {
937
+ valueAttr = " office:value-type=\"float\" office:value=\"".concat(numberValue, "\"");
938
+ if (stringValue != null) {
939
+ textNode = "<text:p>".concat(escapeXml(String(stringValue)), "</text:p>");
940
+ }
941
+ }
942
+ else if (!isNil(boolValue)) {
943
+ valueAttr = " office:value-type=\"boolean\" office:boolean-value=\"".concat(boolValue ? "true" : "false", "\"");
944
+ }
945
+ else if (stringValue != null || formattedValue != null) {
946
+ text = stringValue !== null && stringValue !== void 0 ? stringValue : formattedValue;
947
+ if (text == null)
948
+ return [2 /*return*/, undefined];
949
+ valueAttr = " office:value-type=\"string\" office:string-value=\"".concat(escapeXml(String(text)), "\"");
950
+ textNode = buildRichTextParagraph(String(text), richTextRuns, styleBuilder);
951
+ }
952
+ if (formulaValue) {
953
+ resolvedFormula = resolveStructuredReferencesForOds(formulaValue, tables, rowNumber, columnIndex);
954
+ // If formula contains property references (e.g., =A1.propertyName),
955
+ // skip exporting unsupported formula and use formatted value instead
956
+ if (!hasPropertyReference(resolvedFormula)) {
957
+ formulaAttr = " table:formula=\"".concat(escapeXml(toOdsFormula(resolvedFormula, namedRangeNames)), "\"");
958
+ if (!valueAttr) {
959
+ valueAttr = " office:value-type=\"string\" office:string-value=\"\"";
960
+ }
961
+ valueAttr = "".concat(formulaAttr).concat(valueAttr);
962
+ arrayRef = normalizedCell === null || normalizedCell === void 0 ? void 0 : normalizedCell.af;
963
+ if (arrayRef) {
964
+ spill = addressToSelection(arrayRef);
965
+ if (spill) {
966
+ cols = spill.range.endColumnIndex - spill.range.startColumnIndex + 1;
967
+ rows = spill.range.endRowIndex - spill.range.startRowIndex + 1;
968
+ if (cols > 0) {
969
+ attrs.push("table:number-matrix-columns-spanned=\"".concat(cols, "\""));
970
+ }
971
+ if (rows > 0) {
972
+ attrs.push("table:number-matrix-rows-spanned=\"".concat(rows, "\""));
973
+ }
974
+ }
975
+ }
976
+ }
977
+ }
978
+ hyperlinkValue = normalizeHyperlinkValue(normalizedCell === null || normalizedCell === void 0 ? void 0 : normalizedCell.hyperlink);
979
+ if (hyperlinkValue) {
980
+ href = normalizeOdsHyperlinkHref(hyperlinkValue);
981
+ display = (_o = (_m = (_l = hyperlinkValue.display) !== null && _l !== void 0 ? _l : stringValue) !== null && _m !== void 0 ? _m : formattedValue) !== null && _o !== void 0 ? _o : "";
982
+ if (!valueAttr) {
983
+ valueAttr = " office:value-type=\"string\" office:string-value=\"".concat(escapeXml(String(display !== null && display !== void 0 ? display : "")), "\"");
984
+ }
985
+ textNode = "<text:p><text:a xlink:href=\"".concat(escapeXml(href), "\" xlink:type=\"simple\">").concat(escapeXml(String(display !== null && display !== void 0 ? display : "")), "</text:a></text:p>");
986
+ }
987
+ return [4 /*yield*/, buildCellImageXml({
988
+ imageUrl: normalizedCell === null || normalizedCell === void 0 ? void 0 : normalizedCell.imageUrl,
989
+ rowNumber: rowNumber,
990
+ columnIndex: columnIndex,
991
+ mergeSpan: mergeSpan,
992
+ sheet: sheet,
993
+ mediaEntries: mediaEntries,
994
+ })];
995
+ case 1:
996
+ imageXml = _p.sent();
997
+ annotationXml = "";
998
+ if (annotationsMap && address) {
999
+ annotation = annotationsMap.get(address);
1000
+ if (annotation) {
1001
+ now = new Date().toISOString();
1002
+ annotationXml = "<office:annotation><dc:creator>".concat(escapeXml(annotation.author), "</dc:creator><dc:date>").concat(now, "</dc:date><text:p>").concat(escapeXml(annotation.text), "</text:p></office:annotation>");
1003
+ }
1004
+ }
1005
+ if (!valueAttr && !cellStyle && !textNode && !imageXml && !annotationXml) {
1006
+ return [2 /*return*/, undefined];
1007
+ }
1008
+ return [2 /*return*/, "<table:table-cell".concat(valueAttr).concat(validationAttr).concat(attrs.length ? " " + attrs.join(" ") : "", ">").concat(annotationXml).concat(textNode).concat(imageXml, "</table:table-cell>")];
1009
+ }
1010
+ });
1011
+ }); };
1012
+ var normalizeHyperlinkValue = function (hyperlink) {
1013
+ if (!hyperlink) {
1014
+ return undefined;
1015
+ }
1016
+ if (typeof hyperlink === "string") {
1017
+ return { kind: "external", url: hyperlink };
1018
+ }
1019
+ return hyperlink;
1020
+ };
1021
+ var normalizeOdsHyperlinkHref = function (hyperlink) {
1022
+ if (hyperlink.kind === "external") {
1023
+ return hyperlink.url;
1024
+ }
1025
+ var location = hyperlink.location.trim();
1026
+ if (location.startsWith("#")) {
1027
+ location = location.slice(1);
1028
+ }
1029
+ if (location.includes("!")) {
1030
+ location = location.replace("!", ".");
1031
+ }
1032
+ return "#".concat(location);
1033
+ };
1034
+ var shouldIgnoreFormula = function (formula, patterns) {
1035
+ if (!formula)
1036
+ return false;
1037
+ // Always ignore SPARKLINE formulas - they're exported as native ODS sparklines
1038
+ if (formula.toUpperCase().startsWith("=SPARKLINE(")) {
1039
+ return true;
1040
+ }
1041
+ if (!patterns)
1042
+ return false;
1043
+ var normalized = formula.startsWith("=") ? formula.slice(1) : formula;
1044
+ var list = Array.isArray(patterns) ? patterns : [patterns];
1045
+ return list.some(function (pattern) { return pattern.test(formula) || pattern.test(normalized); });
1046
+ };
1047
+ var hasPropertyReference = function (formula) {
1048
+ if (!formula)
1049
+ return false;
1050
+ // Detects cell references with property access: A1.property, $A$1.nested.value, etc.
1051
+ var propertyReferencePattern = /[$]?[A-Za-z]{1,3}[$]?[1-9][0-9]*\./;
1052
+ return propertyReferencePattern.test(formula);
1053
+ };
1054
+ var resolveStructuredReferencesForOds = function (formula, tables, rowNumber, columnIndex) {
1055
+ if (!formula || !tables.length)
1056
+ return formula;
1057
+ var stringRegex = /"([^"]|"")*"/g;
1058
+ var result = "";
1059
+ var lastIndex = 0;
1060
+ var match;
1061
+ while ((match = stringRegex.exec(formula)) !== null) {
1062
+ var before = formula.slice(lastIndex, match.index);
1063
+ result += resolveStructuredRefsInSegment(before, tables, rowNumber, columnIndex);
1064
+ result += match[0];
1065
+ lastIndex = match.index + match[0].length;
1066
+ }
1067
+ result += resolveStructuredRefsInSegment(formula.slice(lastIndex), tables, rowNumber, columnIndex);
1068
+ return result;
1069
+ };
1070
+ var resolveStructuredRefsInSegment = function (segment, tables, rowNumber, columnIndex) {
1071
+ var e_13, _a, e_14, _b, e_15, _c, e_16, _d;
1072
+ var _e, _f;
1073
+ if (!segment)
1074
+ return segment;
1075
+ var normalized = segment;
1076
+ var tableForCell = findTableForCell(tables, rowNumber, columnIndex);
1077
+ try {
1078
+ for (var tables_1 = __values(tables), tables_1_1 = tables_1.next(); !tables_1_1.done; tables_1_1 = tables_1.next()) {
1079
+ var table = tables_1_1.value;
1080
+ if (!((_e = table.columns) === null || _e === void 0 ? void 0 : _e.length))
1081
+ continue;
1082
+ if (!isRowInTableDataRange(table, rowNumber))
1083
+ continue;
1084
+ var nameVariants = getTableNameVariants(table);
1085
+ for (var idx = 0; idx < table.columns.length; idx++) {
1086
+ var columnName = (_f = table.columns[idx]) === null || _f === void 0 ? void 0 : _f.name;
1087
+ if (!columnName)
1088
+ continue;
1089
+ var columnIndex_1 = table.range.startColumnIndex + idx;
1090
+ var cellRef = "".concat(columnIndexToLetter(columnIndex_1)).concat(rowNumber);
1091
+ var escapedColumn = escapeCharacters(columnName);
1092
+ if (!escapedColumn)
1093
+ continue;
1094
+ try {
1095
+ for (var nameVariants_1 = (e_14 = void 0, __values(nameVariants)), nameVariants_1_1 = nameVariants_1.next(); !nameVariants_1_1.done; nameVariants_1_1 = nameVariants_1.next()) {
1096
+ var tableName = nameVariants_1_1.value;
1097
+ var escapedTable = escapeCharacters(tableName);
1098
+ if (!escapedTable)
1099
+ continue;
1100
+ var patterns = [
1101
+ "".concat(escapedTable, "\\[\\[#This Row\\],\\[").concat(escapedColumn, "\\]\\]"),
1102
+ "".concat(escapedTable, "\\[\\@\\[").concat(escapedColumn, "\\]\\]"),
1103
+ "".concat(escapedTable, "\\[\\@").concat(escapedColumn, "\\]"),
1104
+ ];
1105
+ try {
1106
+ for (var patterns_1 = (e_15 = void 0, __values(patterns)), patterns_1_1 = patterns_1.next(); !patterns_1_1.done; patterns_1_1 = patterns_1.next()) {
1107
+ var pattern = patterns_1_1.value;
1108
+ normalized = normalized.replace(new RegExp(pattern, "g"), cellRef);
1109
+ }
1110
+ }
1111
+ catch (e_15_1) { e_15 = { error: e_15_1 }; }
1112
+ finally {
1113
+ try {
1114
+ if (patterns_1_1 && !patterns_1_1.done && (_c = patterns_1.return)) _c.call(patterns_1);
1115
+ }
1116
+ finally { if (e_15) throw e_15.error; }
1117
+ }
1118
+ }
1119
+ }
1120
+ catch (e_14_1) { e_14 = { error: e_14_1 }; }
1121
+ finally {
1122
+ try {
1123
+ if (nameVariants_1_1 && !nameVariants_1_1.done && (_b = nameVariants_1.return)) _b.call(nameVariants_1);
1124
+ }
1125
+ finally { if (e_14) throw e_14.error; }
1126
+ }
1127
+ if ((tableForCell === null || tableForCell === void 0 ? void 0 : tableForCell.id) !== table.id) {
1128
+ continue;
1129
+ }
1130
+ var unqualifiedPatterns = [
1131
+ "\\[\\[#This Row\\],\\[".concat(escapedColumn, "\\]\\]"),
1132
+ "\\[\\@\\[".concat(escapedColumn, "\\]\\]"),
1133
+ "\\[\\@".concat(escapedColumn, "\\]"),
1134
+ ];
1135
+ try {
1136
+ for (var unqualifiedPatterns_1 = (e_16 = void 0, __values(unqualifiedPatterns)), unqualifiedPatterns_1_1 = unqualifiedPatterns_1.next(); !unqualifiedPatterns_1_1.done; unqualifiedPatterns_1_1 = unqualifiedPatterns_1.next()) {
1137
+ var pattern = unqualifiedPatterns_1_1.value;
1138
+ normalized = normalized.replace(new RegExp(pattern, "g"), cellRef);
1139
+ }
1140
+ }
1141
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
1142
+ finally {
1143
+ try {
1144
+ if (unqualifiedPatterns_1_1 && !unqualifiedPatterns_1_1.done && (_d = unqualifiedPatterns_1.return)) _d.call(unqualifiedPatterns_1);
1145
+ }
1146
+ finally { if (e_16) throw e_16.error; }
1147
+ }
1148
+ }
1149
+ }
1150
+ }
1151
+ catch (e_13_1) { e_13 = { error: e_13_1 }; }
1152
+ finally {
1153
+ try {
1154
+ if (tables_1_1 && !tables_1_1.done && (_a = tables_1.return)) _a.call(tables_1);
1155
+ }
1156
+ finally { if (e_13) throw e_13.error; }
1157
+ }
1158
+ return normalized;
1159
+ };
1160
+ var getTableNameVariants = function (table) {
1161
+ var names = new Set();
1162
+ if (table.name)
1163
+ names.add(table.name);
1164
+ if (table.title)
1165
+ names.add(table.title);
1166
+ return Array.from(names);
1167
+ };
1168
+ var isRowInTableDataRange = function (table, rowNumber) {
1169
+ var headerOffset = table.headerRow === false ? 0 : 1;
1170
+ var totalOffset = table.totalRow ? 1 : 0;
1171
+ var start = table.range.startRowIndex + headerOffset;
1172
+ var end = table.range.endRowIndex - totalOffset;
1173
+ return rowNumber >= start && rowNumber <= end;
1174
+ };
1175
+ var findTableForCell = function (tables, rowNumber, columnIndex) {
1176
+ return tables.find(function (table) {
1177
+ var range = table.range;
1178
+ return (rowNumber >= range.startRowIndex &&
1179
+ rowNumber <= range.endRowIndex &&
1180
+ columnIndex >= range.startColumnIndex &&
1181
+ columnIndex <= range.endColumnIndex);
1182
+ });
1183
+ };
1184
+ var toOdsFormula = function (formula, namedRangeNames) {
1185
+ var trimmed = formula.startsWith("=") ? formula.slice(1) : formula;
1186
+ var converted = convertExcelFormulaToOds(trimmed, namedRangeNames);
1187
+ return "of:=".concat(sanitizeXmlText(converted));
1188
+ };
1189
+ var buildCalculationSettingsXml = function (iterativeCalculationOptions) {
1190
+ if (!iterativeCalculationOptions)
1191
+ return "";
1192
+ var attrs = [
1193
+ "table:use-iteration=\"".concat(iterativeCalculationOptions.enabled ? "true" : "false", "\""),
1194
+ ];
1195
+ if (typeof iterativeCalculationOptions.maxIterations === "number") {
1196
+ attrs.push("table:iteration-count=\"".concat(Math.max(0, Math.floor(iterativeCalculationOptions.maxIterations)), "\""));
1197
+ }
1198
+ if (typeof iterativeCalculationOptions.maxChange === "number") {
1199
+ attrs.push("table:minimum-step=\"".concat(iterativeCalculationOptions.maxChange, "\""));
1200
+ }
1201
+ return "<table:calculation-settings ".concat(attrs.join(" "), "/>");
1202
+ };
1203
+ var buildContentXml = function (_a) {
1204
+ var sheetsXml = _a.sheetsXml, databaseRangesXml = _a.databaseRangesXml, namedRangesXml = _a.namedRangesXml, contentValidationsXml = _a.contentValidationsXml, automaticStylesXml = _a.automaticStylesXml, calculationSettingsXml = _a.calculationSettingsXml;
1205
+ return "".concat(XML_DECLARATION, "<office:document-content xmlns:office=\"").concat(ODS_NS.office, "\" xmlns:style=\"").concat(ODS_NS.style, "\" xmlns:text=\"").concat(ODS_NS.text, "\" xmlns:table=\"").concat(ODS_NS.table, "\" xmlns:draw=\"").concat(ODS_NS.draw, "\" xmlns:fo=\"").concat(ODS_NS.fo, "\" xmlns:xlink=\"").concat(ODS_NS.xlink, "\" xmlns:svg=\"").concat(ODS_NS.svg, "\" xmlns:number=\"").concat(ODS_NS.number, "\" xmlns:of=\"").concat(ODS_NS.of, "\" xmlns:calcext=\"").concat(ODS_NS.calcext, "\" xmlns:dc=\"").concat(ODS_NS.dc, "\" office:version=\"1.2\"><office:scripts/><office:automatic-styles>").concat(automaticStylesXml, "</office:automatic-styles><office:body><office:spreadsheet>").concat(calculationSettingsXml).concat(contentValidationsXml).concat(sheetsXml).concat(namedRangesXml).concat(databaseRangesXml, "</office:spreadsheet></office:body></office:document-content>");
1206
+ };
1207
+ var buildStylesXml = function (conditionalStylesXml) {
1208
+ if (conditionalStylesXml === void 0) { conditionalStylesXml = ""; }
1209
+ return "".concat(XML_DECLARATION, "<office:document-styles xmlns:office=\"").concat(ODS_NS.office, "\" xmlns:style=\"").concat(ODS_NS.style, "\" xmlns:text=\"").concat(ODS_NS.text, "\" xmlns:table=\"").concat(ODS_NS.table, "\" xmlns:draw=\"").concat(ODS_NS.draw, "\" xmlns:fo=\"").concat(ODS_NS.fo, "\" xmlns:xlink=\"").concat(ODS_NS.xlink, "\" xmlns:svg=\"").concat(ODS_NS.svg, "\" xmlns:number=\"").concat(ODS_NS.number, "\" office:version=\"1.2\"><office:styles><style:style style:name=\"Default\" style:family=\"table-cell\"><style:paragraph-properties fo:margin-left=\"0cm\" fo:margin-right=\"0cm\"/></style:style>").concat(conditionalStylesXml, "</office:styles><office:automatic-styles/><office:master-styles/></office:document-styles>");
1210
+ };
1211
+ var buildMetaXml = function () {
1212
+ var now = new Date().toISOString();
1213
+ return "".concat(XML_DECLARATION, "<office:document-meta xmlns:office=\"").concat(ODS_NS.office, "\" xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" office:version=\"1.2\"><office:meta><dc:creator>").concat(CREATOR, "</dc:creator><meta:creation-date>").concat(now, "</meta:creation-date></office:meta></office:document-meta>");
1214
+ };
1215
+ var buildSettingsXml = function (sheets, theme) {
1216
+ var entries = sheets
1217
+ .map(function (sheet, index) {
1218
+ var _a, _b, _c, _d, _e;
1219
+ var name = (_a = sheet.title) !== null && _a !== void 0 ? _a : "Sheet".concat(index + 1);
1220
+ var frozenRows = (_b = sheet.frozenRowCount) !== null && _b !== void 0 ? _b : 0;
1221
+ var frozenColumns = (_c = sheet.frozenColumnCount) !== null && _c !== void 0 ? _c : 0;
1222
+ var showGrid = (_d = sheet.showGridLines) !== null && _d !== void 0 ? _d : true;
1223
+ var tabColor = normalizeColor((_e = sheet.tabColor) !== null && _e !== void 0 ? _e : undefined, theme);
1224
+ var freezeCell = buildFreezeCell(frozenRows, frozenColumns);
1225
+ var items = [];
1226
+ if (!showGrid) {
1227
+ items.push("<config:config-item config:name=\"ShowGrid\" config:type=\"boolean\">false</config:config-item>");
1228
+ }
1229
+ if (freezeCell) {
1230
+ items.push("<config:config-item config:name=\"FreezeCell\" config:type=\"string\">".concat(freezeCell, "</config:config-item>"));
1231
+ }
1232
+ if (typeof frozenRows === "number" && frozenRows > 0) {
1233
+ items.push("<config:config-item config:name=\"VerticalSplitPosition\" config:type=\"int\">".concat(frozenRows, "</config:config-item>"));
1234
+ }
1235
+ if (typeof frozenColumns === "number" && frozenColumns > 0) {
1236
+ items.push("<config:config-item config:name=\"HorizontalSplitPosition\" config:type=\"int\">".concat(frozenColumns, "</config:config-item>"));
1237
+ }
1238
+ if (tabColor) {
1239
+ items.push("<config:config-item config:name=\"TabColor\" config:type=\"string\">".concat(tabColor, "</config:config-item>"));
1240
+ }
1241
+ if (!items.length) {
1242
+ return undefined;
1243
+ }
1244
+ return "<config:config-item-map-entry config:name=\"".concat(escapeXml(name), "\">").concat(items.join(""), "</config:config-item-map-entry>");
1245
+ })
1246
+ .filter(function (entry) { return Boolean(entry); });
1247
+ if (!entries.length) {
1248
+ return undefined;
1249
+ }
1250
+ return "".concat(XML_DECLARATION, "<office:document-settings xmlns:office=\"").concat(ODS_NS.office, "\" xmlns:config=\"").concat(ODS_NS.config, "\" office:version=\"1.2\"><office:settings><config:config-item-set config:name=\"ooo:view-settings\"><config:config-item-map-indexed config:name=\"Tables\">").concat(entries.join(""), "</config:config-item-map-indexed></config:config-item-set></office:settings></office:document-settings>");
1251
+ };
1252
+ var buildManifestXml = function (mediaEntries, chartObjects, includeSettings) {
1253
+ var mediaItems = mediaEntries
1254
+ .map(function (entry) {
1255
+ return "<manifest:file-entry manifest:media-type=\"".concat(entry.mime, "\" manifest:full-path=\"").concat(entry.path, "\"/>");
1256
+ })
1257
+ .join("");
1258
+ var chartEntries = chartObjects
1259
+ .map(function (entry) {
1260
+ return "<manifest:file-entry manifest:media-type=\"application/vnd.oasis.opendocument.chart\" manifest:full-path=\"".concat(entry.folder, "\"/><manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"").concat(entry.folder, "/content.xml\"/>");
1261
+ })
1262
+ .join("");
1263
+ var settingsEntry = includeSettings
1264
+ ? "<manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"settings.xml\"/>"
1265
+ : "";
1266
+ return "".concat(XML_DECLARATION, "<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\"><manifest:file-entry manifest:media-type=\"").concat(ODS_MIMETYPE, "\" manifest:full-path=\"/\"/><manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/><manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"styles.xml\"/><manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"meta.xml\"/>").concat(settingsEntry).concat(mediaItems).concat(chartEntries, "</manifest:manifest>");
1267
+ };
1268
+ var buildFreezeCell = function (rows, columns) {
1269
+ if (!rows && !columns)
1270
+ return undefined;
1271
+ var col = columnIndexToLetter(Math.max(1, columns + 1));
1272
+ var row = Math.max(1, rows + 1);
1273
+ return "".concat(col).concat(row);
1274
+ };
1275
+ var buildColumnsXml = function (sheet, styleBuilder, bounds) {
1276
+ var e_17, _a, e_18, _b;
1277
+ var _c, _d, _e, _f;
1278
+ var metadata = (_c = sheet.columnMetadata) !== null && _c !== void 0 ? _c : [];
1279
+ var maxColumns = Math.max(metadata.length - 1, bounds.maxColumn || 0);
1280
+ if (!maxColumns)
1281
+ return "";
1282
+ var summaryRight = ((_d = sheet.outlinePr) === null || _d === void 0 ? void 0 : _d.summaryRight) !== false;
1283
+ var spans = findOutlineGroupSpans(metadata, maxColumns, summaryRight);
1284
+ var _g = buildOutlineGroupIndex(spans), opensAt = _g.opensAt, closesAt = _g.closesAt;
1285
+ var parts = [];
1286
+ for (var index = 1; index <= maxColumns; index++) {
1287
+ try {
1288
+ for (var _h = (e_17 = void 0, __values((_e = opensAt.get(index)) !== null && _e !== void 0 ? _e : [])), _j = _h.next(); !_j.done; _j = _h.next()) {
1289
+ var span = _j.value;
1290
+ parts.push(outlineGroupOpenTag(span, "table:table-column-group"));
1291
+ }
1292
+ }
1293
+ catch (e_17_1) { e_17 = { error: e_17_1 }; }
1294
+ finally {
1295
+ try {
1296
+ if (_j && !_j.done && (_a = _h.return)) _a.call(_h);
1297
+ }
1298
+ finally { if (e_17) throw e_17.error; }
1299
+ }
1300
+ var props = metadata[index];
1301
+ var widthPx = getColumnWidthPx(sheet, index);
1302
+ var hidden = Boolean((props === null || props === void 0 ? void 0 : props.hiddenByUser) || (props === null || props === void 0 ? void 0 : props.hiddenByFilter));
1303
+ var styleName = styleBuilder.registerColumn(widthPx, hidden);
1304
+ var attrs = [];
1305
+ if (styleName) {
1306
+ attrs.push("table:style-name=\"".concat(styleName, "\""));
1307
+ }
1308
+ parts.push("<table:table-column".concat(attrs.length ? " " + attrs.join(" ") : "", "/>"));
1309
+ try {
1310
+ for (var _k = (e_18 = void 0, __values((_f = closesAt.get(index)) !== null && _f !== void 0 ? _f : [])), _l = _k.next(); !_l.done; _l = _k.next()) {
1311
+ var _3 = _l.value;
1312
+ parts.push("</table:table-column-group>");
1313
+ }
1314
+ }
1315
+ catch (e_18_1) { e_18 = { error: e_18_1 }; }
1316
+ finally {
1317
+ try {
1318
+ if (_l && !_l.done && (_b = _k.return)) _b.call(_k);
1319
+ }
1320
+ finally { if (e_18) throw e_18.error; }
1321
+ }
1322
+ }
1323
+ return parts.join("");
1324
+ };
1325
+ var buildCellStyleXml = function (name, format, numberStyleName, theme) {
1326
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
1327
+ var textProps = [];
1328
+ var paragraphProps = [];
1329
+ var cellProps = [];
1330
+ var textFormat = (_a = format.textFormat) !== null && _a !== void 0 ? _a : undefined;
1331
+ if (textFormat === null || textFormat === void 0 ? void 0 : textFormat.bold) {
1332
+ textProps.push("fo:font-weight=\"bold\"");
1333
+ }
1334
+ if (textFormat === null || textFormat === void 0 ? void 0 : textFormat.italic) {
1335
+ textProps.push("fo:font-style=\"italic\"");
1336
+ }
1337
+ if (textFormat === null || textFormat === void 0 ? void 0 : textFormat.underline) {
1338
+ textProps.push("style:text-underline-style=\"solid\"");
1339
+ }
1340
+ if (textFormat === null || textFormat === void 0 ? void 0 : textFormat.strikethrough) {
1341
+ textProps.push("style:text-line-through-style=\"solid\"");
1342
+ }
1343
+ if ((textFormat === null || textFormat === void 0 ? void 0 : textFormat.baselineOffset) === "superscript") {
1344
+ textProps.push("style:text-position=\"super 58%\"");
1345
+ }
1346
+ else if ((textFormat === null || textFormat === void 0 ? void 0 : textFormat.baselineOffset) === "subscript") {
1347
+ textProps.push("style:text-position=\"sub 58%\"");
1348
+ }
1349
+ if (textFormat === null || textFormat === void 0 ? void 0 : textFormat.fontFamily) {
1350
+ textProps.push("fo:font-family=\"".concat(escapeXml(textFormat.fontFamily), "\""));
1351
+ }
1352
+ if (textFormat === null || textFormat === void 0 ? void 0 : textFormat.fontSize) {
1353
+ textProps.push("fo:font-size=\"".concat(textFormat.fontSize, "pt\""));
1354
+ }
1355
+ var textColor = normalizeColor((_b = textFormat === null || textFormat === void 0 ? void 0 : textFormat.color) !== null && _b !== void 0 ? _b : undefined, theme);
1356
+ if (textColor) {
1357
+ textProps.push("fo:color=\"".concat(textColor, "\""));
1358
+ }
1359
+ if (format.horizontalAlignment) {
1360
+ paragraphProps.push("fo:text-align=\"".concat(format.horizontalAlignment, "\""));
1361
+ }
1362
+ if (format.verticalAlignment) {
1363
+ paragraphProps.push("style:vertical-align=\"".concat(mapVerticalAlignment(format.verticalAlignment), "\""));
1364
+ }
1365
+ if (format.wrapStrategy === "wrap") {
1366
+ cellProps.push("fo:wrap-option=\"wrap\"");
1367
+ }
1368
+ else if (format.wrapStrategy === "clip") {
1369
+ cellProps.push("fo:wrap-option=\"no-wrap\"", "style:overflow-behavior=\"clip\"");
1370
+ }
1371
+ if (format.indent) {
1372
+ paragraphProps.push("fo:margin-left=\"".concat(format.indent, "pt\""));
1373
+ }
1374
+ if (format.textRotation === "vertical") {
1375
+ paragraphProps.push("style:direction=\"ttb\"");
1376
+ }
1377
+ else if (typeof format.textRotation === "number") {
1378
+ paragraphProps.push("style:rotation-angle=\"".concat(format.textRotation, "\""));
1379
+ }
1380
+ // ODS doesn't natively model OOXML's 18 pattern types. When a cell has a
1381
+ // non-solid `fillPattern`, prefer the foreground color as the visible
1382
+ // background (matching LibreOffice's behavior on save). Solid / none /
1383
+ // absent fillPattern falls back to the regular backgroundColor path.
1384
+ var fillPatternForBg = format.fillPattern;
1385
+ var useForegroundForBg = fillPatternForBg &&
1386
+ fillPatternForBg !== "none" &&
1387
+ fillPatternForBg !== "solid" &&
1388
+ format.foregroundColor;
1389
+ var background = useForegroundForBg
1390
+ ? normalizeColor((_c = format.foregroundColor) !== null && _c !== void 0 ? _c : undefined, theme)
1391
+ : normalizeColor((_d = format.backgroundColor) !== null && _d !== void 0 ? _d : undefined, theme);
1392
+ if (background) {
1393
+ cellProps.push("fo:background-color=\"".concat(background, "\""));
1394
+ }
1395
+ var borders = format.borders;
1396
+ if (borders) {
1397
+ var top_1 = borderToCss((_e = borders.top) !== null && _e !== void 0 ? _e : undefined, theme);
1398
+ var bottom = borderToCss((_f = borders.bottom) !== null && _f !== void 0 ? _f : undefined, theme);
1399
+ var left = borderToCss((_g = borders.left) !== null && _g !== void 0 ? _g : undefined, theme);
1400
+ var right = borderToCss((_h = borders.right) !== null && _h !== void 0 ? _h : undefined, theme);
1401
+ var diagUp = borderToCss((_j = borders.diagonalUp) !== null && _j !== void 0 ? _j : undefined, theme);
1402
+ var diagDown = borderToCss((_k = borders.diagonalDown) !== null && _k !== void 0 ? _k : undefined, theme);
1403
+ if (top_1)
1404
+ cellProps.push("fo:border-top=\"".concat(top_1, "\""));
1405
+ if (bottom)
1406
+ cellProps.push("fo:border-bottom=\"".concat(bottom, "\""));
1407
+ if (left)
1408
+ cellProps.push("fo:border-left=\"".concat(left, "\""));
1409
+ if (right)
1410
+ cellProps.push("fo:border-right=\"".concat(right, "\""));
1411
+ if (diagUp)
1412
+ cellProps.push("style:diagonal-bl-tr=\"".concat(diagUp, "\""));
1413
+ if (diagDown)
1414
+ cellProps.push("style:diagonal-tl-br=\"".concat(diagDown, "\""));
1415
+ }
1416
+ var dataStyleAttr = numberStyleName
1417
+ ? " style:data-style-name=\"".concat(numberStyleName, "\"")
1418
+ : "";
1419
+ return "<style:style style:name=\"".concat(name, "\" style:family=\"table-cell\"").concat(dataStyleAttr, "><style:table-cell-properties").concat(cellProps.length ? " " + cellProps.join(" ") : "", "/><style:paragraph-properties").concat(paragraphProps.length ? " " + paragraphProps.join(" ") : "", "/><style:text-properties").concat(textProps.length ? " " + textProps.join(" ") : "", "/></style:style>");
1420
+ };
1421
+ var buildTextStyleXml = function (name, textFormat, theme) {
1422
+ var _a;
1423
+ var textProps = [];
1424
+ if (textFormat.bold) {
1425
+ textProps.push("fo:font-weight=\"bold\"");
1426
+ }
1427
+ if (textFormat.italic) {
1428
+ textProps.push("fo:font-style=\"italic\"");
1429
+ }
1430
+ if (textFormat.underline) {
1431
+ textProps.push("style:text-underline-style=\"solid\"");
1432
+ }
1433
+ if (textFormat.strikethrough) {
1434
+ textProps.push("style:text-line-through-style=\"solid\"");
1435
+ }
1436
+ if (textFormat.baselineOffset === "superscript") {
1437
+ textProps.push("style:text-position=\"super 58%\"");
1438
+ }
1439
+ else if (textFormat.baselineOffset === "subscript") {
1440
+ textProps.push("style:text-position=\"sub 58%\"");
1441
+ }
1442
+ if (textFormat.fontFamily) {
1443
+ textProps.push("fo:font-family=\"".concat(escapeXml(textFormat.fontFamily), "\""));
1444
+ }
1445
+ if (textFormat.fontSize) {
1446
+ textProps.push("fo:font-size=\"".concat(textFormat.fontSize, "pt\""));
1447
+ }
1448
+ var textColor = normalizeColor((_a = textFormat.color) !== null && _a !== void 0 ? _a : undefined, theme);
1449
+ if (textColor) {
1450
+ textProps.push("fo:color=\"".concat(textColor, "\""));
1451
+ }
1452
+ return "<style:style style:name=\"".concat(name, "\" style:family=\"text\"><style:text-properties").concat(textProps.length ? " " + textProps.join(" ") : "", "/></style:style>");
1453
+ };
1454
+ var buildRichTextParagraph = function (text, runs, styleBuilder) {
1455
+ var e_19, _a;
1456
+ if (!(runs === null || runs === void 0 ? void 0 : runs.length)) {
1457
+ return "<text:p>".concat(escapeXml(String(text)), "</text:p>");
1458
+ }
1459
+ var parts = [];
1460
+ var cursor = 0;
1461
+ var sortedRuns = __spreadArray([], __read(runs), false).sort(function (a, b) { return a.startIndex - b.startIndex || a.endIndex - b.endIndex; });
1462
+ try {
1463
+ for (var sortedRuns_1 = __values(sortedRuns), sortedRuns_1_1 = sortedRuns_1.next(); !sortedRuns_1_1.done; sortedRuns_1_1 = sortedRuns_1.next()) {
1464
+ var run = sortedRuns_1_1.value;
1465
+ if (run.nodeType !== "text")
1466
+ continue;
1467
+ var startIndex = Math.max(0, Math.min(text.length, run.startIndex));
1468
+ var endIndex = Math.max(startIndex, Math.min(text.length, run.endIndex));
1469
+ if (endIndex <= cursor)
1470
+ continue;
1471
+ if (cursor < startIndex) {
1472
+ parts.push(escapeXml(text.slice(cursor, startIndex)));
1473
+ }
1474
+ var runText = text.slice(Math.max(cursor, startIndex), endIndex);
1475
+ var styleName = styleBuilder.registerText(run.format);
1476
+ parts.push(styleName
1477
+ ? "<text:span text:style-name=\"".concat(styleName, "\">").concat(escapeXml(runText), "</text:span>")
1478
+ : escapeXml(runText));
1479
+ cursor = endIndex;
1480
+ }
1481
+ }
1482
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
1483
+ finally {
1484
+ try {
1485
+ if (sortedRuns_1_1 && !sortedRuns_1_1.done && (_a = sortedRuns_1.return)) _a.call(sortedRuns_1);
1486
+ }
1487
+ finally { if (e_19) throw e_19.error; }
1488
+ }
1489
+ if (cursor < text.length) {
1490
+ parts.push(escapeXml(text.slice(cursor)));
1491
+ }
1492
+ return "<text:p>".concat(parts.join(""), "</text:p>");
1493
+ };
1494
+ var buildRowStyleXml = function (name, heightPx, hidden) {
1495
+ var props = [];
1496
+ if (heightPx) {
1497
+ props.push("style:row-height=\"".concat(pxToCm(heightPx).toFixed(2), "cm\""));
1498
+ }
1499
+ if (hidden) {
1500
+ props.push("style:visibility=\"collapse\"");
1501
+ }
1502
+ return "<style:style style:name=\"".concat(name, "\" style:family=\"table-row\"><style:table-row-properties").concat(props.length ? " " + props.join(" ") : "", "/></style:style>");
1503
+ };
1504
+ var buildColumnStyleXml = function (name, widthPx, hidden) {
1505
+ var props = [];
1506
+ if (widthPx) {
1507
+ props.push("style:column-width=\"".concat(pxToCm(widthPx).toFixed(2), "cm\""));
1508
+ }
1509
+ if (hidden) {
1510
+ props.push("style:visibility=\"collapse\"");
1511
+ }
1512
+ return "<style:style style:name=\"".concat(name, "\" style:family=\"table-column\"><style:table-column-properties").concat(props.length ? " " + props.join(" ") : "", "/></style:style>");
1513
+ };
1514
+ var buildNumberStyleXml = function (name, format) {
1515
+ if (!format)
1516
+ return "";
1517
+ var type = format.type;
1518
+ if (type === "PERCENT") {
1519
+ return "<number:percentage-style style:name=\"".concat(name, "\"><number:number number:min-integer-digits=\"1\" number:decimal-places=\"2\"/></number:percentage-style>");
1520
+ }
1521
+ if (type === "CURRENCY" || type === "ACCOUNTING") {
1522
+ return "<number:currency-style style:name=\"".concat(name, "\"><number:currency-symbol>$</number:currency-symbol><number:number number:min-integer-digits=\"1\" number:decimal-places=\"2\"/></number:currency-style>");
1523
+ }
1524
+ if (type === "DATE") {
1525
+ return "<number:date-style style:name=\"".concat(name, "\"><number:year number:style=\"long\"/><number:text>-</number:text><number:month number:style=\"long\"/><number:text>-</number:text><number:day number:style=\"long\"/></number:date-style>");
1526
+ }
1527
+ if (type === "TIME") {
1528
+ return "<number:time-style style:name=\"".concat(name, "\"><number:hours/><number:text>:</number:text><number:minutes/><number:text>:</number:text><number:seconds/></number:time-style>");
1529
+ }
1530
+ if (type === "DATE_TIME") {
1531
+ return "<number:date-style style:name=\"".concat(name, "\"><number:year number:style=\"long\"/><number:text>-</number:text><number:month number:style=\"long\"/><number:text>-</number:text><number:day number:style=\"long\"/><number:text> </number:text><number:hours/><number:text>:</number:text><number:minutes/></number:date-style>");
1532
+ }
1533
+ if (type === "SCIENTIFIC") {
1534
+ return "<number:scientific-number-style style:name=\"".concat(name, "\"><number:number number:min-integer-digits=\"1\"/></number:scientific-number-style>");
1535
+ }
1536
+ return "<number:number-style style:name=\"".concat(name, "\"><number:number number:min-integer-digits=\"1\"/></number:number-style>");
1537
+ };
1538
+ var buildAllDataValidationEntries = function (rules, sheetNameById) {
1539
+ if (!rules.length)
1540
+ return [];
1541
+ var entries = rules
1542
+ .map(function (rule) {
1543
+ var _a, _b, _c, _d, _e, _f, _g;
1544
+ var rangeAttr = buildRangeListForValidations((_a = rule.ranges) !== null && _a !== void 0 ? _a : [], sheetNameById);
1545
+ if (!rangeAttr)
1546
+ return undefined;
1547
+ var config = convertDataValidationRule(rule);
1548
+ if (!config)
1549
+ return undefined;
1550
+ var baseCellAddress = buildValidationBaseCellAddress((_b = rule.ranges) !== null && _b !== void 0 ? _b : [], sheetNameById);
1551
+ var attrs = [
1552
+ "table:name=\"".concat(escapeXml(String((_c = rule.id) !== null && _c !== void 0 ? _c : "")), "\""),
1553
+ "table:target-range-address=\"".concat(escapeXmlAddress(rangeAttr), "\""),
1554
+ "table:condition=\"".concat(escapeXml(config.condition), "\""),
1555
+ ];
1556
+ if (config.allowEmptyCell !== undefined) {
1557
+ attrs.push("table:allow-empty-cell=\"".concat(config.allowEmptyCell ? "true" : "false", "\""));
1558
+ }
1559
+ if (config.displayList) {
1560
+ attrs.push("table:display-list=\"".concat(config.displayList, "\""));
1561
+ }
1562
+ if (baseCellAddress) {
1563
+ attrs.push("table:base-cell-address=\"".concat(escapeXmlAddress(baseCellAddress), "\""));
1564
+ }
1565
+ var help = config.helpMessage
1566
+ ? "<table:help-message table:title=\"".concat(escapeXml((_d = config.helpMessage.title) !== null && _d !== void 0 ? _d : ""), "\" table:message=\"").concat(escapeXml((_e = config.helpMessage.message) !== null && _e !== void 0 ? _e : ""), "\"/>")
1567
+ : "";
1568
+ var error = config.errorMessage
1569
+ ? "<table:error-message table:message-type=\"".concat(config.errorMessage.type, "\" table:display=\"true\" table:title=\"").concat(escapeXml((_f = config.errorMessage.title) !== null && _f !== void 0 ? _f : ""), "\" table:message=\"").concat(escapeXml((_g = config.errorMessage.message) !== null && _g !== void 0 ? _g : ""), "\"/>")
1570
+ : "";
1571
+ return "<table:content-validation ".concat(attrs.join(" "), "><table:error-message table:message-type=\"stop\" table:display=\"true\"/></table:content-validation>");
1572
+ })
1573
+ .filter(function (entry) { return Boolean(entry); });
1574
+ return entries;
1575
+ };
1576
+ var buildConditionalFormattingXml = function (_a) {
1577
+ var e_20, _b;
1578
+ var _c, _d, _e, _f, _g, _h, _j, _k;
1579
+ var conditionalFormats = _a.conditionalFormats, sheetName = _a.sheetName, styleBuilder = _a.styleBuilder, namedRangeNames = _a.namedRangeNames;
1580
+ var entries = [];
1581
+ var styleCounter = 1;
1582
+ var escapeConditionText = function (value) { return value.replace(/"/g, '""'); };
1583
+ var ensureFormula = function (formula) {
1584
+ return formula.startsWith("=") ? formula : "=".concat(formula);
1585
+ };
1586
+ var stripFormula = function (formula) {
1587
+ return formula.startsWith("=") ? formula.slice(1) : formula;
1588
+ };
1589
+ var buildFormulaConditionValue = function (formula) {
1590
+ var odsFormula = buildOdsConditionExpression(ensureFormula(formula), namedRangeNames);
1591
+ return odsFormula ? "formula-is(".concat(odsFormula, ")") : undefined;
1592
+ };
1593
+ var orderedRules = conditionalFormats
1594
+ .map(function (rule, index) { return ({ rule: rule, index: index }); })
1595
+ .sort(function (left, right) {
1596
+ var leftPriority = left.rule.priority;
1597
+ var rightPriority = right.rule.priority;
1598
+ if (leftPriority == null && rightPriority == null) {
1599
+ return left.index - right.index;
1600
+ }
1601
+ if (leftPriority == null) {
1602
+ return 1;
1603
+ }
1604
+ if (rightPriority == null) {
1605
+ return -1;
1606
+ }
1607
+ if (leftPriority === rightPriority) {
1608
+ return left.index - right.index;
1609
+ }
1610
+ return leftPriority - rightPriority;
1611
+ })
1612
+ .map(function (_a) {
1613
+ var rule = _a.rule;
1614
+ return rule;
1615
+ });
1616
+ var _loop_2 = function (rule) {
1617
+ if (rule.enabled === false)
1618
+ return "continue";
1619
+ var ranges = (_c = rule.ranges) !== null && _c !== void 0 ? _c : [];
1620
+ if (!ranges.length)
1621
+ return "continue";
1622
+ var rangeAttr = buildCalcextRangeList(ranges, sheetName);
1623
+ if (!rangeAttr)
1624
+ return "continue";
1625
+ var baseCellAddress = buildCalcextBaseAddress(ranges[0], sheetName);
1626
+ var baseCellRef = cellToAddress({
1627
+ rowIndex: ranges[0].startRowIndex,
1628
+ columnIndex: ranges[0].startColumnIndex,
1629
+ });
1630
+ var absoluteRangeRef = (function () {
1631
+ var range = ranges[0];
1632
+ var startCol = columnIndexToLetter(range.startColumnIndex);
1633
+ var endCol = columnIndexToLetter(range.endColumnIndex);
1634
+ return "$".concat(startCol, "$").concat(range.startRowIndex, ":$").concat(endCol, "$").concat(range.endRowIndex);
1635
+ })();
1636
+ var addConditionEntry = function (format, conditionValue) {
1637
+ if (!format || !conditionValue)
1638
+ return;
1639
+ var styleName = styleBuilder.registerConditionalFormat(format, "ConditionalStyle_".concat(styleCounter++));
1640
+ if (!styleName)
1641
+ return;
1642
+ var stopIfTrueAttr = rule.stopIfTrue
1643
+ ? "calcext:stop-if-true=\"true\""
1644
+ : "";
1645
+ var conditionAttrs = [
1646
+ "calcext:apply-style-name=\"".concat(styleName, "\""),
1647
+ "calcext:value=\"".concat(escapeXml(conditionValue), "\""),
1648
+ baseCellAddress
1649
+ ? "calcext:base-cell-address=\"".concat(escapeXml(baseCellAddress), "\"")
1650
+ : "",
1651
+ stopIfTrueAttr,
1652
+ ]
1653
+ .filter(Boolean)
1654
+ .join(" ");
1655
+ entries.push("<calcext:conditional-format calcext:target-range-address=\"".concat(escapeXml(rangeAttr), "\"><calcext:condition ").concat(conditionAttrs, "/></calcext:conditional-format>"));
1656
+ };
1657
+ var buildTextLiteralCondition = function (raw) {
1658
+ return "=\"".concat(escapeConditionText(raw), "\"");
1659
+ };
1660
+ var buildBooleanConditionValue = function () {
1661
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
1662
+ var booleanRule = rule.booleanRule;
1663
+ if (!((_a = booleanRule === null || booleanRule === void 0 ? void 0 : booleanRule.condition) === null || _a === void 0 ? void 0 : _a.type) || !baseCellRef)
1664
+ return undefined;
1665
+ var condition = booleanRule.condition;
1666
+ var values = (_b = condition.values) !== null && _b !== void 0 ? _b : [];
1667
+ var first = (_d = (_c = values[0]) === null || _c === void 0 ? void 0 : _c.userEnteredValue) !== null && _d !== void 0 ? _d : "";
1668
+ var second = (_f = (_e = values[1]) === null || _e === void 0 ? void 0 : _e.userEnteredValue) !== null && _f !== void 0 ? _f : "";
1669
+ var isFormulaValue = function (value) { return value.trim().startsWith("="); };
1670
+ var isNumericValue = function (value) {
1671
+ return value.trim() !== "" && !isNaN(Number(value));
1672
+ };
1673
+ var normalizeDateOperand = function (raw) {
1674
+ var trimmed = raw.trim();
1675
+ if (!trimmed)
1676
+ return "";
1677
+ if (trimmed.startsWith("=")) {
1678
+ return stripFormula(trimmed);
1679
+ }
1680
+ if (isNumericValue(trimmed)) {
1681
+ return trimmed;
1682
+ }
1683
+ return "DATEVALUE(\"".concat(escapeConditionText(trimmed), "\")");
1684
+ };
1685
+ if (condition.type === "CUSTOM_FORMULA") {
1686
+ var formula = (_j = (_h = (_g = condition.values) === null || _g === void 0 ? void 0 : _g[0]) === null || _h === void 0 ? void 0 : _h.userEnteredValue) !== null && _j !== void 0 ? _j : booleanRule.formula;
1687
+ if (!formula)
1688
+ return undefined;
1689
+ return buildFormulaConditionValue(formula);
1690
+ }
1691
+ if (condition.type === "TEXT_EQ") {
1692
+ return buildTextLiteralCondition(first);
1693
+ }
1694
+ if (condition.type === "TEXT_NOT_EQ") {
1695
+ return "not-equal(\"".concat(escapeConditionText(first), "\")");
1696
+ }
1697
+ if (condition.type === "TEXT_CONTAINS") {
1698
+ return "contains-text(\"".concat(escapeConditionText(first), "\")");
1699
+ }
1700
+ if (condition.type === "TEXT_NOT_CONTAINS") {
1701
+ return "not-contains-text(\"".concat(escapeConditionText(first), "\")");
1702
+ }
1703
+ if (condition.type === "TEXT_STARTS_WITH") {
1704
+ return "begins-with(\"".concat(escapeConditionText(first), "\")");
1705
+ }
1706
+ if (condition.type === "TEXT_ENDS_WITH") {
1707
+ return "ends-with(\"".concat(escapeConditionText(first), "\")");
1708
+ }
1709
+ if (condition.type === "NUMBER_BETWEEN" ||
1710
+ condition.type === "NUMBER_NOT_BETWEEN" ||
1711
+ condition.type === "NUMBER_EQ" ||
1712
+ condition.type === "NUMBER_NOT_EQ" ||
1713
+ condition.type === "NUMBER_GREATER" ||
1714
+ condition.type === "NUMBER_GREATER_THAN_EQ" ||
1715
+ condition.type === "NUMBER_LESS" ||
1716
+ condition.type === "NUMBER_LESS_THAN_EQ") {
1717
+ var needsFormula = isFormulaValue(first) ||
1718
+ isFormulaValue(second) ||
1719
+ (!isNumericValue(first) && first) ||
1720
+ (!isNumericValue(second) && second);
1721
+ var operatorMap = {
1722
+ NUMBER_BETWEEN: "between",
1723
+ NUMBER_NOT_BETWEEN: "not-between",
1724
+ NUMBER_EQ: "equal",
1725
+ NUMBER_NOT_EQ: "not-equal",
1726
+ NUMBER_GREATER: "greater-than",
1727
+ NUMBER_GREATER_THAN_EQ: "greater-than-equal",
1728
+ NUMBER_LESS: "less-than",
1729
+ NUMBER_LESS_THAN_EQ: "less-than-equal",
1730
+ };
1731
+ var operator = operatorMap[condition.type];
1732
+ if (!needsFormula && operator) {
1733
+ if ((operator === "between" || operator === "not-between") &&
1734
+ !(first && second)) {
1735
+ return undefined;
1736
+ }
1737
+ if (operator === "between" || operator === "not-between") {
1738
+ return "".concat(operator, "(").concat(first, ",").concat(second, ")");
1739
+ }
1740
+ return "".concat(operator, "(").concat(first, ")");
1741
+ }
1742
+ var firstExpr = first ? stripFormula(first) : "";
1743
+ var secondExpr = second ? stripFormula(second) : "";
1744
+ if ((condition.type === "NUMBER_BETWEEN" ||
1745
+ condition.type === "NUMBER_NOT_BETWEEN") &&
1746
+ (!firstExpr || !secondExpr)) {
1747
+ return undefined;
1748
+ }
1749
+ if (condition.type === "NUMBER_BETWEEN") {
1750
+ return buildFormulaConditionValue("AND(".concat(baseCellRef, ">=").concat(firstExpr, ",").concat(baseCellRef, "<=").concat(secondExpr, ")"));
1751
+ }
1752
+ if (condition.type === "NUMBER_NOT_BETWEEN") {
1753
+ return buildFormulaConditionValue("OR(".concat(baseCellRef, "<").concat(firstExpr, ",").concat(baseCellRef, ">").concat(secondExpr, ")"));
1754
+ }
1755
+ var opMap = {
1756
+ NUMBER_EQ: "=",
1757
+ NUMBER_NOT_EQ: "<>",
1758
+ NUMBER_GREATER: ">",
1759
+ NUMBER_GREATER_THAN_EQ: ">=",
1760
+ NUMBER_LESS: "<",
1761
+ NUMBER_LESS_THAN_EQ: "<=",
1762
+ };
1763
+ var op = opMap[condition.type];
1764
+ if (!op || !firstExpr)
1765
+ return undefined;
1766
+ return ((_k = buildFormulaConditionValue("".concat(baseCellRef).concat(op).concat(firstExpr))) !== null && _k !== void 0 ? _k : undefined);
1767
+ }
1768
+ if (condition.type === "DATE_EQ" ||
1769
+ condition.type === "DATE_NOT_EQ" ||
1770
+ condition.type === "DATE_BEFORE" ||
1771
+ condition.type === "DATE_AFTER" ||
1772
+ condition.type === "DATE_ON_OR_BEFORE" ||
1773
+ condition.type === "DATE_ON_OR_AFTER" ||
1774
+ condition.type === "DATE_BETWEEN" ||
1775
+ condition.type === "DATE_NOT_BETWEEN") {
1776
+ var firstExpr = normalizeDateOperand(first);
1777
+ var secondExpr = normalizeDateOperand(second);
1778
+ if ((condition.type === "DATE_BETWEEN" ||
1779
+ condition.type === "DATE_NOT_BETWEEN") &&
1780
+ (!firstExpr || !secondExpr)) {
1781
+ return undefined;
1782
+ }
1783
+ var opMap = {
1784
+ DATE_EQ: "=",
1785
+ DATE_NOT_EQ: "<>",
1786
+ DATE_BEFORE: "<",
1787
+ DATE_AFTER: ">",
1788
+ DATE_ON_OR_BEFORE: "<=",
1789
+ DATE_ON_OR_AFTER: ">=",
1790
+ };
1791
+ if (condition.type === "DATE_BETWEEN") {
1792
+ return buildFormulaConditionValue("AND(".concat(baseCellRef, ">=").concat(firstExpr, ",").concat(baseCellRef, "<=").concat(secondExpr, ")"));
1793
+ }
1794
+ if (condition.type === "DATE_NOT_BETWEEN") {
1795
+ return buildFormulaConditionValue("OR(".concat(baseCellRef, "<").concat(firstExpr, ",").concat(baseCellRef, ">").concat(secondExpr, ")"));
1796
+ }
1797
+ var op = opMap[condition.type];
1798
+ if (!op || !firstExpr)
1799
+ return undefined;
1800
+ return buildFormulaConditionValue("".concat(baseCellRef).concat(op).concat(firstExpr));
1801
+ }
1802
+ switch (condition.type) {
1803
+ case "BLANK":
1804
+ return buildFormulaConditionValue("".concat(baseCellRef, "=\"\""));
1805
+ case "NOT_BLANK":
1806
+ return buildFormulaConditionValue("".concat(baseCellRef, "<>\"\""));
1807
+ case "ERROR":
1808
+ return buildFormulaConditionValue("ISERROR(".concat(baseCellRef, ")"));
1809
+ case "NOT_ERROR":
1810
+ return buildFormulaConditionValue("NOT(ISERROR(".concat(baseCellRef, "))"));
1811
+ case "BOOLEAN":
1812
+ return buildFormulaConditionValue("OR(".concat(baseCellRef, "=TRUE,").concat(baseCellRef, "=FALSE)"));
1813
+ case "TEXT_IS_EMAIL":
1814
+ return buildFormulaConditionValue("AND(ISNUMBER(SEARCH(\"@\",".concat(baseCellRef, ")),ISNUMBER(SEARCH(\".\",").concat(baseCellRef, ")))"));
1815
+ case "TEXT_IS_URL":
1816
+ return buildFormulaConditionValue("OR(LEFT(".concat(baseCellRef, ",7)=\"http://\",LEFT(").concat(baseCellRef, ",8)=\"https://\")"));
1817
+ case "DATE_IS_VALID":
1818
+ return buildFormulaConditionValue("ISNUMBER(".concat(baseCellRef, ")"));
1819
+ case "NUMBER_ABOVE_AVERAGE":
1820
+ return buildFormulaConditionValue("".concat(baseCellRef, ">AVERAGE(").concat(absoluteRangeRef, ")"));
1821
+ case "NUMBER_BELOW_AVERAGE":
1822
+ return buildFormulaConditionValue("".concat(baseCellRef, "<AVERAGE(").concat(absoluteRangeRef, ")"));
1823
+ case "DATE_TODAY": {
1824
+ var normalized = "INT(".concat(baseCellRef, ")");
1825
+ return buildFormulaConditionValue("".concat(normalized, "=TODAY()"));
1826
+ }
1827
+ case "DATE_YESTERDAY": {
1828
+ var normalized = "INT(".concat(baseCellRef, ")");
1829
+ return buildFormulaConditionValue("".concat(normalized, "=TODAY()-1"));
1830
+ }
1831
+ case "DATE_TOMORROW": {
1832
+ var normalized = "INT(".concat(baseCellRef, ")");
1833
+ return buildFormulaConditionValue("".concat(normalized, "=TODAY()+1"));
1834
+ }
1835
+ case "DATE_LAST_7_DAYS": {
1836
+ var normalized = "INT(".concat(baseCellRef, ")");
1837
+ return buildFormulaConditionValue("AND(".concat(normalized, ">=TODAY()-6,").concat(normalized, "<=TODAY())"));
1838
+ }
1839
+ case "DATE_THIS_WEEK": {
1840
+ var normalized = "INT(".concat(baseCellRef, ")");
1841
+ var weekStart = "TODAY()-WEEKDAY(TODAY(),2)+1";
1842
+ return buildFormulaConditionValue("AND(".concat(normalized, ">=").concat(weekStart, ",").concat(normalized, "<=").concat(weekStart, "+6)"));
1843
+ }
1844
+ case "DATE_LAST_WEEK": {
1845
+ var normalized = "INT(".concat(baseCellRef, ")");
1846
+ var weekStart = "TODAY()-WEEKDAY(TODAY(),2)+1";
1847
+ return buildFormulaConditionValue("AND(".concat(normalized, ">=").concat(weekStart, "-7,").concat(normalized, "<=").concat(weekStart, "-1)"));
1848
+ }
1849
+ case "DATE_NEXT_WEEK": {
1850
+ var normalized = "INT(".concat(baseCellRef, ")");
1851
+ var weekStart = "TODAY()-WEEKDAY(TODAY(),2)+1";
1852
+ return buildFormulaConditionValue("AND(".concat(normalized, ">=").concat(weekStart, "+7,").concat(normalized, "<=").concat(weekStart, "+13)"));
1853
+ }
1854
+ case "DATE_THIS_MONTH": {
1855
+ var normalized = "INT(".concat(baseCellRef, ")");
1856
+ return buildFormulaConditionValue("AND(".concat(normalized, ">=EOMONTH(TODAY(),-1)+1,").concat(normalized, "<=EOMONTH(TODAY(),0))"));
1857
+ }
1858
+ case "DATE_LAST_MONTH": {
1859
+ var normalized = "INT(".concat(baseCellRef, ")");
1860
+ return buildFormulaConditionValue("AND(".concat(normalized, ">=EOMONTH(TODAY(),-2)+1,").concat(normalized, "<=EOMONTH(TODAY(),-1))"));
1861
+ }
1862
+ case "DATE_NEXT_MONTH": {
1863
+ var normalized = "INT(".concat(baseCellRef, ")");
1864
+ return buildFormulaConditionValue("AND(".concat(normalized, ">=EOMONTH(TODAY(),0)+1,").concat(normalized, "<=EOMONTH(TODAY(),1))"));
1865
+ }
1866
+ case "NUMBER_GREATER_THAN_PREVIOUS":
1867
+ return buildFormulaConditionValue("IFERROR(".concat(baseCellRef, ">INDIRECT(\"R[-1]C\",FALSE),TRUE)"));
1868
+ case "NUMBER_GREATER_THAN_EQ_PREVIOUS":
1869
+ return buildFormulaConditionValue("IFERROR(".concat(baseCellRef, ">=INDIRECT(\"R[-1]C\",FALSE),TRUE)"));
1870
+ case "NUMBER_LESS_THAN_PREVIOUS":
1871
+ return buildFormulaConditionValue("IFERROR(".concat(baseCellRef, "<INDIRECT(\"R[-1]C\",FALSE),TRUE)"));
1872
+ case "NUMBER_LESS_THAN_EQ_PREVIOUS":
1873
+ return buildFormulaConditionValue("IFERROR(".concat(baseCellRef, "<=INDIRECT(\"R[-1]C\",FALSE),TRUE)"));
1874
+ case "ONE_OF_LIST": {
1875
+ var entries_1 = values
1876
+ .map(function (value) { return value.userEnteredValue; })
1877
+ .filter(function (value) { return typeof value === "string"; });
1878
+ if (!entries_1.length)
1879
+ return undefined;
1880
+ var conditions = entries_1.map(function (entry) {
1881
+ if (entry.startsWith("=")) {
1882
+ return "".concat(baseCellRef, "=").concat(stripFormula(entry));
1883
+ }
1884
+ if (isNumericValue(entry)) {
1885
+ return "".concat(baseCellRef, "=").concat(entry);
1886
+ }
1887
+ return "".concat(baseCellRef, "=\"").concat(escapeConditionText(entry), "\"");
1888
+ });
1889
+ return buildFormulaConditionValue("OR(".concat(conditions.join(","), ")"));
1890
+ }
1891
+ case "ONE_OF_RANGE": {
1892
+ var rangeRef = (_m = (_l = values[0]) === null || _l === void 0 ? void 0 : _l.userEnteredValue) !== null && _m !== void 0 ? _m : "";
1893
+ if (!rangeRef)
1894
+ return undefined;
1895
+ return buildFormulaConditionValue("COUNTIF(".concat(stripFormula(rangeRef), ",").concat(baseCellRef, ")>0"));
1896
+ }
1897
+ default:
1898
+ return undefined;
1899
+ }
1900
+ };
1901
+ var booleanConditionValue = buildBooleanConditionValue();
1902
+ if (booleanConditionValue) {
1903
+ addConditionEntry((_d = rule.booleanRule) === null || _d === void 0 ? void 0 : _d.format, booleanConditionValue);
1904
+ }
1905
+ if (rule.distinctRule && baseCellRef) {
1906
+ var isUnique = rule.distinctRule.type === "UNIQUE";
1907
+ var op = isUnique ? "=" : ">";
1908
+ addConditionEntry(rule.distinctRule.format, buildFormulaConditionValue("COUNTIF(".concat(absoluteRangeRef, ",").concat(baseCellRef, ")").concat(op, "1")));
1909
+ }
1910
+ if (rule.topBottomRule && baseCellRef) {
1911
+ var rank = Number.isFinite(rule.topBottomRule.rank)
1912
+ ? Math.max(1, rule.topBottomRule.rank)
1913
+ : 10;
1914
+ var isBottom = rule.topBottomRule.type === "BOTTOM";
1915
+ var rankExpr = rule.topBottomRule.isPercent
1916
+ ? "ROUNDUP(COUNT(".concat(absoluteRangeRef, ")*").concat(rank, "/100,0)")
1917
+ : String(rank);
1918
+ var order = isBottom ? ",1" : "";
1919
+ addConditionEntry(rule.topBottomRule.format, buildFormulaConditionValue("RANK(".concat(baseCellRef, ",").concat(absoluteRangeRef).concat(order, ")<=").concat(rankExpr)));
1920
+ }
1921
+ if (rule.gradientRule && baseCellRef) {
1922
+ var gradient = rule.gradientRule;
1923
+ var thresholdForPoint = function (point) {
1924
+ var _a;
1925
+ if (!(point === null || point === void 0 ? void 0 : point.type))
1926
+ return undefined;
1927
+ var type = String(point.type).toUpperCase();
1928
+ var value = (_a = point.value) !== null && _a !== void 0 ? _a : "";
1929
+ switch (type) {
1930
+ case "MIN":
1931
+ return "MIN(".concat(absoluteRangeRef, ")");
1932
+ case "MAX":
1933
+ return "MAX(".concat(absoluteRangeRef, ")");
1934
+ case "NUMBER":
1935
+ return String(value);
1936
+ case "PERCENT":
1937
+ case "PERCENTILE":
1938
+ return "PERCENTILE.INC(".concat(absoluteRangeRef, ",").concat(Number(value) / 100, ")");
1939
+ default:
1940
+ return undefined;
1941
+ }
1942
+ };
1943
+ var minExpr = thresholdForPoint(gradient.minpoint);
1944
+ var midExpr = thresholdForPoint(gradient.midpoint);
1945
+ var maxExpr = thresholdForPoint(gradient.maxpoint);
1946
+ if (((_e = gradient.minpoint) === null || _e === void 0 ? void 0 : _e.color) && (midExpr || maxExpr)) {
1947
+ var upper = (_f = midExpr !== null && midExpr !== void 0 ? midExpr : maxExpr) !== null && _f !== void 0 ? _f : minExpr;
1948
+ if (upper) {
1949
+ addConditionEntry({ backgroundColor: gradient.minpoint.color }, buildFormulaConditionValue("".concat(baseCellRef, "<=").concat(upper)));
1950
+ }
1951
+ }
1952
+ if (((_g = gradient.midpoint) === null || _g === void 0 ? void 0 : _g.color) && midExpr && maxExpr) {
1953
+ addConditionEntry({ backgroundColor: gradient.midpoint.color }, buildFormulaConditionValue("AND(".concat(baseCellRef, ">").concat(midExpr, ",").concat(baseCellRef, "<").concat(maxExpr, ")")));
1954
+ }
1955
+ if (((_h = gradient.maxpoint) === null || _h === void 0 ? void 0 : _h.color) && (maxExpr || midExpr)) {
1956
+ var lower = (_j = maxExpr !== null && maxExpr !== void 0 ? maxExpr : midExpr) !== null && _j !== void 0 ? _j : minExpr;
1957
+ if (lower) {
1958
+ addConditionEntry({ backgroundColor: gradient.maxpoint.color }, buildFormulaConditionValue("".concat(baseCellRef, ">=").concat(lower)));
1959
+ }
1960
+ }
1961
+ }
1962
+ // ODS `calcext:` extension for icon sets and data bars. Same threshold
1963
+ // type vocabulary as ODS gradient, plus a leading "auto-minimum" stop
1964
+ // that LibreOffice expects to match OOXML's leading-cfvo convention.
1965
+ var cfThresholdTypeToOds = function (t) {
1966
+ var _a;
1967
+ if (!(t === null || t === void 0 ? void 0 : t.type))
1968
+ return "";
1969
+ var map = {
1970
+ MIN: "auto-minimum",
1971
+ MAX: "auto-maximum",
1972
+ NUMBER: "value",
1973
+ PERCENT: "percent",
1974
+ PERCENTILE: "percentile",
1975
+ FORMULA: "formula",
1976
+ };
1977
+ var odsType = (_a = map[String(t.type).toUpperCase()]) !== null && _a !== void 0 ? _a : "value";
1978
+ var valueAttr = t.value !== undefined && t.value !== null
1979
+ ? " calcext:value=\"".concat(escapeXml(String(t.value)), "\"")
1980
+ : " calcext:value=\"0\"";
1981
+ return "<calcext:formatting-entry calcext:type=\"".concat(odsType, "\"").concat(valueAttr, "/>");
1982
+ };
1983
+ if (rule.iconSetRule) {
1984
+ var _l = rule.iconSetRule, iconSet = _l.iconSet, thresholds = _l.thresholds;
1985
+ // Prepend the auto-minimum entry that ODS / LibreOffice expects.
1986
+ var entriesXml = __spreadArray([
1987
+ "<calcext:formatting-entry calcext:type=\"auto-minimum\" calcext:value=\"0\"/>"
1988
+ ], __read(thresholds.map(function (t) { return cfThresholdTypeToOds(t); })), false).join("");
1989
+ entries.push("<calcext:conditional-format calcext:target-range-address=\"".concat(escapeXml(rangeAttr), "\"><calcext:icon-set calcext:icon-set-type=\"").concat(iconSet, "\">").concat(entriesXml, "</calcext:icon-set></calcext:conditional-format>"));
1990
+ }
1991
+ if (rule.dataBarRule) {
1992
+ // Data-bar colors are typically authored as hex strings; theme-colored
1993
+ // bars fall back to the LibreOffice default blue rather than resolving
1994
+ // theme indices here (which would require plumbing theme through the
1995
+ // CF builder for one edge case).
1996
+ var colorToHex = function (c) {
1997
+ if (typeof c === "string")
1998
+ return c;
1999
+ return undefined;
2000
+ };
2001
+ var positiveColor = (_k = colorToHex(rule.dataBarRule.color)) !== null && _k !== void 0 ? _k : "#638ec6";
2002
+ var negativeColor = colorToHex(rule.dataBarRule.negativeColor);
2003
+ var entriesXml = [
2004
+ cfThresholdTypeToOds(rule.dataBarRule.minpoint),
2005
+ cfThresholdTypeToOds(rule.dataBarRule.maxpoint),
2006
+ ].join("");
2007
+ var negAttr = negativeColor
2008
+ ? " calcext:negative-color=\"".concat(negativeColor, "\"")
2009
+ : "";
2010
+ entries.push("<calcext:conditional-format calcext:target-range-address=\"".concat(escapeXml(rangeAttr), "\"><calcext:data-bar calcext:positive-color=\"").concat(positiveColor, "\"").concat(negAttr, ">").concat(entriesXml, "</calcext:data-bar></calcext:conditional-format>"));
2011
+ }
2012
+ };
2013
+ try {
2014
+ for (var orderedRules_1 = __values(orderedRules), orderedRules_1_1 = orderedRules_1.next(); !orderedRules_1_1.done; orderedRules_1_1 = orderedRules_1.next()) {
2015
+ var rule = orderedRules_1_1.value;
2016
+ _loop_2(rule);
2017
+ }
2018
+ }
2019
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
2020
+ finally {
2021
+ try {
2022
+ if (orderedRules_1_1 && !orderedRules_1_1.done && (_b = orderedRules_1.return)) _b.call(orderedRules_1);
2023
+ }
2024
+ finally { if (e_20) throw e_20.error; }
2025
+ }
2026
+ if (!entries.length)
2027
+ return "";
2028
+ return "<calcext:conditional-formats>".concat(entries.join(""), "</calcext:conditional-formats>");
2029
+ };
2030
+ var getFilterVisibleValues = function (spec, range, rows, headerRow, totalRow) {
2031
+ var _a, _b, _c;
2032
+ if (headerRow === void 0) { headerRow = true; }
2033
+ if (totalRow === void 0) { totalRow = false; }
2034
+ var values = new Set();
2035
+ var startRowIndex = range.startRowIndex + (headerRow ? 1 : 0);
2036
+ var endRowIndex = range.endRowIndex - (totalRow ? 1 : 0);
2037
+ var columnIndex = range.startColumnIndex + spec.columnIndex;
2038
+ for (var rowIndex = startRowIndex; rowIndex <= endRowIndex; rowIndex++) {
2039
+ var cell = (_b = (_a = rows[rowIndex]) === null || _a === void 0 ? void 0 : _a.values) === null || _b === void 0 ? void 0 : _b[columnIndex];
2040
+ var formattedValue = getCellFormattedValue(cell);
2041
+ var fallbackValue = (_c = formattedValue !== null && formattedValue !== void 0 ? formattedValue : getCellEffectiveValue(cell)) !== null && _c !== void 0 ? _c : getCellUserEnteredValue(cell);
2042
+ if (isNil(fallbackValue) || fallbackValue === "") {
2043
+ values.add(BLANK_LABEL);
2044
+ continue;
2045
+ }
2046
+ values.add(String(fallbackValue));
2047
+ }
2048
+ return __spreadArray([], __read(values), false);
2049
+ };
2050
+ var buildDatabaseRangeEntries = function (tables, sheetName, sheet, rows) {
2051
+ var e_21, _a;
2052
+ var _b, _c, _d, _e, _f, _g, _h, _j, _k;
2053
+ var entries = [];
2054
+ var basicFilter = sheet.basicFilter;
2055
+ try {
2056
+ for (var tables_2 = __values(tables), tables_2_1 = tables_2.next(); !tables_2_1.done; tables_2_1 = tables_2.next()) {
2057
+ var table = tables_2_1.value;
2058
+ var ref = table.ref;
2059
+ if (!ref)
2060
+ continue;
2061
+ var range = "".concat(escapeSheetName(sheetName), ".").concat(ref);
2062
+ var filterButton = table.filterButton !== false;
2063
+ var filterSpecs = (_b = table.filterSpecs) !== null && _b !== void 0 ? _b : (basicFilter && rangesEqual(table.range, basicFilter.range)
2064
+ ? (_c = basicFilter.filterSpecs) !== null && _c !== void 0 ? _c : []
2065
+ : []);
2066
+ var sortSpecs = (_d = table.sortSpecs) !== null && _d !== void 0 ? _d : (basicFilter && rangesEqual(table.range, basicFilter.range)
2067
+ ? (_e = basicFilter.sortSpecs) !== null && _e !== void 0 ? _e : []
2068
+ : []);
2069
+ var filterXml = buildFilterXml(filterSpecs !== null && filterSpecs !== void 0 ? filterSpecs : [], table.range, rows, (_f = table.headerRow) !== null && _f !== void 0 ? _f : true, (_g = table.totalRow) !== null && _g !== void 0 ? _g : false);
2070
+ var sortXml = buildSortXml(sortSpecs !== null && sortSpecs !== void 0 ? sortSpecs : []);
2071
+ var attrs = [
2072
+ "table:name=\"".concat(escapeXml(table.name), "\""),
2073
+ "table:target-range-address=\"".concat(escapeXml(range), "\""),
2074
+ "table:orientation=\"row\"",
2075
+ ];
2076
+ if (filterButton) {
2077
+ attrs.push("table:display-filter-buttons=\"true\"");
2078
+ }
2079
+ entries.push("<table:database-range ".concat(attrs.join(" "), ">").concat(filterXml).concat(sortXml, "</table:database-range>"));
2080
+ }
2081
+ }
2082
+ catch (e_21_1) { e_21 = { error: e_21_1 }; }
2083
+ finally {
2084
+ try {
2085
+ if (tables_2_1 && !tables_2_1.done && (_a = tables_2.return)) _a.call(tables_2);
2086
+ }
2087
+ finally { if (e_21) throw e_21.error; }
2088
+ }
2089
+ if (basicFilter &&
2090
+ !tables.some(function (table) { return rangesEqual(table.range, basicFilter.range); })) {
2091
+ var rangeAddress = buildOdsRangeAddress(basicFilter.range, sheetName);
2092
+ if (rangeAddress) {
2093
+ var filterXml = buildFilterXml((_h = basicFilter.filterSpecs) !== null && _h !== void 0 ? _h : [], basicFilter.range, rows, true, false);
2094
+ var sortXml = buildSortXml((_j = basicFilter.sortSpecs) !== null && _j !== void 0 ? _j : []);
2095
+ var name_1 = (_k = String(basicFilter.id)) !== null && _k !== void 0 ? _k : "Filter_".concat(sheetName);
2096
+ entries.push("<table:database-range table:name=\"".concat(escapeXml(name_1), "\" table:target-range-address=\"").concat(escapeXml(rangeAddress), "\" table:orientation=\"row\" table:display-filter-buttons=\"true\">").concat(filterXml).concat(sortXml, "</table:database-range>"));
2097
+ }
2098
+ }
2099
+ return entries;
2100
+ };
2101
+ var buildDatabaseRangesXml = function (entries) {
2102
+ if (!entries.length)
2103
+ return "";
2104
+ return "<table:database-ranges>".concat(entries.join(""), "</table:database-ranges>");
2105
+ };
2106
+ var buildNamedRangesXml = function (namedRanges, sheetNameById, namedRangeNames) {
2107
+ var e_22, _a;
2108
+ var _b;
2109
+ if (!(namedRanges === null || namedRanges === void 0 ? void 0 : namedRanges.length))
2110
+ return "";
2111
+ var ranges = [];
2112
+ var expressions = [];
2113
+ try {
2114
+ for (var namedRanges_1 = __values(namedRanges), namedRanges_1_1 = namedRanges_1.next(); !namedRanges_1_1.done; namedRanges_1_1 = namedRanges_1.next()) {
2115
+ var namedRange = namedRanges_1_1.value;
2116
+ if (!(namedRange === null || namedRange === void 0 ? void 0 : namedRange.name))
2117
+ continue;
2118
+ if (!isValidNamedRangeName(namedRange.name)) {
2119
+ continue;
2120
+ }
2121
+ if ((_b = namedRange.range) === null || _b === void 0 ? void 0 : _b.sheetId) {
2122
+ var sheetName = sheetNameById.get(namedRange.range.sheetId);
2123
+ if (!sheetName)
2124
+ continue;
2125
+ var address = buildOdsRangeAddressAbsolute(namedRange.range, sheetName);
2126
+ if (!address)
2127
+ continue;
2128
+ var baseAddress = buildOdsBaseAddressAbsolute(namedRange.range, sheetName);
2129
+ if (!baseAddress)
2130
+ continue;
2131
+ ranges.push("<table:named-range table:name=\"".concat(escapeXml(namedRange.name), "\" table:cell-range-address=\"").concat(escapeXml(address), "\" table:base-cell-address=\"").concat(escapeXml(baseAddress), "\"/>"));
2132
+ continue;
2133
+ }
2134
+ var rawValue = namedRange.value;
2135
+ if (typeof rawValue === "string" && rawValue.trim().length) {
2136
+ var trimmed = rawValue.trim();
2137
+ var expression = trimmed.startsWith("=")
2138
+ ? "of:=".concat(sanitizeXmlText(convertExcelFormulaToOds(trimmed.slice(1), namedRangeNames)))
2139
+ : sanitizeXmlText(trimmed);
2140
+ expressions.push("<table:named-expression table:name=\"".concat(escapeXml(namedRange.name), "\" table:expression=\"").concat(escapeXml(expression), "\"/>"));
2141
+ }
2142
+ }
2143
+ }
2144
+ catch (e_22_1) { e_22 = { error: e_22_1 }; }
2145
+ finally {
2146
+ try {
2147
+ if (namedRanges_1_1 && !namedRanges_1_1.done && (_a = namedRanges_1.return)) _a.call(namedRanges_1);
2148
+ }
2149
+ finally { if (e_22) throw e_22.error; }
2150
+ }
2151
+ if (!ranges.length && !expressions.length)
2152
+ return "";
2153
+ return "<table:named-expressions>".concat(ranges.join("")).concat(expressions.join(""), "</table:named-expressions>");
2154
+ };
2155
+ var buildFilterXml = function (filterSpecs, range, rows, headerRow, totalRow) {
2156
+ var e_23, _a, e_24, _b, e_25, _c;
2157
+ var _d, _e, _f;
2158
+ if (headerRow === void 0) { headerRow = true; }
2159
+ if (totalRow === void 0) { totalRow = false; }
2160
+ if (!(filterSpecs === null || filterSpecs === void 0 ? void 0 : filterSpecs.length))
2161
+ return "";
2162
+ var conditions = [];
2163
+ try {
2164
+ for (var filterSpecs_1 = __values(filterSpecs), filterSpecs_1_1 = filterSpecs_1.next(); !filterSpecs_1_1.done; filterSpecs_1_1 = filterSpecs_1.next()) {
2165
+ var spec = filterSpecs_1_1.value;
2166
+ var criteria = spec.filterCriteria;
2167
+ // A condition filter (greater-than / contains / between / blank / …) takes
2168
+ // precedence over a value list, and is emitted as a single operator-based
2169
+ // <table:filter-condition>. Otherwise fall back to value-list entries.
2170
+ var condition = criteria === null || criteria === void 0 ? void 0 : criteria.condition;
2171
+ var mapped = (condition === null || condition === void 0 ? void 0 : condition.type)
2172
+ ? mapConditionToFilterCondition(condition.type, (_d = condition.values) !== null && _d !== void 0 ? _d : [])
2173
+ : undefined;
2174
+ if (mapped) {
2175
+ var attrs = [
2176
+ "table:field-number=\"".concat(spec.columnIndex, "\""),
2177
+ "table:operator=\"".concat(mapped.operator, "\""),
2178
+ ];
2179
+ if (mapped.value !== undefined) {
2180
+ attrs.push("table:value=\"".concat(escapeXml(mapped.value), "\""));
2181
+ }
2182
+ if (mapped.value2 !== undefined) {
2183
+ attrs.push("table:value2=\"".concat(escapeXml(mapped.value2), "\""));
2184
+ }
2185
+ conditions.push("<table:filter-condition ".concat(attrs.join(" "), "/>"));
2186
+ continue;
2187
+ }
2188
+ var visibleValues = (_e = criteria === null || criteria === void 0 ? void 0 : criteria.visibleValues) !== null && _e !== void 0 ? _e : getFilterVisibleValues(spec, range, rows, headerRow, totalRow);
2189
+ var hiddenValues = (_f = criteria === null || criteria === void 0 ? void 0 : criteria.hiddenValues) !== null && _f !== void 0 ? _f : [];
2190
+ try {
2191
+ for (var visibleValues_1 = (e_24 = void 0, __values(visibleValues)), visibleValues_1_1 = visibleValues_1.next(); !visibleValues_1_1.done; visibleValues_1_1 = visibleValues_1.next()) {
2192
+ var value = visibleValues_1_1.value;
2193
+ conditions.push("<table:filter-condition table:field-number=\"".concat(spec.columnIndex, "\" table:operator=\"=\" table:value=\"").concat(escapeXml(value), "\"/>"));
2194
+ }
2195
+ }
2196
+ catch (e_24_1) { e_24 = { error: e_24_1 }; }
2197
+ finally {
2198
+ try {
2199
+ if (visibleValues_1_1 && !visibleValues_1_1.done && (_b = visibleValues_1.return)) _b.call(visibleValues_1);
2200
+ }
2201
+ finally { if (e_24) throw e_24.error; }
2202
+ }
2203
+ try {
2204
+ for (var hiddenValues_1 = (e_25 = void 0, __values(hiddenValues)), hiddenValues_1_1 = hiddenValues_1.next(); !hiddenValues_1_1.done; hiddenValues_1_1 = hiddenValues_1.next()) {
2205
+ var value = hiddenValues_1_1.value;
2206
+ conditions.push("<table:filter-condition table:field-number=\"".concat(spec.columnIndex, "\" table:operator=\"!=\" table:value=\"").concat(escapeXml(value), "\"/>"));
2207
+ }
2208
+ }
2209
+ catch (e_25_1) { e_25 = { error: e_25_1 }; }
2210
+ finally {
2211
+ try {
2212
+ if (hiddenValues_1_1 && !hiddenValues_1_1.done && (_c = hiddenValues_1.return)) _c.call(hiddenValues_1);
2213
+ }
2214
+ finally { if (e_25) throw e_25.error; }
2215
+ }
2216
+ }
2217
+ }
2218
+ catch (e_23_1) { e_23 = { error: e_23_1 }; }
2219
+ finally {
2220
+ try {
2221
+ if (filterSpecs_1_1 && !filterSpecs_1_1.done && (_a = filterSpecs_1.return)) _a.call(filterSpecs_1);
2222
+ }
2223
+ finally { if (e_23) throw e_23.error; }
2224
+ }
2225
+ if (!conditions.length)
2226
+ return "";
2227
+ return "<table:filter><table:filter-and>".concat(conditions.join(""), "</table:filter-and></table:filter>");
2228
+ };
2229
+ var buildSortXml = function (sortSpecs) {
2230
+ if (!(sortSpecs === null || sortSpecs === void 0 ? void 0 : sortSpecs.length))
2231
+ return "";
2232
+ var entries = sortSpecs.map(function (spec) {
2233
+ var order = spec.sortOrder === "DESCENDING" ? "descending" : "ascending";
2234
+ return "<table:sort-by table:field-number=\"".concat(spec.dimensionIndex, "\" table:order=\"").concat(order, "\"/>");
2235
+ });
2236
+ return "<table:sort>".concat(entries.join(""), "</table:sort>");
2237
+ };
2238
+ var mapConditionToFilterCondition = function (type, values) {
2239
+ var _a, _b;
2240
+ var first = (_a = values === null || values === void 0 ? void 0 : values[0]) === null || _a === void 0 ? void 0 : _a.userEnteredValue;
2241
+ var second = (_b = values === null || values === void 0 ? void 0 : values[1]) === null || _b === void 0 ? void 0 : _b.userEnteredValue;
2242
+ switch (type) {
2243
+ case "NUMBER_EQ":
2244
+ case "TEXT_EQ":
2245
+ case "DATE_EQ":
2246
+ return { operator: "=", value: first !== null && first !== void 0 ? first : "" };
2247
+ case "NUMBER_NOT_EQ":
2248
+ case "TEXT_NOT_EQ":
2249
+ case "DATE_NOT_EQ":
2250
+ return { operator: "!=", value: first !== null && first !== void 0 ? first : "" };
2251
+ case "NUMBER_GREATER":
2252
+ case "DATE_AFTER":
2253
+ return { operator: ">", value: first !== null && first !== void 0 ? first : "" };
2254
+ case "NUMBER_GREATER_THAN_EQ":
2255
+ case "DATE_ON_OR_AFTER":
2256
+ return { operator: ">=", value: first !== null && first !== void 0 ? first : "" };
2257
+ case "NUMBER_LESS":
2258
+ case "DATE_BEFORE":
2259
+ return { operator: "<", value: first !== null && first !== void 0 ? first : "" };
2260
+ case "NUMBER_LESS_THAN_EQ":
2261
+ case "DATE_ON_OR_BEFORE":
2262
+ return { operator: "<=", value: first !== null && first !== void 0 ? first : "" };
2263
+ case "NUMBER_BETWEEN":
2264
+ case "DATE_BETWEEN":
2265
+ return { operator: "between", value: first !== null && first !== void 0 ? first : "", value2: second !== null && second !== void 0 ? second : "" };
2266
+ case "NUMBER_NOT_BETWEEN":
2267
+ case "DATE_NOT_BETWEEN":
2268
+ return {
2269
+ operator: "not-between",
2270
+ value: first !== null && first !== void 0 ? first : "",
2271
+ value2: second !== null && second !== void 0 ? second : "",
2272
+ };
2273
+ case "TEXT_CONTAINS":
2274
+ return { operator: "contains", value: first !== null && first !== void 0 ? first : "" };
2275
+ case "TEXT_NOT_CONTAINS":
2276
+ return { operator: "does-not-contain", value: first !== null && first !== void 0 ? first : "" };
2277
+ case "TEXT_STARTS_WITH":
2278
+ return { operator: "begins-with", value: first !== null && first !== void 0 ? first : "" };
2279
+ case "TEXT_ENDS_WITH":
2280
+ return { operator: "ends-with", value: first !== null && first !== void 0 ? first : "" };
2281
+ case "BLANK":
2282
+ return { operator: "empty" };
2283
+ case "NOT_BLANK":
2284
+ return { operator: "non-empty" };
2285
+ case "BOOLEAN":
2286
+ return { operator: "=", value: "TRUE" };
2287
+ default:
2288
+ return undefined;
2289
+ }
2290
+ };
2291
+ var resolveCellDataValidation = function (cell, map) {
2292
+ if (!cell)
2293
+ return undefined;
2294
+ var raw = cell === null || cell === void 0 ? void 0 : cell.dataValidation;
2295
+ if (!raw)
2296
+ return undefined;
2297
+ if (typeof raw === "string" || typeof raw === "number") {
2298
+ return map === null || map === void 0 ? void 0 : map[String(raw)];
2299
+ }
2300
+ return raw;
2301
+ };
2302
+ var buildMergeState = function (ranges) {
2303
+ var e_26, _a;
2304
+ var _b;
2305
+ var normalized = normalizeMergeRanges(ranges);
2306
+ var anchorSpans = new Map();
2307
+ var coveredCells = new Set();
2308
+ var maxColumnByRow = new Map();
2309
+ try {
2310
+ for (var normalized_1 = __values(normalized), normalized_1_1 = normalized_1.next(); !normalized_1_1.done; normalized_1_1 = normalized_1.next()) {
2311
+ var range = normalized_1_1.value;
2312
+ var rows = range.endRowIndex - range.startRowIndex + 1;
2313
+ var columns = range.endColumnIndex - range.startColumnIndex + 1;
2314
+ anchorSpans.set("".concat(range.startRowIndex, ":").concat(range.startColumnIndex), {
2315
+ rows: rows,
2316
+ columns: columns,
2317
+ });
2318
+ for (var r = range.startRowIndex; r <= range.endRowIndex; r++) {
2319
+ for (var c = range.startColumnIndex; c <= range.endColumnIndex; c++) {
2320
+ if (r === range.startRowIndex && c === range.startColumnIndex) {
2321
+ continue;
2322
+ }
2323
+ coveredCells.add("".concat(r, ":").concat(c));
2324
+ }
2325
+ var current = (_b = maxColumnByRow.get(r)) !== null && _b !== void 0 ? _b : 0;
2326
+ maxColumnByRow.set(r, Math.max(current, range.endColumnIndex));
2327
+ }
2328
+ }
2329
+ }
2330
+ catch (e_26_1) { e_26 = { error: e_26_1 }; }
2331
+ finally {
2332
+ try {
2333
+ if (normalized_1_1 && !normalized_1_1.done && (_a = normalized_1.return)) _a.call(normalized_1);
2334
+ }
2335
+ finally { if (e_26) throw e_26.error; }
2336
+ }
2337
+ return { anchorSpans: anchorSpans, coveredCells: coveredCells, maxColumnByRow: maxColumnByRow, ranges: normalized };
2338
+ };
2339
+ var updateBoundsForMerges = function (bounds, state) {
2340
+ var e_27, _a;
2341
+ try {
2342
+ for (var _b = __values(state.ranges), _c = _b.next(); !_c.done; _c = _b.next()) {
2343
+ var range = _c.value;
2344
+ bounds.minRow = Math.min(bounds.minRow, range.startRowIndex);
2345
+ bounds.maxRow = Math.max(bounds.maxRow, range.endRowIndex);
2346
+ bounds.minColumn = Math.min(bounds.minColumn, range.startColumnIndex);
2347
+ bounds.maxColumn = Math.max(bounds.maxColumn, range.endColumnIndex);
2348
+ }
2349
+ }
2350
+ catch (e_27_1) { e_27 = { error: e_27_1 }; }
2351
+ finally {
2352
+ try {
2353
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2354
+ }
2355
+ finally { if (e_27) throw e_27.error; }
2356
+ }
2357
+ };
2358
+ var sanitizeMergeRange = function (range) {
2359
+ var startRow = sanitizeIndex(range === null || range === void 0 ? void 0 : range.startRowIndex);
2360
+ var endRow = sanitizeIndex(range === null || range === void 0 ? void 0 : range.endRowIndex);
2361
+ var startColumn = sanitizeIndex(range === null || range === void 0 ? void 0 : range.startColumnIndex);
2362
+ var endColumn = sanitizeIndex(range === null || range === void 0 ? void 0 : range.endColumnIndex);
2363
+ if (startRow == null ||
2364
+ endRow == null ||
2365
+ startColumn == null ||
2366
+ endColumn == null) {
2367
+ return null;
2368
+ }
2369
+ if (startRow > endRow || startColumn > endColumn) {
2370
+ return null;
2371
+ }
2372
+ if (startRow === endRow && startColumn === endColumn) {
2373
+ return null;
2374
+ }
2375
+ return {
2376
+ startRowIndex: startRow,
2377
+ endRowIndex: endRow,
2378
+ startColumnIndex: startColumn,
2379
+ endColumnIndex: endColumn,
2380
+ };
2381
+ };
2382
+ var sanitizeIndex = function (value) {
2383
+ if (typeof value !== "number" || !Number.isFinite(value))
2384
+ return null;
2385
+ return Math.max(1, Math.floor(value));
2386
+ };
2387
+ var normalizeMergeRanges = function (ranges) {
2388
+ var e_28, _a;
2389
+ if (!(ranges === null || ranges === void 0 ? void 0 : ranges.length))
2390
+ return [];
2391
+ var sanitized = ranges
2392
+ .map(function (range) { return sanitizeMergeRange(range); })
2393
+ .filter(function (range) { return Boolean(range); });
2394
+ if (!sanitized.length)
2395
+ return [];
2396
+ var sorted = sanitized.sort(function (a, b) {
2397
+ if (a.startRowIndex !== b.startRowIndex) {
2398
+ return a.startRowIndex - b.startRowIndex;
2399
+ }
2400
+ if (a.startColumnIndex !== b.startColumnIndex) {
2401
+ return a.startColumnIndex - b.startColumnIndex;
2402
+ }
2403
+ if (a.endRowIndex !== b.endRowIndex) {
2404
+ return b.endRowIndex - a.endRowIndex;
2405
+ }
2406
+ return b.endColumnIndex - a.endColumnIndex;
2407
+ });
2408
+ var valid = [];
2409
+ var active = [];
2410
+ var _loop_3 = function (merge) {
2411
+ if (active.length) {
2412
+ active = active.filter(function (entry) { return entry.endRowIndex >= merge.startRowIndex; });
2413
+ }
2414
+ var isContained = active.some(function (entry) {
2415
+ return entry.startColumnIndex <= merge.startColumnIndex &&
2416
+ entry.endColumnIndex >= merge.endColumnIndex &&
2417
+ entry.endRowIndex >= merge.endRowIndex;
2418
+ });
2419
+ if (!isContained) {
2420
+ valid.push(merge);
2421
+ active.push(merge);
2422
+ }
2423
+ };
2424
+ try {
2425
+ for (var sorted_1 = __values(sorted), sorted_1_1 = sorted_1.next(); !sorted_1_1.done; sorted_1_1 = sorted_1.next()) {
2426
+ var merge = sorted_1_1.value;
2427
+ _loop_3(merge);
2428
+ }
2429
+ }
2430
+ catch (e_28_1) { e_28 = { error: e_28_1 }; }
2431
+ finally {
2432
+ try {
2433
+ if (sorted_1_1 && !sorted_1_1.done && (_a = sorted_1.return)) _a.call(sorted_1);
2434
+ }
2435
+ finally { if (e_28) throw e_28.error; }
2436
+ }
2437
+ return valid;
2438
+ };
2439
+ var buildRangeList = function (ranges, sheetName) {
2440
+ var refs = ranges
2441
+ .map(function (range) { return buildOdsRangeAddress(range, sheetName); })
2442
+ .filter(function (entry) { return Boolean(entry); });
2443
+ if (!refs.length)
2444
+ return "";
2445
+ return refs.join(" ");
2446
+ };
2447
+ var buildRangeListForValidations = function (ranges, sheetNameById) {
2448
+ var refs = ranges
2449
+ .map(function (range) {
2450
+ var _a;
2451
+ var sheetName = sheetNameById.get((_a = range.sheetId) !== null && _a !== void 0 ? _a : 0);
2452
+ if (!sheetName)
2453
+ return undefined;
2454
+ return buildOdsRangeAddress(range, sheetName);
2455
+ })
2456
+ .filter(function (entry) { return Boolean(entry); });
2457
+ if (!refs.length)
2458
+ return "";
2459
+ return refs.join(" ");
2460
+ };
2461
+ var buildValidationBaseCellAddress = function (ranges, sheetNameById) {
2462
+ var _a;
2463
+ if (!ranges.length)
2464
+ return undefined;
2465
+ var range = ranges[0];
2466
+ var sheetName = sheetNameById.get((_a = range.sheetId) !== null && _a !== void 0 ? _a : 0);
2467
+ if (!sheetName)
2468
+ return undefined;
2469
+ return buildOdsBaseAddress(range, sheetName);
2470
+ };
2471
+ var buildCalcextRangeList = function (ranges, sheetName) {
2472
+ var refs = ranges
2473
+ .map(function (range) { return buildCalcextRangeAddress(range, sheetName); })
2474
+ .filter(function (entry) { return Boolean(entry); });
2475
+ if (!refs.length)
2476
+ return "";
2477
+ return refs.join(" ");
2478
+ };
2479
+ var buildOdsRangeAddress = function (range, sheetName) {
2480
+ try {
2481
+ var ref = cellRangeToAddress(undefined, range);
2482
+ if (!ref)
2483
+ return undefined;
2484
+ return "".concat(escapeSheetName(sheetName), ".").concat(ref);
2485
+ }
2486
+ catch (_a) {
2487
+ return undefined;
2488
+ }
2489
+ };
2490
+ var buildOdsBaseAddress = function (range, sheetName) {
2491
+ try {
2492
+ var ref = cellToAddress({
2493
+ rowIndex: range.startRowIndex,
2494
+ columnIndex: range.startColumnIndex,
2495
+ });
2496
+ if (!ref)
2497
+ return undefined;
2498
+ return "".concat(escapeSheetName(sheetName), ".").concat(ref);
2499
+ }
2500
+ catch (_a) {
2501
+ return undefined;
2502
+ }
2503
+ };
2504
+ var buildCalcextRangeAddress = function (range, sheetName) {
2505
+ try {
2506
+ var startCol = columnIndexToLetter(range.startColumnIndex);
2507
+ var endCol = columnIndexToLetter(range.endColumnIndex);
2508
+ var start = "$".concat(escapeSheetName(sheetName), ".$").concat(startCol, "$").concat(range.startRowIndex);
2509
+ var end = "$".concat(escapeSheetName(sheetName), ".$").concat(endCol, "$").concat(range.endRowIndex);
2510
+ return "".concat(start, ":").concat(end);
2511
+ }
2512
+ catch (_a) {
2513
+ return undefined;
2514
+ }
2515
+ };
2516
+ var buildCalcextBaseAddress = function (range, sheetName) {
2517
+ try {
2518
+ var ref = cellToAddress({
2519
+ rowIndex: range.startRowIndex,
2520
+ columnIndex: range.startColumnIndex,
2521
+ });
2522
+ if (!ref)
2523
+ return undefined;
2524
+ return "".concat(escapeSheetName(sheetName), ".").concat(ref);
2525
+ }
2526
+ catch (_a) {
2527
+ return undefined;
2528
+ }
2529
+ };
2530
+ var buildOdsRangeAddressAbsolute = function (range, sheetName) {
2531
+ try {
2532
+ var startCol = columnIndexToLetter(range.startColumnIndex);
2533
+ var endCol = columnIndexToLetter(range.endColumnIndex);
2534
+ var ref = ".$".concat(startCol, "$").concat(range.startRowIndex, ":.").concat("$".concat(endCol, "$").concat(range.endRowIndex));
2535
+ return "$".concat(escapeSheetName(sheetName)).concat(ref);
2536
+ }
2537
+ catch (_a) {
2538
+ return undefined;
2539
+ }
2540
+ };
2541
+ var buildOdsBaseAddressAbsolute = function (range, sheetName) {
2542
+ try {
2543
+ var col = columnIndexToLetter(range.startColumnIndex);
2544
+ var ref = ".$".concat(col, "$").concat(range.startRowIndex);
2545
+ return "$".concat(escapeSheetName(sheetName)).concat(ref);
2546
+ }
2547
+ catch (_a) {
2548
+ return undefined;
2549
+ }
2550
+ };
2551
+ function isValidNamedRangeName(name) {
2552
+ if (!name)
2553
+ return false;
2554
+ if (/^\d/.test(name))
2555
+ return false;
2556
+ if (!/^[A-Za-z_][A-Za-z0-9_.]*$/.test(name))
2557
+ return false;
2558
+ if (/^[A-Za-z]{1,3}\d+$/.test(name))
2559
+ return false;
2560
+ return true;
2561
+ }
2562
+ var rangesEqual = function (left, right) {
2563
+ if (!left || !right)
2564
+ return false;
2565
+ return (left.startRowIndex === right.startRowIndex &&
2566
+ left.endRowIndex === right.endRowIndex &&
2567
+ left.startColumnIndex === right.startColumnIndex &&
2568
+ left.endColumnIndex === right.endColumnIndex);
2569
+ };
2570
+ var escapeSheetName = function (name) {
2571
+ return "'".concat(name.replace(/'/g, "''"), "'");
2572
+ };
2573
+ var columnIndexToLetter = function (index) {
2574
+ var dividend = Math.max(1, index);
2575
+ var columnName = "";
2576
+ while (dividend > 0) {
2577
+ var modulo = (dividend - 1) % 26;
2578
+ columnName = String.fromCharCode(65 + modulo) + columnName;
2579
+ dividend = Math.floor((dividend - modulo) / 26);
2580
+ }
2581
+ return columnName;
2582
+ };
2583
+ var stableStringify = function (value) {
2584
+ return JSON.stringify(value, function (_key, val) {
2585
+ if (val && typeof val === "object" && !Array.isArray(val)) {
2586
+ return Object.keys(val)
2587
+ .sort()
2588
+ .reduce(function (acc, key) {
2589
+ acc[key] = val[key];
2590
+ return acc;
2591
+ }, {});
2592
+ }
2593
+ return val;
2594
+ });
2595
+ };
2596
+ var normalizeCellFormat = function (format) {
2597
+ var normalized = {};
2598
+ if (format.backgroundColor)
2599
+ normalized.backgroundColor = format.backgroundColor;
2600
+ if (format.borders)
2601
+ normalized.borders = format.borders;
2602
+ if (format.textFormat)
2603
+ normalized.textFormat = format.textFormat;
2604
+ if (format.numberFormat)
2605
+ normalized.numberFormat = format.numberFormat;
2606
+ if (format.horizontalAlignment)
2607
+ normalized.horizontalAlignment = format.horizontalAlignment;
2608
+ if (format.verticalAlignment)
2609
+ normalized.verticalAlignment = format.verticalAlignment;
2610
+ if (format.wrapStrategy)
2611
+ normalized.wrapStrategy = format.wrapStrategy;
2612
+ if (format.indent)
2613
+ normalized.indent = format.indent;
2614
+ if (format.textRotation !== undefined)
2615
+ normalized.textRotation = format.textRotation;
2616
+ return normalized;
2617
+ };
2618
+ var normalizeColor = function (color, theme) {
2619
+ if (!color)
2620
+ return undefined;
2621
+ if (typeof color === "string") {
2622
+ var normalized = color.startsWith("#") ? color : "#".concat(color);
2623
+ return normalized.length === 7 ? normalized : undefined;
2624
+ }
2625
+ if (color.rgb) {
2626
+ var rgb = color.rgb;
2627
+ var normalized = rgb.startsWith("#") ? rgb : "#".concat(rgb);
2628
+ return normalized.length === 7 ? normalized : undefined;
2629
+ }
2630
+ if (typeof color.theme === "number") {
2631
+ return resolveThemeColor(color, theme);
2632
+ }
2633
+ return undefined;
2634
+ };
2635
+ var THEME_COLOR_KEYS = {
2636
+ 0: "background1",
2637
+ 1: "text1",
2638
+ 2: "background2",
2639
+ 3: "text2",
2640
+ 4: "accent1",
2641
+ 5: "accent2",
2642
+ 6: "accent3",
2643
+ 7: "accent4",
2644
+ 8: "accent5",
2645
+ 9: "accent6",
2646
+ 10: "hyperlink",
2647
+ };
2648
+ var resolveThemeColor = function (color, theme) {
2649
+ var _a, _b;
2650
+ var themeKey = THEME_COLOR_KEYS[color.theme];
2651
+ if (!themeKey)
2652
+ return undefined;
2653
+ var themeColors = (_a = theme === null || theme === void 0 ? void 0 : theme.themeColors) !== null && _a !== void 0 ? _a : defaultSpreadsheetTheme.themeColors;
2654
+ var base = themeColors[themeKey];
2655
+ if (!base)
2656
+ return undefined;
2657
+ return applyTint(base, (_b = color.tint) !== null && _b !== void 0 ? _b : undefined);
2658
+ };
2659
+ var applyTint = function (hex, tint) {
2660
+ if (tint == null || tint === 0)
2661
+ return hex;
2662
+ var normalized = hex.startsWith("#") ? hex.slice(1) : hex;
2663
+ if (normalized.length !== 6)
2664
+ return "#".concat(normalized);
2665
+ var r = parseInt(normalized.slice(0, 2), 16);
2666
+ var g = parseInt(normalized.slice(2, 4), 16);
2667
+ var b = parseInt(normalized.slice(4, 6), 16);
2668
+ var applyChannel = function (channel) {
2669
+ if (tint < 0) {
2670
+ return Math.round(channel * (1 + tint));
2671
+ }
2672
+ return Math.round(channel * (1 - tint) + 255 * tint);
2673
+ };
2674
+ var toHex = function (value) {
2675
+ return Math.max(0, Math.min(255, value)).toString(16).padStart(2, "0");
2676
+ };
2677
+ return "#".concat(toHex(applyChannel(r))).concat(toHex(applyChannel(g))).concat(toHex(applyChannel(b)));
2678
+ };
2679
+ var mapVerticalAlignment = function (value) {
2680
+ if (value === "middle")
2681
+ return "middle";
2682
+ return value !== null && value !== void 0 ? value : "bottom";
2683
+ };
2684
+ var buildZipStore = function (entries) {
2685
+ var e_29, _a, e_30, _b;
2686
+ var normalized = entries.map(function (entry) {
2687
+ var nameBytes = textEncoder.encode(entry.name);
2688
+ var data = entry.data;
2689
+ var crc = crc32(data);
2690
+ return {
2691
+ name: entry.name,
2692
+ nameBytes: nameBytes,
2693
+ data: data,
2694
+ crc: crc,
2695
+ localSize: 30 + nameBytes.length + data.length,
2696
+ centralSize: 46 + nameBytes.length,
2697
+ localOffset: 0,
2698
+ };
2699
+ });
2700
+ var totalLocal = normalized.reduce(function (sum, entry) { return sum + entry.localSize; }, 0);
2701
+ var totalCentral = normalized.reduce(function (sum, entry) { return sum + entry.centralSize; }, 0);
2702
+ var endSize = 22;
2703
+ var totalSize = totalLocal + totalCentral + endSize;
2704
+ var buffer = new Uint8Array(totalSize);
2705
+ var view = new DataView(buffer.buffer);
2706
+ var cursor = 0;
2707
+ try {
2708
+ for (var normalized_2 = __values(normalized), normalized_2_1 = normalized_2.next(); !normalized_2_1.done; normalized_2_1 = normalized_2.next()) {
2709
+ var entry = normalized_2_1.value;
2710
+ entry.localOffset = cursor;
2711
+ cursor = writeUint32(view, cursor, 0x04034b50);
2712
+ cursor = writeUint16(view, cursor, 20);
2713
+ cursor = writeUint16(view, cursor, 0);
2714
+ cursor = writeUint16(view, cursor, 0);
2715
+ cursor = writeUint16(view, cursor, 0);
2716
+ cursor = writeUint16(view, cursor, 0);
2717
+ cursor = writeUint32(view, cursor, entry.crc);
2718
+ cursor = writeUint32(view, cursor, entry.data.length);
2719
+ cursor = writeUint32(view, cursor, entry.data.length);
2720
+ cursor = writeUint16(view, cursor, entry.nameBytes.length);
2721
+ cursor = writeUint16(view, cursor, 0);
2722
+ buffer.set(entry.nameBytes, cursor);
2723
+ cursor += entry.nameBytes.length;
2724
+ buffer.set(entry.data, cursor);
2725
+ cursor += entry.data.length;
2726
+ }
2727
+ }
2728
+ catch (e_29_1) { e_29 = { error: e_29_1 }; }
2729
+ finally {
2730
+ try {
2731
+ if (normalized_2_1 && !normalized_2_1.done && (_a = normalized_2.return)) _a.call(normalized_2);
2732
+ }
2733
+ finally { if (e_29) throw e_29.error; }
2734
+ }
2735
+ var centralOffset = cursor;
2736
+ try {
2737
+ for (var normalized_3 = __values(normalized), normalized_3_1 = normalized_3.next(); !normalized_3_1.done; normalized_3_1 = normalized_3.next()) {
2738
+ var entry = normalized_3_1.value;
2739
+ cursor = writeUint32(view, cursor, 0x02014b50);
2740
+ cursor = writeUint16(view, cursor, 20);
2741
+ cursor = writeUint16(view, cursor, 20);
2742
+ cursor = writeUint16(view, cursor, 0);
2743
+ cursor = writeUint16(view, cursor, 0);
2744
+ cursor = writeUint16(view, cursor, 0);
2745
+ cursor = writeUint16(view, cursor, 0);
2746
+ cursor = writeUint32(view, cursor, entry.crc);
2747
+ cursor = writeUint32(view, cursor, entry.data.length);
2748
+ cursor = writeUint32(view, cursor, entry.data.length);
2749
+ cursor = writeUint16(view, cursor, entry.nameBytes.length);
2750
+ cursor = writeUint16(view, cursor, 0);
2751
+ cursor = writeUint16(view, cursor, 0);
2752
+ cursor = writeUint16(view, cursor, 0);
2753
+ cursor = writeUint16(view, cursor, 0);
2754
+ cursor = writeUint32(view, cursor, 0);
2755
+ cursor = writeUint32(view, cursor, entry.localOffset);
2756
+ buffer.set(entry.nameBytes, cursor);
2757
+ cursor += entry.nameBytes.length;
2758
+ }
2759
+ }
2760
+ catch (e_30_1) { e_30 = { error: e_30_1 }; }
2761
+ finally {
2762
+ try {
2763
+ if (normalized_3_1 && !normalized_3_1.done && (_b = normalized_3.return)) _b.call(normalized_3);
2764
+ }
2765
+ finally { if (e_30) throw e_30.error; }
2766
+ }
2767
+ var centralSize = cursor - centralOffset;
2768
+ cursor = writeUint32(view, cursor, 0x06054b50);
2769
+ cursor = writeUint16(view, cursor, 0);
2770
+ cursor = writeUint16(view, cursor, 0);
2771
+ cursor = writeUint16(view, cursor, normalized.length);
2772
+ cursor = writeUint16(view, cursor, normalized.length);
2773
+ cursor = writeUint32(view, cursor, centralSize);
2774
+ cursor = writeUint32(view, cursor, centralOffset);
2775
+ cursor = writeUint16(view, cursor, 0);
2776
+ return buffer.buffer;
2777
+ };
2778
+ var writeUint16 = function (view, offset, value) {
2779
+ view.setUint16(offset, value, true);
2780
+ return offset + 2;
2781
+ };
2782
+ var writeUint32 = function (view, offset, value) {
2783
+ view.setUint32(offset, value >>> 0, true);
2784
+ return offset + 4;
2785
+ };
2786
+ var crcTable = null;
2787
+ var getCrcTable = function () {
2788
+ if (crcTable)
2789
+ return crcTable;
2790
+ var table = new Uint32Array(256);
2791
+ for (var i = 0; i < 256; i++) {
2792
+ var c = i;
2793
+ for (var k = 0; k < 8; k++) {
2794
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
2795
+ }
2796
+ table[i] = c >>> 0;
2797
+ }
2798
+ crcTable = table;
2799
+ return table;
2800
+ };
2801
+ var crc32 = function (data) {
2802
+ var table = getCrcTable();
2803
+ var crc = 0xffffffff;
2804
+ for (var i = 0; i < data.length; i++) {
2805
+ crc = table[(crc ^ data[i]) & 0xff] ^ (crc >>> 8);
2806
+ }
2807
+ return (crc ^ 0xffffffff) >>> 0;
2808
+ };
2809
+ var borderToCss = function (border, theme) {
2810
+ var _a, _b;
2811
+ if (!(border === null || border === void 0 ? void 0 : border.style))
2812
+ return undefined;
2813
+ var width = border.width ? Math.max(0.5, border.width) : 1;
2814
+ var color = (_b = normalizeColor((_a = border.color) !== null && _a !== void 0 ? _a : undefined, theme)) !== null && _b !== void 0 ? _b : "#000000";
2815
+ return "".concat(width, "px solid ").concat(color);
2816
+ };
2817
+ var buildOdsConditionExpression = function (formula, namedRangeNames) {
2818
+ var trimmed = formula.startsWith("=") ? formula.slice(1) : formula;
2819
+ return sanitizeXmlText(convertExcelFormulaToOds(trimmed, namedRangeNames));
2820
+ };
2821
+ var convertExcelFormulaToOds = function (formula, namedRangeNames) {
2822
+ if (!formula)
2823
+ return formula;
2824
+ var stringRegex = /"([^"]|"")*"/g;
2825
+ var result = "";
2826
+ var lastIndex = 0;
2827
+ var match;
2828
+ while ((match = stringRegex.exec(formula)) !== null) {
2829
+ var before = formula.slice(lastIndex, match.index);
2830
+ result += convertExcelSegmentToOds(convertArgumentSeparators(before), namedRangeNames);
2831
+ result += match[0];
2832
+ lastIndex = match.index + match[0].length;
2833
+ }
2834
+ result += convertExcelSegmentToOds(convertArgumentSeparators(formula.slice(lastIndex)), namedRangeNames);
2835
+ return result;
2836
+ };
2837
+ var convertExcelSegmentToOds = function (segment, namedRangeNames) {
2838
+ if (!segment)
2839
+ return segment;
2840
+ var converted = segment.replace(/('([^']|'')+'|[A-Za-z0-9_]+)!\$?[A-Za-z]{1,3}\$?\d+(?::\$?[A-Za-z]{1,3}\$?\d+)?/g, function (match) {
2841
+ var _a = __read(match.split("!"), 2), sheetPart = _a[0], refPart = _a[1];
2842
+ var sheetName = formatOdsSheetName(sheetPart);
2843
+ if (!sheetName)
2844
+ return match;
2845
+ if (refPart.includes(":")) {
2846
+ var _b = __read(refPart.split(":"), 2), start = _b[0], end = _b[1];
2847
+ return "[$".concat(sheetName, ".").concat(start, ":$").concat(sheetName, ".").concat(end, "]");
2848
+ }
2849
+ return "[$".concat(sheetName, ".").concat(refPart, "]");
2850
+ });
2851
+ var parts = splitByBracketedSegments(converted);
2852
+ converted = parts
2853
+ .map(function (part) {
2854
+ if (part.isBracket)
2855
+ return part.value;
2856
+ return convertLocalRefsToOds(part.value, namedRangeNames);
2857
+ })
2858
+ .join("");
2859
+ return converted;
2860
+ };
2861
+ var convertArgumentSeparators = function (formula) {
2862
+ if (!formula)
2863
+ return formula;
2864
+ var result = "";
2865
+ var parenDepth = 0;
2866
+ for (var i = 0; i < formula.length; i++) {
2867
+ var char = formula[i];
2868
+ if (char === "(") {
2869
+ parenDepth += 1;
2870
+ result += char;
2871
+ continue;
2872
+ }
2873
+ if (char === ")") {
2874
+ parenDepth = Math.max(0, parenDepth - 1);
2875
+ result += char;
2876
+ continue;
2877
+ }
2878
+ if (char === "," && parenDepth > 0) {
2879
+ while (formula[i + 1] === " ") {
2880
+ i += 1;
2881
+ }
2882
+ result += ";";
2883
+ continue;
2884
+ }
2885
+ result += char;
2886
+ }
2887
+ return result;
2888
+ };
2889
+ var splitByBracketedSegments = function (value) {
2890
+ var regex = /\[[^\]]+\]/g;
2891
+ var segments = [];
2892
+ var lastIndex = 0;
2893
+ var match;
2894
+ while ((match = regex.exec(value)) !== null) {
2895
+ if (match.index > lastIndex) {
2896
+ segments.push({
2897
+ value: value.slice(lastIndex, match.index),
2898
+ isBracket: false,
2899
+ });
2900
+ }
2901
+ segments.push({ value: match[0], isBracket: true });
2902
+ lastIndex = match.index + match[0].length;
2903
+ }
2904
+ if (lastIndex < value.length) {
2905
+ segments.push({ value: value.slice(lastIndex), isBracket: false });
2906
+ }
2907
+ return segments;
2908
+ };
2909
+ var convertLocalRefsToOds = function (value, namedRangeNames) {
2910
+ var converted = value.replace(/(\$?[A-Za-z]{1,3}\$?\d+):(\$?[A-Za-z]{1,3}\$?\d+)/g, function (match, start, end, offset) {
2911
+ if (!isValidRefBoundary(value, offset, match.length)) {
2912
+ return match;
2913
+ }
2914
+ if (isNamedRangeToken(start, namedRangeNames))
2915
+ return match;
2916
+ if (isNamedRangeToken(end, namedRangeNames))
2917
+ return match;
2918
+ return "[.".concat(start, ":.").concat(end, "]");
2919
+ });
2920
+ var parts = splitByBracketedSegments(converted);
2921
+ converted = parts
2922
+ .map(function (part) {
2923
+ if (part.isBracket)
2924
+ return part.value;
2925
+ return part.value.replace(/(\$?[A-Za-z]{1,3}\$?\d+)/g, function (match, ref, offset) {
2926
+ if (!isValidRefBoundary(part.value, offset, match.length)) {
2927
+ return match;
2928
+ }
2929
+ if (isNamedRangeToken(ref, namedRangeNames)) {
2930
+ return match;
2931
+ }
2932
+ return "[.".concat(ref, "]");
2933
+ });
2934
+ })
2935
+ .join("");
2936
+ return converted;
2937
+ };
2938
+ var isValidRefBoundary = function (text, offset, length) {
2939
+ var prev = offset > 0 ? text[offset - 1] : "";
2940
+ var next = offset + length < text.length ? text[offset + length] : "";
2941
+ if (prev && /[A-Za-z0-9_.]/.test(prev))
2942
+ return false;
2943
+ if (next && /[A-Za-z0-9_.]/.test(next))
2944
+ return false;
2945
+ return true;
2946
+ };
2947
+ var isNamedRangeToken = function (token, namedRangeNames) {
2948
+ if (!namedRangeNames || !token)
2949
+ return false;
2950
+ var normalized = token.replace(/\$/g, "").toUpperCase();
2951
+ return namedRangeNames.has(normalized);
2952
+ };
2953
+ var formatOdsSheetName = function (sheet) {
2954
+ if (!sheet)
2955
+ return sheet;
2956
+ var normalized = sheet;
2957
+ if (normalized.startsWith("'") && normalized.endsWith("'")) {
2958
+ normalized = normalized.slice(1, -1).replace(/''/g, "'");
2959
+ }
2960
+ if (/[^A-Za-z0-9_]/.test(normalized)) {
2961
+ return "'".concat(normalized.replace(/'/g, "''"), "'");
2962
+ }
2963
+ return normalized;
2964
+ };
2965
+ var groupEmbedsBySheet = function (embeds) {
2966
+ var e_31, _a;
2967
+ var _b, _c, _d, _e, _f, _g, _h;
2968
+ var result = new Map();
2969
+ try {
2970
+ for (var _j = __values(embeds !== null && embeds !== void 0 ? embeds : []), _k = _j.next(); !_k.done; _k = _j.next()) {
2971
+ var embed = _k.value;
2972
+ if (!((_b = embed.position) === null || _b === void 0 ? void 0 : _b.overlayPosition))
2973
+ continue;
2974
+ if (((_c = embed.spec) === null || _c === void 0 ? void 0 : _c.type) !== "image")
2975
+ continue;
2976
+ var overlay = embed.position.overlayPosition;
2977
+ var placement = {
2978
+ kind: "embed",
2979
+ imageUrl: embed.spec.imageUrl,
2980
+ rowIndex: overlay.anchorCell.rowIndex,
2981
+ columnIndex: overlay.anchorCell.columnIndex,
2982
+ offsetX: (_d = overlay.offsetXPixels) !== null && _d !== void 0 ? _d : 0,
2983
+ offsetY: (_e = overlay.offsetYPixels) !== null && _e !== void 0 ? _e : 0,
2984
+ width: (_f = overlay.widthPixels) !== null && _f !== void 0 ? _f : 120,
2985
+ height: (_g = overlay.heightPixels) !== null && _g !== void 0 ? _g : 120,
2986
+ };
2987
+ var list = (_h = result.get(embed.position.sheetId)) !== null && _h !== void 0 ? _h : [];
2988
+ list.push(placement);
2989
+ result.set(embed.position.sheetId, list);
2990
+ }
2991
+ }
2992
+ catch (e_31_1) { e_31 = { error: e_31_1 }; }
2993
+ finally {
2994
+ try {
2995
+ if (_k && !_k.done && (_a = _j.return)) _a.call(_j);
2996
+ }
2997
+ finally { if (e_31) throw e_31.error; }
2998
+ }
2999
+ return result;
3000
+ };
3001
+ var groupChartsBySheet = function (charts) {
3002
+ var e_32, _a;
3003
+ var _b, _c, _d, _e, _f, _g;
3004
+ var result = new Map();
3005
+ try {
3006
+ for (var _h = __values(charts !== null && charts !== void 0 ? charts : []), _j = _h.next(); !_j.done; _j = _h.next()) {
3007
+ var chart = _j.value;
3008
+ var overlay = (_b = chart.position) === null || _b === void 0 ? void 0 : _b.overlayPosition;
3009
+ if (!overlay)
3010
+ continue;
3011
+ var placement = {
3012
+ chart: chart,
3013
+ rowIndex: overlay.anchorCell.rowIndex,
3014
+ columnIndex: overlay.anchorCell.columnIndex,
3015
+ offsetX: (_c = overlay.offsetXPixels) !== null && _c !== void 0 ? _c : 0,
3016
+ offsetY: (_d = overlay.offsetYPixels) !== null && _d !== void 0 ? _d : 0,
3017
+ width: (_e = overlay.widthPixels) !== null && _e !== void 0 ? _e : 300,
3018
+ height: (_f = overlay.heightPixels) !== null && _f !== void 0 ? _f : 200,
3019
+ };
3020
+ var list = (_g = result.get(chart.position.sheetId)) !== null && _g !== void 0 ? _g : [];
3021
+ list.push(placement);
3022
+ result.set(chart.position.sheetId, list);
3023
+ }
3024
+ }
3025
+ catch (e_32_1) { e_32 = { error: e_32_1 }; }
3026
+ finally {
3027
+ try {
3028
+ if (_j && !_j.done && (_a = _h.return)) _a.call(_h);
3029
+ }
3030
+ finally { if (e_32) throw e_32.error; }
3031
+ }
3032
+ return result;
3033
+ };
3034
+ var buildEmbedFramesXml = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
3035
+ var frames, embeds_1, embeds_1_1, placement, dataUrl, buffer, mediaPath, widthPx, heightPx, offsetXPx, offsetYPx, width, height, origin_1, offsetX, offsetY, anchorRef, anchorCell, anchorAttr, endColumn, endRow, endRef, endCell, endCellAttr, endX, endY, e_33_1;
3036
+ var e_33, _c;
3037
+ var _d, _e, _f, _g;
3038
+ var embeds = _b.embeds, mediaEntries = _b.mediaEntries, sheetName = _b.sheetName, sheet = _b.sheet;
3039
+ return __generator(this, function (_h) {
3040
+ switch (_h.label) {
3041
+ case 0:
3042
+ if (!embeds.length)
3043
+ return [2 /*return*/, []];
3044
+ frames = [];
3045
+ _h.label = 1;
3046
+ case 1:
3047
+ _h.trys.push([1, 6, 7, 8]);
3048
+ embeds_1 = __values(embeds), embeds_1_1 = embeds_1.next();
3049
+ _h.label = 2;
3050
+ case 2:
3051
+ if (!!embeds_1_1.done) return [3 /*break*/, 5];
3052
+ placement = embeds_1_1.value;
3053
+ return [4 /*yield*/, resolveImageDataUrl(placement.imageUrl)];
3054
+ case 3:
3055
+ dataUrl = _h.sent();
3056
+ if (!dataUrl)
3057
+ return [3 /*break*/, 4];
3058
+ buffer = dataUriToBuffer(dataUrl, placement.imageUrl);
3059
+ if (!buffer)
3060
+ return [3 /*break*/, 4];
3061
+ mediaPath = "Pictures/image".concat(mediaEntries.length + 1, ".").concat(buffer.extension);
3062
+ mediaEntries.push({
3063
+ path: mediaPath,
3064
+ data: buffer.data,
3065
+ mime: buffer.contentType,
3066
+ });
3067
+ widthPx = Math.max(5, (_d = placement.width) !== null && _d !== void 0 ? _d : 120);
3068
+ heightPx = Math.max(5, (_e = placement.height) !== null && _e !== void 0 ? _e : 120);
3069
+ offsetXPx = (_f = placement.offsetX) !== null && _f !== void 0 ? _f : 0;
3070
+ offsetYPx = (_g = placement.offsetY) !== null && _g !== void 0 ? _g : 0;
3071
+ width = pxToCm(widthPx).toFixed(2);
3072
+ height = pxToCm(heightPx).toFixed(2);
3073
+ origin_1 = getCellOriginPx(sheet, placement.rowIndex, placement.columnIndex);
3074
+ offsetX = pxToCm(origin_1.x + offsetXPx).toFixed(2);
3075
+ offsetY = pxToCm(origin_1.y + offsetYPx).toFixed(2);
3076
+ anchorRef = cellToAddress({
3077
+ rowIndex: placement.rowIndex,
3078
+ columnIndex: placement.columnIndex,
3079
+ });
3080
+ anchorCell = anchorRef !== null && anchorRef !== void 0 ? anchorRef : undefined;
3081
+ anchorAttr = anchorCell
3082
+ ? " table:anchor-cell-address=\"".concat(escapeXmlAddress(anchorCell), "\"")
3083
+ : "";
3084
+ endColumn = resolveAnchorEndpoint({
3085
+ startIndex: placement.columnIndex,
3086
+ startOffset: offsetXPx,
3087
+ span: widthPx,
3088
+ getSize: function (index) { return getColumnWidthPx(sheet, index); },
3089
+ });
3090
+ endRow = resolveAnchorEndpoint({
3091
+ startIndex: placement.rowIndex,
3092
+ startOffset: offsetYPx,
3093
+ span: heightPx,
3094
+ getSize: function (index) { return getRowHeightPx(sheet, index); },
3095
+ });
3096
+ endRef = cellToAddress({
3097
+ rowIndex: endRow.index,
3098
+ columnIndex: endColumn.index,
3099
+ });
3100
+ endCell = endRef !== null && endRef !== void 0 ? endRef : undefined;
3101
+ endCellAttr = endCell
3102
+ ? " table:end-cell-address=\"".concat(escapeXmlAddress(endCell), "\"")
3103
+ : "";
3104
+ endX = pxToCm(endColumn.offset).toFixed(2);
3105
+ endY = pxToCm(endRow.offset).toFixed(2);
3106
+ frames.push("<draw:frame draw:name=\"Image".concat(mediaEntries.length, "\" svg:width=\"").concat(width, "cm\" svg:height=\"").concat(height, "cm\" svg:x=\"").concat(offsetX, "cm\" svg:y=\"").concat(offsetY, "cm\" table:anchor-type=\"cell\"").concat(anchorAttr).concat(endCellAttr, " table:end-x=\"").concat(endX, "cm\" table:end-y=\"").concat(endY, "cm\"><draw:image xlink:href=\"").concat(mediaPath, "\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/></draw:frame>"));
3107
+ _h.label = 4;
3108
+ case 4:
3109
+ embeds_1_1 = embeds_1.next();
3110
+ return [3 /*break*/, 2];
3111
+ case 5: return [3 /*break*/, 8];
3112
+ case 6:
3113
+ e_33_1 = _h.sent();
3114
+ e_33 = { error: e_33_1 };
3115
+ return [3 /*break*/, 8];
3116
+ case 7:
3117
+ try {
3118
+ if (embeds_1_1 && !embeds_1_1.done && (_c = embeds_1.return)) _c.call(embeds_1);
3119
+ }
3120
+ finally { if (e_33) throw e_33.error; }
3121
+ return [7 /*endfinally*/];
3122
+ case 8: return [2 /*return*/, frames];
3123
+ }
3124
+ });
3125
+ }); };
3126
+ var getDefaultColumnWidthPx = function (sheet) {
3127
+ if (sheet === null || sheet === void 0 ? void 0 : sheet.defaultColumnWidth) {
3128
+ return Number(sheet.defaultColumnWidth) || DEFAULT_COLUMN_WIDTH_PX;
3129
+ }
3130
+ return DEFAULT_COLUMN_WIDTH_PX;
3131
+ };
3132
+ var getColumnWidthPx = function (sheet, columnIndex) {
3133
+ var _a;
3134
+ var metadata = (_a = sheet.columnMetadata) === null || _a === void 0 ? void 0 : _a[columnIndex];
3135
+ if ((metadata === null || metadata === void 0 ? void 0 : metadata.size) && metadata.size > 0) {
3136
+ return metadata.size;
3137
+ }
3138
+ return getDefaultColumnWidthPx(sheet);
3139
+ };
3140
+ var getDefaultRowHeightPx = function (sheet) {
3141
+ if (sheet === null || sheet === void 0 ? void 0 : sheet.defaultRowHeight) {
3142
+ return Number(sheet.defaultRowHeight) || DEFAULT_ROW_HEIGHT_PX;
3143
+ }
3144
+ return DEFAULT_ROW_HEIGHT_PX;
3145
+ };
3146
+ var getRowHeightPx = function (sheet, rowIndex) {
3147
+ var _a;
3148
+ var metadata = (_a = sheet.rowMetadata) === null || _a === void 0 ? void 0 : _a[rowIndex];
3149
+ if ((metadata === null || metadata === void 0 ? void 0 : metadata.size) && metadata.resizedByUser) {
3150
+ return metadata.size;
3151
+ }
3152
+ return getDefaultRowHeightPx(sheet);
3153
+ };
3154
+ var getCellSizePx = function (sheet, rowIndex, columnIndex, mergeSpan) {
3155
+ var _a, _b;
3156
+ var columns = Math.max(1, (_a = mergeSpan === null || mergeSpan === void 0 ? void 0 : mergeSpan.columns) !== null && _a !== void 0 ? _a : 1);
3157
+ var rows = Math.max(1, (_b = mergeSpan === null || mergeSpan === void 0 ? void 0 : mergeSpan.rows) !== null && _b !== void 0 ? _b : 1);
3158
+ var width = 0;
3159
+ for (var col = 0; col < columns; col += 1) {
3160
+ width += getColumnWidthPx(sheet, columnIndex + col);
3161
+ }
3162
+ var height = 0;
3163
+ for (var row = 0; row < rows; row += 1) {
3164
+ height += getRowHeightPx(sheet, rowIndex + row);
3165
+ }
3166
+ return {
3167
+ width: Math.max(5, width),
3168
+ height: Math.max(5, height),
3169
+ };
3170
+ };
3171
+ var getCellOriginPx = function (sheet, rowIndex, columnIndex) {
3172
+ var x = 0;
3173
+ for (var col = 1; col < columnIndex; col += 1) {
3174
+ x += getColumnWidthPx(sheet, col);
3175
+ }
3176
+ var y = 0;
3177
+ for (var row = 1; row < rowIndex; row += 1) {
3178
+ y += getRowHeightPx(sheet, row);
3179
+ }
3180
+ return { x: x, y: y };
3181
+ };
3182
+ var resolveAnchorEndpoint = function (_a) {
3183
+ var startIndex = _a.startIndex, startOffset = _a.startOffset, span = _a.span, getSize = _a.getSize;
3184
+ var remaining = Math.max(0, span);
3185
+ var index = Math.max(1, startIndex);
3186
+ var offset = Math.max(0, startOffset);
3187
+ while (remaining > 0) {
3188
+ var size = Math.max(1, getSize(index));
3189
+ var available = size - offset;
3190
+ if (remaining <= available) {
3191
+ return {
3192
+ index: index,
3193
+ offset: offset + remaining,
3194
+ };
3195
+ }
3196
+ remaining -= available;
3197
+ index += 1;
3198
+ offset = 0;
3199
+ }
3200
+ return { index: index, offset: offset };
3201
+ };
3202
+ var buildChartObjectXml = function (chart, sheetNameById) {
3203
+ var _a, _b, _c, _d, _e;
3204
+ var spec = chart.spec;
3205
+ var series = (_a = spec === null || spec === void 0 ? void 0 : spec.series) !== null && _a !== void 0 ? _a : [];
3206
+ if (!series.length)
3207
+ return undefined;
3208
+ var domain = (_d = (_c = (_b = spec === null || spec === void 0 ? void 0 : spec.domains) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.sources) === null || _d === void 0 ? void 0 : _d[0];
3209
+ var domainRange = domain
3210
+ ? buildChartRangeAddress(domain, sheetNameById)
3211
+ : undefined;
3212
+ var seriesRanges = series
3213
+ .map(function (entry) { var _a; return (_a = entry === null || entry === void 0 ? void 0 : entry.sources) === null || _a === void 0 ? void 0 : _a[0]; })
3214
+ .map(function (range) {
3215
+ return range ? buildChartRangeAddress(range, sheetNameById) : undefined;
3216
+ })
3217
+ .filter(function (range) { return Boolean(range); });
3218
+ if (!seriesRanges.length)
3219
+ return undefined;
3220
+ var typeMap = {
3221
+ bar: "chart:bar",
3222
+ column: "chart:bar",
3223
+ line: "chart:line",
3224
+ pie: "chart:circle",
3225
+ scatter: "chart:scatter",
3226
+ area: "chart:area",
3227
+ };
3228
+ var chartClass = (_e = typeMap[spec.chartType]) !== null && _e !== void 0 ? _e : "chart:bar";
3229
+ var title = spec.title
3230
+ ? "<chart:title><text:p>".concat(escapeXml(String(spec.title)), "</text:p></chart:title>")
3231
+ : "";
3232
+ var seriesPalette = [
3233
+ "#4285f4",
3234
+ "#ea4335",
3235
+ "#fbbc04",
3236
+ "#34a853",
3237
+ "#ff6d01",
3238
+ "#46bdc6",
3239
+ ];
3240
+ // Series chart styles + (optional) gradient defs. When a series
3241
+ // carries an explicit gradient we emit a `<draw:gradient>` def
3242
+ // alongside it and reference the def via `draw:fill-gradient-name`
3243
+ // on the series's graphic-properties. ODS uses 1/10ths of a degree
3244
+ // for `draw:angle` (so a 90° XLSX gradient is `900` here) and
3245
+ // `linear` / `radial` for the two flavors we round-trip.
3246
+ var gradientDefs = [];
3247
+ var seriesStyles = seriesRanges
3248
+ .map(function (_range, index) {
3249
+ var _a, _b, _c, _d, _e, _f;
3250
+ var color = seriesPalette[index % seriesPalette.length];
3251
+ var seriesData = series[index];
3252
+ var gradient = seriesData === null || seriesData === void 0 ? void 0 : seriesData.gradient;
3253
+ if (gradient && ((_a = gradient.stops) === null || _a === void 0 ? void 0 : _a.length) >= 2) {
3254
+ var gradName = "grad".concat(index);
3255
+ var startColor = gradient.stops[0].color;
3256
+ var endColor = gradient.stops[gradient.stops.length - 1].color;
3257
+ if (gradient.type === "path") {
3258
+ // Path / radial. ODS center is in 0..100% — use the inset
3259
+ // midpoints if supplied, fall back to dead center.
3260
+ var cx = Math.round(((((_b = gradient.left) !== null && _b !== void 0 ? _b : 0) + (1 - ((_c = gradient.right) !== null && _c !== void 0 ? _c : 0))) / 2) * 100);
3261
+ var cy = Math.round(((((_d = gradient.top) !== null && _d !== void 0 ? _d : 0) + (1 - ((_e = gradient.bottom) !== null && _e !== void 0 ? _e : 0))) / 2) * 100);
3262
+ gradientDefs.push("<draw:gradient draw:name=\"".concat(gradName, "\" draw:style=\"radial\" draw:start-color=\"").concat(startColor, "\" draw:end-color=\"").concat(endColor, "\" draw:start-intensity=\"100%\" draw:end-intensity=\"100%\" draw:cx=\"").concat(cx, "%\" draw:cy=\"").concat(cy, "%\"/>"));
3263
+ }
3264
+ else {
3265
+ // XLSX `degree` (0..360 clockwise from right) ↔ ODS
3266
+ // `draw:angle` (0..3600 = 1/10° units; 0 is "upward").
3267
+ // We don't try to reconcile the start-of-axis difference —
3268
+ // most viewers tolerate either convention as long as the
3269
+ // two endpoints match.
3270
+ var angle = Math.round(((_f = gradient.degree) !== null && _f !== void 0 ? _f : 0) * 10);
3271
+ gradientDefs.push("<draw:gradient draw:name=\"".concat(gradName, "\" draw:style=\"linear\" draw:start-color=\"").concat(startColor, "\" draw:end-color=\"").concat(endColor, "\" draw:start-intensity=\"100%\" draw:end-intensity=\"100%\" draw:angle=\"").concat(angle, "\"/>"));
3272
+ }
3273
+ return "<style:style style:name=\"series".concat(index, "\" style:family=\"chart\"><style:graphic-properties svg:stroke-color=\"").concat(startColor, "\" svg:stroke-width=\"0.08cm\" draw:fill=\"gradient\" draw:fill-gradient-name=\"").concat(gradName, "\"/></style:style>");
3274
+ }
3275
+ var fillColor = (seriesData === null || seriesData === void 0 ? void 0 : seriesData.color) || color;
3276
+ return "<style:style style:name=\"series".concat(index, "\" style:family=\"chart\"><style:graphic-properties svg:stroke-color=\"").concat(fillColor, "\" svg:stroke-width=\"0.08cm\" draw:fill=\"none\"/></style:style>");
3277
+ })
3278
+ .join("");
3279
+ var gradientDefsXml = gradientDefs.join("");
3280
+ var hasSeriesLabels = false;
3281
+ var seriesXml = seriesRanges
3282
+ .map(function (range, index) {
3283
+ var _a, _b, _c, _d, _e, _f;
3284
+ var labelAddress = buildChartLabelAddress((_a = series[index]) === null || _a === void 0 ? void 0 : _a.dataLabel, sheetNameById, (_b = chart.position) === null || _b === void 0 ? void 0 : _b.sheetId) ||
3285
+ buildChartLabelAddressFromRange((_d = (_c = series[index]) === null || _c === void 0 ? void 0 : _c.sources) === null || _d === void 0 ? void 0 : _d[0], sheetNameById);
3286
+ var labelAttr = labelAddress
3287
+ ? " chart:label-cell-address=\"".concat(escapeXmlAddress(labelAddress), "\"")
3288
+ : "";
3289
+ if (labelAddress) {
3290
+ hasSeriesLabels = true;
3291
+ }
3292
+ var count = getRangePointCount((_f = (_e = series[index]) === null || _e === void 0 ? void 0 : _e.sources) === null || _f === void 0 ? void 0 : _f[0]);
3293
+ var pointsXml = count
3294
+ ? "<chart:data-point chart:repeated=\"".concat(count, "\"/>")
3295
+ : "";
3296
+ return "<chart:series chart:class=\"".concat(chartClass, "\" chart:style-name=\"series").concat(index, "\" chart:values-cell-range-address=\"").concat(escapeXmlAddress(range), "\"").concat(labelAttr, ">").concat(pointsXml, "</chart:series>");
3297
+ })
3298
+ .join("");
3299
+ var axisXml = chartClass === "chart:circle"
3300
+ ? ""
3301
+ : "<chart:axis chart:dimension=\"x\" chart:name=\"primary-x\" chart:style-name=\"axisx\"><chart:title/></chart:axis><chart:axis chart:dimension=\"y\" chart:name=\"primary-y\" chart:style-name=\"axisy\"><chart:title/></chart:axis>";
3302
+ var categoriesAttr = domainRange
3303
+ ? " chart:categories-cell-range-address=\"".concat(escapeXmlAddress(domainRange), "\"")
3304
+ : "";
3305
+ var labelMode = domainRange ? "both" : hasSeriesLabels ? "row" : "none";
3306
+ var plotAreaAttrs = " chart:data-source-has-labels=\"".concat(labelMode, "\"").concat(categoriesAttr);
3307
+ var wallFloor = chartClass === "chart:circle"
3308
+ ? ""
3309
+ : "<chart:wall chart:style-name=\"wall1\"/><chart:floor chart:style-name=\"floor1\"/>";
3310
+ var legendXml = chartClass === "chart:circle"
3311
+ ? ""
3312
+ : "<chart:legend chart:legend-position=\"end\" chart:legend-align=\"center\" chart:style-name=\"legend1\"/>";
3313
+ return "".concat(XML_DECLARATION, "<office:document-content xmlns:office=\"").concat(ODS_NS.office, "\" xmlns:chart=\"").concat(ODS_NS.chart, "\" xmlns:table=\"").concat(ODS_NS.table, "\" xmlns:text=\"").concat(ODS_NS.text, "\" xmlns:style=\"").concat(ODS_NS.style, "\" xmlns:draw=\"").concat(ODS_NS.draw, "\" xmlns:svg=\"").concat(ODS_NS.svg, "\" xmlns:fo=\"").concat(ODS_NS.fo, "\" office:version=\"1.2\"><office:automatic-styles>").concat(gradientDefsXml, "<style:style style:name=\"ch1\" style:family=\"chart\"><style:graphic-properties draw:fill=\"solid\" draw:fill-color=\"#ffffff\"/></style:style><style:style style:name=\"plot1\" style:family=\"chart\"><style:graphic-properties draw:fill=\"solid\" draw:fill-color=\"#ffffff\" svg:stroke-color=\"#b3b3b3\"/></style:style><style:style style:name=\"wall1\" style:family=\"chart\"><style:graphic-properties draw:fill=\"solid\" draw:fill-color=\"#ffffff\" svg:stroke-color=\"#b3b3b3\" svg:stroke-width=\"0.01cm\"/></style:style><style:style style:name=\"floor1\" style:family=\"chart\"><style:graphic-properties draw:fill=\"none\" svg:stroke-color=\"#b3b3b3\"/></style:style><style:style style:name=\"legend1\" style:family=\"chart\"><style:graphic-properties draw:fill=\"none\" svg:stroke-color=\"#b3b3b3\"/><style:text-properties fo:font-size=\"10pt\"/></style:style><style:style style:name=\"axisx\" style:family=\"chart\"><style:chart-properties chart:display-label=\"true\" chart:tick-marks-major-inner=\"false\" chart:tick-marks-major-outer=\"true\"/><style:graphic-properties svg:stroke-color=\"#b3b3b3\"/><style:text-properties fo:font-size=\"9pt\"/></style:style><style:style style:name=\"axisy\" style:family=\"chart\"><style:chart-properties chart:display-label=\"true\" chart:tick-marks-major-inner=\"false\" chart:tick-marks-major-outer=\"true\"/><style:graphic-properties svg:stroke-color=\"#b3b3b3\"/><style:text-properties fo:font-size=\"9pt\"/></style:style>").concat(seriesStyles, "</office:automatic-styles><office:body><office:chart><chart:chart chart:class=\"").concat(chartClass, "\" chart:style-name=\"ch1\">").concat(title).concat(legendXml, "<chart:plot-area chart:style-name=\"plot1\"").concat(plotAreaAttrs, ">").concat(axisXml).concat(seriesXml).concat(wallFloor, "</chart:plot-area></chart:chart></office:chart></office:body></office:document-content>");
3314
+ };
3315
+ var buildChartRangeAddress = function (range, sheetNameById) {
3316
+ var sheetName = sheetNameById.get(range.sheetId);
3317
+ if (!sheetName)
3318
+ return undefined;
3319
+ var start = cellToAddress({
3320
+ rowIndex: range.startRowIndex,
3321
+ columnIndex: range.startColumnIndex,
3322
+ }, true, true);
3323
+ var end = cellToAddress({
3324
+ rowIndex: range.endRowIndex,
3325
+ columnIndex: range.endColumnIndex,
3326
+ }, true, true);
3327
+ if (!start || !end)
3328
+ return undefined;
3329
+ var escaped = escapeSheetName(sheetName);
3330
+ return "".concat(escaped, ".").concat(start, ":").concat(end);
3331
+ };
3332
+ var getRangePointCount = function (range) {
3333
+ if (!range)
3334
+ return undefined;
3335
+ var rows = Math.abs(range.endRowIndex - range.startRowIndex) + 1;
3336
+ var cols = Math.abs(range.endColumnIndex - range.startColumnIndex) + 1;
3337
+ return Math.max(rows, cols);
3338
+ };
3339
+ var buildChartLabelAddress = function (label, sheetNameById, sheetId) {
3340
+ if (!label)
3341
+ return "";
3342
+ if (label.startsWith("=")) {
3343
+ var formula = label.slice(1).trim();
3344
+ if (formula.includes("."))
3345
+ return formula;
3346
+ var sheetName = sheetId != null ? sheetNameById.get(sheetId) : undefined;
3347
+ return sheetName ? "".concat(escapeSheetName(sheetName), ".").concat(formula) : formula;
3348
+ }
3349
+ return "";
3350
+ };
3351
+ var buildChartLabelAddressFromRange = function (range, sheetNameById) {
3352
+ if (!range || range.startRowIndex <= 1)
3353
+ return "";
3354
+ var sheetName = sheetNameById.get(range.sheetId);
3355
+ if (!sheetName)
3356
+ return "";
3357
+ var labelRef = cellToAddress({
3358
+ rowIndex: range.startRowIndex - 1,
3359
+ columnIndex: range.startColumnIndex,
3360
+ }, true, true);
3361
+ if (!labelRef)
3362
+ return "";
3363
+ return "".concat(escapeSheetName(sheetName), ".").concat(labelRef);
3364
+ };
3365
+ var buildChartFramesXml = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
3366
+ var frames, chartObjects, index, charts_1, charts_1_1, placement, chartXml, folder, widthPx, heightPx, offsetXPx, offsetYPx, width, height, origin_2, offsetX, offsetY, anchorRef, anchorCell, anchorAttr, endColumn, endRow, endRef, endCell, endCellAttr, endX, endY;
3367
+ var e_34, _c;
3368
+ var _d, _e, _f, _g;
3369
+ var charts = _b.charts, sheet = _b.sheet, sheetName = _b.sheetName, sheetNameById = _b.sheetNameById, startIndex = _b.startIndex;
3370
+ return __generator(this, function (_h) {
3371
+ if (!charts.length) {
3372
+ return [2 /*return*/, { frames: [], chartObjects: [], nextIndex: startIndex }];
3373
+ }
3374
+ frames = [];
3375
+ chartObjects = [];
3376
+ index = startIndex;
3377
+ try {
3378
+ for (charts_1 = __values(charts), charts_1_1 = charts_1.next(); !charts_1_1.done; charts_1_1 = charts_1.next()) {
3379
+ placement = charts_1_1.value;
3380
+ chartXml = buildChartObjectXml(placement.chart, sheetNameById);
3381
+ if (!chartXml)
3382
+ continue;
3383
+ folder = "Object ".concat(index);
3384
+ chartObjects.push({ folder: folder, contentXml: chartXml });
3385
+ widthPx = Math.max(5, (_d = placement.width) !== null && _d !== void 0 ? _d : 300);
3386
+ heightPx = Math.max(5, (_e = placement.height) !== null && _e !== void 0 ? _e : 200);
3387
+ offsetXPx = (_f = placement.offsetX) !== null && _f !== void 0 ? _f : 0;
3388
+ offsetYPx = (_g = placement.offsetY) !== null && _g !== void 0 ? _g : 0;
3389
+ width = pxToCm(widthPx).toFixed(2);
3390
+ height = pxToCm(heightPx).toFixed(2);
3391
+ origin_2 = getCellOriginPx(sheet, placement.rowIndex, placement.columnIndex);
3392
+ offsetX = pxToCm(origin_2.x + offsetXPx).toFixed(2);
3393
+ offsetY = pxToCm(origin_2.y + offsetYPx).toFixed(2);
3394
+ anchorRef = cellToAddress({
3395
+ rowIndex: placement.rowIndex,
3396
+ columnIndex: placement.columnIndex,
3397
+ });
3398
+ anchorCell = anchorRef !== null && anchorRef !== void 0 ? anchorRef : undefined;
3399
+ anchorAttr = anchorCell
3400
+ ? " table:anchor-cell-address=\"".concat(escapeXmlAddress(anchorCell), "\"")
3401
+ : "";
3402
+ endColumn = resolveAnchorEndpoint({
3403
+ startIndex: placement.columnIndex,
3404
+ startOffset: offsetXPx,
3405
+ span: widthPx,
3406
+ getSize: function (index) { return getColumnWidthPx(sheet, index); },
3407
+ });
3408
+ endRow = resolveAnchorEndpoint({
3409
+ startIndex: placement.rowIndex,
3410
+ startOffset: offsetYPx,
3411
+ span: heightPx,
3412
+ getSize: function (index) { return getRowHeightPx(sheet, index); },
3413
+ });
3414
+ endRef = cellToAddress({
3415
+ rowIndex: endRow.index,
3416
+ columnIndex: endColumn.index,
3417
+ });
3418
+ endCell = endRef !== null && endRef !== void 0 ? endRef : undefined;
3419
+ endCellAttr = endCell
3420
+ ? " table:end-cell-address=\"".concat(escapeXmlAddress(endCell), "\"")
3421
+ : "";
3422
+ endX = pxToCm(endColumn.offset).toFixed(2);
3423
+ endY = pxToCm(endRow.offset).toFixed(2);
3424
+ frames.push("<draw:frame draw:name=\"Chart".concat(index, "\" svg:width=\"").concat(width, "cm\" svg:height=\"").concat(height, "cm\" svg:x=\"").concat(offsetX, "cm\" svg:y=\"").concat(offsetY, "cm\" table:anchor-type=\"cell\"").concat(anchorAttr).concat(endCellAttr, " table:end-x=\"").concat(endX, "cm\" table:end-y=\"").concat(endY, "cm\"><draw:object xlink:href=\"").concat(folder, "\" xlink:type=\"simple\"/></draw:frame>"));
3425
+ index += 1;
3426
+ }
3427
+ }
3428
+ catch (e_34_1) { e_34 = { error: e_34_1 }; }
3429
+ finally {
3430
+ try {
3431
+ if (charts_1_1 && !charts_1_1.done && (_c = charts_1.return)) _c.call(charts_1);
3432
+ }
3433
+ finally { if (e_34) throw e_34.error; }
3434
+ }
3435
+ return [2 /*return*/, { frames: frames, chartObjects: chartObjects, nextIndex: index }];
3436
+ });
3437
+ }); };
3438
+ var buildCellImageXml = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
3439
+ var dataUrl, buffer, mediaPath, size, width, height;
3440
+ var imageUrl = _b.imageUrl, rowNumber = _b.rowNumber, columnIndex = _b.columnIndex, mergeSpan = _b.mergeSpan, sheet = _b.sheet, mediaEntries = _b.mediaEntries;
3441
+ return __generator(this, function (_c) {
3442
+ switch (_c.label) {
3443
+ case 0:
3444
+ if (!imageUrl)
3445
+ return [2 /*return*/, ""];
3446
+ return [4 /*yield*/, resolveImageDataUrl(imageUrl)];
3447
+ case 1:
3448
+ dataUrl = _c.sent();
3449
+ if (!dataUrl)
3450
+ return [2 /*return*/, ""];
3451
+ buffer = dataUriToBuffer(dataUrl, imageUrl);
3452
+ if (!buffer)
3453
+ return [2 /*return*/, ""];
3454
+ mediaPath = "Pictures/image".concat(mediaEntries.length + 1, ".").concat(buffer.extension);
3455
+ mediaEntries.push({
3456
+ path: mediaPath,
3457
+ data: buffer.data,
3458
+ mime: buffer.contentType,
3459
+ });
3460
+ size = getCellSizePx(sheet, rowNumber, columnIndex, mergeSpan);
3461
+ width = pxToCm(size.width).toFixed(2);
3462
+ height = pxToCm(size.height).toFixed(2);
3463
+ return [2 /*return*/, "<draw:frame draw:name=\"CellImage".concat(mediaEntries.length, "\" svg:width=\"").concat(width, "cm\" svg:height=\"").concat(height, "cm\" table:anchor-type=\"cell\"><draw:image xlink:href=\"").concat(mediaPath, "\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/></draw:frame>")];
3464
+ }
3465
+ });
3466
+ }); };
3467
+ var resolveImageDataUrl = function (imageUrl) { return __awaiter(void 0, void 0, void 0, function () {
3468
+ var _a;
3469
+ return __generator(this, function (_b) {
3470
+ switch (_b.label) {
3471
+ case 0:
3472
+ if (imageUrl.startsWith("data:")) {
3473
+ return [2 /*return*/, imageUrl];
3474
+ }
3475
+ _b.label = 1;
3476
+ case 1:
3477
+ _b.trys.push([1, 3, , 4]);
3478
+ return [4 /*yield*/, imageUrlToBase64(imageUrl)];
3479
+ case 2: return [2 /*return*/, _b.sent()];
3480
+ case 3:
3481
+ _a = _b.sent();
3482
+ return [2 /*return*/, undefined];
3483
+ case 4: return [2 /*return*/];
3484
+ }
3485
+ });
3486
+ }); };
3487
+ var dataUriToBuffer = function (dataUrl, fallbackName) {
3488
+ var _a, _b;
3489
+ var match = /^data:(.+?);base64,(.+)$/.exec(dataUrl);
3490
+ if (!match)
3491
+ return undefined;
3492
+ var _c = __read(match, 3), mime = _c[1], base64 = _c[2];
3493
+ var binaryString = decodeBase64(base64);
3494
+ var buffer = new Uint8Array(binaryString.length);
3495
+ for (var i = 0; i < binaryString.length; i++) {
3496
+ buffer[i] = binaryString.charCodeAt(i);
3497
+ }
3498
+ var extension = (_b = (_a = mime.split("/")[1]) !== null && _a !== void 0 ? _a : fallbackName === null || fallbackName === void 0 ? void 0 : fallbackName.split(".").pop()) !== null && _b !== void 0 ? _b : "bin";
3499
+ return {
3500
+ data: buffer,
3501
+ extension: extension.toLowerCase(),
3502
+ contentType: mime,
3503
+ };
3504
+ };
3505
+ var decodeBase64 = function (value) {
3506
+ if (typeof atob === "function") {
3507
+ return atob(value);
3508
+ }
3509
+ var bufferCtor = globalThis.Buffer;
3510
+ if (bufferCtor) {
3511
+ return bufferCtor.from(value, "base64").toString("binary");
3512
+ }
3513
+ throw new Error("Base64 decoding is not supported in this environment");
3514
+ };
3515
+ var prepareTables = function (tables) {
3516
+ var result = [];
3517
+ tables.forEach(function (table, index) {
3518
+ var _a;
3519
+ var ref = gridRangeToRef(table.range);
3520
+ if (!ref)
3521
+ return;
3522
+ var id = index + 1;
3523
+ var sanitized = sanitizeTableName((_a = table.title) !== null && _a !== void 0 ? _a : "Table".concat(id));
3524
+ result.push(__assign(__assign({}, table), { id: id, ref: ref, name: sanitized }));
3525
+ });
3526
+ return result;
3527
+ };
3528
+ var sanitizeTableName = function (name) {
3529
+ var cleaned = name.replace(/[^A-Za-z0-9_]/g, "") || "Table";
3530
+ if (/^\d/.test(cleaned)) {
3531
+ return "T".concat(cleaned);
3532
+ }
3533
+ return cleaned;
3534
+ };
3535
+ var gridRangeToRef = function (range) {
3536
+ if (!range)
3537
+ return undefined;
3538
+ try {
3539
+ var ref = cellRangeToAddress(undefined, range);
3540
+ return ref !== null && ref !== void 0 ? ref : undefined;
3541
+ }
3542
+ catch (_a) {
3543
+ return undefined;
3544
+ }
3545
+ };
3546
+ var convertDataValidationRule = function (rule) {
3547
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;
3548
+ if (!((_a = rule === null || rule === void 0 ? void 0 : rule.condition) === null || _a === void 0 ? void 0 : _a.type))
3549
+ return undefined;
3550
+ var condition = rule.condition;
3551
+ var values = (_b = condition.values) !== null && _b !== void 0 ? _b : [];
3552
+ var allowBlank = rule.allowBlank !== false;
3553
+ var displayStyle = rule.displayStyle === "plain"
3554
+ ? "none"
3555
+ : rule.displayStyle === "arrow"
3556
+ ? "list"
3557
+ : undefined;
3558
+ var inputMessage = rule.inputMessage;
3559
+ var alert = rule.alert;
3560
+ var base = {
3561
+ allowEmptyCell: allowBlank,
3562
+ displayList: displayStyle,
3563
+ helpMessage: inputMessage
3564
+ ? { title: inputMessage.title, message: inputMessage.message }
3565
+ : undefined,
3566
+ errorMessage: (alert === null || alert === void 0 ? void 0 : alert.message)
3567
+ ? {
3568
+ type: (_c = alert.style) !== null && _c !== void 0 ? _c : "stop",
3569
+ title: alert.message.title,
3570
+ message: alert.message.message,
3571
+ }
3572
+ : undefined,
3573
+ };
3574
+ var ensureFormula = function (value) {
3575
+ return value.startsWith("=") ? value.slice(1) : value;
3576
+ };
3577
+ if (condition.type === "ONE_OF_LIST") {
3578
+ var entries = values
3579
+ .map(function (value) { return value.userEnteredValue; })
3580
+ .filter(function (value) { return typeof value === "string"; });
3581
+ if (!entries.length)
3582
+ return undefined;
3583
+ var args = entries.map(function (entry) { return "\"".concat(entry.replace(/"/g, '""'), "\""); });
3584
+ return __assign(__assign({}, base), { condition: "of:cell-content-is-in-list(".concat(args.join(";"), ")"), displayList: "unsorted" });
3585
+ }
3586
+ if (condition.type === "ONE_OF_RANGE") {
3587
+ var references = values
3588
+ .map(function (value) { return value.userEnteredValue; })
3589
+ .filter(function (value) { return typeof value === "string"; });
3590
+ if (!references.length)
3591
+ return undefined;
3592
+ var ref = references[0];
3593
+ var normalized = ref.replace(/^=/, "");
3594
+ return __assign({ condition: "of:=cell-content-is-in-list(".concat(normalized, ")") }, base);
3595
+ }
3596
+ if (condition.type === "CUSTOM_FORMULA") {
3597
+ var raw = (_e = (_d = values[0]) === null || _d === void 0 ? void 0 : _d.userEnteredValue) !== null && _e !== void 0 ? _e : "";
3598
+ if (!raw)
3599
+ return undefined;
3600
+ return __assign({ condition: "of:=".concat(ensureFormula(raw)) }, base);
3601
+ }
3602
+ if (condition.type === "BOOLEAN") {
3603
+ return __assign({ condition: "of:=OR(cell-content()=TRUE(),cell-content()=FALSE())" }, base);
3604
+ }
3605
+ if (condition.type === "BLANK") {
3606
+ return __assign({ condition: "of:=cell-content()=\"\"" }, base);
3607
+ }
3608
+ if (condition.type === "NOT_BLANK") {
3609
+ return __assign({ condition: "of:=cell-content()<>\"\"" }, base);
3610
+ }
3611
+ if (condition.type === "TEXT_EQ" || condition.type === "TEXT_NOT_EQ") {
3612
+ var raw = (_g = (_f = values[0]) === null || _f === void 0 ? void 0 : _f.userEnteredValue) !== null && _g !== void 0 ? _g : "";
3613
+ if (!raw)
3614
+ return undefined;
3615
+ var op = condition.type === "TEXT_EQ" ? "=" : "<>";
3616
+ return __assign({ condition: "of:=cell-content()".concat(op, "\"").concat(raw.replace(/"/g, '""'), "\"") }, base);
3617
+ }
3618
+ if (condition.type === "TEXT_CONTAINS") {
3619
+ var raw = (_j = (_h = values[0]) === null || _h === void 0 ? void 0 : _h.userEnteredValue) !== null && _j !== void 0 ? _j : "";
3620
+ if (!raw)
3621
+ return undefined;
3622
+ return __assign({ condition: "of:=ISNUMBER(SEARCH(\"".concat(raw.replace(/"/g, '""'), "\",cell-content()))") }, base);
3623
+ }
3624
+ if (condition.type === "TEXT_NOT_CONTAINS") {
3625
+ var raw = (_l = (_k = values[0]) === null || _k === void 0 ? void 0 : _k.userEnteredValue) !== null && _l !== void 0 ? _l : "";
3626
+ if (!raw)
3627
+ return undefined;
3628
+ return __assign({ condition: "of:=ISERROR(SEARCH(\"".concat(raw.replace(/"/g, '""'), "\",cell-content()))") }, base);
3629
+ }
3630
+ if (condition.type === "TEXT_STARTS_WITH") {
3631
+ var raw = (_o = (_m = values[0]) === null || _m === void 0 ? void 0 : _m.userEnteredValue) !== null && _o !== void 0 ? _o : "";
3632
+ if (!raw)
3633
+ return undefined;
3634
+ return __assign({ condition: "of:=LEFT(cell-content(),LEN(\"".concat(raw.replace(/"/g, '""'), "\"))=\"").concat(raw.replace(/"/g, '""'), "\"") }, base);
3635
+ }
3636
+ if (condition.type === "TEXT_ENDS_WITH") {
3637
+ var raw = (_q = (_p = values[0]) === null || _p === void 0 ? void 0 : _p.userEnteredValue) !== null && _q !== void 0 ? _q : "";
3638
+ if (!raw)
3639
+ return undefined;
3640
+ return __assign({ condition: "of:=RIGHT(cell-content(),LEN(\"".concat(raw.replace(/"/g, '""'), "\"))=\"").concat(raw.replace(/"/g, '""'), "\"") }, base);
3641
+ }
3642
+ if (condition.type === "TEXT_IS_EMAIL") {
3643
+ return __assign({ condition: "of:=AND(ISNUMBER(SEARCH(\"@\",cell-content())),ISNUMBER(SEARCH(\".\",cell-content())))" }, base);
3644
+ }
3645
+ if (condition.type === "TEXT_IS_URL") {
3646
+ return __assign({ condition: "of:=OR(LEFT(cell-content(),7)=\"http://\",LEFT(cell-content(),8)=\"https://\")" }, base);
3647
+ }
3648
+ if (condition.type === "NUMBER_BETWEEN" ||
3649
+ condition.type === "NUMBER_NOT_BETWEEN" ||
3650
+ condition.type === "NUMBER_EQ" ||
3651
+ condition.type === "NUMBER_NOT_EQ" ||
3652
+ condition.type === "NUMBER_GREATER" ||
3653
+ condition.type === "NUMBER_GREATER_THAN_EQ" ||
3654
+ condition.type === "NUMBER_LESS" ||
3655
+ condition.type === "NUMBER_LESS_THAN_EQ") {
3656
+ var first = (_s = (_r = values[0]) === null || _r === void 0 ? void 0 : _r.userEnteredValue) !== null && _s !== void 0 ? _s : "";
3657
+ if (!first)
3658
+ return undefined;
3659
+ var second = (_u = (_t = values[1]) === null || _t === void 0 ? void 0 : _t.userEnteredValue) !== null && _u !== void 0 ? _u : "";
3660
+ var opMap = {
3661
+ NUMBER_BETWEEN: "cell-content-is-between",
3662
+ NUMBER_NOT_BETWEEN: "cell-content-is-not-between",
3663
+ NUMBER_EQ: "cell-content-is-equal-to",
3664
+ NUMBER_NOT_EQ: "cell-content-is-not-equal-to",
3665
+ NUMBER_GREATER: "cell-content-is-greater-than",
3666
+ NUMBER_GREATER_THAN_EQ: "cell-content-is-greater-than-or-equal-to",
3667
+ NUMBER_LESS: "cell-content-is-less-than",
3668
+ NUMBER_LESS_THAN_EQ: "cell-content-is-less-than-or-equal-to",
3669
+ };
3670
+ var fn = opMap[condition.type];
3671
+ if (!fn)
3672
+ return undefined;
3673
+ if (condition.type === "NUMBER_BETWEEN" ||
3674
+ condition.type === "NUMBER_NOT_BETWEEN") {
3675
+ return __assign({ condition: "of:=".concat(fn, "(").concat(first, ",").concat(second, ")") }, base);
3676
+ }
3677
+ return __assign({ condition: "of:=".concat(fn, "(").concat(first, ")") }, base);
3678
+ }
3679
+ if (condition.type === "DATE_EQ" ||
3680
+ condition.type === "DATE_NOT_EQ" ||
3681
+ condition.type === "DATE_BEFORE" ||
3682
+ condition.type === "DATE_AFTER" ||
3683
+ condition.type === "DATE_ON_OR_BEFORE" ||
3684
+ condition.type === "DATE_ON_OR_AFTER" ||
3685
+ condition.type === "DATE_BETWEEN" ||
3686
+ condition.type === "DATE_NOT_BETWEEN") {
3687
+ var first = (_w = (_v = values[0]) === null || _v === void 0 ? void 0 : _v.userEnteredValue) !== null && _w !== void 0 ? _w : "";
3688
+ if (!first)
3689
+ return undefined;
3690
+ var second = (_y = (_x = values[1]) === null || _x === void 0 ? void 0 : _x.userEnteredValue) !== null && _y !== void 0 ? _y : "";
3691
+ var opMap = {
3692
+ DATE_EQ: "cell-content-date-equal-to",
3693
+ DATE_NOT_EQ: "cell-content-date-not-equal-to",
3694
+ DATE_BEFORE: "cell-content-date-before",
3695
+ DATE_AFTER: "cell-content-date-after",
3696
+ DATE_ON_OR_BEFORE: "cell-content-date-on-or-before",
3697
+ DATE_ON_OR_AFTER: "cell-content-date-on-or-after",
3698
+ DATE_BETWEEN: "cell-content-date-is-between",
3699
+ DATE_NOT_BETWEEN: "cell-content-date-is-not-between",
3700
+ };
3701
+ var fn = opMap[condition.type];
3702
+ if (!fn)
3703
+ return undefined;
3704
+ if (condition.type === "DATE_BETWEEN" ||
3705
+ condition.type === "DATE_NOT_BETWEEN") {
3706
+ return __assign({ condition: "of:=".concat(fn, "(").concat(first, ",").concat(second, ")") }, base);
3707
+ }
3708
+ return __assign({ condition: "of:=".concat(fn, "(").concat(first, ")") }, base);
3709
+ }
3710
+ if (condition.type === "DATE_IS_VALID") {
3711
+ return __assign({ condition: "of:=ISNUMBER(cell-content())" }, base);
3712
+ }
3713
+ return __assign({ condition: "of:=cell-content()" }, base);
3714
+ };