@quirekit/xlsx 0.0.0-stage → 0.3.0

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 (336) hide show
  1. package/LICENSE.md +21 -0
  2. package/THIRD_PARTY_NOTICES.md +150 -0
  3. package/dist/index.d.mts +122 -0
  4. package/dist/index.d.mts.map +1 -0
  5. package/dist/index.mjs +19167 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/licenses/saxes.LICENSE +64 -0
  8. package/licenses/xmlchars.LICENSE +18 -0
  9. package/package.json +52 -3
  10. package/src/bundle.ts +17 -0
  11. package/src/comments/legacy/read.ts +68 -0
  12. package/src/comments/legacy/write.ts +64 -0
  13. package/src/comments/package/ranges.ts +78 -0
  14. package/src/comments/package/read.ts +95 -0
  15. package/src/comments/package/roundtrip.test.ts +106 -0
  16. package/src/comments/package/write.ts +130 -0
  17. package/src/comments/thread/read.ts +69 -0
  18. package/src/comments/thread/write.ts +61 -0
  19. package/src/comments/types.ts +43 -0
  20. package/src/comments/xml.ts +50 -0
  21. package/src/create.ts +13 -0
  22. package/src/drawing/cache.ts +48 -0
  23. package/src/drawing/chart.test.ts +96 -0
  24. package/src/drawing/chart.ts +87 -0
  25. package/src/drawing/definition/plots.ts +76 -0
  26. package/src/drawing/definition/read.ts +65 -0
  27. package/src/drawing/definition/shape.ts +40 -0
  28. package/src/drawing/definition/types.ts +24 -0
  29. package/src/drawing/editable-picture.ts +80 -0
  30. package/src/drawing/graph.ts +148 -0
  31. package/src/drawing/identity.ts +22 -0
  32. package/src/drawing/import.ts +133 -0
  33. package/src/drawing/namespaces.ts +11 -0
  34. package/src/drawing/picture.test.ts +98 -0
  35. package/src/drawing/picture.ts +54 -0
  36. package/src/drawing/placement/anchor.ts +71 -0
  37. package/src/drawing/placement/axes.ts +113 -0
  38. package/src/drawing/placement/marker.ts +16 -0
  39. package/src/drawing/placement/transform.ts +132 -0
  40. package/src/drawing/placement/types.ts +20 -0
  41. package/src/drawing/presentation/cartesian/axes.ts +103 -0
  42. package/src/drawing/presentation/cartesian/plot.ts +109 -0
  43. package/src/drawing/presentation/cartesian/types.ts +9 -0
  44. package/src/drawing/presentation/layout.ts +29 -0
  45. package/src/drawing/presentation/paint.ts +56 -0
  46. package/src/drawing/presentation/properties.ts +31 -0
  47. package/src/drawing/read.ts +85 -0
  48. package/src/drawing/shapes/connector.ts +55 -0
  49. package/src/drawing/shapes/paint.ts +108 -0
  50. package/src/drawing/shapes/read.ts +89 -0
  51. package/src/drawing/shapes/text.ts +89 -0
  52. package/src/drawing/shapes/types.ts +13 -0
  53. package/src/drawing/sources.test.ts +27 -0
  54. package/src/drawing/sources.ts +43 -0
  55. package/src/drawing/types.ts +54 -0
  56. package/src/drawing/worksheet-connector.test.ts +135 -0
  57. package/src/drawing/worksheet-shape.test.ts +61 -0
  58. package/src/drawing/write/anchor.ts +17 -0
  59. package/src/drawing/write/axes.ts +23 -0
  60. package/src/drawing/write/chart.ts +56 -0
  61. package/src/drawing/write/drawing.ts +61 -0
  62. package/src/drawing/write/pictures.ts +68 -0
  63. package/src/drawing/write/series.ts +43 -0
  64. package/src/drawing/write/shapes.ts +113 -0
  65. package/src/drawing/write/text.ts +26 -0
  66. package/src/drawing/write/workbook.test.ts +199 -0
  67. package/src/drawing/write/workbook.ts +217 -0
  68. package/src/external-links/formulas.ts +21 -0
  69. package/src/external-links/read.test.ts +93 -0
  70. package/src/external-links/read.ts +104 -0
  71. package/src/external-links/types.ts +9 -0
  72. package/src/external-links/write.ts +120 -0
  73. package/src/image/excel.ts +122 -0
  74. package/src/image/native.ts +21 -0
  75. package/src/image/ownership.ts +77 -0
  76. package/src/image/parts.ts +45 -0
  77. package/src/image/raster.ts +25 -0
  78. package/src/image/read.test.ts +95 -0
  79. package/src/image/read.ts +66 -0
  80. package/src/image/relationships.ts +26 -0
  81. package/src/image/types.ts +48 -0
  82. package/src/image/wps.ts +43 -0
  83. package/src/image/write.test.ts +53 -0
  84. package/src/image/write.ts +118 -0
  85. package/src/index.ts +6 -0
  86. package/src/metadata/dynamic-array.ts +105 -0
  87. package/src/metadata/package.ts +75 -0
  88. package/src/metadata/types.ts +7 -0
  89. package/src/opc/archive.ts +26 -0
  90. package/src/opc/ownership.ts +40 -0
  91. package/src/opc/relationships.ts +98 -0
  92. package/src/opc/revision.ts +28 -0
  93. package/src/opc/shape.ts +23 -0
  94. package/src/opc/types.ts +13 -0
  95. package/src/opc/xml.test.ts +49 -0
  96. package/src/opc/xml.ts +128 -0
  97. package/src/optimization/blanks.ts +53 -0
  98. package/src/optimization/optimize.test.ts +117 -0
  99. package/src/optimization/optimize.ts +41 -0
  100. package/src/optimization/package.ts +65 -0
  101. package/src/optimization/rules.ts +46 -0
  102. package/src/optimization/styles.ts +76 -0
  103. package/src/optimization/types.ts +33 -0
  104. package/src/package/assembly.test.ts +117 -0
  105. package/src/package/calculation-metadata.test.ts +85 -0
  106. package/src/package/calculation-metadata.ts +88 -0
  107. package/src/package/checkboxes.ts +37 -0
  108. package/src/package/cleanup.test.ts +61 -0
  109. package/src/package/dashboard.test.ts +53 -0
  110. package/src/package/dashboard.ts +84 -0
  111. package/src/package/extensions.ts +16 -0
  112. package/src/package/merge-recipes.ts +84 -0
  113. package/src/package/names/conditional.ts +64 -0
  114. package/src/package/names/defined.test.ts +52 -0
  115. package/src/package/names/defined.ts +75 -0
  116. package/src/package/names/filter.ts +68 -0
  117. package/src/package/names/print-layout.ts +62 -0
  118. package/src/package/names/print.ts +62 -0
  119. package/src/package/new.ts +46 -0
  120. package/src/package/open/appearance.ts +46 -0
  121. package/src/package/open/directory.ts +61 -0
  122. package/src/package/open/restrictions.ts +27 -0
  123. package/src/package/open/snapshot.test.ts +48 -0
  124. package/src/package/open/snapshot.ts +34 -0
  125. package/src/package/open/source-write.ts +130 -0
  126. package/src/package/open/types.ts +73 -0
  127. package/src/package/open/worksheets.ts +149 -0
  128. package/src/package/positions.ts +40 -0
  129. package/src/package/read.ts +143 -0
  130. package/src/package/save/types.ts +57 -0
  131. package/src/package/save/worksheets.ts +126 -0
  132. package/src/package/selection-copy.test.ts +70 -0
  133. package/src/package/styles.ts +39 -0
  134. package/src/package/types.ts +52 -0
  135. package/src/package/workbook-views.ts +34 -0
  136. package/src/package/worksheets.test.ts +190 -0
  137. package/src/package/worksheets.ts +162 -0
  138. package/src/package/write.ts +175 -0
  139. package/src/pivot/cache/calculated.ts +34 -0
  140. package/src/pivot/cache/dates.ts +124 -0
  141. package/src/pivot/cache/groups.ts +11 -0
  142. package/src/pivot/cache/members.ts +99 -0
  143. package/src/pivot/cache/numbers.ts +63 -0
  144. package/src/pivot/cache/read.ts +131 -0
  145. package/src/pivot/cache/time.ts +20 -0
  146. package/src/pivot/cache/values.ts +43 -0
  147. package/src/pivot/cache/write.ts +117 -0
  148. package/src/pivot/definition/axes.ts +35 -0
  149. package/src/pivot/definition/dates.ts +87 -0
  150. package/src/pivot/definition/display.ts +86 -0
  151. package/src/pivot/definition/extension.ts +57 -0
  152. package/src/pivot/definition/field-settings/caption.ts +38 -0
  153. package/src/pivot/definition/field-settings/comparison.ts +47 -0
  154. package/src/pivot/definition/field-settings/field.ts +66 -0
  155. package/src/pivot/definition/field-settings/filters.ts +86 -0
  156. package/src/pivot/definition/field-settings/measure.ts +79 -0
  157. package/src/pivot/definition/field-settings/types.ts +19 -0
  158. package/src/pivot/definition/functions.ts +21 -0
  159. package/src/pivot/definition/items.ts +144 -0
  160. package/src/pivot/definition/members.ts +98 -0
  161. package/src/pivot/definition/numbers.ts +19 -0
  162. package/src/pivot/definition/presentation.ts +52 -0
  163. package/src/pivot/definition/read.ts +143 -0
  164. package/src/pivot/definition/report-layout.ts +39 -0
  165. package/src/pivot/definition/write.ts +157 -0
  166. package/src/pivot/package/calculated.test.ts +103 -0
  167. package/src/pivot/package/dates.test.ts +266 -0
  168. package/src/pivot/package/display.test.ts +133 -0
  169. package/src/pivot/package/field-settings.test.ts +59 -0
  170. package/src/pivot/package/layout.test.ts +148 -0
  171. package/src/pivot/package/measure-settings.test.ts +85 -0
  172. package/src/pivot/package/members.test.ts +167 -0
  173. package/src/pivot/package/numbers.test.ts +120 -0
  174. package/src/pivot/package/read.ts +93 -0
  175. package/src/pivot/package/roundtrip.test.ts +244 -0
  176. package/src/pivot/package/write.ts +103 -0
  177. package/src/pivot/types.ts +36 -0
  178. package/src/pivot/xml.ts +50 -0
  179. package/src/presentation.test.ts +186 -0
  180. package/src/roundtrip.test.ts +72 -0
  181. package/src/styles/checkbox/bags.ts +85 -0
  182. package/src/styles/checkbox/style.ts +45 -0
  183. package/src/styles/checkbox/types.ts +7 -0
  184. package/src/styles/color.ts +64 -0
  185. package/src/styles/differential-preview.ts +60 -0
  186. package/src/styles/differential.ts +119 -0
  187. package/src/styles/numbers.ts +9 -0
  188. package/src/styles/parts.ts +107 -0
  189. package/src/styles/read.ts +95 -0
  190. package/src/styles/reference.ts +14 -0
  191. package/src/styles/types.ts +9 -0
  192. package/src/styles/write.test.ts +88 -0
  193. package/src/styles/write.ts +162 -0
  194. package/src/table/conversion.test.ts +73 -0
  195. package/src/table/definition.ts +89 -0
  196. package/src/table/filter.ts +42 -0
  197. package/src/table/ownership.ts +112 -0
  198. package/src/table/read.test.ts +274 -0
  199. package/src/table/read.ts +117 -0
  200. package/src/table/remove.ts +55 -0
  201. package/src/table/sort.test.ts +79 -0
  202. package/src/table/styles/builtin.ts +40 -0
  203. package/src/table/styles/differential.ts +55 -0
  204. package/src/table/styles/preset-data.ts +17 -0
  205. package/src/table/styles/presets/dark.ts +104 -0
  206. package/src/table/styles/presets/light-grid.ts +68 -0
  207. package/src/table/styles/presets/light.ts +145 -0
  208. package/src/table/styles/presets/medium-edges.ts +131 -0
  209. package/src/table/styles/presets/medium.ts +131 -0
  210. package/src/table/styles/read.ts +70 -0
  211. package/src/table/styles/types.ts +27 -0
  212. package/src/table/totals.test.ts +77 -0
  213. package/src/table/totals.ts +79 -0
  214. package/src/table/types.ts +21 -0
  215. package/src/table/write.ts +189 -0
  216. package/src/types.ts +74 -0
  217. package/src/value/date.ts +21 -0
  218. package/src/worksheet/appearance.ts +55 -0
  219. package/src/worksheet/axis.test.ts +185 -0
  220. package/src/worksheet/axis.ts +131 -0
  221. package/src/worksheet/background/read.ts +41 -0
  222. package/src/worksheet/background/roundtrip.test.ts +77 -0
  223. package/src/worksheet/background/write.ts +96 -0
  224. package/src/worksheet/cell-shift.ts +44 -0
  225. package/src/worksheet/cells.ts +75 -0
  226. package/src/worksheet/checkbox/formats.ts +53 -0
  227. package/src/worksheet/checkbox/ranges.ts +112 -0
  228. package/src/worksheet/checkbox/write.test.ts +62 -0
  229. package/src/worksheet/conditional/color-scale.ts +61 -0
  230. package/src/worksheet/conditional/data-bar.ts +76 -0
  231. package/src/worksheet/conditional/extensions.ts +95 -0
  232. package/src/worksheet/conditional/icon-reference.ts +69 -0
  233. package/src/worksheet/conditional/icon-set.test.ts +60 -0
  234. package/src/worksheet/conditional/icon-set.ts +79 -0
  235. package/src/worksheet/conditional/preview.ts +44 -0
  236. package/src/worksheet/conditional/read.ts +185 -0
  237. package/src/worksheet/conditional/text.test.ts +71 -0
  238. package/src/worksheet/conditional/text.ts +122 -0
  239. package/src/worksheet/conditional/threshold.ts +47 -0
  240. package/src/worksheet/conditional/types.ts +20 -0
  241. package/src/worksheet/conditional/write-bar.ts +66 -0
  242. package/src/worksheet/conditional/write.test.ts +218 -0
  243. package/src/worksheet/conditional/write.ts +103 -0
  244. package/src/worksheet/copied-axis.ts +70 -0
  245. package/src/worksheet/data/rows.ts +59 -0
  246. package/src/worksheet/data/source.test.ts +68 -0
  247. package/src/worksheet/data/source.ts +31 -0
  248. package/src/worksheet/data/types.ts +9 -0
  249. package/src/worksheet/data.test.ts +314 -0
  250. package/src/worksheet/dimensions/columns.ts +87 -0
  251. package/src/worksheet/dimensions/write.test.ts +110 -0
  252. package/src/worksheet/dimensions/write.ts +36 -0
  253. package/src/worksheet/filters/advanced.test.ts +57 -0
  254. package/src/worksheet/filters/color.ts +105 -0
  255. package/src/worksheet/filters/icon.test.ts +83 -0
  256. package/src/worksheet/filters/icon.ts +39 -0
  257. package/src/worksheet/filters/read.ts +114 -0
  258. package/src/worksheet/filters/relative-dates.ts +47 -0
  259. package/src/worksheet/filters/restore-icons.ts +33 -0
  260. package/src/worksheet/filters/restore.ts +169 -0
  261. package/src/worksheet/filters/rules.ts +23 -0
  262. package/src/worksheet/filters/types.ts +23 -0
  263. package/src/worksheet/filters/visibility.ts +188 -0
  264. package/src/worksheet/filters/write.ts +121 -0
  265. package/src/worksheet/formula/cache.ts +29 -0
  266. package/src/worksheet/formula/external-results.test.ts +39 -0
  267. package/src/worksheet/formula/functions.ts +29 -0
  268. package/src/worksheet/formula/prefix.ts +27 -0
  269. package/src/worksheet/formula/shared/read.test.ts +121 -0
  270. package/src/worksheet/formula/shared/read.ts +94 -0
  271. package/src/worksheet/formula/shared/references.ts +100 -0
  272. package/src/worksheet/formula/shared/types.ts +21 -0
  273. package/src/worksheet/formula/spill-read.ts +54 -0
  274. package/src/worksheet/formula/spill-write.ts +32 -0
  275. package/src/worksheet/formula/spill.test.ts +101 -0
  276. package/src/worksheet/formula/write.test.ts +26 -0
  277. package/src/worksheet/hyperlinks/location.ts +59 -0
  278. package/src/worksheet/hyperlinks/model.ts +22 -0
  279. package/src/worksheet/hyperlinks/read.ts +70 -0
  280. package/src/worksheet/hyperlinks/types.ts +21 -0
  281. package/src/worksheet/hyperlinks/write.test.ts +203 -0
  282. package/src/worksheet/hyperlinks/write.ts +51 -0
  283. package/src/worksheet/merge.test.ts +58 -0
  284. package/src/worksheet/merge.ts +61 -0
  285. package/src/worksheet/outline/columns.ts +46 -0
  286. package/src/worksheet/outline/metadata.ts +68 -0
  287. package/src/worksheet/outline/native.ts +81 -0
  288. package/src/worksheet/outline/read.ts +50 -0
  289. package/src/worksheet/outline/roundtrip.test.ts +73 -0
  290. package/src/worksheet/outline/types.ts +37 -0
  291. package/src/worksheet/outline/write.ts +110 -0
  292. package/src/worksheet/positions.test.ts +46 -0
  293. package/src/worksheet/positions.ts +48 -0
  294. package/src/worksheet/print/breaks.ts +72 -0
  295. package/src/worksheet/print/elements.ts +16 -0
  296. package/src/worksheet/print/page-text.ts +139 -0
  297. package/src/worksheet/print/setup.test.ts +141 -0
  298. package/src/worksheet/print/setup.ts +116 -0
  299. package/src/worksheet/progress/read.ts +73 -0
  300. package/src/worksheet/progress/solid.ts +26 -0
  301. package/src/worksheet/progress/types.ts +11 -0
  302. package/src/worksheet/progress/write.test.ts +63 -0
  303. package/src/worksheet/progress/write.ts +46 -0
  304. package/src/worksheet/read.ts +197 -0
  305. package/src/worksheet/rich-text.test.ts +41 -0
  306. package/src/worksheet/rich-text.ts +76 -0
  307. package/src/worksheet/sort/read.ts +115 -0
  308. package/src/worksheet/sort/relocate.ts +62 -0
  309. package/src/worksheet/sort/roundtrip.test.ts +116 -0
  310. package/src/worksheet/sort/types.ts +11 -0
  311. package/src/worksheet/sort/write.ts +77 -0
  312. package/src/worksheet/template.ts +9 -0
  313. package/src/worksheet/text.ts +33 -0
  314. package/src/worksheet/validation/extended.ts +36 -0
  315. package/src/worksheet/validation/image.ts +7 -0
  316. package/src/worksheet/validation/list-options/portable.ts +90 -0
  317. package/src/worksheet/validation/list-options/types.ts +14 -0
  318. package/src/worksheet/validation/list-options/wps.ts +51 -0
  319. package/src/worksheet/validation/read.ts +162 -0
  320. package/src/worksheet/validation/text.ts +13 -0
  321. package/src/worksheet/validation/write.test.ts +259 -0
  322. package/src/worksheet/validation/write.ts +99 -0
  323. package/src/worksheet/view/coordinates.ts +39 -0
  324. package/src/worksheet/view/named/read.ts +116 -0
  325. package/src/worksheet/view/named/roundtrip.test.ts +136 -0
  326. package/src/worksheet/view/named/sort.ts +57 -0
  327. package/src/worksheet/view/named/types.ts +15 -0
  328. package/src/worksheet/view/named/write.ts +107 -0
  329. package/src/worksheet/view/named/xml.ts +33 -0
  330. package/src/worksheet/view/panes.ts +75 -0
  331. package/src/worksheet/view/read.ts +61 -0
  332. package/src/worksheet/view/relocate.ts +57 -0
  333. package/src/worksheet/view/write.test.ts +91 -0
  334. package/src/worksheet/view/write.ts +57 -0
  335. package/src/worksheet/write.ts +86 -0
  336. package/README.md +0 -3
@@ -0,0 +1,27 @@
1
+ import { formatWorkbookSpillReferences, scanWorkbookFormula, type WorkbookFormulaToken } from "@quirekit/workbook";
2
+ import { xlsxFutureFunctions, xlsxWorksheetFutureFunctions } from "./functions";
3
+
4
+ /**
5
+ * @param formula - Cell formula body, without its leading equals sign.
6
+ * @returns Native OOXML formula text, changing only unqualified future call names.
7
+ */
8
+ export function prefixXlsxFormulaFunctions(formula: string): string {
9
+ const source = formatWorkbookSpillReferences(formula, "function").formula;
10
+ let previous: WorkbookFormulaToken | undefined;
11
+ let qualifier: WorkbookFormulaToken | undefined;
12
+ let next = "";
13
+ let offset = 0;
14
+ for (const token of scanWorkbookFormula(source)) {
15
+ if (token.text === "(" && previous?.kind === "word" && qualifier?.text !== "!") {
16
+ const name = previous.text.toUpperCase();
17
+ const prefix = xlsxWorksheetFutureFunctions.has(name) ? "_xlfn._xlws." : xlsxFutureFunctions.has(name) ? "_xlfn." : "";
18
+ if (prefix) {
19
+ next += source.slice(offset, previous.start) + prefix;
20
+ offset = previous.start;
21
+ }
22
+ }
23
+ qualifier = previous;
24
+ previous = token;
25
+ }
26
+ return next + source.slice(offset);
27
+ }
@@ -0,0 +1,121 @@
1
+ import { parseWorkbookRange, type WorkbookSnapshot } from "@quirekit/workbook";
2
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
3
+ import { expect, it } from "vitest";
4
+ import { createXlsx, openXlsx } from "../../../index";
5
+
6
+ const sheetPath = "xl/worksheets/sheet1.xml";
7
+ const workbookPath = "xl/workbook.xml";
8
+ const base: WorkbookSnapshot = { version: 1, id: "shared", name: "Shared formulas", revision: 0, sheets: [
9
+ { id: "orders", name: "Orders", cells: [] }, { id: "next", name: "Next Data", cells: [] }
10
+ ] };
11
+
12
+ /** @param rows - Native row records containing shared and independent formulas.
13
+ * @param manual - Source calculation mode. @param names - Optional native defined name record.
14
+ * @returns An XLSX fixture with the supplied native worksheet representation. */
15
+ function sharedFile(rows: string, manual = false, names = ""): Uint8Array {
16
+ const parts = unzipSync(createXlsx(base));
17
+ parts[sheetPath] = strToU8(strFromU8(parts[sheetPath]!).replace(/<sheetData(?:\/>|>[\s\S]*?<\/sheetData>)/u, "<sheetData>" + rows + "</sheetData>"));
18
+ if (manual || names) {
19
+ const workbook = strFromU8(parts[workbookPath]!).replace(
20
+ /<calcPr[^>]*\/>/u, (names && "<definedNames>" + names + "</definedNames>") + (manual ? '<calcPr calcMode="manual"/>' : "<calcPr/>")
21
+ );
22
+ parts[workbookPath] = strToU8(workbook);
23
+ }
24
+ return zipSync(parts);
25
+ }
26
+
27
+ /** @param file - Opened test workbook. @param a1 - Stored point to inspect. @returns The cell's authored input. */
28
+ function inputAt(file: ReturnType<typeof openXlsx>, a1: string) {
29
+ const sheet = file.snapshot.sheets[0]!;
30
+ const { startRow, startColumn } = parseWorkbookRange(sheet.id, a1);
31
+ return sheet.cells.find(({ row, column }) => row === startRow && column === startColumn)?.input;
32
+ }
33
+
34
+ it("expands native shared formulas from the master and writes individually authored members and caches", () => {
35
+ const master = 'IF(B2="A1",$B2+D$1+SUM(2:3,A:C)+LOG10($A$1),\'Next Data\'!B2)';
36
+ const bytes = sharedFile('<row r="3"><c r="D3"><f>B3*10</f><v>70</v></c><c r="E3"><f t="shared" si="0"/><v>7</v></c></row>'
37
+ + '<row r="2"><c r="D2"><f t="shared" si="0" ref="D2:E3">' + master + '</f><v>2</v></c>'
38
+ + '<c r="E2"><f t="shared" si="0">999</f><v>3</v></c></row>');
39
+ const file = openXlsx("Orders", bytes);
40
+ expect(file.restrictions).toEqual([]);
41
+ expect(inputAt(file, "D2")).toEqual({ kind: "formula", formula: "=" + master });
42
+ expect(inputAt(file, "E2")).toEqual({ kind: "formula",
43
+ formula: '=IF(C2="A1",$B2+E$1+SUM(2:3,B:D)+LOG10($A$1),\'Next Data\'!C2)' });
44
+ expect(inputAt(file, "D3")).toEqual({ kind: "formula", formula: "=B3*10" });
45
+ expect(inputAt(file, "E3")).toEqual({ kind: "formula",
46
+ formula: '=IF(C3="A1",$B3+E$1+SUM(3:4,B:D)+LOG10($A$1),\'Next Data\'!C3)' });
47
+ expect(file.write(file.snapshot)).toEqual(bytes);
48
+
49
+ const [sheet, next] = file.snapshot.sheets;
50
+ const formatted = file.write({ ...file.snapshot, revision: 1, sheets: [
51
+ { ...sheet!, formats: [{ row: 1, column: 3, format: { bold: true } }] }, next!
52
+ ] });
53
+ expect(strFromU8(unzipSync(formatted)[sheetPath]!)).toContain('t="shared" si="0"');
54
+
55
+ const changed = file.write({ ...file.snapshot, revision: 1, sheets: [
56
+ { ...sheet!, cells: sheet!.cells.map(cell => cell.row === 1 && cell.column === 3
57
+ ? { ...cell, input: { kind: "value", value: 8 } } : cell) }, next!
58
+ ] }, { result: () => ({ status: "value", value: 21 }) });
59
+ const xml = strFromU8(unzipSync(changed)[sheetPath]!);
60
+ expect(xml).not.toContain('t="shared"');
61
+ expect(xml).toContain("<v>21</v>");
62
+ const reopened = openXlsx("Reopened", changed);
63
+ expect(reopened.restrictions).toEqual([]);
64
+ expect(inputAt(reopened, "D2")).toEqual({ kind: "value", value: 8 });
65
+ expect(inputAt(reopened, "E3")).toEqual(inputAt(file, "E3"));
66
+ });
67
+
68
+ it("retains each native shared formula's manual calculation cache", () => {
69
+ const bytes = sharedFile('<row r="2"><c r="B2"><f t="shared" si="4" ref="B2:B3">A2*2</f><v>12</v></c></row>'
70
+ + '<row r="3"><c r="B3" t="b"><f t="shared" si="4"/><v>1</v></c></row>', true);
71
+ const file = openXlsx("Manual", bytes);
72
+ expect(file.restrictions).toEqual([]);
73
+ expect(file.snapshot.calculationSettings?.mode).toBe("manual");
74
+ expect(inputAt(file, "B3")).toEqual({ kind: "formula", formula: "=A3*2" });
75
+ expect(file.snapshot.formulaResults?.map(({ row, result }) => [row, result])).toEqual([
76
+ [1, { status: "value", value: 12 }], [2, { status: "value", value: true }]
77
+ ]);
78
+ });
79
+
80
+ it("keeps cached values and preserves the original when a shared group has no valid master", () => {
81
+ const bytes = sharedFile('<row r="2"><c r="B2"><f t="shared" si="4"/><v>12</v></c></row>');
82
+ const file = openXlsx("Missing master", bytes);
83
+ expect(file.restrictions).toContain("共享公式分组或引用无法展开");
84
+ expect(inputAt(file, "B2")).toEqual({ kind: "value", value: 12 });
85
+ expect(file.write(file.snapshot)).toEqual(bytes);
86
+ });
87
+
88
+ it("resolves implicit cell positions and preserves structured text and qualified references", () => {
89
+ const bytes = sharedFile('<row><c><f t="shared" si="4" ref="A1:B1">SUM($A$2,A2,Table1[Q1],\'Q1:Q2\'!A2,$B:C)</f></c>'
90
+ + '<c><f t="shared" si="4"/></c></row>');
91
+ const file = openXlsx("Implicit coordinates", bytes);
92
+ expect(file.restrictions).toEqual([]);
93
+ expect(inputAt(file, "B1")).toEqual({ kind: "formula", formula: "=SUM($A$2,B2,Table1[Q1],'Q1:Q2'!B2,$B:D)" });
94
+ });
95
+
96
+ it("protects overlapping or out-of-range groups and leaves their native caches readable", () => {
97
+ const bytes = sharedFile('<row r="2"><c r="B2"><f t="shared" si="1" ref="B2:C2">A2*2</f><v>10</v></c>'
98
+ + '<c r="C2"><f t="shared" si="2" ref="C2:D2">B2*2</f><v>20</v></c>'
99
+ + '<c r="D2"><f t="shared" si="2"/><v>40</v></c>'
100
+ + '<c r="E2"><f t="shared" si="3" ref="E2">D2*2</f><v>80</v></c>'
101
+ + '<c r="F2"><f t="shared" si="3"/><v>160</v></c></row>');
102
+ const file = openXlsx("Invalid coverage", bytes);
103
+ expect(file.restrictions).toContain("共享公式分组或引用无法展开");
104
+ expect(inputAt(file, "B2")).toEqual({ kind: "value", value: 10 });
105
+ expect(inputAt(file, "D2")).toEqual({ kind: "value", value: 40 });
106
+ expect(inputAt(file, "E2")).toEqual({ kind: "formula", formula: "=D2*2" });
107
+ expect(inputAt(file, "F2")).toEqual({ kind: "value", value: 160 });
108
+ expect(file.write(file.snapshot)).toEqual(bytes);
109
+ });
110
+
111
+ it("keeps shared caches that depend on an unsupported defined name while opening the other groups", () => {
112
+ const bytes = sharedFile('<row r="2"><c r="B2"><f t="shared" si="1" ref="B2:B3">WorkItem</f><v>12</v></c>'
113
+ + '<c r="C2"><f t="shared" si="2" ref="C2:C3">A2*2</f><v>18</v></c></row>'
114
+ + '<row r="3"><c r="B3"><f t="shared" si="1"/><v>15</v></c><c r="C3"><f t="shared" si="2"/><v>20</v></c></row>',
115
+ false, '<definedName name="WorkItem" localSheetId="0">Orders!$A2</definedName>');
116
+ const file = openXlsx("Relative name", bytes);
117
+ expect(file.restrictions).toContain("相对或动态定义名称");
118
+ expect(inputAt(file, "B3")).toEqual({ kind: "value", value: 15 });
119
+ expect(inputAt(file, "C3")).toEqual({ kind: "formula", formula: "=A3*2" });
120
+ expect(file.write(file.snapshot)).toEqual(bytes);
121
+ });
@@ -0,0 +1,94 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { indexWorkbookRanges, parseWorkbookRange, workbookRangeContains, type WorkbookRange } from "@quirekit/workbook";
3
+ import { hasKnownAttributes, hasKnownChildren } from "../../../opc/shape";
4
+ import { isTrue, readIndex, spreadNs } from "../../../opc/xml";
5
+ import { indexCells, indexRows } from "../../positions";
6
+ import { compileXlsxSharedReferences } from "./references";
7
+
8
+ /** A verified shared master and its formula in native worksheet coordinates. */
9
+ interface XlsxSharedMaster {
10
+ /** Actual source cell used to measure member offsets. */
11
+ readonly source: WorkbookRange;
12
+ /** Inclusive bounds of the native shared group. */
13
+ readonly range: WorkbookRange;
14
+ /** Compiled relative references for expanding this group's inputs. */
15
+ readonly translate: ReturnType<typeof compileXlsxSharedReferences>;
16
+ }
17
+
18
+ const sharedAttributes = ["t", "si", "ref", "ca", "bx"];
19
+
20
+ /** @param formula - A native shared formula element. @returns Its index when the formula metadata is supported. */
21
+ function sharedIndex(formula: Element): number | undefined {
22
+ const index = readIndex(formula, "si");
23
+ return formula.namespaceURI === spreadNs && index !== undefined && index <= 0xffffffff
24
+ && !isTrue(formula.getAttribute("bx")) && hasKnownAttributes(formula, sharedAttributes)
25
+ && hasKnownChildren(formula, []) ? index : undefined;
26
+ }
27
+
28
+ /** @param data - Native sheetData containing the formula elements.
29
+ * @param supportsNames - Checks that the shared expression's names can keep their native meaning.
30
+ * @returns A member resolver that indexes masters only on a worksheet containing shared formulas. */
31
+ export function createXlsxSharedFormulaReader(data: Element, supportsNames?: (formula: string, source: WorkbookRange) => boolean) {
32
+ let masters: ReadonlyMap<number, XlsxSharedMaster | undefined> | undefined;
33
+
34
+ /** @returns Masters indexed by their worksheet-local shared group ID. */
35
+ function indexMasters(): ReadonlyMap<number, XlsxSharedMaster | undefined> {
36
+ const groups = new Map<number, XlsxSharedMaster | undefined>();
37
+ let rows: Map<Element, number> | undefined;
38
+ for (const formula of Array.from(data.getElementsByTagNameNS(spreadNs, "f"))) {
39
+ if (formula.getAttribute("t") !== "shared" || !formula.hasAttribute("ref")) continue;
40
+ const id = readIndex(formula, "si");
41
+ if (id === undefined) continue;
42
+ const cell = formula.parentNode as Element | null;
43
+ const row = cell?.parentNode as Element | null;
44
+ if (cell?.localName !== "c" || row?.localName !== "row" || row.parentNode !== data) continue;
45
+ groups.set(id, groups.has(id) ? undefined : readMaster(formula, cell, row));
46
+ }
47
+ const entries = [...groups.values()].filter((group): group is XlsxSharedMaster => group !== undefined);
48
+ if (entries.length > 1) {
49
+ entries.sort((left, right) => left.range.startRow - right.range.startRow || left.range.startColumn - right.range.startColumn);
50
+ const intersecting = indexWorkbookRanges(entries, entry => entry.range);
51
+ for (const [id, entry] of groups) {
52
+ if (entry && intersecting(entry.range, other => other !== entry)) groups.set(id, undefined);
53
+ }
54
+ }
55
+ return groups;
56
+
57
+ /** @param formula - Candidate master. @param cell - Its source XML cell. @param row - Its containing native row.
58
+ * @returns Shared expression and validated origin, when the source can be expanded. */
59
+ function readMaster(formula: Element, cell: Element, row: Element): XlsxSharedMaster | undefined {
60
+ const expression = formula.textContent;
61
+ if (!expression?.trim() || expression.length >= 8192 || sharedIndex(formula) === undefined) return;
62
+ let source: WorkbookRange;
63
+ let range: WorkbookRange;
64
+ try {
65
+ range = parseWorkbookRange("", formula.getAttribute("ref") ?? "");
66
+ const reference = cell.getAttribute("r");
67
+ if (reference) source = parseWorkbookRange("", reference);
68
+ else {
69
+ rows ??= new Map([...indexRows(data)].map(([index, element]) => [element, index]));
70
+ const index = rows.get(row);
71
+ const column = [...indexCells(row)].find(([, element]) => element === cell)?.[0];
72
+ if (index === undefined || column === undefined) return;
73
+ source = { sheetId: "", startRow: index, endRow: index, startColumn: column, endColumn: column };
74
+ }
75
+ } catch { return; }
76
+ if (source.startRow !== source.endRow || source.startColumn !== source.endColumn || !workbookRangeContains(range, source)
77
+ || supportsNames && !supportsNames(expression, source)) return;
78
+ return { source, range, translate: compileXlsxSharedReferences(expression) };
79
+ }
80
+ }
81
+
82
+ /** @param formula - Member's native formula record. @param row - Zero-based worksheet row.
83
+ * @param column - Zero-based worksheet column. @returns Exact member expression, if it is safe to expand. */
84
+ return function readSharedFormula(formula: Element, row: number, column: number): string | undefined {
85
+ const id = sharedIndex(formula);
86
+ if (id === undefined) return;
87
+ masters ??= indexMasters();
88
+ const master = masters.get(id);
89
+ if (!master || row < master.range.startRow || row > master.range.endRow
90
+ || column < master.range.startColumn || column > master.range.endColumn) return;
91
+ const expression = master.translate(row - master.source.startRow, column - master.source.startColumn);
92
+ return expression.length < 8192 ? expression : undefined;
93
+ };
94
+ }
@@ -0,0 +1,100 @@
1
+ import { formatWorkbookColumn, parseWorkbookColumn, scanWorkbookFormula, workbookColumns, workbookRows,
2
+ type WorkbookFormulaToken } from "@quirekit/workbook";
3
+ import type { XlsxFormulaAxis, XlsxFormulaEndpoint } from "./types";
4
+
5
+ /** @param token - Row digits in a cell or whole-row range. @param absolute - Whether the row was anchored.
6
+ * @returns A row inside the Excel grid. */
7
+ function readRow(token: string, absolute: boolean): XlsxFormulaAxis | undefined {
8
+ if (!/^[1-9]\d{0,6}$/u.test(token)) return;
9
+ const index = Number(token) - 1;
10
+ return index < workbookRows ? { index, absolute } : undefined;
11
+ }
12
+
13
+ /** @param tokens - Source formula tokens. @param index - Possible start of an A1 endpoint.
14
+ * @returns Valid worksheet axes and the exact bounds of their spelling. */
15
+ function readEndpoint(tokens: readonly WorkbookFormulaToken[], index: number): XlsxFormulaEndpoint | undefined {
16
+ const first = tokens[index];
17
+ if (!first) return;
18
+ const absolute = first.text === "$";
19
+ const wordIndex = index + Number(absolute);
20
+ const token = tokens[wordIndex];
21
+ if (token?.kind !== "word" || absolute && first.end !== token.start) return;
22
+
23
+ const start = first.start;
24
+ const onlyRow = readRow(token.text, absolute);
25
+ if (onlyRow) return { start, end: token.end, next: wordIndex + 1, row: onlyRow };
26
+ const match = /^([A-Z]{1,3})([1-9]\d{0,6})?$/iu.exec(token.text);
27
+ if (!match) return;
28
+ let column: XlsxFormulaAxis;
29
+ try { column = { index: parseWorkbookColumn(match[1]!), absolute }; }
30
+ catch { return; }
31
+
32
+ if (match[2]) {
33
+ const row = readRow(match[2], false);
34
+ return row && { start, end: token.end, next: wordIndex + 1, row, column };
35
+ }
36
+ const anchor = tokens[wordIndex + 1];
37
+ const digits = tokens[wordIndex + 2];
38
+ if (anchor?.text === "$" && token.end === anchor.start && digits?.kind === "word" && anchor.end === digits.start) {
39
+ const row = readRow(digits.text, true);
40
+ return row && { start, end: digits.end, next: wordIndex + 3, row, column };
41
+ }
42
+ return { start, end: token.end, next: wordIndex + 1, column };
43
+ }
44
+
45
+ /** @param endpoint - One Excel address or axis. @param rows - Relative row shift. @param columns - Relative column shift.
46
+ * @returns Translated coordinates, or undefined for an out-of-sheet reference. */
47
+ function moveEndpoint(endpoint: XlsxFormulaEndpoint, rows: number, columns: number): string | undefined {
48
+ let address = "";
49
+ if (endpoint.column) {
50
+ const index = endpoint.column.index + (endpoint.column.absolute ? 0 : columns);
51
+ if (index < 0 || index >= workbookColumns) return;
52
+ address = (endpoint.column.absolute ? "$" : "") + formatWorkbookColumn(index);
53
+ }
54
+ if (endpoint.row) {
55
+ const index = endpoint.row.index + (endpoint.row.absolute ? 0 : rows);
56
+ if (index < 0 || index >= workbookRows) return;
57
+ address += (endpoint.row.absolute ? "$" : "") + (index + 1);
58
+ }
59
+ return address;
60
+ }
61
+
62
+ /** @param formula - Authored A1 expression from the master.
63
+ * @returns A translator that visits only the compiled references for each shared member. */
64
+ export function compileXlsxSharedReferences(formula: string) {
65
+ const tokens = [...scanWorkbookFormula(formula)];
66
+ const references: { first: XlsxFormulaEndpoint; last?: XlsxFormulaEndpoint }[] = [];
67
+
68
+ // Sheet qualifiers and opaque literals are outside the axes that change on a copy.
69
+ for (let index = 0; index < tokens.length; index++) {
70
+ const next = tokens[index + 1];
71
+ if (next?.text === "!") { index++; continue; }
72
+ if (next?.text === ":" && tokens[index + 3]?.text === "!") { index += 3; continue; }
73
+ if (next?.text === "(" || next?.kind === "opaque" && next.text.startsWith("[")) continue;
74
+ const first = readEndpoint(tokens, index);
75
+ if (!first) continue;
76
+ const other = tokens[first.next]?.text === ":" ? readEndpoint(tokens, first.next + 1) : undefined;
77
+ const last = other && Boolean(first.row) === Boolean(other.row) && Boolean(first.column) === Boolean(other.column)
78
+ && tokens[other.next]?.text !== "!" ? other : undefined;
79
+ if (!last && (!first.row || !first.column)) continue;
80
+ references.push(last ? { first, last } : { first });
81
+ index = (last ?? first).next - 1;
82
+ }
83
+
84
+ /** @param rows - Member row minus master row. @param columns - Member column minus master column.
85
+ * @returns Formula in the member's A1 coordinates. */
86
+ return function translate(rows: number, columns: number): string {
87
+ if ((!rows && !columns) || !references.length) return formula;
88
+ let read = 0;
89
+ let result = "";
90
+ for (const { first, last } of references) {
91
+ const left = moveEndpoint(first, rows, columns);
92
+ const right = last && moveEndpoint(last, rows, columns);
93
+ result += formula.slice(read, first.start);
94
+ if (!left || last && !right) result += "#REF!";
95
+ else result += last ? left + formula.slice(first.end, last.start) + right : left;
96
+ read = (last ?? first).end;
97
+ }
98
+ return result + formula.slice(read);
99
+ };
100
+ }
@@ -0,0 +1,21 @@
1
+ /** One numeric axis of an A1 reference. */
2
+ export interface XlsxFormulaAxis {
3
+ /** Zero-based worksheet position. */
4
+ readonly index: number;
5
+ /** Whether a copied formula keeps this axis fixed. */
6
+ readonly absolute: boolean;
7
+ }
8
+
9
+ /** A cell or one endpoint of a whole-row or whole-column reference. */
10
+ export interface XlsxFormulaEndpoint {
11
+ /** First source character in the endpoint. */
12
+ readonly start: number;
13
+ /** Exclusive source character boundary. */
14
+ readonly end: number;
15
+ /** Index of the next token. */
16
+ readonly next: number;
17
+ /** Worksheet row, present for a cell or a row range. */
18
+ readonly row?: XlsxFormulaAxis | undefined;
19
+ /** Worksheet column, present for a cell or a column range. */
20
+ readonly column?: XlsxFormulaAxis | undefined;
21
+ }
@@ -0,0 +1,54 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { indexWorkbookFormulaSpills, parseWorkbookRange, workbookRangeSize, workbookSpillOffset,
3
+ workbookTransactionCellLimit, type WorkbookAddress, type WorkbookCachedFormulaResult, type WorkbookFormulaSpill } from "@quirekit/workbook";
4
+ import { child, children, readIndex, spreadNs } from "../../opc/xml";
5
+
6
+ /** @param data - Native sheetData. @param sheetId - Stable worksheet ID. @param indexes - Recognized dynamic metadata indexes.
7
+ * @param restrictions - Preserved source diagnostics. @returns Array ownership and a collector for the child caches. */
8
+ export function readXlsxWorksheetSpills(data: Element, sheetId: string, indexes: ReadonlySet<number>, restrictions: Set<string>) {
9
+ const entries: WorkbookFormulaSpill[] = [];
10
+ const mutable = new Map<WorkbookFormulaSpill, WorkbookCachedFormulaResult[]>();
11
+ const occupied: WorkbookAddress[] = [];
12
+ let count = 0;
13
+ try {
14
+ // Find sources first because covered values can appear before their source in the native row stream.
15
+ for (const row of children(data, "row")) for (const cell of children(row, "c")) {
16
+ const formula = child(cell, "f");
17
+ if (!formula && !cell.hasAttribute("cm") && !cell.hasAttribute("vm")) continue;
18
+ const reference = cell.getAttribute("r");
19
+ if (!reference && !cell.hasAttribute("cm")) continue;
20
+ const position = parseWorkbookRange(sheetId, reference ?? "");
21
+ if (workbookRangeSize(position) !== 1) throw new Error("数组源单元格地址无效。");
22
+ const address = { sheetId, row: position.startRow, column: position.startColumn };
23
+ occupied.push(address);
24
+ if (!indexes.has(readIndex(cell, "cm") ?? 0)) continue;
25
+ if (formula?.namespaceURI !== spreadNs || formula.getAttribute("t") !== "array" || !formula.textContent || cell.hasAttribute("vm")) {
26
+ throw new Error("数组元数据缺少有效源公式。");
27
+ }
28
+ const range = parseWorkbookRange(sheetId, formula.getAttribute("ref") ?? "");
29
+ if (range.startRow !== address.row || range.startColumn !== address.column) throw new Error("数组公式不在源区域左上角。");
30
+ const size = workbookRangeSize(range);
31
+ count += size;
32
+ if (count > workbookTransactionCellLimit) throw new Error("动态数组缓存超过当前容量。");
33
+ const values: WorkbookCachedFormulaResult[] = Array.from({ length: size - 1 }, () => ({ status: "unavailable" }));
34
+ const entry = { range, values };
35
+ entries.push(entry);
36
+ mutable.set(entry, values);
37
+ }
38
+ const arrays = indexWorkbookFormulaSpills(entries);
39
+ for (const address of occupied) {
40
+ const spill = arrays.at(address);
41
+ if (spill && workbookSpillOffset(spill, address) > 0) throw new Error("数组范围包含其他公式或元数据。");
42
+ }
43
+ return {
44
+ at: arrays.at,
45
+ /** @param spill - Owning source and outputs. @param offset - Positive row-major offset. @param result - Native child cache. */
46
+ record(spill: WorkbookFormulaSpill, offset: number, result: WorkbookCachedFormulaResult): void {
47
+ mutable.get(spill)![offset - 1] = result;
48
+ }
49
+ };
50
+ } catch {
51
+ restrictions.add("暂未支持的动态数组范围或缓存");
52
+ return undefined;
53
+ }
54
+ }
@@ -0,0 +1,32 @@
1
+ import { mapWorkbookPosition, workbookColumns, type WorkbookAddress, type WorkbookCell, type WorkbookFormulaSpill,
2
+ type WorkbookPositionEdit, type WorkbookSheet } from "@quirekit/workbook";
3
+
4
+ /** @param changes - Sparse native cell patches. @param sheet - Committed authored cells.
5
+ * @param before - Source file arrays. @param after - Current arrays. @param moves - Source-to-current coordinate mappings. */
6
+ export function includeXlsxSpillOutputs(changes: Map<number, Map<number, WorkbookCell | null>>, sheet: WorkbookSheet,
7
+ before: readonly WorkbookFormulaSpill[], after: readonly WorkbookFormulaSpill[], moves: readonly WorkbookPositionEdit[]): void {
8
+ if (!before.length && !after.length) return;
9
+ const authored = new Set(sheet.cells.map(({ row, column }) => row * workbookColumns + column));
10
+ /** @param entries - Output rectangles. @param positions - Mapping for previously stored rows or columns. */
11
+ function include(entries: readonly WorkbookFormulaSpill[], positions: readonly WorkbookPositionEdit[]): void {
12
+ for (const { range } of entries) {
13
+ for (let row = range.startRow; row <= range.endRow; row++) {
14
+ for (let column = range.startColumn; column <= range.endColumn; column++) {
15
+ if (row === range.startRow && column === range.startColumn) continue;
16
+ let point: WorkbookAddress | null = { sheetId: sheet.id, row, column };
17
+ for (const move of positions) {
18
+ if (!point) break;
19
+ point = mapWorkbookPosition(point, move);
20
+ }
21
+ if (!point || authored.has(point.row * workbookColumns + point.column)) continue;
22
+ const target = changes.get(point.row) ?? new Map<number, WorkbookCell | null>();
23
+ if (!target.has(point.column)) target.set(point.column, null);
24
+ changes.set(point.row, target);
25
+ }
26
+ }
27
+ }
28
+ }
29
+ // Retired output cells are visited as well, so existing XML nodes drop their old cached payloads.
30
+ include(before, moves);
31
+ include(after, []);
32
+ }
@@ -0,0 +1,101 @@
1
+ /// <reference types="node" />
2
+
3
+ import { readFileSync } from "node:fs";
4
+ import { parseWorkbookRange, retainWorkbookFormulaResults, type WorkbookSnapshot } from "@quirekit/workbook";
5
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
6
+ import { expect, it } from "vitest";
7
+ import { createXlsx, openXlsx } from "../../index";
8
+
9
+ /** @param name - Synthetic producer file. @returns Its native XLSX. */
10
+ function fixture(name: string): Uint8Array {
11
+ return Uint8Array.from(readFileSync(new URL("../../../test/fixtures/" + name, import.meta.url)));
12
+ }
13
+
14
+ it("loads a producer's array source and removes retired child caches when it shrinks", () => {
15
+ const bytes = fixture("dynamic-array-xlsxwriter.xlsx");
16
+ const file = openXlsx("动态数组", bytes);
17
+ const sheet = file.snapshot.sheets[0]!;
18
+ expect(file.restrictions).toEqual([]);
19
+ expect(sheet.cells.map(({ row, column, input }) => [row, column, input])).toEqual([
20
+ [0, 0, { kind: "formula", formula: "=_xlfn.SEQUENCE(2,2,11,1)" }],
21
+ [0, 4, { kind: "formula", formula: "=SUM(A1:B2)" }]
22
+ ]);
23
+ const next: WorkbookSnapshot = { ...file.snapshot, revision: 1, sheets: [
24
+ { ...sheet, cells: [{ row: 0, column: 0, input: { kind: "formula", formula: "=SEQUENCE(1,2,21)" } }, sheet.cells[1]!] }
25
+ ], formulaResults: [
26
+ { sheetId: sheet.id, row: 0, column: 0, result: { status: "value", value: 21 },
27
+ spill: { range: parseWorkbookRange(sheet.id, "A1:B1"), values: [{ status: "value", value: 22 }] } },
28
+ { sheetId: sheet.id, row: 0, column: 4, result: { status: "value", value: 43 } }
29
+ ] };
30
+ const saved = file.write(next);
31
+ const parts = unzipSync(saved);
32
+ const xml = strFromU8(parts["xl/worksheets/sheet1.xml"]!);
33
+ expect(xml).toContain('<c r="A1" cm="1"><f t="array" ref="A1:B1">_xlfn.SEQUENCE(1,2,21)</f><v>21</v></c>');
34
+ expect(xml).toContain('<c r="B1"><v>22</v></c>');
35
+ expect(xml).not.toMatch(/<c r="[AB]2"[^>]*>\s*<v>/u);
36
+ const reopened = openXlsx("重开", saved);
37
+ expect(reopened.restrictions).toEqual([]);
38
+ expect(reopened.snapshot.sheets[0]?.cells).toHaveLength(2);
39
+ const cached = retainWorkbookFormulaResults(reopened.snapshot)!;
40
+ expect(cached.read({ sheetId: reopened.snapshot.sheets[0]!.id, row: 0, column: 1 })).toEqual({ status: "value", value: 22 });
41
+
42
+ const removed = reopened.write({ ...reopened.snapshot, revision: 1, formulaResults: undefined, sheets: [
43
+ { ...reopened.snapshot.sheets[0]!, cells: [reopened.snapshot.sheets[0]!.cells[1]!] }
44
+ ] });
45
+ expect(Object.keys(unzipSync(removed))).not.toContain("xl/metadata.xml");
46
+ expect(openXlsx("清除源公式", removed).restrictions).toEqual([]);
47
+ });
48
+
49
+ it("shares one native metadata part with images and round-trips mixed array results", () => {
50
+ const imageFile = openXlsx("图片", fixture("excel-cell-images.xlsx"));
51
+ const source = imageFile.snapshot.sheets[0]!;
52
+ const picture = source.cells.find(({ input }) => input.kind === "image")!;
53
+ const snapshot: WorkbookSnapshot = { ...imageFile.snapshot, sheets: [
54
+ { id: source.id, name: source.name, cells: [picture, { row: 0, column: 5, input: { kind: "formula", formula: '={"001",TRUE;1,NA()}' } }] }
55
+ ], formulaResults: [{ sheetId: source.id, row: 0, column: 5, result: { status: "value", value: "001" },
56
+ spill: { range: parseWorkbookRange(source.id, "F1:G2"), values: [
57
+ { status: "value", value: true }, { status: "value", value: 1 }, { status: "error", code: "#N/A" }
58
+ ] } }] };
59
+ const saved = createXlsx(snapshot);
60
+ const parts = unzipSync(saved);
61
+ const metadata = strFromU8(parts["xl/metadata.xml"]!);
62
+ expect(metadata).toContain('metadataTypes count="2"');
63
+ expect(metadata).toContain("<cellMetadata count=\"1\"><bk><rc t=\"2\" v=\"0\"/></bk></cellMetadata>");
64
+ const reopened = openXlsx("同时有图片", saved);
65
+ expect(reopened.restrictions).toEqual([]);
66
+ expect(reopened.snapshot.sheets[0]!.cells).toHaveLength(2);
67
+ expect(reopened.snapshot.formulaResults?.[0]?.spill?.values).toEqual(snapshot.formulaResults?.[0]?.spill?.values);
68
+ const removed = openXlsx("仅保留图片", reopened.write({ ...reopened.snapshot, revision: 1, formulaResults: undefined,
69
+ sheets: [{ ...reopened.snapshot.sheets[0]!, cells: reopened.snapshot.sheets[0]!.cells.filter(({ input }) => input.kind === "image") }] }));
70
+ expect(removed.restrictions).toEqual([]);
71
+ expect(removed.snapshot.sheets[0]!.cells[0]?.input.kind).toBe("image");
72
+ });
73
+
74
+ it("round-trips the native spill operator in formulas and absolute defined names", () => {
75
+ const source = openXlsx("源区域", fixture("dynamic-array-xlsxwriter.xlsx")).snapshot;
76
+ const sheet = source.sheets[0]!;
77
+ const formula = "=SUM(A1#)+N(\"A1#\")";
78
+ const bytes = createXlsx({ ...source, sheets: [{ ...sheet, cells: [
79
+ sheet.cells[0]!, { row: 0, column: 4, input: { kind: "formula", formula } }
80
+ ] }], definedNames: [{ id: "dynamic-name", name: "结果范围",
81
+ target: { kind: "range", range: parseWorkbookRange(sheet.id, "A1"), spill: true } }]
82
+ });
83
+ const parts = unzipSync(bytes);
84
+ const sheetPath = "xl/worksheets/sheet1.xml";
85
+ const worksheet = strFromU8(parts[sheetPath]!);
86
+ expect(worksheet).toContain('SUM(_xlfn.ANCHORARRAY(A1))+N("A1#")');
87
+ expect(strFromU8(parts["xl/workbook.xml"]!)).toContain("_xlfn.ANCHORARRAY('Results'!$A$1)");
88
+ const reopened = openXlsx("重开结果范围", bytes);
89
+ expect(reopened.restrictions).toEqual([]);
90
+ expect(reopened.snapshot.sheets[0]?.cells[1]?.input).toEqual({ kind: "formula", formula });
91
+ expect(reopened.snapshot.definedNames?.[0]?.target).toEqual({
92
+ kind: "range", range: parseWorkbookRange(reopened.snapshot.sheets[0]!.id, "A1"), spill: true
93
+ });
94
+ expect(reopened.write(reopened.snapshot)).toEqual(bytes);
95
+
96
+ parts[sheetPath] = strToU8(worksheet.replace("_xlfn.ANCHORARRAY(A1)", "_xlfn.ANCHORARRAY(OFFSET(A1,0,0))"));
97
+ const unsupported = zipSync(parts);
98
+ const preserved = openXlsx("其他引用", unsupported);
99
+ expect(preserved.restrictions).toContain("工作簿含暂未支持的溢出范围引用");
100
+ expect(preserved.original()).toEqual(unsupported);
101
+ });
@@ -0,0 +1,26 @@
1
+ import { strFromU8, unzipSync } from "fflate";
2
+ import { expect, it } from "vitest";
3
+ import { createXlsx, openXlsx } from "../../index";
4
+ import { prefixXlsxFormulaFunctions } from "./prefix";
5
+
6
+ it("prefixes only unqualified future calls, including nested calls after an array constant", () => {
7
+ const formula = String.raw`SUM(XLOOKUP(2,{1,2},{10,20}), _xlfn.XOR(TRUE,FALSE), 'XLOOKUP(''s'!A1, "TEXTJOIN(""x"")", T[XLOOKUP(], Data!XLOOKUP(1), FILTER(A1:A2,B1:B2))`;
8
+ expect(prefixXlsxFormulaFunctions(formula)).toBe(formula
9
+ .replace("SUM(XLOOKUP", "SUM(_xlfn.XLOOKUP")
10
+ .replace(" FILTER(", " _xlfn._xlws.FILTER("));
11
+ expect(prefixXlsxFormulaFunctions("xlookup (1,A1:A2,B1:B2)")).toBe("_xlfn.xlookup (1,A1:A2,B1:B2)");
12
+ expect(prefixXlsxFormulaFunctions("SUM(1,XLOOKUP)")).toBe("SUM(1,XLOOKUP)");
13
+ });
14
+
15
+ it("serializes a scalar future function and its calculation cache as a normal native cell", () => {
16
+ const bytes = createXlsx({
17
+ version: 1, id: "lookup", name: "Lookup", revision: 0,
18
+ sheets: [{ id: "orders", name: "订单", cells: [
19
+ { row: 0, column: 0, input: { kind: "formula", formula: '=XLOOKUP(2,{1,2},{10,20})' } }
20
+ ] }]
21
+ }, { result: () => ({ status: "value", value: 20 }) });
22
+ expect(strFromU8(unzipSync(bytes)["xl/worksheets/sheet1.xml"]!)).toContain("<f>_xlfn.XLOOKUP(2,{1,2},{10,20})</f><v>20</v>");
23
+ const file = openXlsx("Lookup", bytes);
24
+ expect(file.snapshot.sheets[0]?.cells[0]?.input).toEqual({ kind: "formula", formula: '=_xlfn.XLOOKUP(2,{1,2},{10,20})' });
25
+ expect(file.write(file.snapshot)).toEqual(bytes);
26
+ });
@@ -0,0 +1,59 @@
1
+ import { formatWorkbookRange, isWorkbookDefinedName, parseWorkbookRange,
2
+ type WorkbookDefinedName, type WorkbookHyperlinkTarget, type workbookDefinedNameLookup } from "@quirekit/workbook";
3
+
4
+ /** @param name - Worksheet display name. @returns A sheet qualifier accepted by native link editors. */
5
+ function hyperlinkSheetName(name: string): string {
6
+ // WPS resolves a quoted simple name to the current worksheet. Quotes escape names containing separators or spaces.
7
+ return /^[\p{L}\p{M}\p{N}_.]+$/u.test(name) ? name : "'" + name.replaceAll("'", "''") + "'";
8
+ }
9
+
10
+ /** @param location - Native A1 or defined-name reference, optionally qualified.
11
+ * @param sheetId - Source worksheet. @param sheets - Stable sheet IDs by lower-case display name.
12
+ * @param resolveName - Workbook and worksheet name catalog. @returns The decoded internal destination. */
13
+ export function readXlsxHyperlinkLocation(location: string, sheetId: string, sheets: ReadonlyMap<string, string>,
14
+ resolveName: ReturnType<typeof workbookDefinedNameLookup>): WorkbookHyperlinkTarget | undefined {
15
+ const normalized = location.replace(/^#/u, "");
16
+ const separator = normalized.lastIndexOf("!");
17
+ let owner = sheetId;
18
+ let qualifier: string | undefined;
19
+ if (separator >= 0) {
20
+ const raw = normalized.slice(0, separator);
21
+ if (raw.startsWith("'") && !/^'(?:[^']|'')+'$/u.test(raw)) return;
22
+ qualifier = raw.startsWith("'") ? raw.slice(1, -1).replaceAll("''", "'") : raw;
23
+ owner = sheets.get(qualifier.toLowerCase()) ?? "";
24
+ if (!owner) return;
25
+ }
26
+ const reference = normalized.slice(separator + 1);
27
+ if (isWorkbookDefinedName(reference)) {
28
+ // Explicit sheet qualifiers name local definitions. Bare native links name workbook definitions where available.
29
+ const name = resolveName(reference, "", qualifier) ?? (qualifier === undefined ? resolveName(reference, owner) : undefined);
30
+ return name && { kind: "definedName", nameId: name.id };
31
+ }
32
+ return { kind: "worksheet", range: parseWorkbookRange(owner, reference) };
33
+ }
34
+
35
+ /** @param definitions - Workbook's exact name definitions. @param sheets - Sheet display names by ID.
36
+ * @returns Native internal link locations keyed by the stable name ID. */
37
+ export function xlsxNamedHyperlinkLocations(definitions: readonly WorkbookDefinedName[] = [],
38
+ sheets: ReadonlyMap<string, string>): ReadonlyMap<string, string> {
39
+ return new Map(definitions.flatMap(entry => {
40
+ const { id, name, scopeSheetId } = entry;
41
+ if (scopeSheetId === undefined) return [[id, name]];
42
+ const sheet = sheets.get(scopeSheetId);
43
+ return sheet ? [[id, hyperlinkSheetName(sheet) + "!" + name]] : [];
44
+ }));
45
+ }
46
+
47
+ /** @param target - Internal destination. @param sheets - Worksheet display names.
48
+ * @param locations - Current native spellings of named destinations. @returns Workbook-local SpreadsheetML location. */
49
+ export function writeXlsxHyperlinkLocation(target: Exclude<WorkbookHyperlinkTarget, { kind: "external" }>,
50
+ sheets: ReadonlyMap<string, string>, locations: ReadonlyMap<string, string>): string {
51
+ if (target.kind === "definedName") {
52
+ const name = locations.get(target.nameId);
53
+ if (!name) throw new Error("超链接指向的定义名称已不存在。");
54
+ return name;
55
+ }
56
+ const name = sheets.get(target.range.sheetId);
57
+ if (!name) throw new Error("超链接指向的工作表已不存在。");
58
+ return hyperlinkSheetName(name) + "!" + formatWorkbookRange(target.range);
59
+ }