@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,118 @@
1
+ import { workbookImagePresentation, type WorkbookImageCell, type WorkbookRasterAsset, type WorkbookSnapshot } from "@quirekit/workbook";
2
+ import { editPartRelationships, relationshipsPath } from "../opc/relationships";
3
+ import { children, contentTypeNs, parsePart, relationshipNs, rootOf, writePart } from "../opc/xml";
4
+ import type { XlsxPackage } from "../package/types";
5
+ import { xlsxImageRoles } from "./native";
6
+ import { xlsxImageMetadata, xlsxImageRelations, xlsxImageStructures, xlsxImageValues } from "./parts";
7
+ import { retainedXlsxRelationshipTargets } from "./relationships";
8
+ import type { XlsxCellImageValue } from "./types";
9
+
10
+ /** @param source - Workbook and any fully owned original image graph. @param parts - Staged archive.
11
+ * @param snapshot - Final worksheet placements and local resources.
12
+ * @returns Lookup for the native one-based vm attribute of each authored image value. */
13
+ export function writeWorkbookCellImages(source: XlsxPackage, parts: Record<string, Uint8Array>, snapshot: WorkbookSnapshot):
14
+ ((input: WorkbookImageCell) => number) | undefined {
15
+ if (!source.imageGraph
16
+ && !snapshot.sheets.some(sheet => sheet.cells.some(({ input }) => input.kind === "image"))) return;
17
+ const values: XlsxCellImageValue[] = [];
18
+ const valueIndices = new Map<string, number>();
19
+ const mediaIndices = new Map<string, number>();
20
+ const chosenAssets: WorkbookRasterAsset[] = [];
21
+ const assets = new Map(snapshot.imageAssets?.map(asset => [asset.id, asset]));
22
+
23
+ // Commit one native media part per resource. Alternate text belongs to the value, so several values may share a file.
24
+ for (const sheet of snapshot.sheets) for (const { input } of sheet.cells) {
25
+ if (input.kind !== "image") continue;
26
+ const key = imageValueKey(input);
27
+ if (valueIndices.has(key)) continue;
28
+ let index = mediaIndices.get(input.assetId);
29
+ if (index === undefined) {
30
+ const asset = assets.get(input.assetId);
31
+ if (!asset) throw new Error("工作簿格内图片的原始资源缺失。");
32
+ index = chosenAssets.length;
33
+ mediaIndices.set(input.assetId, index);
34
+ chosenAssets.push(asset);
35
+ }
36
+ values.push({ media: index, ...(input.alt && { alt: input.alt }) });
37
+ valueIndices.set(key, values.length);
38
+ }
39
+
40
+ const manifestPath = "[Content_Types].xml";
41
+ const manifest = parsePart(parts[manifestPath], manifestPath);
42
+ const types = rootOf(manifest, contentTypeNs, "Types");
43
+ const overrides = new Map(children(types, "Override").map(node => [node.getAttribute("PartName"), node]));
44
+ const workbook = editPartRelationships(parts, source.workbookPath);
45
+ const preserved = source.imageGraph?.roles.find(role => role.type === xlsxImageRoles.types);
46
+
47
+ /** @param path - Previously owned part leaving the package. */
48
+ function remove(path: string): void {
49
+ delete parts[path];
50
+ const override = overrides.get("/" + path);
51
+ if (override) { types.removeChild(override); overrides.delete("/" + path); }
52
+ }
53
+
54
+ if (source.imageGraph) {
55
+ const { relationPath, roles, media } = source.imageGraph;
56
+ for (const role of roles) {
57
+ if (values.length && role === preserved) continue;
58
+ workbook.remove(role.id);
59
+ if (role.path) remove(role.path);
60
+ }
61
+ delete parts[relationshipsPath(relationPath)];
62
+ workbook.write();
63
+ const targets = retainedXlsxRelationshipTargets(parts);
64
+ if (targets) for (const path of media) { if (!targets.has(path)) remove(path); }
65
+ }
66
+ if (!values.length) {
67
+ parts[manifestPath] = writePart(manifest);
68
+ return;
69
+ }
70
+
71
+ const base = source.workbookPath.slice(0, source.workbookPath.lastIndexOf("/") + 1);
72
+ const reserved = new Set([...Object.keys(parts), ...[...overrides.keys()].map(key => key?.slice(1) ?? "")].map(path => path.toLowerCase()));
73
+
74
+ /** @param basename - Desired relative directory and name without extension. @param extension - Native suffix.
75
+ * @param type - MIME for this OPC part. @returns Unused, declared path relative to the workbook. */
76
+ function allocate(basename: string, extension: string, type: string): string {
77
+ let relative = basename + "." + extension;
78
+ for (let suffix = 1; reserved.has((base + relative).toLowerCase()) || reserved.has(relationshipsPath(base + relative).toLowerCase()); suffix++) {
79
+ relative = basename + suffix + "." + extension;
80
+ }
81
+ reserved.add((base + relative).toLowerCase());
82
+ const override = manifest.createElementNS(contentTypeNs, "Override");
83
+ override.setAttribute("PartName", "/" + base + relative);
84
+ override.setAttribute("ContentType", type);
85
+ types.appendChild(override);
86
+ return relative;
87
+ }
88
+
89
+ /** @param key - Image graph relationship role. @param name - Proposed XLSX part name. @param mime - Native content type.
90
+ * @returns Full staged archive path. */
91
+ function register(key: keyof typeof xlsxImageRoles, name: string, mime: string): string {
92
+ const target = allocate(name, "xml", mime);
93
+ workbook.add(xlsxImageRoles[key], target);
94
+ return base + target;
95
+ }
96
+
97
+ const metadata = register("metadata", "metadata", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml");
98
+ const structure = register("structures", "richData/rdrichvaluestructure", "application/vnd.ms-excel.rdRichValueStructure+xml");
99
+ const data = register("values", "richData/rdrichvalue", "application/vnd.ms-excel.rdRichValue+xml");
100
+ const relation = register("relations", "richData/richValueRel", "application/vnd.ms-excel.richvaluerel+xml");
101
+ const media = editPartRelationships(parts, relation);
102
+ const ids = chosenAssets.map((asset, index) => {
103
+ const path = allocate("media/cellImage" + (index + 1), asset.mimeType === "image/png" ? "png" : "jpeg", asset.mimeType);
104
+ parts[base + path] = workbookImagePresentation(asset).bytes();
105
+ return media.add(relationshipNs + "/image", "../" + path);
106
+ });
107
+ parts[metadata] = xlsxImageMetadata(values.length);
108
+ parts[structure] = xlsxImageStructures();
109
+ parts[data] = xlsxImageValues(values);
110
+ parts[relation] = xlsxImageRelations(ids);
111
+ media.write();
112
+ workbook.write();
113
+ parts[manifestPath] = writePart(manifest);
114
+ return input => valueIndices.get(imageValueKey(input))!;
115
+ }
116
+
117
+ /** @param input - Authored image and alt text. @returns Native value identity within the resource graph. */
118
+ function imageValueKey({ assetId, alt }: WorkbookImageCell): string { return JSON.stringify([assetId, alt ?? ""]); }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export { createXlsx } from "./create";
2
+ export { createXlsxBundle } from "./bundle";
3
+ export { openXlsx } from "./package/read";
4
+ export { optimizeXlsx } from "./optimization/optimize";
5
+ export type { XlsxOptimizationResult, XlsxOptimizedCopy } from "./optimization/types";
6
+ export type { XlsxChart, XlsxFloatingPicture, XlsxOpenOptions, XlsxWorkbookFile, XlsxWriteOptions } from "./types";
@@ -0,0 +1,105 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { hasKnownAttributes, hasKnownChildren } from "../opc/shape";
3
+ import { child, children, readIndex, spreadNs } from "../opc/xml";
4
+ import type { XlsxDynamicArrayMetadata } from "./types";
5
+
6
+ const name = "XLDAPR";
7
+ const extensionId = "{bdbb8cdc-fa1e-496e-a857-3c3f30c029c3}";
8
+ const namespace = "http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray";
9
+
10
+ /** Known flags on a native metadata type. */
11
+ export const xlsxMetadataFlags = ["name", "minSupportedVersion", "ghostRow", "ghostCol", "edit", "delete", "copy", "pasteAll", "pasteValues",
12
+ "pasteFormats", "pasteComments", "pasteDataValidation", "pasteBorders", "pasteColWidths", "pasteNumberFormats",
13
+ "merge", "splitFirst", "splitAll", "rowColShift", "clearAll", "clearFormats", "clearContents", "clearComments", "assign", "coerce", "cellMeta"];
14
+
15
+ /** @param owner - Repeated metadata elements. @param localName - Modeled child name. @returns Records in their native order. */
16
+ function records(owner: Element, localName: string): Element[] | undefined {
17
+ const entries = children(owner);
18
+ if (entries.some(entry => entry.namespaceURI !== spreadNs || entry.localName !== localName)
19
+ || owner.hasAttribute("count") && readIndex(owner, "count") !== entries.length) return;
20
+ return entries;
21
+ }
22
+
23
+ /** @param block - A futureMetadata record. @returns Whether its only extension enables dynamic arrays. */
24
+ function isDynamicArrayRecord(block: Element): boolean {
25
+ const extensions = child(block, "extLst"), extension = extensions && child(extensions, "ext");
26
+ const properties = extension && child(extension, "dynamicArrayProperties");
27
+ return Boolean(properties && extension && extensions && hasKnownAttributes(block, []) && hasKnownChildren(block, ["extLst"])
28
+ && hasKnownAttributes(extensions, []) && hasKnownChildren(extensions, ["ext"])
29
+ && hasKnownAttributes(extension, ["uri"]) && extension.getAttribute("uri")?.toLowerCase() === extensionId
30
+ && hasKnownChildren(extension, ["dynamicArrayProperties"], spreadNs, { dynamicArrayProperties: namespace })
31
+ && hasKnownAttributes(properties, ["fDynamic", "fCollapsed"]) && hasKnownChildren(properties, [])
32
+ && /^(?:1|true)$/u.test(properties.getAttribute("fDynamic") ?? "")
33
+ && /^(?:0|false)?$/u.test(properties.getAttribute("fCollapsed") ?? ""));
34
+ }
35
+
36
+ /** @param root - Native worksheet metadata root. @returns Writable dynamic records and their one-based cell indexes. */
37
+ export function readXlsxDynamicArrayMetadata(root: Element): XlsxDynamicArrayMetadata | undefined {
38
+ const types = child(root, "metadataTypes"), cells = child(root, "cellMetadata");
39
+ const futures = children(root, "futureMetadata").filter(node => node.namespaceURI === spreadNs && node.getAttribute("name") === name);
40
+ const future = futures.length === 1 ? futures[0] : undefined;
41
+ if (!types || !future || !cells || !hasKnownAttributes(root, [])
42
+ || !hasKnownAttributes(types, ["count"]) || !hasKnownAttributes(future, ["count", "name"]) || !hasKnownAttributes(cells, ["count"])) return;
43
+ const typeList = records(types, "metadataType");
44
+ const arrayTypes = typeList?.filter(type => type.getAttribute("name") === name);
45
+ const type = arrayTypes?.length === 1 ? arrayTypes[0] : undefined;
46
+ if (!type || !hasKnownAttributes(type, xlsxMetadataFlags) || !hasKnownChildren(type, [])
47
+ || !/^(?:1|true)$/u.test(type.getAttribute("cellMeta") ?? "")) return;
48
+ const blocks = records(future, "bk");
49
+ if (!blocks?.length || !blocks.every(isDynamicArrayRecord)) return;
50
+ const typeIndex = typeList!.indexOf(type) + 1;
51
+ const cellBlocks = records(cells, "bk");
52
+ if (!cellBlocks?.length) return;
53
+ const indexes = new Set<number>();
54
+ for (const [index, block] of cellBlocks.entries()) {
55
+ const record = child(block, "rc");
56
+ const value = record && readIndex(record, "v");
57
+ if (!record || !hasKnownAttributes(block, []) || !hasKnownChildren(block, ["rc"])
58
+ || !hasKnownAttributes(record, ["t", "v"]) || !hasKnownChildren(record, [])
59
+ || readIndex(record, "t") !== typeIndex || typeof value !== "number" || !blocks[value]) return;
60
+ indexes.add(index + 1);
61
+ }
62
+ return { indexes, exclusive: typeList!.length === 1 && hasKnownChildren(root, ["metadataTypes", "futureMetadata", "cellMetadata"]) };
63
+ }
64
+
65
+ /** @param root - Empty metadata or the image writer's modeled metadata. Appends a one-based record shared by all dynamic formula sources. */
66
+ export function appendXlsxDynamicArrayMetadata(root: Element): void {
67
+ const document = root.ownerDocument!;
68
+ const existing = child(root, "metadataTypes");
69
+ const types = existing ?? document.createElementNS(spreadNs, "metadataTypes");
70
+ const typeIndex = children(types).length + 1;
71
+ types.setAttribute("count", String(typeIndex));
72
+ if (!existing) root.insertBefore(types, root.firstChild);
73
+ const type = document.createElementNS(spreadNs, "metadataType");
74
+ type.setAttribute("name", name);
75
+ type.setAttribute("minSupportedVersion", "120000");
76
+ for (const flag of ["copy", "pasteAll", "pasteValues", "merge", "splitFirst", "rowColShift", "clearFormats", "clearComments", "assign", "coerce", "cellMeta"]) {
77
+ type.setAttribute(flag, "1");
78
+ }
79
+ types.appendChild(type);
80
+ const future = document.createElementNS(spreadNs, "futureMetadata");
81
+ future.setAttribute("name", name);
82
+ future.setAttribute("count", "1");
83
+ const block = document.createElementNS(spreadNs, "bk");
84
+ const extensions = document.createElementNS(spreadNs, "extLst");
85
+ const extension = document.createElementNS(spreadNs, "ext");
86
+ extension.setAttribute("uri", extensionId);
87
+ const properties = document.createElementNS(namespace, "xda:dynamicArrayProperties");
88
+ properties.setAttribute("fDynamic", "1");
89
+ properties.setAttribute("fCollapsed", "0");
90
+ extension.appendChild(properties);
91
+ extensions.appendChild(extension);
92
+ block.appendChild(extensions);
93
+ future.appendChild(block);
94
+ const valueMetadata = child(root, "valueMetadata");
95
+ root.insertBefore(future, valueMetadata ?? null);
96
+ const cells = document.createElementNS(spreadNs, "cellMetadata");
97
+ cells.setAttribute("count", "1");
98
+ const entry = document.createElementNS(spreadNs, "bk");
99
+ const record = document.createElementNS(spreadNs, "rc");
100
+ record.setAttribute("t", String(typeIndex));
101
+ record.setAttribute("v", "0");
102
+ entry.appendChild(record);
103
+ cells.appendChild(entry);
104
+ root.insertBefore(cells, valueMetadata ?? null);
105
+ }
@@ -0,0 +1,75 @@
1
+ import { strToU8 } from "fflate";
2
+ import { retainedXlsxRelationshipTargets } from "../image/relationships";
3
+ import { editPartRelationships, relationshipsPath } from "../opc/relationships";
4
+ import type { PackageRelationship } from "../opc/types";
5
+ import { children, contentTypeNs, parsePart, relationshipNs, rootOf, spreadNs, writePart } from "../opc/xml";
6
+ import { appendXlsxDynamicArrayMetadata, readXlsxDynamicArrayMetadata } from "./dynamic-array";
7
+
8
+ const metadataRole = relationshipNs + "/sheetMetadata";
9
+ const contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml";
10
+ const manifestPath = "[Content_Types].xml";
11
+
12
+ /** @param parts - Native parts. @param relations - Workbook relationship table. @param workbook - Owning workbook path.
13
+ * @returns Array metadata and its owned relationship when all records have defined owners. */
14
+ export function readXlsxArrayMetadataPart(parts: Readonly<Record<string, Uint8Array>>, relations: ReadonlyMap<string, PackageRelationship>, workbook: string) {
15
+ const matches = [...relations.values()].filter(relation => relation.type === metadataRole);
16
+ const relation = matches.length === 1 ? matches[0] : undefined;
17
+ const path = relation?.path;
18
+ if (!relation || !path) return;
19
+ try {
20
+ const decoded = readXlsxDynamicArrayMetadata(rootOf(parsePart(parts[path], path), spreadNs, "metadata"));
21
+ if (!decoded) return;
22
+ const foreign = retainedXlsxRelationshipTargets(parts, relationshipsPath(workbook));
23
+ const owned = decoded.exclusive && foreign && !foreign.has(path) && !parts[relationshipsPath(path)]
24
+ && [...relations.values()].every(other => other === relation || other.path !== path);
25
+ return { indexes: decoded.indexes, relation, owned: Boolean(owned) };
26
+ } catch { return undefined; }
27
+ }
28
+
29
+ /** @param parts - Staged archive. @param workbook - Owning workbook part. @param relation - Exclusively dynamic source metadata. */
30
+ export function removeXlsxArrayMetadataPart(parts: Record<string, Uint8Array>, workbook: string, relation: PackageRelationship | undefined): void {
31
+ const path = relation?.path;
32
+ if (!relation || !path) return;
33
+ const links = editPartRelationships(parts, workbook);
34
+ links.remove(relation.id);
35
+ links.write();
36
+ const manifest = parsePart(parts[manifestPath], manifestPath);
37
+ const types = rootOf(manifest, contentTypeNs, "Types");
38
+ for (const entry of children(types, "Override")) {
39
+ if (entry.getAttribute("PartName") === "/" + path) types.removeChild(entry);
40
+ }
41
+ delete parts[path];
42
+ parts[manifestPath] = writePart(manifest);
43
+ }
44
+
45
+ /** @param parts - Staged archive, including any rebuilt image metadata. @param workbook - Owning workbook part. */
46
+ export function writeXlsxArrayMetadataPart(parts: Record<string, Uint8Array>, workbook: string): void {
47
+ const links = editPartRelationships(parts, workbook);
48
+ const metadata = [...links.entries.values()].find(relation => relation.type === metadataRole);
49
+ if (metadata?.path) {
50
+ const document = parsePart(parts[metadata.path], metadata.path);
51
+ appendXlsxDynamicArrayMetadata(rootOf(document, spreadNs, "metadata"));
52
+ parts[metadata.path] = writePart(document);
53
+ return;
54
+ }
55
+ const base = workbook.slice(0, workbook.lastIndexOf("/") + 1);
56
+ const manifest = parsePart(parts[manifestPath], manifestPath);
57
+ const types = rootOf(manifest, contentTypeNs, "Types");
58
+ const reserved = new Set([...Object.keys(parts), ...children(types, "Override").map(entry => entry.getAttribute("PartName")?.slice(1) ?? "")]
59
+ .map(path => path.toLowerCase()));
60
+ let relative = "metadata.xml";
61
+ for (let suffix = 1; reserved.has((base + relative).toLowerCase()) || reserved.has(relationshipsPath(base + relative).toLowerCase()); suffix++) {
62
+ relative = "metadata" + suffix + ".xml";
63
+ }
64
+ const path = base + relative;
65
+ const document = parsePart(strToU8('<metadata xmlns="' + spreadNs + '"/>'), path);
66
+ appendXlsxDynamicArrayMetadata(rootOf(document, spreadNs, "metadata"));
67
+ parts[path] = writePart(document);
68
+ const override = manifest.createElementNS(contentTypeNs, "Override");
69
+ override.setAttribute("PartName", "/" + path);
70
+ override.setAttribute("ContentType", contentType);
71
+ types.appendChild(override);
72
+ parts[manifestPath] = writePart(manifest);
73
+ links.add(metadataRole, relative);
74
+ links.write();
75
+ }
@@ -0,0 +1,7 @@
1
+ /** Origin of a supported dynamic cell metadata record. */
2
+ export interface XlsxDynamicArrayMetadata {
3
+ /** Native cellMetadata indexes consumed by dynamic source cells. */
4
+ readonly indexes: ReadonlySet<number>;
5
+ /** Whether the metadata part only contains dynamic array records. */
6
+ readonly exclusive: boolean;
7
+ }
@@ -0,0 +1,26 @@
1
+ import { unzipSync } from "fflate";
2
+
3
+ /**
4
+ * Reads a bounded local package before XML parsing.
5
+ * @param bytes - Original XLSX file.
6
+ * @returns Exact decompressed parts by case-sensitive OPC path.
7
+ */
8
+ export function openArchive(bytes: Uint8Array): Record<string, Uint8Array> {
9
+ if (bytes.length > 32 * 1024 * 1024) throw new Error("此工作台能打开 32 MiB 以内的 XLSX 文件。");
10
+ const names = new Set<string>();
11
+ let declared = 0;
12
+ const archive = unzipSync(bytes, { filter: entry => {
13
+ const { name } = entry;
14
+ if (name === "__proto__" || names.has(name) || name.startsWith("/") || name.includes("\\") || name.split("/").some(part => part === ".." || part === ".")) {
15
+ throw new Error("XLSX 包含无效或重复的部件路径。");
16
+ }
17
+ names.add(name);
18
+ declared += entry.originalSize;
19
+ if (names.size > 4096 || declared > 128 * 1024 * 1024) throw new Error("XLSX 解包体积超过工作台的读取范围。");
20
+ return !name.endsWith("/");
21
+ } });
22
+ if (Object.values(archive).reduce((total, bytes) => total + bytes.length, 0) > 128 * 1024 * 1024) {
23
+ throw new Error("XLSX 实际解包体积超过工作台的读取范围。");
24
+ }
25
+ return archive;
26
+ }
@@ -0,0 +1,40 @@
1
+ import { readRelationships } from "./relationships";
2
+ import { children, contentTypeNs, parsePart, rootOf } from "./xml";
3
+
4
+ /** @param parts - Original ZIP members. @param owners - Allowed part owners by target URI.
5
+ * @param types - Expected content type for each target. */
6
+ export function verifyXlsxPartOwnership(parts: Readonly<Record<string, Uint8Array>>,
7
+ owners: ReadonlyMap<string, ReadonlySet<string>>, types: ReadonlyMap<string, string>): void {
8
+ const manifest = rootOf(parsePart(parts["[Content_Types].xml"], "[Content_Types].xml"), contentTypeNs, "Types");
9
+ const defaults = new Map(children(manifest, "Default").map(node => [node.getAttribute("Extension")?.toLowerCase(), node.getAttribute("ContentType")]));
10
+ const checkedTypes = new Set<string>();
11
+ for (const entry of children(manifest, "Override")) {
12
+ const name = (entry.getAttribute("PartName") ?? "").slice(1);
13
+ if (!types.has(name)) continue;
14
+ if (checkedTypes.has(name) || types.get(name) !== entry.getAttribute("ContentType")) throw new Error("XLSX 部件类型不一致。");
15
+ checkedTypes.add(name);
16
+ }
17
+ for (const [path, type] of types) {
18
+ if (!checkedTypes.has(path) && defaults.get(path.split(".").at(-1)?.toLowerCase()) !== type) {
19
+ throw new Error("XLSX 部件缺少对应的内容类型。");
20
+ }
21
+ }
22
+ const folded = new Set([...owners.keys()].map(path => path.toLowerCase()));
23
+ const seen = new Map<string, Set<string>>();
24
+ for (const [path, data] of Object.entries(parts)) {
25
+ if (folded.has(path.toLowerCase()) && !owners.has(path)) throw new Error("XLSX 部件路径存在大小写冲突。");
26
+ const relationshipPart = /^(.*)_rels\/([^/]*)\.rels$/u.exec(path);
27
+ if (!relationshipPart) continue;
28
+ const owner = relationshipPart[1]! + relationshipPart[2]!;
29
+ for (const link of readRelationships(parsePart(data, path), owner).values()) {
30
+ if (!link.path || !folded.has(link.path.toLowerCase())) continue;
31
+ const used = seen.get(link.path) ?? new Set<string>();
32
+ if (!owners.get(link.path)?.has(owner) || used.has(owner)) throw new Error("XLSX 部件与其他关系共用。");
33
+ used.add(owner);
34
+ seen.set(link.path, used);
35
+ }
36
+ }
37
+ for (const [path, expected] of owners) {
38
+ if (seen.get(path)?.size !== expected.size) throw new Error("XLSX 部件关系不完整。");
39
+ }
40
+ }
@@ -0,0 +1,98 @@
1
+ import { strToU8 } from "fflate";
2
+ import type { Document } from "@xmldom/xmldom";
3
+ import type { PackageRelationship } from "./types";
4
+ import { children, packageRelationshipNs, parsePart, relationshipNs, rootOf, writePart } from "./xml";
5
+
6
+ /** Standard role of native SpreadsheetML hyperlink targets. */
7
+ export const hyperlinkRelationship = relationshipNs + "/hyperlink";
8
+
9
+ /**
10
+ * @param owner - Part owning the relationships, or the package root.
11
+ * @returns OPC relationship part path.
12
+ */
13
+ export function relationshipsPath(owner: string): string {
14
+ const index = owner.lastIndexOf("/");
15
+ return `${owner.slice(0, index + 1)}_rels/${owner.slice(index + 1)}.rels`;
16
+ }
17
+
18
+ /**
19
+ * @param owner - Part containing the relationship.
20
+ * @param target - URI relative to that part.
21
+ * @returns Normalized path in the ZIP package.
22
+ */
23
+ function resolveTarget(owner: string, target: string): string {
24
+ const path = decodeURIComponent(target);
25
+ if (!path || /[:?#\\]/u.test(path)) throw new Error(`不支持的 XLSX 关系路径 ${target}。`);
26
+ const segments = path.startsWith("/") ? [] : owner.split("/").slice(0, -1);
27
+ for (const part of path.split("/")) {
28
+ if (part === "..") {
29
+ if (segments.length === 0) throw new Error("XLSX 部件关系超出文件范围。");
30
+ segments.pop();
31
+ } else if (part !== "." && part !== "") segments.push(part);
32
+ }
33
+ return segments.join("/");
34
+ }
35
+
36
+ /**
37
+ * @param document - OPC .rels part.
38
+ * @param owner - Part the relationships are relative to.
39
+ * @returns Relationship table by ID.
40
+ */
41
+ export function readRelationships(document: Document, owner: string): Map<string, PackageRelationship> {
42
+ const result = new Map<string, PackageRelationship>();
43
+ for (const element of children(rootOf(document, packageRelationshipNs, "Relationships"), "Relationship")) {
44
+ const id = element.getAttribute("Id");
45
+ const type = element.getAttribute("Type");
46
+ const target = element.getAttribute("Target");
47
+ if (!id || !target || !type || result.has(id)) throw new Error("XLSX 包含无效的部件关系。");
48
+ result.set(id, { id, type, path: element.getAttribute("TargetMode") === "External" ? null : resolveTarget(owner, target), element });
49
+ }
50
+ return result;
51
+ }
52
+
53
+ /**
54
+ * @param table - Related parts by relationship ID.
55
+ * @param type - Last segment of the required relationship type URI.
56
+ * @returns Member whose declared type matches.
57
+ */
58
+ export function relationshipOfType(table: ReadonlyMap<string, PackageRelationship>, type: string): PackageRelationship | undefined {
59
+ return [...table.values()].find(relation => relation.type.endsWith(`/${type}`));
60
+ }
61
+
62
+ /** @param parts - Mutable staged package. @param owner - Originating native part.
63
+ * @returns Targeted relationship editing while preserving other relationship nodes. */
64
+ export function editPartRelationships(parts: Record<string, Uint8Array>, owner: string) {
65
+ const path = relationshipsPath(owner);
66
+ const document = parsePart(parts[path] ?? strToU8('<Relationships xmlns="' + packageRelationshipNs + '"/>'), path);
67
+ const root = rootOf(document, packageRelationshipNs, "Relationships");
68
+ const entries = readRelationships(document, owner);
69
+ let nextId = 1;
70
+ return {
71
+ entries,
72
+ /** @param id - Relationship owned by the feature making the change. */
73
+ remove(id: string): void {
74
+ const relation = entries.get(id);
75
+ if (relation) root.removeChild(relation.element);
76
+ entries.delete(id);
77
+ },
78
+ /** @param type - Full relationship role. @param target - Native URI. @param external - Whether to use TargetMode External.
79
+ * @returns A fresh ID local to the same owner. */
80
+ add(type: string, target: string, external = false): string {
81
+ while (entries.has("rId" + nextId)) nextId++;
82
+ const id = "rId" + nextId++;
83
+ const element = document.createElementNS(packageRelationshipNs, "Relationship");
84
+ element.setAttribute("Id", id);
85
+ element.setAttribute("Type", type);
86
+ element.setAttribute("Target", target);
87
+ if (external) element.setAttribute("TargetMode", "External");
88
+ root.appendChild(element);
89
+ entries.set(id, { id, type, path: external ? null : resolveTarget(owner, target), element });
90
+ return id;
91
+ },
92
+ /** Writes the shared relationship part, or removes it once empty. */
93
+ write(): void {
94
+ if (children(root).length) parts[path] = writePart(document);
95
+ else delete parts[path];
96
+ }
97
+ };
98
+ }
@@ -0,0 +1,28 @@
1
+ import type { Attr, Element } from "@xmldom/xmldom";
2
+
3
+ export const xlsxFilterUidNs = "http://schemas.microsoft.com/office/spreadsheetml/2014/revision";
4
+ export const xlsxTableColumnUidNs = "http://schemas.microsoft.com/office/spreadsheetml/2016/revision3";
5
+ const mc = "http://schemas.openxmlformats.org/markup-compatibility/2006";
6
+ const guid = /^\{([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})\}$/iu;
7
+
8
+ /** @param value - Native braced GUID. @returns Identity in the workbook's lower-case form. */
9
+ export function readXlsxRevisionGuid(value?: string | null): string | undefined {
10
+ return value && guid.exec(value)?.[1]?.toLowerCase() || undefined;
11
+ }
12
+
13
+ /** @param attribute - Native revision metadata. @param namespace - UID namespace admitted for this node.
14
+ * @returns Whether the attribute is a passive identifier or its markup compatibility declaration. */
15
+ export function isXlsxRevisionAttribute(attribute: Attr, namespace: string): boolean {
16
+ if (attribute.namespaceURI === namespace && attribute.localName === "uid") return readXlsxRevisionGuid(attribute.value) !== undefined;
17
+ return attribute.namespaceURI === mc && attribute.localName === "Ignorable"
18
+ && attribute.value.trim().split(/\s+/u).every(prefix => {
19
+ const scope = attribute.ownerElement?.lookupNamespaceURI(prefix);
20
+ return scope === xlsxFilterUidNs || scope === xlsxTableColumnUidNs;
21
+ });
22
+ }
23
+
24
+ /** @param source - Previous filter element. @param target - Replacement filter preserving the same native owner. */
25
+ export function preserveXlsxFilterUid(source: Element | undefined, target: Element): void {
26
+ const attribute = source?.getAttributeNodeNS(xlsxFilterUidNs, "uid");
27
+ if (attribute && readXlsxRevisionGuid(attribute.value)) target.setAttributeNS(xlsxFilterUidNs, attribute.name, attribute.value);
28
+ }
@@ -0,0 +1,23 @@
1
+ import type { Attr, Element } from "@xmldom/xmldom";
2
+ import { children, relationshipNs } from "./xml";
3
+
4
+ /** @param node - Native element. @param names - Modeled local names. @param namespace - Default child namespace.
5
+ * @param overrides - Child names with a different namespace. @returns Whether all children are unique and modeled. */
6
+ export function hasKnownChildren(node: Element, names: readonly string[], namespace = node.namespaceURI,
7
+ overrides: Readonly<Record<string, string>> = {}): boolean {
8
+ const members = children(node);
9
+ return members.every(member => {
10
+ const name = member.localName ?? "";
11
+ return names.includes(name) && member.namespaceURI === (overrides[name] ?? namespace);
12
+ }) && members.length === new Set(members.map(member => member.localName)).size;
13
+ }
14
+
15
+ /** @param node - Native element. @param names - Modeled unqualified attributes.
16
+ * @param relationship - Whether the standard relationship ID is modeled.
17
+ * @param additional - Explicitly handled namespaced attributes in this owner. @returns Whether all attributes are known. */
18
+ export function hasKnownAttributes(node: Element, names: readonly string[], relationship = false, additional?: (attribute: Attr) => boolean): boolean {
19
+ return Array.from(node.attributes).every(attr => attr.namespaceURI === "http://www.w3.org/2000/xmlns/"
20
+ || (!attr.namespaceURI && names.includes(attr.localName ?? attr.name))
21
+ || (relationship && attr.namespaceURI === relationshipNs && attr.localName === "id")
22
+ || additional?.(attr) === true);
23
+ }
@@ -0,0 +1,13 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+
3
+ /** One relationship and its normalized internal part target. */
4
+ export interface PackageRelationship {
5
+ /** Relationship ID scoped to the owner part. */
6
+ readonly id: string;
7
+ /** Full relationship type URI. */
8
+ readonly type: string;
9
+ /** Internal archive path, or null for an external target. */
10
+ readonly path: string | null;
11
+ /** Source node retained for targeted updates. */
12
+ readonly element: Element;
13
+ }
@@ -0,0 +1,49 @@
1
+ import { DOMParser, onErrorStopParsing } from "@xmldom/xmldom";
2
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
3
+ import { afterEach, expect, it, vi } from "vitest";
4
+ import { createXlsx, openXlsx } from "../index";
5
+ import { spreadNs } from "./xml";
6
+
7
+ const worksheetPart = "xl/worksheets/sheet1.xml";
8
+ const source = createXlsx({ version: 1, revision: 0, id: "test", name: "Worksheet", sheets: [
9
+ { id: "sheet", name: "Sheet", cells: [
10
+ { row: 0, column: 0, input: { kind: "value", value: " Keep & <字> " } },
11
+ { row: 0, column: 1, input: { kind: "formula", formula: "=LEN(A1)" } }
12
+ ] }
13
+ ] });
14
+
15
+ afterEach(() => vi.unstubAllGlobals());
16
+
17
+ it("uses platform XML only for the worksheet read and retains the portable writer", () => {
18
+ const browser = new DOMParser({ onError: onErrorStopParsing });
19
+ const parse = vi.fn((xml: string, type: "application/xml") => browser.parseFromString(xml, type));
20
+ vi.stubGlobal("DOMParser", class { parseFromString = parse; });
21
+
22
+ const file = openXlsx("Example", source);
23
+ const sheet = file.snapshot.sheets[0]!;
24
+ expect(parse).toHaveBeenCalledExactlyOnceWith(expect.stringContaining("<sheetData>"), "application/xml");
25
+ expect(sheet.cells[0]?.input).toEqual({ kind: "value", value: " Keep & <字> " });
26
+ const changed = file.write({ ...file.snapshot, sheets: [{ ...sheet, cells: [
27
+ { row: 0, column: 0, input: { kind: "value", value: " 新值 " } }, sheet.cells[1]!
28
+ ] }] });
29
+ expect(parse).toHaveBeenCalledTimes(1);
30
+ expect(openXlsx("Reopened", changed).snapshot.sheets[0]?.cells).toEqual([
31
+ { row: 0, column: 0, input: { kind: "value", value: " 新值 " } },
32
+ { row: 0, column: 1, input: { kind: "formula", formula: "=LEN(A1)" } }
33
+ ]);
34
+ });
35
+
36
+ it("falls back from an embedded native parser error and rejects DTDs before either parser runs", () => {
37
+ const partial = new DOMParser().parseFromString(`<worksheet xmlns="${spreadNs}">
38
+ <parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml"/>
39
+ </worksheet>`, "application/xml");
40
+ const parse = vi.fn(() => partial);
41
+ vi.stubGlobal("DOMParser", class { parseFromString = parse; });
42
+
43
+ expect(openXlsx("Example", source).snapshot.sheets[0]?.cells).toHaveLength(2);
44
+ expect(parse).toHaveBeenCalledTimes(1);
45
+ const parts = unzipSync(source);
46
+ parts[worksheetPart] = strToU8("<!DOCTYPE worksheet>" + strFromU8(parts[worksheetPart]!));
47
+ expect(() => openXlsx("DTD", zipSync(parts))).toThrow(/包含不支持的文档类型声明/u);
48
+ expect(parse).toHaveBeenCalledTimes(1);
49
+ });