@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,34 @@
1
+ import type { WorkbookSnapshot, WorkbookStoredCell } from "@quirekit/workbook";
2
+
3
+ /** @param cells - Parsed data owned exclusively by the native reader.
4
+ * @returns The same coordinates and deeply frozen cell inputs. */
5
+ function sealCells(cells: readonly WorkbookStoredCell[]): readonly WorkbookStoredCell[] {
6
+ for (const cell of cells) {
7
+ const { input } = cell;
8
+ if (input.kind === "value" && input.textRuns) {
9
+ for (const run of input.textRuns) {
10
+ Object.freeze(run.style);
11
+ Object.freeze(run);
12
+ }
13
+ Object.freeze(input.textRuns);
14
+ }
15
+ if (input.kind === "formula" && input.externalResult) Object.freeze(input.externalResult);
16
+ Object.freeze(input);
17
+ Object.freeze(cell);
18
+ }
19
+ return Object.freeze(cells);
20
+ }
21
+
22
+ /** @param snapshot - Source-owned import at its original revision.
23
+ * @param shared - Whether this consumer can reuse immutable source cells.
24
+ * @returns An independent projection with detached metadata and the requested cell ownership. */
25
+ export function projectXlsxSnapshot(snapshot: WorkbookSnapshot, shared = false): WorkbookSnapshot {
26
+ if (!shared) return structuredClone(snapshot);
27
+ const metadata = structuredClone({
28
+ ...snapshot, sheets: snapshot.sheets.map(({ cells, ...worksheet }) => worksheet)
29
+ });
30
+ return {
31
+ ...metadata,
32
+ sheets: metadata.sheets.map((worksheet, index) => ({ ...worksheet, cells: sealCells(snapshot.sheets[index]!.cells) }))
33
+ };
34
+ }
@@ -0,0 +1,130 @@
1
+ import { defaultWorkbookCalculationSettings, emptyWorkbookDimensions, projectWorkbookStructuredTables, sameWorkbookAutoFilter,
2
+ sameWorkbookCalculationSettings, sameWorkbookCell, sameWorkbookCheckboxes, sameWorkbookConditionalFormats, sameWorkbookDimensions,
3
+ sameWorkbookFormulaResults, sameWorkbookHyperlinks, sameWorkbookMerges, sameWorkbookPrintLayout, sameWorkbookStructuredTableLayout,
4
+ sameWorkbookValidations, sameWorkbookWorksheetSorts, sameWorkbookWorksheetView, workbookPositionEdits, workbookRowVisibilityChanged,
5
+ type WorkbookSnapshot } from "@quirekit/workbook";
6
+ import { sameXlsxComments } from "../../comments/package/write";
7
+ import { sameXlsxCharts } from "../../drawing/write/workbook";
8
+ import { sameXlsxPictures } from "../../drawing/write/pictures";
9
+ import { sameXlsxShapes } from "../../drawing/write/shapes";
10
+ import { xlsxExternalLinksChanged } from "../../external-links/formulas";
11
+ import { openArchive } from "../../opc/archive";
12
+ import { sameXlsxPivots } from "../../pivot/package/write";
13
+ import { supportsXlsxStructuredFormulas } from "../../table/ownership";
14
+ import { sameXlsxStructuredTables } from "../../table/write";
15
+ import type { XlsxWorkbookFile } from "../../types";
16
+ import { sameXlsxDashboards } from "../dashboard";
17
+ import { sameXlsxMergeRecipes } from "../merge-recipes";
18
+ import { assertXlsxPositionWrites } from "../positions";
19
+ import type { XlsxPackage } from "../types";
20
+ import { assertWorksheetDirectory, sameWorksheetDirectory, sameWorksheetStructure } from "../worksheets";
21
+ import { writeXlsxPackage } from "../write";
22
+ import type { XlsxSourceWriteState } from "./types";
23
+
24
+ /** @param source - Native metadata and the authored baseline associated with the original bytes.
25
+ * @param state - Original file and edit restrictions from the same import.
26
+ * @returns Save operation that preserves the archive when no authored changes require write-back. */
27
+ export function createXlsxSourceWriter(source: Omit<XlsxPackage, "parts"> & { readonly baseline: WorkbookSnapshot },
28
+ state: XlsxSourceWriteState): XlsxWorkbookFile["write"] {
29
+ const { baseline, appearance, sheetPaths, printLayoutRestrictions } = source;
30
+ const { original, sheets, restrictions, worksheetRestriction, axisRestrictions, sortRestrictions, cellShiftRestrictions, freezeRestrictions } = state;
31
+ /** @param snapshot - Authored workbook at one revision. @param options - Host result readers for that revision.
32
+ * @returns Detached original bytes when possible, or a new archive reflecting the authorized changes. */
33
+ return function write(snapshot, options = {}) {
34
+ const externalLinksChanged = xlsxExternalLinksChanged(baseline.externalLinks, snapshot.externalLinks);
35
+ const mediaUnchanged = sameImageAssets(baseline, snapshot);
36
+ const inputsUnchanged = sameWorkbookInputs(baseline, snapshot)
37
+ && (mediaUnchanged || sameCellImageAssets(baseline, snapshot));
38
+ const calculationChanged = !sameWorkbookCalculationSettings(baseline.calculationSettings ?? defaultWorkbookCalculationSettings,
39
+ snapshot.calculationSettings ?? defaultWorkbookCalculationSettings)
40
+ || !sameWorkbookFormulaResults(baseline.formulaResults, snapshot.formulaResults)
41
+ || (baseline.formulaPendingRevision !== undefined) !== (snapshot.formulaPendingRevision !== undefined);
42
+ const namesChanged = JSON.stringify(baseline.definedNames ?? []) !== JSON.stringify(snapshot.definedNames ?? []);
43
+ const pivotsChanged = !sameXlsxPivots(baseline, snapshot);
44
+ const nativeTablesChanged = !sameXlsxStructuredTables(baseline, snapshot);
45
+ const nativeTableLayoutsChanged = nativeTablesChanged && !sameXlsxStructuredTables(baseline, snapshot, sameWorkbookStructuredTableLayout);
46
+ const commentsChanged = !sameXlsxComments(baseline, snapshot);
47
+ const mergeRecipesChanged = !sameXlsxMergeRecipes(baseline.tableMergeRecipes, snapshot.tableMergeRecipes);
48
+ const dashboardsChanged = !sameXlsxDashboards(baseline.sheets, snapshot.sheets);
49
+ const directoryChanged = !sameWorksheetDirectory(sheets, snapshot.sheets);
50
+ const directoryStructureChanged = !sameWorksheetStructure(sheets, snapshot.sheets);
51
+ const structureChanged = directoryStructureChanged || workbookPositionEdits(snapshot).length > 0;
52
+ const hyperlinksChanged = !directoryStructureChanged && snapshot.sheets.some((sheet, index) =>
53
+ !sameWorkbookHyperlinks(sheets[index]?.hyperlinks, sheet.hyperlinks));
54
+ const filterChanged = !directoryStructureChanged && snapshot.sheets.some((sheet, index) => !sameWorkbookAutoFilter(sheet.autoFilter, sheets[index]?.autoFilter));
55
+ const sortsChanged = !directoryStructureChanged && snapshot.sheets.some((sheet, index) => !sameWorkbookWorksheetSorts(sheet.sorts, sheets[index]?.sorts));
56
+ const viewChanged = !directoryStructureChanged && snapshot.sheets.some((sheet, index) => !sameWorkbookWorksheetView(sheet.view, sheets[index]?.view));
57
+ const dimensionsChanged = !directoryStructureChanged && snapshot.sheets.some((sheet, index) => !sameWorkbookDimensions(sheet.dimensions, sheets[index]?.dimensions));
58
+ const manualVisibilityChanged = dimensionsChanged && snapshot.sheets.some((sheet, index) =>
59
+ workbookRowVisibilityChanged(sheets[index]?.dimensions ?? emptyWorkbookDimensions, sheet.dimensions ?? emptyWorkbookDimensions));
60
+ const mergesChanged = !directoryStructureChanged && snapshot.sheets.some((sheet, index) => !sameWorkbookMerges(sheets[index]?.merges, sheet.merges));
61
+ const validationsChanged = !directoryStructureChanged && snapshot.sheets.some((sheet, index) => !sameWorkbookValidations(sheet.validations, sheets[index]?.validations));
62
+ const checkboxesChanged = !directoryStructureChanged && snapshot.sheets.some((sheet, index) => !sameWorkbookCheckboxes(sheet.checkboxes, sheets[index]?.checkboxes));
63
+ const conditionalChanged = !directoryStructureChanged && snapshot.sheets.some((sheet, index) => !sameWorkbookConditionalFormats(sheet.conditionalFormats, sheets[index]?.conditionalFormats));
64
+ if (inputsUnchanged && mediaUnchanged && !externalLinksChanged && !calculationChanged && !namesChanged
65
+ && !pivotsChanged && !nativeTablesChanged && !commentsChanged && !mergeRecipesChanged && !dashboardsChanged
66
+ && !hyperlinksChanged && !validationsChanged && !checkboxesChanged && !conditionalChanged
67
+ && !structureChanged && !directoryChanged && !filterChanged && !sortsChanged && !viewChanged && !dimensionsChanged
68
+ && !mergesChanged && sameXlsxCharts(baseline, snapshot) && sameXlsxPictures(baseline, snapshot) && sameXlsxShapes(baseline, snapshot)
69
+ && !snapshot.sheets.some(sheet => sheet.formats?.length)) return original.slice();
70
+ if (restrictions.size > 0) throw new Error(`原文件仅可原样下载:${[...restrictions].join("、")}。`);
71
+ if (snapshot.dateSystem !== baseline.dateSystem) throw new Error("原文件的日期系统无法修改。");
72
+ if (printLayoutRestrictions?.size) for (const sheet of snapshot.sheets) {
73
+ const originalId = sheet.origin?.sheetId ?? sheet.id;
74
+ const reason = printLayoutRestrictions.get(originalId);
75
+ if (reason && !sameWorkbookPrintLayout(sheets.find(item => item.id === originalId)?.view?.printLayout, sheet.view?.printLayout)) {
76
+ throw new Error(reason);
77
+ }
78
+ }
79
+ if (directoryChanged) {
80
+ if (worksheetRestriction) throw new Error(worksheetRestriction);
81
+ assertWorksheetDirectory(snapshot.sheets, sheetPaths);
82
+ }
83
+ assertXlsxPositionWrites(snapshot, axisRestrictions, cellShiftRestrictions, sortRestrictions, freezeRestrictions, baseline.structuredTables);
84
+ const currentTableLayout = projectWorkbookStructuredTables(appearance, snapshot.structuredTables ?? baseline.structuredTables ?? [], "replace");
85
+ if (currentTableLayout && !supportsXlsxStructuredFormulas(snapshot, currentTableLayout)) throw new Error("原生表公式使用暂未支持的结构化引用组合。");
86
+ // Release the inflated parts after import. A changed, authorized save starts from the exact original archive.
87
+ const parts = openArchive(original);
88
+ return writeXlsxPackage({ ...source, parts }, snapshot, options,
89
+ !inputsUnchanged || externalLinksChanged || calculationChanged || namesChanged || pivotsChanged || nativeTableLayoutsChanged || structureChanged || filterChanged || manualVisibilityChanged);
90
+ };
91
+ }
92
+
93
+ /**
94
+ * @param left - Original input projection.
95
+ * @param right - Current committed workbook.
96
+ * @returns Whether the file can be returned byte-for-byte.
97
+ */
98
+ function sameWorkbookInputs(left: WorkbookSnapshot, right: WorkbookSnapshot): boolean {
99
+ if (left.dateSystem !== right.dateSystem || left.sheets.length !== right.sheets.length) return false;
100
+ return left.sheets.every((sheet, index) => {
101
+ const updated = right.sheets[index];
102
+ if (!updated || sheet.name !== updated.name || sheet.id !== updated.id || sheet.cells.length !== updated.cells.length) return false;
103
+ const contents = new Map(updated.cells.map(({ row, column, input }) => [`${row}:${column}`, input]));
104
+ return sheet.cells.every(({ row, column, input }) => sameWorkbookCell(input, contents.get(`${row}:${column}`) ?? null));
105
+ });
106
+ }
107
+
108
+ /** @param left - Source workbook. @param right - Saved snapshot. @returns Whether all encoded image resources match the source. */
109
+ function sameImageAssets(left: WorkbookSnapshot, right: WorkbookSnapshot): boolean {
110
+ const before = left.imageAssets ?? [], after = right.imageAssets ?? [];
111
+ if (before.length !== after.length) return false;
112
+ const resources = new Map(after.map(asset => [asset.id, asset]));
113
+ return before.every(asset => {
114
+ const counterpart = resources.get(asset.id);
115
+ return counterpart?.mimeType === asset.mimeType && counterpart.data === asset.data;
116
+ });
117
+ }
118
+
119
+ /** @param left - Source checkpoint. @param right - Snapshot with equal cell placements.
120
+ * @returns Whether all rasters referenced by cells are unchanged. */
121
+ function sameCellImageAssets(left: WorkbookSnapshot, right: WorkbookSnapshot): boolean {
122
+ const before = new Map(left.imageAssets?.map(asset => [asset.id, asset]));
123
+ const after = new Map(right.imageAssets?.map(asset => [asset.id, asset]));
124
+ for (const sheet of left.sheets) for (const { input } of sheet.cells) {
125
+ if (input.kind !== "image") continue;
126
+ const original = before.get(input.assetId), current = after.get(input.assetId);
127
+ if (!original || current?.mimeType !== original.mimeType || current.data !== original.data) return false;
128
+ }
129
+ return true;
130
+ }
@@ -0,0 +1,73 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import type { workbookDefinedNameLookup, WorkbookSheet, WorkbookStoredFormulaResult, WorkbookWorksheetIdentity } from "@quirekit/workbook";
3
+ import type { readXlsxCommentPackage } from "../../comments/package/read";
4
+ import type { readXlsxExternalLinks } from "../../external-links/read";
5
+ import type { createXlsxCellImageImport } from "../../image/read";
6
+ import type { readXlsxArrayMetadataPart } from "../../metadata/package";
7
+ import type { readXlsxWpsListOptions } from "../../worksheet/validation/list-options/wps";
8
+ import type { createXlsxConditionalNameResolver } from "../names/conditional";
9
+ import type { readXlsxAppearance } from "./appearance";
10
+
11
+ /** One entry in the original workbook directory. */
12
+ export interface XlsxWorksheetEntry extends WorkbookWorksheetIdentity {
13
+ /** Native worksheet part path. */
14
+ readonly path: string;
15
+ }
16
+
17
+ /** Native defined names used to construct worksheet print settings. */
18
+ export interface XlsxWorksheetPrintNames {
19
+ /** Scoped formulas grouped by their native worksheet index. */
20
+ readonly printBySheet: ReadonlyMap<number, readonly Element[]>;
21
+ /** Whether any native print name has no worksheet owner. */
22
+ readonly unknownPrintOwner: boolean;
23
+ }
24
+
25
+ /** Shared native inputs and readers resolved before reading worksheets. */
26
+ export interface XlsxWorksheetReadResources {
27
+ /** Raw contents of the source ZIP. */
28
+ readonly parts: Readonly<Record<string, Uint8Array>>;
29
+ /** Workbook directory in source order. */
30
+ readonly entries: readonly XlsxWorksheetEntry[];
31
+ /** Theme, strings, styles, and native table style resolver. */
32
+ readonly presentation: ReturnType<typeof readXlsxAppearance>;
33
+ /** Scoped print definitions. */
34
+ readonly print: XlsxWorksheetPrintNames;
35
+ /** Calendar basis for reading date serials. */
36
+ readonly dateSystem: "1900" | "1904";
37
+ /** WPS-specific list presentation tied to validated worksheet rules. */
38
+ readonly wpsLists: ReturnType<typeof readXlsxWpsListOptions>;
39
+ /** Scoped names resolved for conditional-format formulas. */
40
+ readonly conditionalNames: ReturnType<typeof createXlsxConditionalNameResolver>;
41
+ /** Existing named targets of native hyperlinks. */
42
+ readonly resolveHyperlinkName: ReturnType<typeof workbookDefinedNameLookup>;
43
+ /** Native comment parts and their worksheet relationships. */
44
+ readonly comments: ReturnType<typeof readXlsxCommentPackage>;
45
+ /** Cells that refer to native image values. */
46
+ readonly images: ReturnType<typeof createXlsxCellImageImport>;
47
+ /** Optional collection of retained formula caches at their source locations. */
48
+ readonly retainResult: ((entry: WorkbookStoredFormulaResult) => void) | undefined;
49
+ /** Native array metadata graph. */
50
+ readonly arrays: ReturnType<typeof readXlsxArrayMetadataPart>;
51
+ /** Supported native external links and cached values. */
52
+ readonly external: ReturnType<typeof readXlsxExternalLinks>;
53
+ }
54
+
55
+ /** Import-time facts required to decide whether and how a source workbook may be saved. */
56
+ export interface XlsxSourceWriteState {
57
+ /** Private copy of the original file. */
58
+ readonly original: Uint8Array;
59
+ /** Source worksheets before applying workbook-level presentations. */
60
+ readonly sheets: readonly WorkbookSheet[];
61
+ /** Reasons an exact original is the only available download. */
62
+ readonly restrictions: ReadonlySet<string>;
63
+ /** Reason native sheet directory operations are unavailable. */
64
+ readonly worksheetRestriction: string | undefined;
65
+ /** Unsupported row and column changes by worksheet. */
66
+ readonly axisRestrictions: ReadonlyMap<string, string>;
67
+ /** Unsupported in-sheet cell shifts by worksheet. */
68
+ readonly cellShiftRestrictions: ReadonlyMap<string, string>;
69
+ /** Unsupported in-sheet sorts by worksheet. */
70
+ readonly sortRestrictions: ReadonlyMap<string, string>;
71
+ /** Unsupported pane edits by worksheet. */
72
+ readonly freezeRestrictions: ReadonlyMap<string, string>;
73
+ }
@@ -0,0 +1,149 @@
1
+ import { defaultWorkbookWorksheetView, type WorkbookSheet, type WorkbookSheetAppearance, type WorkbookSheetCellImages,
2
+ type WorkbookWorksheetPrintLayout } from "@quirekit/workbook";
3
+ import { createXlsxDrawingImport } from "../../drawing/import";
4
+ import { drawingPartRelationships } from "../../drawing/read";
5
+ import { worksheetShapeTheme } from "../../drawing/shapes/paint";
6
+ import { verifyXlsxPartOwnership } from "../../opc/ownership";
7
+ import type { PackageRelationship } from "../../opc/types";
8
+ import { child } from "../../opc/xml";
9
+ import { pivotRoles } from "../../pivot/xml";
10
+ import { readXlsxTables } from "../../table/read";
11
+ import type { XlsxSourceTable } from "../../table/types";
12
+ import { worksheetPositionRestrictions } from "../../worksheet/axis";
13
+ import { createXlsxWorksheetBackgroundImport } from "../../worksheet/background/read";
14
+ import { readXlsxCheckboxRanges } from "../../worksheet/checkbox/ranges";
15
+ import { readXlsxConditionalFormats } from "../../worksheet/conditional/read";
16
+ import { openXlsxWorksheetSource } from "../../worksheet/data/source";
17
+ import { hasUnknownWorksheetExtensions } from "../../worksheet/filters/visibility";
18
+ import { readXlsxHyperlinks } from "../../worksheet/hyperlinks/read";
19
+ import { readXlsxPageSetup } from "../../worksheet/print/setup";
20
+ import { readXlsxProgressFormats } from "../../worksheet/progress/read";
21
+ import { readWorksheet } from "../../worksheet/read";
22
+ import { xlsxSortRestriction } from "../../worksheet/sort/relocate";
23
+ import { readXlsxValidations } from "../../worksheet/validation/read";
24
+ import { readXlsxNamedViews } from "../../worksheet/view/named/read";
25
+ import { xlsxNamedViewContentType } from "../../worksheet/view/named/xml";
26
+ import { readXlsxWorksheetView, xlsxFreezeRestriction } from "../../worksheet/view/read";
27
+ import { readXlsxPrintRanges } from "../names/print-layout";
28
+ import type { XlsxWorksheetReadResources } from "./types";
29
+
30
+ /** @param resources - Worksheet directory and shared readers created from native package parts.
31
+ * @param restrictions - Read-only diagnostics accumulated during the import.
32
+ * @param worksheetRestrictions - Reasons why directory edits cannot safely follow the source graph.
33
+ * @returns Worksheet inputs and per-sheet presentation, relationships, and write constraints. */
34
+ export function readXlsxWorksheetParts(resources: XlsxWorksheetReadResources, restrictions: Set<string>, worksheetRestrictions: Set<string>) {
35
+ const { parts, entries, presentation, print: { printBySheet, unknownPrintOwner }, dateSystem, wpsLists,
36
+ conditionalNames, resolveHyperlinkName, comments, images, retainResult, arrays, external } = resources;
37
+ const { themeRoot, theme, runColor, strings, styles, checkboxStyles, differentials, differentialPreviews, tableStyles } = presentation;
38
+ const cellImages = new Map<string, WorkbookSheetCellImages>();
39
+ const sheetAppearance = new Map<string, WorkbookSheetAppearance>();
40
+ const hyperlinkRelations = new Map<string, ReadonlySet<string>>();
41
+ const axisRestrictions = new Map<string, string>();
42
+ const cellShiftRestrictions = new Map<string, string>();
43
+ const sortRestrictions = new Map<string, string>();
44
+ const freezeRestrictions = new Map<string, string>();
45
+ const printLayoutRestrictions = new Map<string, string>();
46
+ const sheets: WorkbookSheet[] = [];
47
+ const sourceTables: XlsxSourceTable[] = [];
48
+ const namedViewPaths = new Map<string, string>();
49
+ const namedViewOwners = new Map<string, ReadonlySet<string>>();
50
+
51
+ const sheetNames = new Map(entries.map(({ name, id }) => [name.toLowerCase(), id]));
52
+ const drawings = createXlsxDrawingImport(parts, theme, sheetNames, worksheetShapeTheme(themeRoot, theme));
53
+ const backgrounds = createXlsxWorksheetBackgroundImport(parts);
54
+ for (const [index, owner] of entries.entries()) {
55
+ const { id, name, path, visibility } = owner;
56
+ const worksheetSource = openXlsxWorksheetSource(parts[path], path, Boolean(arrays?.indexes));
57
+ const worksheet = worksheetSource.root;
58
+ const tablePresentation = readXlsxTables(worksheet, path, id, parts, tableStyles, { dateSystem, differentials, resolveColor: runColor });
59
+ if (child(worksheet, "tableParts") && !tablePresentation?.supported) restrictions.add("结构化表");
60
+ if (child(worksheet, "customSheetViews")) worksheetRestrictions.add("自定义工作表视图");
61
+ const progress = child(worksheet, "dataValidations") ? readXlsxProgressFormats(worksheet, id, differentials, runColor) : undefined;
62
+ const { writable: managedValidations, rules: validations, progressConditions } = readXlsxValidations(worksheet, id, entries, progress, wpsLists);
63
+ if (!managedValidations) restrictions.add("数据有效性包含暂未支持的规则");
64
+ const { formats: conditionalFormats, previews: conditionalPreviews } = readXlsxConditionalFormats(worksheet, id, {
65
+ styles: differentials, previewStyles: differentialPreviews, color: runColor,
66
+ resolveNames: (source, anchor) => conditionalNames(source, owner, anchor)
67
+ }, progressConditions);
68
+ const { cells, cellImages: sheetImages, appearance, dimensions, autoFilter, sorts, merges, managedMerges, restoredTables } =
69
+ readWorksheet(worksheetSource, id, strings, runColor, dateSystem, restrictions, styles, images?.resolve, tablePresentation?.tables, differentials,
70
+ retainResult, arrays?.indexes, conditionalFormats, external?.supports,
71
+ (formula, anchor) => conditionalNames(formula, owner, anchor) === formula);
72
+ if (tablePresentation) sourceTables.push(...tablePresentation.records.map(record => {
73
+ const layout = restoredTables.get(record.layout);
74
+ return layout ? { ...record, layout } : record;
75
+ }));
76
+ if (sheetImages.size) {
77
+ cellImages.set(id, sheetImages);
78
+ restrictions.add("单元格图片");
79
+ }
80
+ const links = readXlsxHyperlinks(worksheet, { id, cells, validations }, path, parts, sheetNames, resolveHyperlinkName);
81
+ if (links) hyperlinkRelations.set(id, links.ids);
82
+ const commentRelations = comments.graph?.worksheetRelations.get(path);
83
+ const managed = new Set([...(links?.ids ?? []), ...(commentRelations ?? []), ...(tablePresentation?.ids ?? [])]);
84
+ let sheetRelationships: ReadonlyMap<string, PackageRelationship> | undefined;
85
+ try { sheetRelationships = drawingPartRelationships(parts, path); }
86
+ catch { restrictions.add("工作表附加关系"); }
87
+ // The pivot codec verifies these relationships after the source styles are available.
88
+ for (const relation of sheetRelationships?.values() ?? []) {
89
+ if (relation.type === pivotRoles.definition) managed.add(relation.id);
90
+ }
91
+ let namedViews;
92
+ try {
93
+ const saved = readXlsxNamedViews(parts, sheetRelationships, worksheet, autoFilter, tablePresentation?.records ?? [],
94
+ { dateSystem, differentials, resolveColor: runColor });
95
+ if (saved) {
96
+ if (namedViewOwners.has(saved.path)) throw new Error("命名视图部件存在多个所有者。");
97
+ namedViewPaths.set(id, saved.path);
98
+ namedViewOwners.set(saved.path, new Set([path]));
99
+ managed.add(saved.relationshipId);
100
+ namedViews = saved.views;
101
+ }
102
+ } catch { restrictions.add("命名工作表视图包含暂未支持的规则"); }
103
+ const backgroundAssetId = backgrounds.add(worksheet, sheetRelationships, managed);
104
+ if (child(worksheet, "picture") && !backgroundAssetId) restrictions.add("未支持的工作表背景");
105
+ const managedDrawing = drawings.add(path, worksheet, id, appearance, managed);
106
+ if (child(worksheet, "drawing") && !managedDrawing) restrictions.add("绘图或图表");
107
+ if (!managedDrawing && sheetRelationships && [...sheetRelationships.keys()].some(id => !managed.has(id))) restrictions.add("工作表附加关系");
108
+ if (child(worksheet, "legacyDrawing") && !comments.graph?.legacyDrawings.has(path)) restrictions.add("未支持的旧式绘图");
109
+ if (child(worksheet, "hyperlinks") && !links) restrictions.add("未支持的原生超链接");
110
+ const checkboxes = readXlsxCheckboxRanges(worksheet, id, appearance, checkboxStyles?.indexes, restrictions);
111
+ if (!conditionalFormats) restrictions.add("条件格式包含暂未支持的规则或样式");
112
+ if (hasUnknownWorksheetExtensions(worksheet, managedValidations, conditionalFormats !== undefined)) restrictions.add("工作表扩展");
113
+ const cellPositions = xlsxSortRestriction(worksheet, Boolean(links), Boolean(sorts.worksheet));
114
+ if (cellPositions) sortRestrictions.set(id, `工作表「${name}」含${cellPositions},当前无法安全排序。`);
115
+ const unsupportedPane = xlsxFreezeRestriction(worksheet);
116
+ if (unsupportedPane) freezeRestrictions.set(id, unsupportedPane);
117
+ const localPrint = printBySheet.get(index) ?? [];
118
+ let printLayout: WorkbookWorksheetPrintLayout | undefined;
119
+ try {
120
+ if (unknownPrintOwner) throw new Error("无法定位原文件的打印区域或标题。");
121
+ printLayout = readXlsxPageSetup(worksheet, readXlsxPrintRanges(localPrint, name));
122
+ } catch (cause) {
123
+ printLayoutRestrictions.set(id, cause instanceof Error ? cause.message : "无法读取原生打印版式。");
124
+ }
125
+ const nativePositions = worksheetPositionRestrictions(worksheet, managedDrawing, managedMerges, managedValidations, conditionalFormats !== undefined,
126
+ Boolean(links), Boolean(sorts.worksheet), Boolean(tablePresentation?.supported && tablePresentation.records.every(table => table.dataWritable)),
127
+ !printLayoutRestrictions.has(id));
128
+ const printPositions = unknownPrintOwner || Boolean(localPrint.length && !printLayout);
129
+ const structuralReasons = [...nativePositions.axes, ...(printPositions ? ["打印区域或打印标题"] : [])];
130
+ const shiftReasons = [...nativePositions.cells, ...(printPositions ? ["打印区域或打印标题"] : [])];
131
+ if (structuralReasons.length) axisRestrictions.set(id, `工作表「${name}」含${structuralReasons.join("、")},当前无法安全移动这些位置。`);
132
+ if (shiftReasons.length) cellShiftRestrictions.set(id, `工作表「${name}」含${shiftReasons.join("、")},当前无法安全移动单元格。`);
133
+ const savedView = readXlsxWorksheetView(worksheet);
134
+ const view = backgroundAssetId || printLayout || namedViews ? { ...(savedView ?? defaultWorkbookWorksheetView),
135
+ ...(backgroundAssetId && { backgroundAssetId }), ...(printLayout && { printLayout }), ...(namedViews && { namedViews }) } : savedView;
136
+ sheetAppearance.set(id, { ...appearance, ...(conditionalPreviews?.length && { conditionalPreviews }),
137
+ ...(tablePresentation?.tables.length && { tables: tablePresentation.tables.map(table => restoredTables.get(table) ?? table) }) });
138
+ sheets.push({ id, name, cells, ...(visibility && { visibility }), ...(dimensions && { dimensions }), ...(links?.hyperlinks.length && { hyperlinks: links.hyperlinks }), ...(autoFilter && { autoFilter }), ...(view && { view }), ...(merges?.length && { merges }),
139
+ ...((sorts.worksheet || sorts.filter) && { sorts }), ...(validations?.length && { validations }),
140
+ ...(checkboxes.length && { checkboxes }), ...(conditionalFormats?.length && { conditionalFormats }) });
141
+ }
142
+
143
+ if (namedViewOwners.size) {
144
+ try { verifyXlsxPartOwnership(parts, namedViewOwners, new Map([...namedViewOwners.keys()].map(path => [path, xlsxNamedViewContentType]))); }
145
+ catch { restrictions.add("命名工作表视图部件关系"); }
146
+ }
147
+ return { sheets, namedViewPaths, sourceTables, sheetAppearance, cellImages, drawings, backgrounds, hyperlinkRelations,
148
+ axisRestrictions, cellShiftRestrictions, sortRestrictions, freezeRestrictions, printLayoutRestrictions };
149
+ }
@@ -0,0 +1,40 @@
1
+ import { isWorkbookAxisMove, isWorkbookAxisSplice, isWorkbookCellShift, validateWorkbookPositionEdit, workbookCellShiftWriteRange,
2
+ workbookPositionEdits, workbookRangesOverlap, type WorkbookPositionEdit, type WorkbookSnapshot, type WorkbookStructuredTable } from "@quirekit/workbook";
3
+
4
+ /** @param snapshot - Pending save. @param axis - Source restrictions on axis positions.
5
+ * @param shift - Source restrictions for local cell movement. @param sort - Source restrictions for row ordering.
6
+ * @param freeze - Source restrictions on native panes. @param tables - Original native table owners. */
7
+ export function assertXlsxPositionWrites(snapshot: WorkbookSnapshot, axis: ReadonlyMap<string, string>,
8
+ shift: ReadonlyMap<string, string>, sort: ReadonlyMap<string, string>, freeze: ReadonlyMap<string, string>,
9
+ tables: readonly WorkbookStructuredTable[] = []): void {
10
+ const directory = new Map(snapshot.sheets.map(sheet => [sheet.id, sheet]));
11
+ const active = new Set((snapshot.structuredTables ?? tables).map(table => table.id));
12
+ const retained = tables.filter(table => active.has(table.id));
13
+ /** @param edit - Sheet edit or inherited copy edit. */
14
+ function assertPosition(edit: WorkbookPositionEdit): void {
15
+ validateWorkbookPositionEdit(edit);
16
+ const sheet = directory.get(edit.sheetId);
17
+ if (!sheet) throw new Error("结构修改指向已删除的工作表。");
18
+ const rules = isWorkbookAxisSplice(edit) ? axis : isWorkbookCellShift(edit) || isWorkbookAxisMove(edit) ? shift : sort;
19
+ const restriction = rules.get(sheet.origin?.sheetId ?? sheet.id);
20
+ if (restriction) throw new Error(restriction);
21
+ const native = retained.filter(table => table.range.sheetId === edit.sheetId);
22
+ if (native.length && isWorkbookAxisSplice(edit)) throw new Error("原生表仍依赖所在行列,请先将表转换为区域。");
23
+ if (native.length && isWorkbookCellShift(edit)) {
24
+ const scope = workbookCellShiftWriteRange(edit);
25
+ if (native.some(table => table.id !== edit.totalsTableId && workbookRangesOverlap(table.range, scope))) {
26
+ throw new Error("结构修改涉及原文件的结构化表,请选择表外区域或调整所属表的汇总行。");
27
+ }
28
+ }
29
+ }
30
+ for (const sheet of snapshot.sheets) {
31
+ const view = sheet.view;
32
+ const restriction = freeze.get(sheet.origin?.sheetId ?? sheet.id);
33
+ if (restriction && (view?.freeze.rows || view?.freeze.columns || view?.scrollAnchor)) throw new Error(restriction);
34
+ for (const edit of workbookPositionEdits(sheet.origin)) {
35
+ if (edit.sheetId !== sheet.id) throw new Error("复制工作表的结构修改指向另一张工作表。");
36
+ assertPosition(edit);
37
+ }
38
+ }
39
+ for (const edit of workbookPositionEdits(snapshot)) assertPosition(edit);
40
+ }
@@ -0,0 +1,143 @@
1
+ import { copyWorkbookCalculationSettings, workbookDefinedNameLookup, workbookTransactionCellLimit,
2
+ type WorkbookSnapshot, type WorkbookStoredFormulaResult } from "@quirekit/workbook";
3
+ import { v4 as uuidv4 } from "uuid";
4
+ import { readXlsxCommentPackage } from "../comments/package/read";
5
+ import { readXlsxExternalLinks } from "../external-links/read";
6
+ import { createXlsxCellImageImport } from "../image/read";
7
+ import { readXlsxArrayMetadataPart } from "../metadata/package";
8
+ import { openArchive } from "../opc/archive";
9
+ import { readRelationships, relationshipOfType, relationshipsPath } from "../opc/relationships";
10
+ import { child, children, parsePart, rootOf, spreadNs } from "../opc/xml";
11
+ import { readXlsxPivotPackage } from "../pivot/package/read";
12
+ import { canWriteXlsxSourceTables, supportsXlsxStructuredFormulas, xlsxStructuredTableDefinitions } from "../table/ownership";
13
+ import type { XlsxOpenOptions, XlsxWorkbookFile } from "../types";
14
+ import { readXlsxWpsListOptions } from "../worksheet/validation/list-options/wps";
15
+ import { hasRetainedXlsxCalculation, readXlsxCalculationSettings, xlsxCalculationIsPending } from "./calculation-metadata";
16
+ import { readXlsxDashboards } from "./dashboard";
17
+ import { readXlsxMergeRecipes } from "./merge-recipes";
18
+ import { createXlsxConditionalNameResolver } from "./names/conditional";
19
+ import { readWorkbookDefinedNames } from "./names/defined";
20
+ import { isWorksheetFilterName, validateFilterDatabaseNames } from "./names/filter";
21
+ import { isPrintName } from "./names/print";
22
+ import { readXlsxAppearance } from "./open/appearance";
23
+ import { readXlsxWorksheetDirectory, readXlsxWorksheetPrintNames } from "./open/directory";
24
+ import { noteXlsxWorkbookRestrictions } from "./open/restrictions";
25
+ import { projectXlsxSnapshot } from "./open/snapshot";
26
+ import { createXlsxSourceWriter } from "./open/source-write";
27
+ import { readXlsxWorksheetParts } from "./open/worksheets";
28
+
29
+ /**
30
+ * @param name - Workbook display name supplied by the host.
31
+ * @param input - Local XLSX bytes.
32
+ * @param options - Cell input ownership for the import consumer.
33
+ * @returns Editable workbook or a read-only projection and its retained original.
34
+ */
35
+ export function openXlsx(name: string, input: Uint8Array, options: XlsxOpenOptions = {}): XlsxWorkbookFile {
36
+ // Own the archived bytes even when callers pass a Node Buffer, whose slice shares storage.
37
+ const original = new Uint8Array(input);
38
+ const parts = openArchive(original);
39
+ const rootRels = relationshipsPath("");
40
+ const rootRelationships = readRelationships(parsePart(parts[rootRels], rootRels), "");
41
+ const workbookPath = relationshipOfType(rootRelationships, "officeDocument")?.path;
42
+ if (!workbookPath) throw new Error("该文件没有可读取的 XLSX 工作簿。");
43
+ const workbookXml = parsePart(parts[workbookPath], workbookPath);
44
+ const workbook = rootOf(workbookXml, spreadNs, "workbook");
45
+ const relPath = relationshipsPath(workbookPath);
46
+ const relationships = readRelationships(parsePart(parts[relPath], relPath), workbookPath);
47
+ const wpsLists = readXlsxWpsListOptions(parts, relationships);
48
+
49
+ const restrictions = new Set<string>();
50
+ const external = readXlsxExternalLinks(parts, workbook, relationships, restrictions);
51
+ const importedCalculationSettings = readXlsxCalculationSettings(workbook, restrictions);
52
+ const manualCalculation = importedCalculationSettings?.mode === "manual";
53
+ const cachedCalculation = hasRetainedXlsxCalculation(workbook);
54
+ const arrays = readXlsxArrayMetadataPart(parts, relationships, workbookPath);
55
+ const retainedCalculation: WorkbookStoredFormulaResult[] | undefined = manualCalculation || cachedCalculation || arrays ? [] : undefined;
56
+ let retainedCells = 0;
57
+ /** @param entry - One native formula cache. Keeps imported result collection within the workbook's retention budget. */
58
+ function retainResult(entry: WorkbookStoredFormulaResult): void {
59
+ retainedCells += 1 + (entry.spill?.values.length ?? 0);
60
+ if (retainedCalculation && retainedCells <= workbookTransactionCellLimit) retainedCalculation.push(entry);
61
+ }
62
+ const images = createXlsxCellImageImport(parts, relationships, restrictions, workbookPath);
63
+ const imageRoles = new Set(images?.graph?.roles.map(({ id }) => id));
64
+ const worksheetRestrictions = new Set<string>();
65
+ noteXlsxWorkbookRestrictions(parts, workbook, relationships, imageRoles, external?.ids,
66
+ arrays?.owned ? arrays.relation.id : undefined, restrictions, worksheetRestrictions);
67
+ const names = children(child(workbook, "definedNames") ?? workbook, "definedName");
68
+ const printNames = names.filter(isPrintName);
69
+ const filterNames = names.filter(isWorksheetFilterName);
70
+ const date1904 = child(workbook, "workbookPr")?.getAttribute("date1904");
71
+ const dateSystem = date1904 === "1" || date1904 === "true" ? "1904" : "1900";
72
+
73
+ const presentation = readXlsxAppearance(parts, relationships, restrictions);
74
+ const { styles, tableStyles, checkboxStyles } = presentation;
75
+ const { entries, sheetPaths, initialWorksheetId } = readXlsxWorksheetDirectory(workbook, relationships, restrictions);
76
+ const comments = readXlsxCommentPackage(parts, workbookPath, relationships, sheetPaths, restrictions);
77
+ const definedNames = readWorkbookDefinedNames(names, entries, restrictions);
78
+ const resolveHyperlinkName = workbookDefinedNameLookup(definedNames, entries);
79
+ const conditionalNames = createXlsxConditionalNameResolver(names, entries, definedNames);
80
+ const print = readXlsxWorksheetPrintNames(printNames, entries, relationships, worksheetRestrictions);
81
+ // Resolve worksheet ownership before parsing the PivotTable caches and source formats that depend on it.
82
+ const { sheets, namedViewPaths, sourceTables, sheetAppearance, cellImages, drawings, backgrounds, hyperlinkRelations,
83
+ axisRestrictions, cellShiftRestrictions, sortRestrictions, freezeRestrictions, printLayoutRestrictions } =
84
+ readXlsxWorksheetParts({ parts, entries, presentation, print, dateSystem, wpsLists, conditionalNames,
85
+ resolveHyperlinkName, comments, images, retainResult: retainedCalculation && retainResult, arrays, external },
86
+ restrictions, worksheetRestrictions);
87
+ const pivots = readXlsxPivotPackage(parts, workbook, workbookPath, relationships, entries, sheetPaths, dateSystem,
88
+ { ...styles, sheets: sheetAppearance }, restrictions);
89
+ if (!validateFilterDatabaseNames(filterNames, sheets)) restrictions.add("筛选名称与工作表范围不一致");
90
+
91
+ const { charts: editableCharts, drawingGraphs, previews, pictures, shapes, editablePictures, editableShapes, pictureAssets } = drawings.finish(restrictions);
92
+ const imageAssets = [...(images?.assets() ?? []), ...pictureAssets, ...backgrounds.assets()];
93
+ const fitsCache = retainedCells <= workbookTransactionCellLimit;
94
+ if (!fitsCache && manualCalculation) restrictions.add("手动计算缓存超出当前工作簿容量,预览使用自动计算");
95
+ if (!fitsCache && arrays) restrictions.add("动态数组缓存超出当前工作簿容量");
96
+ const calculationSettings = !fitsCache && manualCalculation
97
+ ? copyWorkbookCalculationSettings({ ...importedCalculationSettings, mode: undefined }) : importedCalculationSettings;
98
+ const formulaResults = fitsCache && (manualCalculation || retainedCalculation?.length) ? retainedCalculation : undefined;
99
+ const calculationPending = manualCalculation && formulaResults?.length
100
+ && (xlsxCalculationIsPending(workbook) || formulaResults.some(entry => entry.result.status === "unavailable"));
101
+ const tableMergeRecipes = readXlsxMergeRecipes(workbook, entries);
102
+ const dashboards = readXlsxDashboards(workbook, entries);
103
+ if (!dashboards) restrictions.add("仪表盘的配置无法读取");
104
+ const content: WorkbookSnapshot = {
105
+ version: 1, revision: 0, id: uuidv4(), name,
106
+ dateSystem,
107
+ ...(external && { externalLinks: external.links }),
108
+ ...(calculationSettings && { calculationSettings }),
109
+ ...(formulaResults && { formulaResults }),
110
+ ...(calculationPending && { formulaPendingRevision: 0 }),
111
+ sheets: sheets.map(sheet => dashboards?.has(sheet.id) ? { ...sheet, dashboard: dashboards.get(sheet.id)! } : sheet), ...(definedNames.length && { definedNames }), ...(editableCharts.length && { charts: editableCharts }),
112
+ ...(editablePictures.length && { pictures: editablePictures }), ...(editableShapes.length && { shapes: editableShapes }),
113
+ ...(tableMergeRecipes.length && { tableMergeRecipes }),
114
+ ...(pivots.tables.length && { pivotTables: pivots.tables }), ...(imageAssets.length && { imageAssets }),
115
+ ...(comments.threads.length && { commentThreads: comments.threads })
116
+ };
117
+ const appearance = { ...styles, sheets: sheetAppearance, newTableStyle: tableStyles.authored };
118
+ if (!canWriteXlsxSourceTables(parts, sourceTables, content)) restrictions.add("结构化表");
119
+ if (sourceTables.length && !supportsXlsxStructuredFormulas(content, appearance)) restrictions.add("结构化引用包含暂未支持的组合");
120
+ if (restrictions.size) for (const [id, sheet] of sheetAppearance) {
121
+ if (sheet.tables?.length) sheetAppearance.set(id, { ...sheet, tables: sheet.tables.map(table => ({ ...table, id: undefined })) });
122
+ }
123
+ const baseline = !restrictions.size && sourceTables.length
124
+ ? { ...content, structuredTables: xlsxStructuredTableDefinitions(sourceTables) } : content;
125
+ const worksheetRestriction = worksheetRestrictions.size
126
+ ? `原文件含${[...worksheetRestrictions].join("、")},当前无法安全操作工作表目录。` : undefined;
127
+ // Keep the originating spill footprint for write-back. Auto files with a requested recalculation open on newly calculated values.
128
+ const snapshot = arrays && !manualCalculation && !cachedCalculation && !restrictions.size
129
+ ? { ...baseline, formulaResults: undefined } : baseline;
130
+ return {
131
+ snapshot: projectXlsxSnapshot(snapshot, options.shareCellInputs), restrictions: [...restrictions], axisRestrictions: new Map(axisRestrictions), sortRestrictions: new Map(sortRestrictions),
132
+ cellShiftRestrictions: new Map(cellShiftRestrictions),
133
+ appearance, charts: previews, pictures, shapes, cellImages, initialWorksheetId, freezeRestrictions: new Map(freezeRestrictions),
134
+ printLayoutRestrictions: new Map(printLayoutRestrictions),
135
+ ...(worksheetRestriction && { worksheetRestriction }),
136
+ original: () => original.slice(),
137
+ write: createXlsxSourceWriter({ workbookPath, workbookXml, relationships, sheetPaths, backgroundPaths: backgrounds.paths, baseline,
138
+ externalLinkParts: external?.native, appearance, drawingGraphs, checkboxStyles,
139
+ hyperlinkRelations, imageGraph: images?.graph, arrayMetadata: arrays?.owned ? arrays.relation : undefined,
140
+ pivotGraph: pivots.graph, commentGraph: comments.graph, namedViewPaths, sourceTables, printLayoutRestrictions },
141
+ { original, sheets, restrictions, worksheetRestriction, axisRestrictions, cellShiftRestrictions, sortRestrictions, freezeRestrictions })
142
+ };
143
+ }
@@ -0,0 +1,57 @@
1
+ import type { retainWorkbookFormulaResults, workbookProgressRules, WorkbookAppearance, WorkbookFormulaSpill,
2
+ WorkbookPositionEdit, WorkbookSheet } from "@quirekit/workbook";
3
+ import type { xlsxExternalFormulaCheck } from "../../external-links/formulas";
4
+ import type { writeWorkbookCellImages } from "../../image/write";
5
+ import type { XlsxDifferentialStyle } from "../../styles/types";
6
+ import type { createXlsxStyleWriter } from "../../styles/write";
7
+ import type { xlsxTableFiltersBySheet } from "../../table/write";
8
+ import type { XlsxWriteOptions } from "../../types";
9
+ import type { xlsxNamedHyperlinkLocations } from "../../worksheet/hyperlinks/location";
10
+
11
+ /** Workbook-scoped resources shared across one pass of native worksheet writes. */
12
+ export interface XlsxWorksheetWriteBasis {
13
+ /** Save options including formula value and conditional presentation readers. */
14
+ readonly options: XlsxWriteOptions;
15
+ /** Whether authored inputs and formula results need replacement. */
16
+ readonly writeInputs: boolean;
17
+ /** Target sheet part paths after any directory changes. */
18
+ readonly paths: ReadonlyMap<string, string>;
19
+ /** Imported worksheets before relocation. */
20
+ readonly originals: ReadonlyMap<string, WorkbookSheet>;
21
+ /** Position edits since the archive was opened. */
22
+ readonly positions: readonly WorkbookPositionEdit[];
23
+ /** Appearance after projecting source dimensions and formats through those edits. */
24
+ readonly appearance: WorkbookAppearance | undefined;
25
+ /** Sheets with revised print settings. */
26
+ readonly printChanges: ReadonlySet<string>;
27
+ /** Sheets whose native conditional rules must be replaced. */
28
+ readonly ruleChanges: ReadonlySet<string>;
29
+ /** Progress fields represented by native conditional rules, keyed by sheet. */
30
+ readonly progress: ReadonlyMap<string, ReturnType<typeof workbookProgressRules>>;
31
+ /** Imported arrays whose cached cells may need clearing. */
32
+ readonly oldArrays: ReadonlyMap<string, readonly WorkbookFormulaSpill[]>;
33
+ /** Current arrays whose cached cells may need writing. */
34
+ readonly newArrays: ReadonlyMap<string, readonly WorkbookFormulaSpill[]>;
35
+ /** Filters applied by native tables in the source. */
36
+ readonly priorTableFilters: ReturnType<typeof xlsxTableFiltersBySheet>;
37
+ /** Filters applied by native tables at the saved revision. */
38
+ readonly tableFilters: ReturnType<typeof xlsxTableFiltersBySheet>;
39
+ /** Sheet names used by native links and range sources. */
40
+ readonly names: ReadonlyMap<string, string>;
41
+ /** Current native named hyperlink destinations. */
42
+ readonly namedLocations: ReturnType<typeof xlsxNamedHyperlinkLocations>;
43
+ /** Native named hyperlink destinations at import. */
44
+ readonly oldLocations: ReturnType<typeof xlsxNamedHyperlinkLocations>;
45
+ /** Sheet IDs whose name changed since import. */
46
+ readonly renamedSheets: ReadonlySet<string>;
47
+ /** Lookup for native external cache slots that may be referenced. */
48
+ readonly supportsExternalFormula: ReturnType<typeof xlsxExternalFormulaCheck>;
49
+ /** Shared style writer when a revised sheet requires native styles. */
50
+ readonly styles: ReturnType<typeof createXlsxStyleWriter> | undefined;
51
+ /** Native metadata index resolver for grid image cells. */
52
+ readonly imageIndex: ReturnType<typeof writeWorkbookCellImages>;
53
+ /** Resolves derived spill cells when the current sheet writes its calculated arrays. */
54
+ readonly retainedResultsAt: (sheetId: string) => NonNullable<ReturnType<typeof retainWorkbookFormulaResults>>["spills"]["at"] | undefined;
55
+ /** Registers a differential style needed by a native filter or sort. */
56
+ readonly addFilterStyle: (style: XlsxDifferentialStyle) => number;
57
+ }