ooxml.js 2.4.1 → 2.5.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 (138) hide show
  1. package/README.md +11 -2
  2. package/dist/codec.cjs +28 -0
  3. package/dist/codec.d.cts +72 -0
  4. package/dist/codec.d.ts +72 -0
  5. package/dist/codec.js +24 -0
  6. package/dist/compact.cjs +162 -0
  7. package/dist/compact.d.cts +70 -0
  8. package/dist/compact.d.ts +70 -0
  9. package/dist/compact.js +152 -0
  10. package/dist/image/sniff.cjs +28 -0
  11. package/dist/image/sniff.d.cts +5 -0
  12. package/dist/image/sniff.d.ts +5 -0
  13. package/dist/image/sniff.js +27 -0
  14. package/dist/index.cjs +83 -3025
  15. package/dist/index.d.cts +22 -527
  16. package/dist/index.d.ts +22 -527
  17. package/dist/index.js +22 -2964
  18. package/dist/model/node.cjs +67 -0
  19. package/dist/model/node.d.cts +2 -0
  20. package/dist/model/node.d.ts +2 -0
  21. package/dist/model/node.js +58 -0
  22. package/dist/model/package.cjs +19 -0
  23. package/dist/model/package.d.cts +2 -0
  24. package/dist/model/package.d.ts +2 -0
  25. package/dist/model/package.js +15 -0
  26. package/dist/node-CkBWRjNR.d.cts +83 -0
  27. package/dist/node-CkBWRjNR.d.ts +83 -0
  28. package/dist/package-BUojjTXf.d.ts +114 -0
  29. package/dist/package-L24lkba-.d.cts +114 -0
  30. package/dist/package-io/read.cjs +33 -0
  31. package/dist/package-io/read.d.cts +5 -0
  32. package/dist/package-io/read.d.ts +5 -0
  33. package/dist/package-io/read.js +32 -0
  34. package/dist/package-io/write.cjs +18 -0
  35. package/dist/package-io/write.d.cts +5 -0
  36. package/dist/package-io/write.d.ts +5 -0
  37. package/dist/package-io/write.js +17 -0
  38. package/dist/typed/docx/read.cjs +332 -0
  39. package/dist/typed/docx/read.d.cts +52 -0
  40. package/dist/typed/docx/read.d.ts +52 -0
  41. package/dist/typed/docx/read.js +328 -0
  42. package/dist/typed/docx/styles.cjs +148 -0
  43. package/dist/typed/docx/styles.d.cts +29 -0
  44. package/dist/typed/docx/styles.d.ts +29 -0
  45. package/dist/typed/docx/styles.js +146 -0
  46. package/dist/typed/pptx/inherit.cjs +96 -0
  47. package/dist/typed/pptx/inherit.d.cts +30 -0
  48. package/dist/typed/pptx/inherit.d.ts +30 -0
  49. package/dist/typed/pptx/inherit.js +90 -0
  50. package/dist/typed/pptx/read.cjs +364 -0
  51. package/dist/typed/pptx/read.d.cts +44 -0
  52. package/dist/typed/pptx/read.d.ts +44 -0
  53. package/dist/typed/pptx/read.js +362 -0
  54. package/dist/typed/shared/color.cjs +85 -0
  55. package/dist/typed/shared/color.d.cts +9 -0
  56. package/dist/typed/shared/color.d.ts +9 -0
  57. package/dist/typed/shared/color.js +84 -0
  58. package/dist/typed/shared/drawingml.cjs +191 -0
  59. package/dist/typed/shared/drawingml.d.cts +40 -0
  60. package/dist/typed/shared/drawingml.d.ts +40 -0
  61. package/dist/typed/shared/drawingml.js +180 -0
  62. package/dist/typed/shared/metadata.cjs +44 -0
  63. package/dist/typed/shared/metadata.d.cts +16 -0
  64. package/dist/typed/shared/metadata.d.ts +16 -0
  65. package/dist/typed/shared/metadata.js +42 -0
  66. package/dist/typed/shared/source-path.cjs +18 -0
  67. package/dist/typed/shared/source-path.d.cts +5 -0
  68. package/dist/typed/shared/source-path.d.ts +5 -0
  69. package/dist/typed/shared/source-path.js +17 -0
  70. package/dist/typed/shared/units.cjs +55 -0
  71. package/dist/typed/shared/units.d.cts +20 -0
  72. package/dist/typed/shared/units.d.ts +20 -0
  73. package/dist/typed/shared/units.js +38 -0
  74. package/dist/typed/util.cjs +85 -0
  75. package/dist/typed/util.d.cts +18 -0
  76. package/dist/typed/util.d.ts +18 -0
  77. package/dist/typed/util.js +77 -0
  78. package/dist/typed/xlsx/a1.cjs +64 -0
  79. package/dist/typed/xlsx/a1.d.cts +19 -0
  80. package/dist/typed/xlsx/a1.d.ts +19 -0
  81. package/dist/typed/xlsx/a1.js +58 -0
  82. package/dist/typed/xlsx/build.cjs +456 -0
  83. package/dist/typed/xlsx/build.d.cts +6 -0
  84. package/dist/typed/xlsx/build.d.ts +6 -0
  85. package/dist/typed/xlsx/build.js +455 -0
  86. package/dist/typed/xlsx/content.cjs +257 -0
  87. package/dist/typed/xlsx/content.d.cts +6 -0
  88. package/dist/typed/xlsx/content.d.ts +6 -0
  89. package/dist/typed/xlsx/content.js +256 -0
  90. package/dist/typed/xlsx/defined-names.cjs +90 -0
  91. package/dist/typed/xlsx/defined-names.d.cts +20 -0
  92. package/dist/typed/xlsx/defined-names.d.ts +20 -0
  93. package/dist/typed/xlsx/defined-names.js +83 -0
  94. package/dist/typed/xlsx/print-settings.cjs +116 -0
  95. package/dist/typed/xlsx/print-settings.d.cts +8 -0
  96. package/dist/typed/xlsx/print-settings.d.ts +8 -0
  97. package/dist/typed/xlsx/print-settings.js +114 -0
  98. package/dist/typed/xlsx/shared-strings.cjs +35 -0
  99. package/dist/typed/xlsx/shared-strings.d.cts +12 -0
  100. package/dist/typed/xlsx/shared-strings.d.ts +12 -0
  101. package/dist/typed/xlsx/shared-strings.js +33 -0
  102. package/dist/typed/xlsx/units.cjs +21 -0
  103. package/dist/typed/xlsx/units.d.cts +8 -0
  104. package/dist/typed/xlsx/units.d.ts +8 -0
  105. package/dist/typed/xlsx/units.js +16 -0
  106. package/dist/typed/xlsx/util.cjs +53 -0
  107. package/dist/typed/xlsx/util.d.cts +10 -0
  108. package/dist/typed/xlsx/util.d.ts +10 -0
  109. package/dist/typed/xlsx/util.js +47 -0
  110. package/dist/typed/xlsx.cjs +140 -0
  111. package/dist/typed/xlsx.d.cts +43 -0
  112. package/dist/typed/xlsx.d.ts +43 -0
  113. package/dist/typed/xlsx.js +135 -0
  114. package/dist/util/base64.cjs +48 -0
  115. package/dist/util/base64.d.cts +5 -0
  116. package/dist/util/base64.d.ts +5 -0
  117. package/dist/util/base64.js +46 -0
  118. package/dist/xml/build.cjs +46 -0
  119. package/dist/xml/build.d.cts +5 -0
  120. package/dist/xml/build.d.ts +5 -0
  121. package/dist/xml/build.js +46 -0
  122. package/dist/xml/entities.cjs +7 -0
  123. package/dist/xml/entities.d.cts +4 -0
  124. package/dist/xml/entities.d.ts +4 -0
  125. package/dist/xml/entities.js +6 -0
  126. package/dist/xml/fragment.cjs +22 -0
  127. package/dist/xml/fragment.d.cts +6 -0
  128. package/dist/xml/fragment.d.ts +6 -0
  129. package/dist/xml/fragment.js +20 -0
  130. package/dist/xml/parse.cjs +88 -0
  131. package/dist/xml/parse.d.cts +5 -0
  132. package/dist/xml/parse.d.ts +5 -0
  133. package/dist/xml/parse.js +88 -0
  134. package/dist/zip.cjs +12 -0
  135. package/dist/zip.d.cts +5 -0
  136. package/dist/zip.d.ts +5 -0
  137. package/dist/zip.js +10 -0
  138. package/package.json +9 -1
package/dist/index.js CHANGED
@@ -1,2965 +1,23 @@
1
- import { z } from "zod";
2
- import { XMLBuilder, XMLParser } from "fast-xml-parser";
3
- import { unzipSync, zipSync } from "fflate";
4
- import { AlignmentSchema, BoxSchema, COLOR_BLACK, CONTENT_FORMAT_VERSION, CONTENT_FORMAT_VERSION as CONTENT_FORMAT_VERSION$1, ColorSchema, ContentBlockSchema, ContentCellValueSchema, ContentDocumentSchema, ContentImageBlockSchema, ContentListMembershipSchema, ContentPageBreakSchema, ContentParagraphSchema, ContentRunSchema, ContentSectionSchema, ContentSectionSchema as ContentSectionSchema$1, ContentShapeSchema, ContentSheetCellSchema, ContentSheetColumnSchema, ContentSheetImageSchema, ContentSheetPrintRangeSchema, ContentSheetPrintSettingsSchema, ContentSheetRepeatRangeSchema, ContentSheetRowSchema, ContentSheetSchema, ContentSlideSchema, ContentSlideSchema as ContentSlideSchema$1, ContentTableCellSchema, ContentTableRowSchema, ContentTableSchema, MarginsSchema, PAGE_SIZE_A4, PAGE_SIZE_A4 as PAGE_SIZE_A4$1, PAGE_SIZE_LETTER, PAGE_SIZE_LETTER as PAGE_SIZE_LETTER$1, PageSizeSchema, SLIDE_SIZE_STANDARD, SLIDE_SIZE_WIDESCREEN, SLIDE_SIZE_WIDESCREEN as SLIDE_SIZE_WIDESCREEN$1, colorToRgbHex, isContentBlock, rgbHexToColor, rgbHexToColor as rgbHexToColor$1 } from "document-schema.js";
5
- //#region src/model/node.ts
6
- const AttributeSchema = z.object({
7
- name: z.string(),
8
- value: z.string()
9
- });
10
- const XmlTextSchema = z.object({
11
- type: z.literal("text"),
12
- value: z.string()
13
- });
14
- const XmlCdataSchema = z.object({
15
- type: z.literal("cdata"),
16
- value: z.string()
17
- });
18
- const XmlCommentSchema = z.object({
19
- type: z.literal("comment"),
20
- value: z.string()
21
- });
22
- const XmlDeclarationSchema = z.object({
23
- type: z.literal("declaration"),
24
- attributes: z.array(AttributeSchema)
25
- });
26
- const XmlPiSchema = z.object({
27
- type: z.literal("pi"),
28
- target: z.string(),
29
- content: z.string()
30
- });
31
- function isRecord$1(value) {
32
- return typeof value === "object" && value !== null && !Array.isArray(value);
33
- }
34
- function isAttribute(value) {
35
- return isRecord$1(value) && typeof value.name === "string" && typeof value.value === "string";
36
- }
37
- function isXmlNode(value) {
38
- if (!isRecord$1(value)) return false;
39
- const t = value.type;
40
- if (t === "text" || t === "cdata" || t === "comment") return typeof value.value === "string";
41
- if (t === "declaration") return Array.isArray(value.attributes) && value.attributes.every(isAttribute);
42
- if (t === "pi") return typeof value.target === "string" && typeof value.content === "string";
43
- if (t === "element") return typeof value.tag === "string" && Array.isArray(value.attributes) && value.attributes.every(isAttribute) && Array.isArray(value.children) && value.children.every(isXmlNode);
44
- return false;
45
- }
46
- const XmlElementSchema = z.object({
47
- type: z.literal("element"),
48
- tag: z.string(),
49
- attributes: z.array(AttributeSchema),
50
- children: z.array(z.custom(isXmlNode))
51
- });
52
- const XmlNodeSchema = z.discriminatedUnion("type", [
53
- XmlTextSchema,
54
- XmlCdataSchema,
55
- XmlCommentSchema,
56
- XmlDeclarationSchema,
57
- XmlPiSchema,
58
- XmlElementSchema
59
- ]);
60
- //#endregion
61
- //#region src/model/package.ts
62
- const XmlPartSchema = z.object({
63
- kind: z.literal("xml"),
64
- nodes: z.array(XmlNodeSchema)
65
- });
66
- const BinaryPartSchema = z.object({
67
- kind: z.literal("binary"),
68
- base64: z.string()
69
- });
70
- const PartSchema = z.discriminatedUnion("kind", [XmlPartSchema, BinaryPartSchema]);
71
- const PackageSchema = z.object({ parts: z.record(z.string(), PartSchema) });
72
- //#endregion
73
- //#region src/util/base64.ts
74
- const TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
75
- const DECODE = (() => {
76
- const map = (/* @__PURE__ */ new Uint8Array(256)).fill(255);
77
- for (let i = 0; i < 64; i = i + 1) map[TABLE.charCodeAt(i)] = i;
78
- return map;
79
- })();
80
- function bytesToBase64(bytes) {
81
- let out = "";
82
- const len = bytes.length;
83
- for (let i = 0; i < len; i = i + 3) {
84
- const b0 = bytes[i];
85
- const b1 = i + 1 < len ? bytes[i + 1] : 0;
86
- const b2 = i + 2 < len ? bytes[i + 2] : 0;
87
- out += TABLE[b0 >> 2];
88
- out += TABLE[(b0 & 3) << 4 | b1 >> 4];
89
- out += i + 1 < len ? TABLE[(b1 & 15) << 2 | b2 >> 6] : "=";
90
- out += i + 2 < len ? TABLE[b2 & 63] : "=";
91
- }
92
- return out;
93
- }
94
- function base64ToBytes(b64) {
95
- const clean = b64.replace(/[^A-Za-z0-9+/=]/g, "");
96
- const len = clean.length;
97
- const out = new Uint8Array(len * 3 / 4 | 0);
98
- let p = 0;
99
- for (let i = 0; i < len; i = i + 4) {
100
- const c0 = DECODE[clean.charCodeAt(i)];
101
- const c1 = DECODE[clean.charCodeAt(i + 1)];
102
- const c2 = clean.charCodeAt(i + 2);
103
- const c3 = clean.charCodeAt(i + 3);
104
- if (c0 === 255 || c1 === 255) throw new Error("invalid base64 input");
105
- out[p++] = c0 << 2 | c1 >> 4;
106
- if (c2 !== 61) {
107
- const d2 = DECODE[c2];
108
- out[p++] = (c1 & 15) << 4 | d2 >> 2;
109
- if (c3 !== 61) {
110
- const d3 = DECODE[c3];
111
- out[p++] = (d2 & 3) << 6 | d3;
112
- }
113
- }
114
- }
115
- return out.subarray(0, p);
116
- }
117
- //#endregion
118
- //#region src/xml/parse.ts
119
- const PARSER = new XMLParser({
120
- preserveOrder: true,
121
- attributeNamePrefix: "@_",
122
- ignoreAttributes: false,
123
- textNodeName: "#text",
124
- cdataPropName: "__cdata",
125
- commentPropName: "__comment",
126
- processEntities: false,
127
- parseTagValue: false,
128
- trimValues: false
129
- });
130
- function parseXml(xml) {
131
- return parseNodes(PARSER.parse(xml));
132
- }
133
- function isRecord(value) {
134
- return typeof value === "object" && value !== null && !Array.isArray(value);
135
- }
136
- function isUnknownArray$1(value) {
137
- return Array.isArray(value);
138
- }
139
- function asString(value) {
140
- if (typeof value !== "string") throw new Error(`expected string while parsing XML, got ${typeof value}`);
141
- return value;
142
- }
143
- function parseNodes(raw) {
144
- if (!isUnknownArray$1(raw)) throw new Error("fast-xml-parser output was not an ordered array");
145
- return raw.map(parseNode);
146
- }
147
- function parseNode(raw) {
148
- if (!isRecord(raw)) throw new Error("fast-xml-parser node was not an object");
149
- let tagKey;
150
- for (const key of Object.keys(raw)) if (key !== ":@") {
151
- if (tagKey !== void 0) throw new Error("XML node had multiple tag keys");
152
- tagKey = key;
153
- }
154
- if (tagKey === void 0) throw new Error("XML node had no tag key");
155
- const attributes = parseAttributes(raw[":@"]);
156
- if (tagKey === "#text") return {
157
- type: "text",
158
- value: asString(raw["#text"])
159
- };
160
- if (tagKey === "__comment") return {
161
- type: "comment",
162
- value: scalarText(raw.__comment)
163
- };
164
- if (tagKey === "__cdata") return {
165
- type: "cdata",
166
- value: scalarText(raw.__cdata)
167
- };
168
- if (tagKey === "?xml") return {
169
- type: "declaration",
170
- attributes
171
- };
172
- if (tagKey.startsWith("?")) return {
173
- type: "pi",
174
- target: tagKey.slice(1),
175
- content: scalarText(raw[tagKey])
176
- };
177
- return {
178
- type: "element",
179
- tag: tagKey,
180
- attributes,
181
- children: parseNodes(raw[tagKey])
182
- };
183
- }
184
- function parseAttributes(raw) {
185
- if (raw === void 0) return [];
186
- if (!isRecord(raw)) throw new Error("XML attributes were not an object");
187
- const attrs = [];
188
- for (const key of Object.keys(raw)) {
189
- if (!key.startsWith("@_")) throw new Error(`unexpected attribute key without @_ prefix: ${key}`);
190
- attrs.push({
191
- name: key.slice(2),
192
- value: asString(raw[key])
193
- });
194
- }
195
- return attrs;
196
- }
197
- function scalarText(raw) {
198
- if (!isUnknownArray$1(raw) || raw.length === 0) throw new Error("expected a scalar-text wrapper array");
199
- const first = raw[0];
200
- if (!isRecord(first)) throw new Error("scalar-text wrapper was not an object");
201
- return asString(first["#text"]);
202
- }
203
- //#endregion
204
- //#region src/zip.ts
205
- function unzipPackage(bytes) {
206
- return unzipSync(bytes);
207
- }
208
- function zipPackage(parts) {
209
- return zipSync(parts);
210
- }
211
- //#endregion
212
- //#region src/package-io/read.ts
213
- function parsePackage(bytes) {
214
- const entries = unzipPackage(bytes);
215
- const parts = {};
216
- for (const [path, partBytes] of Object.entries(entries)) if (looksLikeXml(partBytes)) parts[path] = {
217
- kind: "xml",
218
- nodes: parseXml(new TextDecoder("utf-8").decode(partBytes))
219
- };
220
- else parts[path] = {
221
- kind: "binary",
222
- base64: bytesToBase64(partBytes)
223
- };
224
- return { parts };
225
- }
226
- function looksLikeXml(bytes) {
227
- let i = 0;
228
- if (bytes.length >= 3 && bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) i = 3;
229
- while (i < bytes.length) {
230
- const b = bytes[i];
231
- if (b === 32 || b === 9 || b === 10 || b === 13) {
232
- i = i + 1;
233
- continue;
234
- }
235
- return b === 60;
236
- }
237
- return false;
238
- }
239
- //#endregion
240
- //#region src/xml/build.ts
241
- const BUILDER = new XMLBuilder({
242
- preserveOrder: true,
243
- attributeNamePrefix: "@_",
244
- ignoreAttributes: false,
245
- textNodeName: "#text",
246
- cdataPropName: "__cdata",
247
- commentPropName: "__comment",
248
- processEntities: false,
249
- format: false,
250
- suppressEmptyNode: false
251
- });
252
- function buildXml(nodes) {
253
- const out = BUILDER.build(toOrdered(nodes));
254
- if (typeof out !== "string") throw new Error("XMLBuilder did not return a string");
255
- return out;
256
- }
257
- function toOrdered(nodes) {
258
- return nodes.map(toOrderedNode);
259
- }
260
- function attrsObject(attributes) {
261
- const obj = {};
262
- for (const a of attributes) obj[`@_${a.name}`] = a.value;
263
- return obj;
264
- }
265
- function toOrderedNode(node) {
266
- switch (node.type) {
267
- case "text": return { "#text": node.value };
268
- case "comment": return { __comment: [{ "#text": node.value }] };
269
- case "cdata": return { __cdata: [{ "#text": node.value }] };
270
- case "pi": return { [`?${node.target}`]: [{ "#text": node.content }] };
271
- case "declaration": return {
272
- "?xml": [{ "#text": "" }],
273
- ":@": attrsObject(node.attributes)
274
- };
275
- case "element": {
276
- const obj = { [node.tag]: toOrdered(node.children) };
277
- const attrs = attrsObject(node.attributes);
278
- if (Object.keys(attrs).length > 0) obj[":@"] = attrs;
279
- return obj;
280
- }
281
- }
282
- }
283
- //#endregion
284
- //#region src/package-io/write.ts
285
- function serializePackage(pkg) {
286
- const entries = {};
287
- for (const [path, part] of Object.entries(pkg.parts)) entries[path] = partToBytes(part);
288
- return zipPackage(entries);
289
- }
290
- function partToBytes(part) {
291
- switch (part.kind) {
292
- case "xml": return new TextEncoder().encode(buildXml(part.nodes));
293
- case "binary": return base64ToBytes(part.base64);
294
- }
295
- }
296
- //#endregion
297
- //#region src/codec.ts
298
- const xmlCodec = z.codec(z.string(), z.array(XmlNodeSchema), {
299
- decode: (xml) => parseXml(xml),
300
- encode: (nodes) => buildXml(nodes)
301
- });
302
- const packageCodec = z.codec(z.instanceof(Uint8Array), PackageSchema, {
303
- decode: (bytes) => parsePackage(bytes),
304
- encode: (pkg) => serializePackage(pkg)
305
- });
306
- function decodePackage(bytes) {
307
- return z.decode(packageCodec, bytes);
308
- }
309
- function encodePackage(pkg) {
310
- return z.encode(packageCodec, pkg);
311
- }
312
- //#endregion
313
- //#region src/xml/fragment.ts
314
- function el(tag, attrs = {}, children = []) {
315
- return {
316
- type: "element",
317
- tag,
318
- attributes: Object.entries(attrs).map(([name, value]) => ({
319
- name,
320
- value
321
- })),
322
- children
323
- };
324
- }
325
- function txt(value) {
326
- return {
327
- type: "text",
328
- value
329
- };
330
- }
331
- //#endregion
332
- //#region src/xml/entities.ts
333
- function encodeXmlText(value) {
334
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
335
- }
336
- //#endregion
337
- //#region src/typed/util.ts
338
- function* walk(nodes) {
339
- for (const node of nodes) {
340
- yield node;
341
- if (node.type === "element") yield* walk(node.children);
342
- }
343
- }
344
- function elementsWithTag(nodes, tag) {
345
- const out = [];
346
- for (const node of walk(nodes)) if (node.type === "element" && node.tag === tag) out.push(node);
347
- return out;
348
- }
349
- function childrenWithTag(element, tag) {
350
- const out = [];
351
- for (const child of element.children) if (child.type === "element" && child.tag === tag) out.push(child);
352
- return out;
353
- }
354
- function attr(element, name) {
355
- for (const a of element.attributes) if (a.name === name) return a.value;
356
- }
357
- function rootElement(part) {
358
- if (part?.kind !== "xml") return;
359
- for (const node of part.nodes) if (node.type === "element") return node;
360
- }
361
- function decodeEntities(value) {
362
- return value.replace(/&(?:amp|lt|gt|quot|apos);/g, (entity) => {
363
- switch (entity) {
364
- case "&amp;": return "&";
365
- case "&lt;": return "<";
366
- case "&gt;": return ">";
367
- case "&quot;": return "\"";
368
- case "&apos;": return "'";
369
- default: return entity;
370
- }
371
- });
372
- }
373
- function textContent(element) {
374
- let text = "";
375
- for (const node of walk(element.children)) if (node.type === "text" || node.type === "cdata") text += node.value;
376
- return decodeEntities(text);
377
- }
378
- function relsPathFor(partPath) {
379
- const lastSlash = partPath.lastIndexOf("/");
380
- return `${lastSlash === -1 ? "" : partPath.slice(0, lastSlash)}/_rels/${lastSlash === -1 ? partPath : partPath.slice(lastSlash + 1)}.rels`;
381
- }
382
- function resolveRelTarget$1(partPath, target) {
383
- if (target.startsWith("/")) return target.slice(1);
384
- const lastSlash = partPath.lastIndexOf("/");
385
- const baseDir = lastSlash === -1 ? "" : partPath.slice(0, lastSlash);
386
- const resolved = [];
387
- for (const segment of `${baseDir}/${target}`.split("/")) {
388
- if (segment === "" || segment === ".") continue;
389
- if (segment === "..") resolved.pop();
390
- else resolved.push(segment);
391
- }
392
- return resolved.join("/");
393
- }
394
- function resolveRelationships(pkg, partPath) {
395
- const map = /* @__PURE__ */ new Map();
396
- const rels = rootElement(pkg.parts[relsPathFor(partPath)]);
397
- if (rels === void 0) return map;
398
- for (const rel of childrenWithTag(rels, "Relationship")) {
399
- const id = attr(rel, "Id");
400
- const type = attr(rel, "Type");
401
- const target = attr(rel, "Target");
402
- if (id === void 0 || type === void 0 || target === void 0) continue;
403
- const targetMode = attr(rel, "TargetMode");
404
- map.set(id, {
405
- type,
406
- target: targetMode === "External" ? target : resolveRelTarget$1(partPath, target),
407
- targetMode
408
- });
409
- }
410
- return map;
411
- }
412
- //#endregion
413
- //#region src/compact.ts
414
- function isUnknownArray(value) {
415
- return Array.isArray(value);
416
- }
417
- function isCompactAttrPairs(value) {
418
- return isUnknownArray(value) && value.every((v) => typeof v === "number");
419
- }
420
- function isCompactXmlNode(value) {
421
- if (!isUnknownArray(value)) return false;
422
- const code = value[0];
423
- if (code === 1 || code === 2 || code === 3) return value.length === 2 && typeof value[1] === "number";
424
- if (code === 4) return value.length === 2 && isCompactAttrPairs(value[1]);
425
- if (code === 5) return value.length === 3 && typeof value[1] === "number" && typeof value[2] === "number";
426
- if (code === 0) return value.length === 4 && typeof value[1] === "number" && isCompactAttrPairs(value[2]) && Array.isArray(value[3]) && value[3].every(isCompactXmlNode);
427
- return false;
428
- }
429
- const CompactXmlNodeSchema = z.custom(isCompactXmlNode);
430
- const CompactPartSchema = z.union([z.array(CompactXmlNodeSchema), z.number()]);
431
- const CompactPackageSchema = z.object({
432
- s: z.array(z.string()),
433
- p: z.record(z.string(), CompactPartSchema)
434
- });
435
- var StringTable = class {
436
- indices = /* @__PURE__ */ new Map();
437
- strings = [];
438
- intern(value) {
439
- const existing = this.indices.get(value);
440
- if (existing !== void 0) return existing;
441
- const index = this.strings.length;
442
- this.indices.set(value, index);
443
- this.strings.push(value);
444
- return index;
445
- }
446
- };
447
- function encodeAttrs(attributes, table) {
448
- const pairs = [];
449
- for (const attribute of attributes) pairs.push(table.intern(attribute.name), table.intern(attribute.value));
450
- return pairs;
451
- }
452
- function encodeNode(node, table) {
453
- switch (node.type) {
454
- case "text": return [1, table.intern(node.value)];
455
- case "cdata": return [2, table.intern(node.value)];
456
- case "comment": return [3, table.intern(node.value)];
457
- case "declaration": return [4, encodeAttrs(node.attributes, table)];
458
- case "pi": return [
459
- 5,
460
- table.intern(node.target),
461
- table.intern(node.content)
462
- ];
463
- case "element": return [
464
- 0,
465
- table.intern(node.tag),
466
- encodeAttrs(node.attributes, table),
467
- node.children.map((child) => encodeNode(child, table))
468
- ];
469
- }
470
- }
471
- function packageToCompact(pkg) {
472
- const table = new StringTable();
473
- const p = {};
474
- for (const [path, part] of Object.entries(pkg.parts)) p[path] = part.kind === "binary" ? table.intern(part.base64) : part.nodes.map((node) => encodeNode(node, table));
475
- return {
476
- s: table.strings,
477
- p
478
- };
479
- }
480
- function stringAt(strings, index) {
481
- const value = strings[index];
482
- if (value === void 0) throw new Error(`fromCompact: string table index ${index} is out of range`);
483
- return value;
484
- }
485
- function decodeAttrs(pairs, strings) {
486
- const attributes = [];
487
- for (let i = 0; i < pairs.length; i += 2) {
488
- const nameIdx = pairs[i];
489
- const valueIdx = pairs[i + 1];
490
- if (nameIdx === void 0 || valueIdx === void 0) throw new Error("fromCompact: attribute index pairs array has odd length");
491
- attributes.push({
492
- name: stringAt(strings, nameIdx),
493
- value: stringAt(strings, valueIdx)
494
- });
495
- }
496
- return attributes;
497
- }
498
- function decodeNode(node, strings) {
499
- switch (node[0]) {
500
- case 1: return {
501
- type: "text",
502
- value: stringAt(strings, node[1])
503
- };
504
- case 2: return {
505
- type: "cdata",
506
- value: stringAt(strings, node[1])
507
- };
508
- case 3: return {
509
- type: "comment",
510
- value: stringAt(strings, node[1])
511
- };
512
- case 4: return {
513
- type: "declaration",
514
- attributes: decodeAttrs(node[1], strings)
515
- };
516
- case 5: return {
517
- type: "pi",
518
- target: stringAt(strings, node[1]),
519
- content: stringAt(strings, node[2])
520
- };
521
- case 0: return {
522
- type: "element",
523
- tag: stringAt(strings, node[1]),
524
- attributes: decodeAttrs(node[2], strings),
525
- children: node[3].map((child) => decodeNode(child, strings))
526
- };
527
- }
528
- }
529
- function compactToPackage(cpkg) {
530
- const parts = {};
531
- for (const [path, part] of Object.entries(cpkg.p)) parts[path] = typeof part === "number" ? {
532
- kind: "binary",
533
- base64: stringAt(cpkg.s, part)
534
- } : {
535
- kind: "xml",
536
- nodes: part.map((node) => decodeNode(node, cpkg.s))
537
- };
538
- return { parts };
539
- }
540
- const compactCodec = z.codec(PackageSchema, CompactPackageSchema, {
541
- decode: (pkg) => packageToCompact(pkg),
542
- encode: (cpkg) => compactToPackage(cpkg)
543
- });
544
- function toCompact(pkg) {
545
- return z.decode(compactCodec, pkg);
546
- }
547
- function fromCompact(cpkg) {
548
- return z.encode(compactCodec, cpkg);
549
- }
550
- const compactPackageCodec = z.codec(z.instanceof(Uint8Array), CompactPackageSchema, {
551
- decode: (bytes) => toCompact(decodePackage(bytes)),
552
- encode: (cpkg) => encodePackage(fromCompact(cpkg))
553
- });
554
- function decodeCompactPackage(bytes) {
555
- return z.decode(compactPackageCodec, bytes);
556
- }
557
- function encodeCompactPackage(cpkg) {
558
- return z.encode(compactPackageCodec, cpkg);
559
- }
560
- //#endregion
561
- //#region src/typed/shared/color.ts
562
- const OOXML_PERCENT_SCALE = 1e5;
563
- function clamp01(x) {
564
- return Math.max(0, Math.min(1, x));
565
- }
566
- function srgbToLinear(c) {
567
- return c <= .04045 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;
568
- }
569
- function linearToSrgb(c) {
570
- return c <= .0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - .055;
571
- }
572
- function applyShadeOrTint(color, kind, value) {
573
- const pct = value / OOXML_PERCENT_SCALE;
574
- const transform = kind === "shade" ? (linear) => linear * pct : (linear) => 1 - (1 - linear) * pct;
575
- return {
576
- r: clamp01(linearToSrgb(transform(srgbToLinear(color.r)))),
577
- g: clamp01(linearToSrgb(transform(srgbToLinear(color.g)))),
578
- b: clamp01(linearToSrgb(transform(srgbToLinear(color.b))))
579
- };
580
- }
581
- function rgbToHsl(color) {
582
- const { r, g, b } = color;
583
- const max = Math.max(r, g, b);
584
- const min = Math.min(r, g, b);
585
- const l = (max + min) / 2;
586
- if (max === min) return {
587
- h: 0,
588
- s: 0,
589
- l
590
- };
591
- const d = max - min;
592
- const s = l > .5 ? d / (2 - max - min) : d / (max + min);
593
- let h;
594
- if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
595
- else if (max === g) h = (b - r) / d + 2;
596
- else h = (r - g) / d + 4;
597
- return {
598
- h: h * 60,
599
- s,
600
- l
601
- };
602
- }
603
- function hueToRgbComponent(p, q, hue) {
604
- let t = hue;
605
- if (t < 0) t += 1;
606
- if (t > 1) t -= 1;
607
- if (t < 1 / 6) return p + (q - p) * 6 * t;
608
- if (t < 1 / 2) return q;
609
- if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
610
- return p;
611
- }
612
- function hslToRgb(hsl) {
613
- const { h, s, l } = hsl;
614
- if (s === 0) return {
615
- r: l,
616
- g: l,
617
- b: l
618
- };
619
- const q = l < .5 ? l * (1 + s) : l + s - l * s;
620
- const p = 2 * l - q;
621
- const hk = h / 360;
622
- return {
623
- r: clamp01(hueToRgbComponent(p, q, hk + 1 / 3)),
624
- g: clamp01(hueToRgbComponent(p, q, hk)),
625
- b: clamp01(hueToRgbComponent(p, q, hk - 1 / 3))
626
- };
627
- }
628
- function applyLumModOrOff(color, kind, value) {
629
- const hsl = rgbToHsl(color);
630
- const pct = value / OOXML_PERCENT_SCALE;
631
- const l = clamp01(kind === "lumMod" ? hsl.l * pct : hsl.l + pct);
632
- return hslToRgb({
633
- ...hsl,
634
- l
635
- });
636
- }
637
- function applyColorTransforms(base, transforms) {
638
- let color = base;
639
- for (const t of transforms) if (t.kind === "shade" || t.kind === "tint") color = applyShadeOrTint(color, t.kind, t.value);
640
- for (const t of transforms) if (t.kind === "lumMod" || t.kind === "lumOff") color = applyLumModOrOff(color, t.kind, t.value);
641
- return color;
642
- }
643
- //#endregion
644
- //#region src/typed/shared/metadata.ts
645
- const DocumentMetadataSchema = z.object({
646
- title: z.string().optional(),
647
- author: z.string().optional(),
648
- subject: z.string().optional(),
649
- keywords: z.array(z.string()).optional(),
650
- creator: z.string().optional(),
651
- createdIso: z.string().optional(),
652
- modifiedIso: z.string().optional()
653
- });
654
- const CORE_PROPERTIES_PATH = "docProps/core.xml";
655
- const APP_PROPERTIES_PATH = "docProps/app.xml";
656
- function firstElementText(root, tag) {
657
- if (root === void 0) return;
658
- const element = childrenWithTag(root, tag)[0];
659
- if (element === void 0) return;
660
- const text = textContent(element);
661
- return text.length > 0 ? text : void 0;
662
- }
663
- function readKeywords(core) {
664
- const raw = firstElementText(core, "cp:keywords");
665
- if (raw === void 0) return;
666
- const parts = raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
667
- return parts.length > 0 ? parts : void 0;
668
- }
669
- function readCoreProperties(pkg) {
670
- const core = rootElement(pkg.parts[CORE_PROPERTIES_PATH]);
671
- const app = rootElement(pkg.parts[APP_PROPERTIES_PATH]);
672
- return {
673
- title: firstElementText(core, "dc:title"),
674
- author: firstElementText(core, "dc:creator"),
675
- subject: firstElementText(core, "dc:subject"),
676
- keywords: readKeywords(core),
677
- creator: firstElementText(app, "Application"),
678
- createdIso: firstElementText(core, "dcterms:created"),
679
- modifiedIso: firstElementText(core, "dcterms:modified")
680
- };
681
- }
682
- //#endregion
683
- //#region src/image/sniff.ts
684
- const PNG_SIGNATURE = [
685
- 137,
686
- 80,
687
- 78,
688
- 71,
689
- 13,
690
- 10,
691
- 26,
692
- 10
693
- ];
694
- const JPEG_SIGNATURE = [
695
- 255,
696
- 216,
697
- 255
698
- ];
699
- function startsWith(bytes, signature) {
700
- if (bytes.length < signature.length) return false;
701
- for (let i = 0; i < signature.length; i++) if (bytes[i] !== signature[i]) return false;
702
- return true;
703
- }
704
- function sniffImageFormat(bytes) {
705
- if (startsWith(bytes, PNG_SIGNATURE)) return "png";
706
- if (startsWith(bytes, JPEG_SIGNATURE)) return "jpeg";
707
- }
708
- const EMU_PER_POINT = 914400 / 72;
709
- function emuToPt(emu) {
710
- return emu / EMU_PER_POINT;
711
- }
712
- function twipsToPt(twips) {
713
- return twips / 20;
714
- }
715
- function halfPointsToPt(halfPoints) {
716
- return halfPoints / 2;
717
- }
718
- function drawingMlFontSizeToPt(hundredths) {
719
- return hundredths / 100;
720
- }
721
- function lineUnitsToMultiplier(lineUnits) {
722
- return lineUnits / 240;
723
- }
724
- //#endregion
725
- //#region src/typed/shared/drawingml.ts
726
- const ROTATION_UNITS_PER_DEGREE = 6e4;
727
- function readXfrm(xfrm) {
728
- if (xfrm === void 0) return;
729
- const off = childrenWithTag(xfrm, "a:off")[0];
730
- const ext = childrenWithTag(xfrm, "a:ext")[0];
731
- if (off === void 0 || ext === void 0) return;
732
- const x = attr(off, "x");
733
- const y = attr(off, "y");
734
- const cx = attr(ext, "cx");
735
- const cy = attr(ext, "cy");
736
- if (x === void 0 || y === void 0 || cx === void 0 || cy === void 0) return;
737
- const rot = attr(xfrm, "rot");
738
- return {
739
- xPt: emuToPt(Number(x)),
740
- yPt: emuToPt(Number(y)),
741
- widthPt: emuToPt(Number(cx)),
742
- heightPt: emuToPt(Number(cy)),
743
- rotationDeg: rot === void 0 ? 0 : Number(rot) / ROTATION_UNITS_PER_DEGREE,
744
- flipH: attr(xfrm, "flipH") === "1",
745
- flipV: attr(xfrm, "flipV") === "1"
746
- };
747
- }
748
- const CLR_SCHEME_SLOTS = [
749
- "dk1",
750
- "lt1",
751
- "dk2",
752
- "lt2",
753
- "accent1",
754
- "accent2",
755
- "accent3",
756
- "accent4",
757
- "accent5",
758
- "accent6",
759
- "hlink",
760
- "folHlink"
761
- ];
762
- function readThemeSlotColor(colorEl) {
763
- if (colorEl.tag === "a:srgbClr") {
764
- const val = attr(colorEl, "val");
765
- return val === void 0 ? void 0 : rgbHexToColor$1(val);
766
- }
767
- if (colorEl.tag === "a:sysClr") {
768
- const lastClr = attr(colorEl, "lastClr");
769
- if (lastClr !== void 0) return rgbHexToColor$1(lastClr);
770
- return attr(colorEl, "val") === "window" ? {
771
- r: 1,
772
- g: 1,
773
- b: 1
774
- } : {
775
- r: 0,
776
- g: 0,
777
- b: 0
778
- };
779
- }
780
- }
781
- function readClrScheme(clrSchemeEl) {
782
- const map = /* @__PURE__ */ new Map();
783
- for (const slot of CLR_SCHEME_SLOTS) {
784
- const wrapper = childrenWithTag(clrSchemeEl, `a:${slot}`)[0];
785
- if (wrapper === void 0) continue;
786
- const colorEl = wrapper.children.find((c) => c.type === "element");
787
- if (colorEl === void 0) continue;
788
- const color = readThemeSlotColor(colorEl);
789
- if (color !== void 0) map.set(slot, color);
790
- }
791
- return map;
792
- }
793
- function readSchemeFont(fontSchemeEl, tag) {
794
- if (fontSchemeEl === void 0) return;
795
- const fontEl = childrenWithTag(fontSchemeEl, tag)[0];
796
- const latin = fontEl === void 0 ? void 0 : childrenWithTag(fontEl, "a:latin")[0];
797
- return latin === void 0 ? void 0 : attr(latin, "typeface");
798
- }
799
- const DEFAULT_THEME_FONT = "Calibri";
800
- const EMPTY_THEME = {
801
- colorScheme: /* @__PURE__ */ new Map(),
802
- majorFont: DEFAULT_THEME_FONT,
803
- minorFont: DEFAULT_THEME_FONT
804
- };
805
- function readTheme(themeRoot) {
806
- const clrSchemeEl = elementsWithTag([themeRoot], "a:clrScheme")[0];
807
- const colorScheme = clrSchemeEl === void 0 ? /* @__PURE__ */ new Map() : readClrScheme(clrSchemeEl);
808
- const fontSchemeEl = elementsWithTag([themeRoot], "a:fontScheme")[0];
809
- return {
810
- colorScheme,
811
- majorFont: readSchemeFont(fontSchemeEl, "a:majorFont") ?? DEFAULT_THEME_FONT,
812
- minorFont: readSchemeFont(fontSchemeEl, "a:minorFont") ?? DEFAULT_THEME_FONT
813
- };
814
- }
815
- function resolveThemeFontReference(typeface, theme) {
816
- if (typeface === "+mj-lt") return theme.majorFont;
817
- if (typeface === "+mn-lt") return theme.minorFont;
818
- return typeface;
819
- }
820
- function readColorMap(clrMapEl) {
821
- const map = /* @__PURE__ */ new Map();
822
- if (clrMapEl === void 0) return map;
823
- for (const a of clrMapEl.attributes) map.set(a.name, a.value);
824
- return map;
825
- }
826
- function resolveSchemeColorSlot(schemeVal, colorMap) {
827
- return colorMap.get(schemeVal) ?? schemeVal;
828
- }
829
- const COLOR_TRANSFORM_TAGS = /* @__PURE__ */ new Map([
830
- ["a:shade", "shade"],
831
- ["a:tint", "tint"],
832
- ["a:lumMod", "lumMod"],
833
- ["a:lumOff", "lumOff"]
834
- ]);
835
- function readColorTransforms(container) {
836
- const transforms = [];
837
- for (const child of container.children) {
838
- if (child.type !== "element") continue;
839
- const kind = COLOR_TRANSFORM_TAGS.get(child.tag);
840
- if (kind === void 0) continue;
841
- const val = attr(child, "val");
842
- if (val === void 0) continue;
843
- transforms.push({
844
- kind,
845
- value: Number(val)
846
- });
847
- }
848
- return transforms;
849
- }
850
- function readSchemeColor(schemeClrEl, colorMap, theme) {
851
- const val = attr(schemeClrEl, "val");
852
- if (val === void 0) return;
853
- const base = theme.colorScheme.get(resolveSchemeColorSlot(val, colorMap));
854
- return base === void 0 ? void 0 : applyColorTransforms(base, readColorTransforms(schemeClrEl));
855
- }
856
- function readSrgbColor(srgbClrEl) {
857
- const val = attr(srgbClrEl, "val");
858
- return val === void 0 ? void 0 : applyColorTransforms(rgbHexToColor$1(val), readColorTransforms(srgbClrEl));
859
- }
860
- function readSolidFillColor(solidFillEl, colorMap, theme) {
861
- if (solidFillEl === void 0) return;
862
- const schemeClr = childrenWithTag(solidFillEl, "a:schemeClr")[0];
863
- if (schemeClr !== void 0) return readSchemeColor(schemeClr, colorMap, theme);
864
- const srgbClr = childrenWithTag(solidFillEl, "a:srgbClr")[0];
865
- return srgbClr === void 0 ? void 0 : readSrgbColor(srgbClr);
866
- }
867
- function readGroupXfrm(xfrm) {
868
- const base = readXfrm(xfrm);
869
- if (base === void 0 || xfrm === void 0) return;
870
- const chOff = childrenWithTag(xfrm, "a:chOff")[0];
871
- const chExt = childrenWithTag(xfrm, "a:chExt")[0];
872
- if (chOff === void 0 || chExt === void 0) return;
873
- const cx = attr(chOff, "x");
874
- const cy = attr(chOff, "y");
875
- const ccx = attr(chExt, "cx");
876
- const ccy = attr(chExt, "cy");
877
- if (cx === void 0 || cy === void 0 || ccx === void 0 || ccy === void 0) return;
878
- return {
879
- offXPt: base.xPt,
880
- offYPt: base.yPt,
881
- extWidthPt: base.widthPt,
882
- extHeightPt: base.heightPt,
883
- childOffXPt: emuToPt(Number(cx)),
884
- childOffYPt: emuToPt(Number(cy)),
885
- childExtWidthPt: emuToPt(Number(ccx)),
886
- childExtHeightPt: emuToPt(Number(ccy))
887
- };
888
- }
889
- function applyGroupTransform(group, childFrame) {
890
- const scaleX = group.childExtWidthPt === 0 ? 1 : group.extWidthPt / group.childExtWidthPt;
891
- const scaleY = group.childExtHeightPt === 0 ? 1 : group.extHeightPt / group.childExtHeightPt;
892
- return {
893
- xPt: group.offXPt + (childFrame.xPt - group.childOffXPt) * scaleX,
894
- yPt: group.offYPt + (childFrame.yPt - group.childOffYPt) * scaleY,
895
- widthPt: childFrame.widthPt * scaleX,
896
- heightPt: childFrame.heightPt * scaleY
897
- };
898
- }
899
- //#endregion
900
- //#region src/typed/shared/source-path.ts
901
- function assignSourcePaths(blocks, prefix) {
902
- blocks.forEach((block, blockIndex) => {
903
- const blockPath = `${prefix}.blocks[${blockIndex}]`;
904
- block.sourcePath = blockPath;
905
- if (block.kind === "paragraph") block.runs.forEach((run, runIndex) => {
906
- run.sourcePath = `${blockPath}.runs[${runIndex}]`;
907
- });
908
- else if (block.kind === "table") block.rows.forEach((row, rowIndex) => {
909
- row.cells.forEach((cell, cellIndex) => {
910
- assignSourcePaths(cell.blocks, `${blockPath}.rows[${rowIndex}].cells[${cellIndex}]`);
911
- });
912
- });
913
- });
914
- }
915
- //#endregion
916
- //#region src/typed/docx/styles.ts
917
- function mergeParagraphLayer(base, layer) {
918
- return {
919
- alignment: layer.alignment ?? base.alignment,
920
- spacingBeforePt: layer.spacingBeforePt ?? base.spacingBeforePt,
921
- spacingAfterPt: layer.spacingAfterPt ?? base.spacingAfterPt,
922
- lineSpacing: layer.lineSpacing ?? base.lineSpacing,
923
- indentLeftPt: layer.indentLeftPt ?? base.indentLeftPt,
924
- indentFirstLinePt: layer.indentFirstLinePt ?? base.indentFirstLinePt
925
- };
926
- }
927
- function mergeRunLayer(base, layer) {
928
- return {
929
- bold: layer.bold ?? base.bold,
930
- italic: layer.italic ?? base.italic,
931
- underline: layer.underline ?? base.underline,
932
- strike: layer.strike ?? base.strike,
933
- fontFamily: layer.fontFamily ?? base.fontFamily,
934
- sizePt: layer.sizePt ?? base.sizePt,
935
- color: layer.color ?? base.color
936
- };
937
- }
938
- function readToggle$1(el) {
939
- if (el === void 0) return;
940
- const val = attr(el, "w:val");
941
- return val === void 0 || val !== "0" && val !== "false" && val !== "off";
942
- }
943
- function readUnderline(u) {
944
- if (u === void 0) return;
945
- const val = attr(u, "w:val");
946
- return val !== void 0 && val !== "none";
947
- }
948
- function readRunColor(colorEl) {
949
- if (colorEl === void 0) return;
950
- const val = attr(colorEl, "w:val");
951
- return val === void 0 || val === "auto" ? void 0 : rgbHexToColor$1(val);
952
- }
953
- function readRunFontFamily(rFonts, theme) {
954
- if (rFonts === void 0) return;
955
- const ascii = attr(rFonts, "w:ascii");
956
- if (ascii !== void 0) return ascii;
957
- const asciiTheme = attr(rFonts, "w:asciiTheme");
958
- if (asciiTheme === "majorHAnsi" || asciiTheme === "majorAscii") return theme.majorFont;
959
- if (asciiTheme === "minorHAnsi" || asciiTheme === "minorAscii") return theme.minorFont;
960
- }
961
- function readRunPropertiesLayer(rPr, theme) {
962
- if (rPr === void 0) return {};
963
- const sz = childrenWithTag(rPr, "w:sz")[0];
964
- const szVal = sz === void 0 ? void 0 : attr(sz, "w:val");
965
- return {
966
- bold: readToggle$1(childrenWithTag(rPr, "w:b")[0]),
967
- italic: readToggle$1(childrenWithTag(rPr, "w:i")[0]),
968
- underline: readUnderline(childrenWithTag(rPr, "w:u")[0]),
969
- strike: readToggle$1(childrenWithTag(rPr, "w:strike")[0]),
970
- fontFamily: readRunFontFamily(childrenWithTag(rPr, "w:rFonts")[0], theme),
971
- sizePt: szVal === void 0 ? void 0 : halfPointsToPt(Number(szVal)),
972
- color: readRunColor(childrenWithTag(rPr, "w:color")[0])
973
- };
974
- }
975
- function readAlignment$1(jc) {
976
- const val = jc === void 0 ? void 0 : attr(jc, "w:val");
977
- if (val === "left" || val === "start") return "left";
978
- if (val === "center") return "center";
979
- if (val === "right" || val === "end") return "right";
980
- if (val === "both" || val === "distribute") return "justify";
981
- }
982
- function readParagraphPropertiesLayer(pPr) {
983
- if (pPr === void 0) return {};
984
- const spacing = childrenWithTag(pPr, "w:spacing")[0];
985
- const before = spacing === void 0 ? void 0 : attr(spacing, "w:before");
986
- const after = spacing === void 0 ? void 0 : attr(spacing, "w:after");
987
- const line = spacing === void 0 ? void 0 : attr(spacing, "w:line");
988
- const lineRule = spacing === void 0 ? void 0 : attr(spacing, "w:lineRule");
989
- const ind = childrenWithTag(pPr, "w:ind")[0];
990
- const left = ind === void 0 ? void 0 : attr(ind, "w:left") ?? attr(ind, "w:start");
991
- const firstLine = ind === void 0 ? void 0 : attr(ind, "w:firstLine");
992
- const hanging = ind === void 0 ? void 0 : attr(ind, "w:hanging");
993
- return {
994
- alignment: readAlignment$1(childrenWithTag(pPr, "w:jc")[0]),
995
- spacingBeforePt: before === void 0 ? void 0 : twipsToPt(Number(before)),
996
- spacingAfterPt: after === void 0 ? void 0 : twipsToPt(Number(after)),
997
- lineSpacing: line === void 0 || lineRule === "exact" || lineRule === "atLeast" ? void 0 : lineUnitsToMultiplier(Number(line)),
998
- indentLeftPt: left === void 0 ? void 0 : twipsToPt(Number(left)),
999
- indentFirstLinePt: firstLine !== void 0 ? twipsToPt(Number(firstLine)) : hanging !== void 0 ? -twipsToPt(Number(hanging)) : void 0
1000
- };
1001
- }
1002
- function findStyle(stylesRoot, styleId, type) {
1003
- return elementsWithTag([stylesRoot], "w:style").find((s) => attr(s, "w:type") === type && attr(s, "w:styleId") === styleId);
1004
- }
1005
- function findDefaultStyle(stylesRoot, type) {
1006
- return elementsWithTag([stylesRoot], "w:style").find((s) => attr(s, "w:type") === type && attr(s, "w:default") === "1");
1007
- }
1008
- function resolveBasedOnChain(stylesRoot, styleId, type) {
1009
- const chain = [];
1010
- const visited = /* @__PURE__ */ new Set();
1011
- let currentId = styleId;
1012
- while (currentId !== void 0 && !visited.has(currentId)) {
1013
- visited.add(currentId);
1014
- const style = findStyle(stylesRoot, currentId, type);
1015
- if (style === void 0) break;
1016
- chain.unshift(style);
1017
- const basedOn = childrenWithTag(style, "w:basedOn")[0];
1018
- currentId = basedOn === void 0 ? void 0 : attr(basedOn, "w:val");
1019
- }
1020
- return chain;
1021
- }
1022
- function docDefaultsElement(stylesRoot, wrapperTag, innerTag) {
1023
- const docDefaults = stylesRoot === void 0 ? void 0 : childrenWithTag(stylesRoot, "w:docDefaults")[0];
1024
- const wrapper = docDefaults === void 0 ? void 0 : childrenWithTag(docDefaults, wrapperTag)[0];
1025
- return wrapper === void 0 ? void 0 : childrenWithTag(wrapper, innerTag)[0];
1026
- }
1027
- function resolveParagraphProperties(paragraph, context) {
1028
- const pPr = childrenWithTag(paragraph, "w:pPr")[0];
1029
- const pStyleEl = pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:pStyle")[0];
1030
- const styleId = pStyleEl === void 0 ? void 0 : attr(pStyleEl, "w:val");
1031
- let resolved = readParagraphPropertiesLayer(docDefaultsElement(context.stylesRoot, "w:pPrDefault", "w:pPr"));
1032
- if (context.stylesRoot !== void 0) {
1033
- const defaultStyle = findDefaultStyle(context.stylesRoot, "paragraph");
1034
- if (defaultStyle !== void 0) resolved = mergeParagraphLayer(resolved, readParagraphPropertiesLayer(childrenWithTag(defaultStyle, "w:pPr")[0]));
1035
- if (styleId !== void 0) for (const style of resolveBasedOnChain(context.stylesRoot, styleId, "paragraph")) resolved = mergeParagraphLayer(resolved, readParagraphPropertiesLayer(childrenWithTag(style, "w:pPr")[0]));
1036
- }
1037
- return mergeParagraphLayer(resolved, readParagraphPropertiesLayer(pPr));
1038
- }
1039
- function resolveRunProperties(run, paragraph, context) {
1040
- const pPr = childrenWithTag(paragraph, "w:pPr")[0];
1041
- const pStyleEl = pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:pStyle")[0];
1042
- const pStyleId = pStyleEl === void 0 ? void 0 : attr(pStyleEl, "w:val");
1043
- let resolved = readRunPropertiesLayer(docDefaultsElement(context.stylesRoot, "w:rPrDefault", "w:rPr"), context.theme);
1044
- if (context.stylesRoot !== void 0) {
1045
- const defaultStyle = findDefaultStyle(context.stylesRoot, "paragraph");
1046
- if (defaultStyle !== void 0) resolved = mergeRunLayer(resolved, readRunPropertiesLayer(childrenWithTag(defaultStyle, "w:rPr")[0], context.theme));
1047
- if (pStyleId !== void 0) for (const style of resolveBasedOnChain(context.stylesRoot, pStyleId, "paragraph")) resolved = mergeRunLayer(resolved, readRunPropertiesLayer(childrenWithTag(style, "w:rPr")[0], context.theme));
1048
- }
1049
- const paragraphMarkRPr = pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:rPr")[0];
1050
- resolved = mergeRunLayer(resolved, readRunPropertiesLayer(paragraphMarkRPr, context.theme));
1051
- const rPr = childrenWithTag(run, "w:rPr")[0];
1052
- const rStyleEl = rPr === void 0 ? void 0 : childrenWithTag(rPr, "w:rStyle")[0];
1053
- const rStyleId = rStyleEl === void 0 ? void 0 : attr(rStyleEl, "w:val");
1054
- if (context.stylesRoot !== void 0 && rStyleId !== void 0) for (const style of resolveBasedOnChain(context.stylesRoot, rStyleId, "character")) resolved = mergeRunLayer(resolved, readRunPropertiesLayer(childrenWithTag(style, "w:rPr")[0], context.theme));
1055
- return mergeRunLayer(resolved, readRunPropertiesLayer(rPr, context.theme));
1056
- }
1057
- //#endregion
1058
- //#region src/typed/docx/read.ts
1059
- const CommentSchema = z.object({
1060
- author: z.string().optional(),
1061
- text: z.string()
1062
- });
1063
- const FootnoteSchema = z.object({
1064
- type: z.string().optional(),
1065
- text: z.string()
1066
- });
1067
- const DocxDocumentSchema = z.object({
1068
- metadata: DocumentMetadataSchema,
1069
- sections: z.array(ContentSectionSchema$1),
1070
- comments: z.array(CommentSchema),
1071
- footnotes: z.array(FootnoteSchema),
1072
- headers: z.array(z.string()),
1073
- footers: z.array(z.string())
1074
- });
1075
- const DOCUMENT_PART_PATH = "word/document.xml";
1076
- const STYLES_PART_PATH = "word/styles.xml";
1077
- const THEME_REL_SUFFIX$1 = "/theme";
1078
- const DEFAULT_MARGIN_PT = 72;
1079
- const DEFAULT_MARGINS$1 = {
1080
- topPt: DEFAULT_MARGIN_PT,
1081
- rightPt: DEFAULT_MARGIN_PT,
1082
- bottomPt: DEFAULT_MARGIN_PT,
1083
- leftPt: DEFAULT_MARGIN_PT
1084
- };
1085
- function readPageSize$1(sectPr) {
1086
- const pgSz = childrenWithTag(sectPr, "w:pgSz")[0];
1087
- const w = pgSz === void 0 ? void 0 : attr(pgSz, "w:w");
1088
- const h = pgSz === void 0 ? void 0 : attr(pgSz, "w:h");
1089
- return w === void 0 || h === void 0 ? PAGE_SIZE_LETTER$1 : {
1090
- widthPt: twipsToPt(Number(w)),
1091
- heightPt: twipsToPt(Number(h))
1092
- };
1093
- }
1094
- function readMargins$1(sectPr) {
1095
- const pgMar = childrenWithTag(sectPr, "w:pgMar")[0];
1096
- if (pgMar === void 0) return DEFAULT_MARGINS$1;
1097
- const top = attr(pgMar, "w:top");
1098
- const right = attr(pgMar, "w:right");
1099
- const bottom = attr(pgMar, "w:bottom");
1100
- const left = attr(pgMar, "w:left");
1101
- return {
1102
- topPt: top === void 0 ? DEFAULT_MARGIN_PT : twipsToPt(Number(top)),
1103
- rightPt: right === void 0 ? DEFAULT_MARGIN_PT : twipsToPt(Number(right)),
1104
- bottomPt: bottom === void 0 ? DEFAULT_MARGIN_PT : twipsToPt(Number(bottom)),
1105
- leftPt: left === void 0 ? DEFAULT_MARGIN_PT : twipsToPt(Number(left))
1106
- };
1107
- }
1108
- function readListMembership(pPr) {
1109
- const numPr = pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:numPr")[0];
1110
- if (numPr === void 0) return;
1111
- const numIdEl = childrenWithTag(numPr, "w:numId")[0];
1112
- const numId = numIdEl === void 0 ? void 0 : attr(numIdEl, "w:val");
1113
- if (numId === void 0) return;
1114
- const ilvlEl = childrenWithTag(numPr, "w:ilvl")[0];
1115
- const ilvlVal = ilvlEl === void 0 ? void 0 : attr(ilvlEl, "w:val");
1116
- return {
1117
- numId,
1118
- level: ilvlVal === void 0 ? 0 : Number(ilvlVal)
1119
- };
1120
- }
1121
- function readToggle(el) {
1122
- if (el === void 0) return false;
1123
- const val = attr(el, "w:val");
1124
- return val === void 0 || val !== "0" && val !== "false" && val !== "off";
1125
- }
1126
- function hasPageBreakBefore(paragraph) {
1127
- const pPr = childrenWithTag(paragraph, "w:pPr")[0];
1128
- return readToggle(pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:pageBreakBefore")[0]);
1129
- }
1130
- function readRunText(run) {
1131
- let text = "";
1132
- for (const child of run.children) {
1133
- if (child.type !== "element") continue;
1134
- if (child.tag === "w:t") text += textContent(child);
1135
- else if (child.tag === "w:tab") text += " ";
1136
- else if (child.tag === "w:br" || child.tag === "w:cr") text += "\n";
1137
- }
1138
- return text;
1139
- }
1140
- function readRun$1(run, paragraph, context) {
1141
- const props = resolveRunProperties(run, paragraph, context);
1142
- return {
1143
- text: readRunText(run),
1144
- bold: props.bold,
1145
- italic: props.italic,
1146
- underline: props.underline,
1147
- strike: props.strike,
1148
- fontFamily: props.fontFamily,
1149
- sizePt: props.sizePt,
1150
- color: props.color
1151
- };
1152
- }
1153
- function readParagraphRuns(paragraph, context, rels) {
1154
- const runs = [];
1155
- let fieldState = "none";
1156
- function walk(nodes, hyperlinkTarget) {
1157
- for (const node of nodes) {
1158
- if (node.type !== "element") continue;
1159
- if (node.tag === "w:r") {
1160
- const fldChar = childrenWithTag(node, "w:fldChar")[0];
1161
- if (fldChar !== void 0) {
1162
- const type = attr(fldChar, "w:fldCharType");
1163
- if (type === "begin") fieldState = "code";
1164
- else if (type === "separate") fieldState = "result";
1165
- else if (type === "end") fieldState = "none";
1166
- continue;
1167
- }
1168
- if (fieldState === "code") continue;
1169
- const run = readRun$1(node, paragraph, context);
1170
- runs.push(hyperlinkTarget === void 0 ? run : {
1171
- ...run,
1172
- hyperlink: hyperlinkTarget
1173
- });
1174
- } else if (node.tag === "w:fldSimple") walk(node.children, hyperlinkTarget);
1175
- else if (node.tag === "w:hyperlink") {
1176
- const rId = attr(node, "r:id");
1177
- const target = rId === void 0 ? void 0 : rels.get(rId)?.target;
1178
- walk(node.children, target ?? hyperlinkTarget);
1179
- } else if (node.tag === "w:ins") walk(node.children, hyperlinkTarget);
1180
- }
1181
- }
1182
- walk(paragraph.children, void 0);
1183
- return runs;
1184
- }
1185
- function readParagraph$1(paragraph, context, rels) {
1186
- const pPr = childrenWithTag(paragraph, "w:pPr")[0];
1187
- const pStyleEl = pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:pStyle")[0];
1188
- const props = resolveParagraphProperties(paragraph, context);
1189
- return {
1190
- kind: "paragraph",
1191
- runs: readParagraphRuns(paragraph, context, rels),
1192
- styleId: pStyleEl === void 0 ? void 0 : attr(pStyleEl, "w:val"),
1193
- alignment: props.alignment,
1194
- list: readListMembership(pPr),
1195
- spacingBeforePt: props.spacingBeforePt,
1196
- spacingAfterPt: props.spacingAfterPt,
1197
- lineSpacing: props.lineSpacing,
1198
- indentLeftPt: props.indentLeftPt,
1199
- indentFirstLinePt: props.indentFirstLinePt
1200
- };
1201
- }
1202
- function readCellShading(tcPr) {
1203
- const shd = tcPr === void 0 ? void 0 : childrenWithTag(tcPr, "w:shd")[0];
1204
- const fill = shd === void 0 ? void 0 : attr(shd, "w:fill");
1205
- return fill === void 0 || fill === "auto" || fill === "none" ? void 0 : rgbHexToColor$1(fill);
1206
- }
1207
- function readRawCell(tc, context, rels) {
1208
- const tcPr = childrenWithTag(tc, "w:tcPr")[0];
1209
- const gridSpanEl = tcPr === void 0 ? void 0 : childrenWithTag(tcPr, "w:gridSpan")[0];
1210
- const gridSpanVal = gridSpanEl === void 0 ? void 0 : attr(gridSpanEl, "w:val");
1211
- const vMerge = tcPr === void 0 ? void 0 : childrenWithTag(tcPr, "w:vMerge")[0];
1212
- const vMergeVal = vMerge === void 0 ? void 0 : attr(vMerge, "w:val") ?? "continue";
1213
- return {
1214
- gridSpan: gridSpanVal === void 0 ? 1 : Number(gridSpanVal),
1215
- isVMergeContinuation: vMergeVal === "continue",
1216
- background: readCellShading(tcPr),
1217
- blocks: readBodyBlocks(tc.children, context, rels)
1218
- };
1219
- }
1220
- function readTable$1(tbl, context, rels) {
1221
- const tblGrid = childrenWithTag(tbl, "w:tblGrid")[0];
1222
- const columnWidthsPt = tblGrid === void 0 ? [] : childrenWithTag(tblGrid, "w:gridCol").map((col) => twipsToPt(Number(attr(col, "w:w") ?? "0")));
1223
- const rawRows = childrenWithTag(tbl, "w:tr").map((tr) => childrenWithTag(tr, "w:tc").map((tc) => readRawCell(tc, context, rels)));
1224
- const rowColumnIndices = rawRows.map((row) => {
1225
- const indices = [];
1226
- let col = 0;
1227
- for (const cell of row) {
1228
- indices.push(col);
1229
- col += cell.gridSpan;
1230
- }
1231
- return indices;
1232
- });
1233
- return {
1234
- kind: "table",
1235
- columnWidthsPt,
1236
- rows: rawRows.map((row, rowIndex) => ({ cells: row.map((cell, cellIndex) => {
1237
- if (cell.isVMergeContinuation) return { blocks: [] };
1238
- const colIndex = rowColumnIndices[rowIndex][cellIndex];
1239
- let rowSpan = 1;
1240
- for (let r = rowIndex + 1; r < rawRows.length; r++) {
1241
- const matchIndex = rowColumnIndices[r].indexOf(colIndex);
1242
- if (!(matchIndex === -1 ? void 0 : rawRows[r][matchIndex])?.isVMergeContinuation) break;
1243
- rowSpan++;
1244
- }
1245
- return {
1246
- blocks: cell.blocks,
1247
- colSpan: cell.gridSpan > 1 ? cell.gridSpan : void 0,
1248
- rowSpan: rowSpan > 1 ? rowSpan : void 0,
1249
- background: cell.background
1250
- };
1251
- }) }))
1252
- };
1253
- }
1254
- function readBodyBlocks(nodes, context, rels) {
1255
- const blocks = [];
1256
- for (const node of nodes) {
1257
- if (node.type !== "element") continue;
1258
- if (node.tag === "w:p") {
1259
- if (hasPageBreakBefore(node)) blocks.push({ kind: "pageBreak" });
1260
- blocks.push(readParagraph$1(node, context, rels));
1261
- } else if (node.tag === "w:tbl") blocks.push(readTable$1(node, context, rels));
1262
- else if (node.tag === "w:sdt") {
1263
- const sdtContent = childrenWithTag(node, "w:sdtContent")[0];
1264
- if (sdtContent !== void 0) blocks.push(...readBodyBlocks(sdtContent.children, context, rels));
1265
- } else if (node.tag === "w:ins") blocks.push(...readBodyBlocks(node.children, context, rels));
1266
- else if (node.tag === "mc:AlternateContent") {
1267
- const target = childrenWithTag(node, "mc:Fallback")[0] ?? childrenWithTag(node, "mc:Choice")[0];
1268
- if (target !== void 0) blocks.push(...readBodyBlocks(target.children, context, rels));
1269
- }
1270
- }
1271
- return blocks;
1272
- }
1273
- function readSections(body, context, rels) {
1274
- const sections = [];
1275
- let currentBlocks = [];
1276
- for (const node of body.children) {
1277
- if (node.type !== "element") continue;
1278
- if (node.tag === "w:sectPr") {
1279
- sections.push({
1280
- pageSize: readPageSize$1(node),
1281
- margins: readMargins$1(node),
1282
- blocks: currentBlocks
1283
- });
1284
- currentBlocks = [];
1285
- continue;
1286
- }
1287
- if (node.tag === "w:p") {
1288
- const pPr = childrenWithTag(node, "w:pPr")[0];
1289
- const sectPr = pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:sectPr")[0];
1290
- if (hasPageBreakBefore(node)) currentBlocks.push({ kind: "pageBreak" });
1291
- currentBlocks.push(readParagraph$1(node, context, rels));
1292
- if (sectPr !== void 0) {
1293
- sections.push({
1294
- pageSize: readPageSize$1(sectPr),
1295
- margins: readMargins$1(sectPr),
1296
- blocks: currentBlocks
1297
- });
1298
- currentBlocks = [];
1299
- }
1300
- continue;
1301
- }
1302
- currentBlocks.push(...readBodyBlocks([node], context, rels));
1303
- }
1304
- if (currentBlocks.length > 0 || sections.length === 0) sections.push({
1305
- pageSize: PAGE_SIZE_LETTER$1,
1306
- margins: DEFAULT_MARGINS$1,
1307
- blocks: currentBlocks
1308
- });
1309
- sections.forEach((section, sectionIndex) => assignSourcePaths(section.blocks, `sections[${sectionIndex}]`));
1310
- return sections;
1311
- }
1312
- function readDocumentTheme(pkg, docRels) {
1313
- for (const rel of docRels.values()) if (rel.type.endsWith(THEME_REL_SUFFIX$1)) {
1314
- const themeRoot = rootElement(pkg.parts[rel.target]);
1315
- if (themeRoot !== void 0) return readTheme(themeRoot);
1316
- }
1317
- return EMPTY_THEME;
1318
- }
1319
- function readComment(comment) {
1320
- const author = attr(comment, "w:author");
1321
- const result = { text: elementsWithTag(comment.children, "w:t").map(textContent).join("") };
1322
- if (author !== void 0) result.author = author;
1323
- return result;
1324
- }
1325
- function readFootnote(footnote) {
1326
- const type = attr(footnote, "w:type");
1327
- const result = { text: elementsWithTag(footnote.children, "w:t").map(textContent).join("") };
1328
- if (type !== void 0) result.type = type;
1329
- return result;
1330
- }
1331
- function readComments(pkg) {
1332
- const root = rootElement(pkg.parts["word/comments.xml"]);
1333
- if (root === void 0) return [];
1334
- return childrenWithTag(root, "w:comment").map(readComment);
1335
- }
1336
- function readFootnotes(pkg) {
1337
- const root = rootElement(pkg.parts["word/footnotes.xml"]);
1338
- if (root === void 0) return [];
1339
- const out = [];
1340
- for (const fn of childrenWithTag(root, "w:footnote")) {
1341
- const type = attr(fn, "w:type");
1342
- if (type === "separator" || type === "continuationSeparator") continue;
1343
- out.push(readFootnote(fn));
1344
- }
1345
- return out;
1346
- }
1347
- function readHeaderFooterText(pkg, prefix) {
1348
- const out = [];
1349
- for (const path of Object.keys(pkg.parts)) {
1350
- if (!path.startsWith(prefix) || !path.endsWith(".xml")) continue;
1351
- const part = pkg.parts[path];
1352
- if (part?.kind !== "xml") continue;
1353
- out.push(elementsWithTag(part.nodes, "w:t").map(textContent).join(""));
1354
- }
1355
- return out;
1356
- }
1357
- function readDocx(pkg) {
1358
- const documentRoot = rootElement(pkg.parts[DOCUMENT_PART_PATH]);
1359
- if (documentRoot === void 0) throw new Error(`readDocx: package has no ${DOCUMENT_PART_PATH} part`);
1360
- const body = childrenWithTag(documentRoot, "w:body")[0];
1361
- if (body === void 0) throw new Error(`readDocx: ${DOCUMENT_PART_PATH} has no w:body element`);
1362
- const docRels = resolveRelationships(pkg, DOCUMENT_PART_PATH);
1363
- const context = {
1364
- stylesRoot: rootElement(pkg.parts[STYLES_PART_PATH]),
1365
- theme: readDocumentTheme(pkg, docRels)
1366
- };
1367
- return {
1368
- metadata: readCoreProperties(pkg),
1369
- sections: readSections(body, context, docRels),
1370
- comments: readComments(pkg),
1371
- footnotes: readFootnotes(pkg),
1372
- headers: readHeaderFooterText(pkg, "word/header"),
1373
- footers: readHeaderFooterText(pkg, "word/footer")
1374
- };
1375
- }
1376
- //#endregion
1377
- //#region src/typed/pptx/inherit.ts
1378
- const SLIDE_LAYOUT_REL_SUFFIX = "/slideLayout";
1379
- const SLIDE_MASTER_REL_SUFFIX = "/slideMaster";
1380
- const THEME_REL_SUFFIX = "/theme";
1381
- function findRelTarget(pkg, partPath, typeSuffix) {
1382
- for (const rel of resolveRelationships(pkg, partPath).values()) if (rel.type.endsWith(typeSuffix)) return rel.target;
1383
- }
1384
- function resolveSlideInheritance(pkg, slidePath) {
1385
- const layoutPath = findRelTarget(pkg, slidePath, SLIDE_LAYOUT_REL_SUFFIX);
1386
- const layoutRoot = layoutPath === void 0 ? void 0 : rootElement(pkg.parts[layoutPath]);
1387
- const masterPath = layoutPath === void 0 ? void 0 : findRelTarget(pkg, layoutPath, SLIDE_MASTER_REL_SUFFIX);
1388
- const masterRoot = masterPath === void 0 ? void 0 : rootElement(pkg.parts[masterPath]);
1389
- const themePath = masterPath === void 0 ? void 0 : findRelTarget(pkg, masterPath, THEME_REL_SUFFIX);
1390
- const themeRoot = themePath === void 0 ? void 0 : rootElement(pkg.parts[themePath]);
1391
- return {
1392
- layoutRoot,
1393
- masterRoot,
1394
- theme: themeRoot === void 0 ? EMPTY_THEME : readTheme(themeRoot),
1395
- colorMap: readColorMap(masterRoot === void 0 ? void 0 : childrenWithTag(masterRoot, "p:clrMap")[0])
1396
- };
1397
- }
1398
- const TYPE_NORMALIZATION = /* @__PURE__ */ new Map([["ctrTitle", "title"], ["subTitle", "body"]]);
1399
- function normalizePlaceholderType(type) {
1400
- return type === void 0 ? void 0 : TYPE_NORMALIZATION.get(type) ?? type;
1401
- }
1402
- function readPlaceholderKey(shape) {
1403
- const ph = elementsWithTag([shape], "p:ph")[0];
1404
- return ph === void 0 ? void 0 : {
1405
- type: attr(ph, "type"),
1406
- idx: attr(ph, "idx")
1407
- };
1408
- }
1409
- function shapesOf(root) {
1410
- return root === void 0 ? [] : elementsWithTag([root], "p:sp");
1411
- }
1412
- function findMatchingPlaceholder(root, key) {
1413
- const shapes = shapesOf(root);
1414
- if (key.idx !== void 0) {
1415
- const byIdx = shapes.find((shape) => readPlaceholderKey(shape)?.idx === key.idx);
1416
- if (byIdx !== void 0) return byIdx;
1417
- }
1418
- const normalizedTarget = normalizePlaceholderType(key.type);
1419
- if (normalizedTarget === void 0) return;
1420
- return shapes.find((shape) => normalizePlaceholderType(readPlaceholderKey(shape)?.type) === normalizedTarget);
1421
- }
1422
- function shapeXfrm(shape) {
1423
- if (shape === void 0) return;
1424
- const spPr = childrenWithTag(shape, "p:spPr")[0];
1425
- return spPr === void 0 ? void 0 : readXfrm(childrenWithTag(spPr, "a:xfrm")[0]);
1426
- }
1427
- function resolvePlaceholderXfrm(key, context) {
1428
- return shapeXfrm(findMatchingPlaceholder(context.layoutRoot, key)) ?? shapeXfrm(findMatchingPlaceholder(context.masterRoot, key));
1429
- }
1430
- function readRunPropertiesFromElement(rPr, context) {
1431
- const sz = attr(rPr, "sz");
1432
- const latin = childrenWithTag(rPr, "a:latin")[0];
1433
- const typeface = latin === void 0 ? void 0 : attr(latin, "typeface");
1434
- const solidFill = childrenWithTag(rPr, "a:solidFill")[0];
1435
- const bold = attr(rPr, "b");
1436
- const italic = attr(rPr, "i");
1437
- return {
1438
- fontFamily: typeface === void 0 ? void 0 : resolveThemeFontReference(typeface, context.theme),
1439
- sizePt: sz === void 0 ? void 0 : drawingMlFontSizeToPt(Number(sz)),
1440
- bold: bold === void 0 ? void 0 : bold === "1",
1441
- italic: italic === void 0 ? void 0 : italic === "1",
1442
- color: readSolidFillColor(solidFill, context.colorMap, context.theme)
1443
- };
1444
- }
1445
- function txStyleTagFor(placeholderType) {
1446
- const normalized = normalizePlaceholderType(placeholderType);
1447
- if (normalized === "title") return "p:titleStyle";
1448
- if (normalized === "body") return "p:bodyStyle";
1449
- return "p:otherStyle";
1450
- }
1451
- function levelTag(level) {
1452
- return `a:lvl${Math.min(Math.max(level, 0), 8) + 1}pPr`;
1453
- }
1454
- function resolveDefaultRunProperties(placeholderType, level, context) {
1455
- if (context.masterRoot === void 0) return {};
1456
- const txStyles = childrenWithTag(context.masterRoot, "p:txStyles")[0];
1457
- const styleEl = txStyles === void 0 ? void 0 : childrenWithTag(txStyles, txStyleTagFor(placeholderType))[0];
1458
- const lvlPPr = styleEl === void 0 ? void 0 : childrenWithTag(styleEl, levelTag(level))[0];
1459
- const defRPr = lvlPPr === void 0 ? void 0 : childrenWithTag(lvlPPr, "a:defRPr")[0];
1460
- return defRPr === void 0 ? {} : readRunPropertiesFromElement(defRPr, context);
1461
- }
1462
- //#endregion
1463
- //#region src/typed/pptx/read.ts
1464
- const PptxDocumentSchema = z.object({
1465
- metadata: DocumentMetadataSchema,
1466
- slides: z.array(ContentSlideSchema$1)
1467
- });
1468
- const PRESENTATION_PATH = "ppt/presentation.xml";
1469
- const TABLE_GRAPHIC_URI = "http://schemas.openxmlformats.org/drawingml/2006/table";
1470
- function readSlideSize(presentationRoot) {
1471
- const sldSz = presentationRoot === void 0 ? void 0 : childrenWithTag(presentationRoot, "p:sldSz")[0];
1472
- const cx = sldSz === void 0 ? void 0 : attr(sldSz, "cx");
1473
- const cy = sldSz === void 0 ? void 0 : attr(sldSz, "cy");
1474
- return cx === void 0 || cy === void 0 ? SLIDE_SIZE_WIDESCREEN$1 : {
1475
- widthPt: emuToPt(Number(cx)),
1476
- heightPt: emuToPt(Number(cy))
1477
- };
1478
- }
1479
- function readSlidePathsInOrder(pkg, presentationRoot) {
1480
- if (presentationRoot === void 0) return [];
1481
- const sldIdLst = childrenWithTag(presentationRoot, "p:sldIdLst")[0];
1482
- if (sldIdLst === void 0) return [];
1483
- const presentationRels = resolveRelationships(pkg, PRESENTATION_PATH);
1484
- const paths = [];
1485
- for (const sldId of childrenWithTag(sldIdLst, "p:sldId")) {
1486
- const rId = attr(sldId, "r:id");
1487
- const rel = rId === void 0 ? void 0 : presentationRels.get(rId);
1488
- if (rel !== void 0) paths.push(rel.target);
1489
- }
1490
- return paths;
1491
- }
1492
- function shapeName(shape) {
1493
- const cNvPr = elementsWithTag([shape], "p:cNvPr")[0];
1494
- return cNvPr === void 0 ? void 0 : attr(cNvPr, "name");
1495
- }
1496
- function mergeRunProperties(base, override) {
1497
- return {
1498
- fontFamily: override.fontFamily ?? base.fontFamily,
1499
- sizePt: override.sizePt ?? base.sizePt,
1500
- bold: override.bold ?? base.bold,
1501
- italic: override.italic ?? base.italic,
1502
- color: override.color ?? base.color
1503
- };
1504
- }
1505
- function isUnderlined(rPr) {
1506
- if (rPr === void 0) return;
1507
- const u = attr(rPr, "u");
1508
- return u === void 0 ? void 0 : u !== "none";
1509
- }
1510
- function isStrikethrough(rPr) {
1511
- if (rPr === void 0) return;
1512
- const strike = attr(rPr, "strike");
1513
- return strike === void 0 ? void 0 : strike !== "noStrike";
1514
- }
1515
- function readHyperlink(rPr, slideRels) {
1516
- if (rPr === void 0) return;
1517
- const hlink = childrenWithTag(rPr, "a:hlinkClick")[0];
1518
- const rId = hlink === void 0 ? void 0 : attr(hlink, "r:id");
1519
- const rel = rId === void 0 ? void 0 : slideRels.get(rId);
1520
- return rel?.targetMode === "External" ? rel.target : void 0;
1521
- }
1522
- function readRun(runEl, cascadeBase, context, slideRels) {
1523
- const rPr = childrenWithTag(runEl, "a:rPr")[0];
1524
- const merged = mergeRunProperties(cascadeBase, rPr === void 0 ? {} : readRunPropertiesFromElement(rPr, context));
1525
- const tEl = childrenWithTag(runEl, "a:t")[0];
1526
- return {
1527
- text: tEl === void 0 ? "" : textContent(tEl),
1528
- bold: merged.bold,
1529
- italic: merged.italic,
1530
- underline: isUnderlined(rPr),
1531
- strike: isStrikethrough(rPr),
1532
- fontFamily: merged.fontFamily,
1533
- sizePt: merged.sizePt,
1534
- color: merged.color,
1535
- hyperlink: readHyperlink(rPr, slideRels)
1536
- };
1537
- }
1538
- function readAlignment(algn) {
1539
- if (algn === "l") return "left";
1540
- if (algn === "ctr") return "center";
1541
- if (algn === "r") return "right";
1542
- if (algn === "just" || algn === "justLow") return "justify";
1543
- }
1544
- function readAbsoluteSpacingPt(spc) {
1545
- if (spc === void 0) return;
1546
- const pts = childrenWithTag(spc, "a:spcPts")[0];
1547
- const val = pts === void 0 ? void 0 : attr(pts, "val");
1548
- return val === void 0 ? void 0 : drawingMlFontSizeToPt(Number(val));
1549
- }
1550
- function readLineSpacingMultiplier(pPr) {
1551
- const lnSpc = pPr === void 0 ? void 0 : childrenWithTag(pPr, "a:lnSpc")[0];
1552
- const pct = lnSpc === void 0 ? void 0 : childrenWithTag(lnSpc, "a:spcPct")[0];
1553
- const val = pct === void 0 ? void 0 : attr(pct, "val");
1554
- return val === void 0 ? void 0 : Number(val) / 1e5;
1555
- }
1556
- function readParagraph(pEl, placeholderType, context, slideRels) {
1557
- const pPr = childrenWithTag(pEl, "a:pPr")[0];
1558
- const masterDefaults = resolveDefaultRunProperties(placeholderType, pPr === void 0 ? 0 : Number(attr(pPr, "lvl") ?? "0"), context);
1559
- const pPrDefRPr = pPr === void 0 ? void 0 : childrenWithTag(pPr, "a:defRPr")[0];
1560
- const paragraphDefaults = pPrDefRPr === void 0 ? masterDefaults : mergeRunProperties(masterDefaults, readRunPropertiesFromElement(pPrDefRPr, context));
1561
- const runs = [];
1562
- for (const child of pEl.children) {
1563
- if (child.type !== "element") continue;
1564
- if (child.tag === "a:r" || child.tag === "a:fld") runs.push(readRun(child, paragraphDefaults, context, slideRels));
1565
- else if (child.tag === "a:br") runs.push({ text: "\n" });
1566
- }
1567
- const marL = pPr === void 0 ? void 0 : attr(pPr, "marL");
1568
- const indent = pPr === void 0 ? void 0 : attr(pPr, "indent");
1569
- return {
1570
- kind: "paragraph",
1571
- runs,
1572
- alignment: pPr === void 0 ? void 0 : readAlignment(attr(pPr, "algn")),
1573
- spacingBeforePt: readAbsoluteSpacingPt(pPr === void 0 ? void 0 : childrenWithTag(pPr, "a:spcBef")[0]),
1574
- spacingAfterPt: readAbsoluteSpacingPt(pPr === void 0 ? void 0 : childrenWithTag(pPr, "a:spcAft")[0]),
1575
- lineSpacing: readLineSpacingMultiplier(pPr),
1576
- indentLeftPt: marL === void 0 ? void 0 : emuToPt(Number(marL)),
1577
- indentFirstLinePt: indent === void 0 ? void 0 : emuToPt(Number(indent))
1578
- };
1579
- }
1580
- function textBodyParagraphs(txBody, placeholderType, context, slideRels) {
1581
- return txBody === void 0 ? [] : childrenWithTag(txBody, "a:p").map((p) => readParagraph(p, placeholderType, context, slideRels));
1582
- }
1583
- const DEFAULT_INSET_LEFT_RIGHT_EMU = 91440;
1584
- const DEFAULT_INSET_TOP_BOTTOM_EMU = 45720;
1585
- const NO_TEXT_BODY_EXTRAS = {
1586
- insetLeftPt: 0,
1587
- insetTopPt: 0,
1588
- insetRightPt: 0,
1589
- insetBottomPt: 0,
1590
- fontScale: void 0,
1591
- lineSpacingReduction: void 0
1592
- };
1593
- function readShapeTextExtras(txBody) {
1594
- if (txBody === void 0) return NO_TEXT_BODY_EXTRAS;
1595
- const bodyPr = childrenWithTag(txBody, "a:bodyPr")[0];
1596
- const lIns = bodyPr === void 0 ? void 0 : attr(bodyPr, "lIns");
1597
- const tIns = bodyPr === void 0 ? void 0 : attr(bodyPr, "tIns");
1598
- const rIns = bodyPr === void 0 ? void 0 : attr(bodyPr, "rIns");
1599
- const bIns = bodyPr === void 0 ? void 0 : attr(bodyPr, "bIns");
1600
- const normAutofit = bodyPr === void 0 ? void 0 : childrenWithTag(bodyPr, "a:normAutofit")[0];
1601
- const fontScale = normAutofit === void 0 ? void 0 : attr(normAutofit, "fontScale");
1602
- const lnSpcReduction = normAutofit === void 0 ? void 0 : attr(normAutofit, "lnSpcReduction");
1603
- return {
1604
- insetLeftPt: emuToPt(lIns === void 0 ? DEFAULT_INSET_LEFT_RIGHT_EMU : Number(lIns)),
1605
- insetTopPt: emuToPt(tIns === void 0 ? DEFAULT_INSET_TOP_BOTTOM_EMU : Number(tIns)),
1606
- insetRightPt: emuToPt(rIns === void 0 ? DEFAULT_INSET_LEFT_RIGHT_EMU : Number(rIns)),
1607
- insetBottomPt: emuToPt(bIns === void 0 ? DEFAULT_INSET_TOP_BOTTOM_EMU : Number(bIns)),
1608
- fontScale: fontScale === void 0 ? void 0 : Number(fontScale) / 1e5,
1609
- lineSpacingReduction: lnSpcReduction === void 0 ? void 0 : Number(lnSpcReduction) / 1e5
1610
- };
1611
- }
1612
- function resolveShapeFrame(shape, context, parentTransform) {
1613
- const key = readPlaceholderKey(shape);
1614
- const spPr = childrenWithTag(shape, "p:spPr")[0];
1615
- const xfrm = (spPr === void 0 ? void 0 : readXfrm(childrenWithTag(spPr, "a:xfrm")[0])) ?? (key === void 0 ? void 0 : resolvePlaceholderXfrm(key, context));
1616
- if (xfrm === void 0) return;
1617
- const localFrame = {
1618
- xPt: xfrm.xPt,
1619
- yPt: xfrm.yPt,
1620
- widthPt: xfrm.widthPt,
1621
- heightPt: xfrm.heightPt
1622
- };
1623
- return {
1624
- frame: parentTransform === void 0 ? localFrame : applyGroupTransform(parentTransform, localFrame),
1625
- rotationDeg: xfrm.rotationDeg === 0 ? void 0 : xfrm.rotationDeg
1626
- };
1627
- }
1628
- function readSpShape(sp, context, slideRels, parentTransform) {
1629
- const resolved = resolveShapeFrame(sp, context, parentTransform);
1630
- if (resolved === void 0) return;
1631
- const key = readPlaceholderKey(sp);
1632
- const txBody = childrenWithTag(sp, "p:txBody")[0];
1633
- const blocks = textBodyParagraphs(txBody, key?.type, context, slideRels);
1634
- const extras = readShapeTextExtras(txBody);
1635
- return {
1636
- name: shapeName(sp),
1637
- frame: resolved.frame,
1638
- rotationDeg: resolved.rotationDeg,
1639
- ...extras,
1640
- blocks
1641
- };
1642
- }
1643
- function readPicShape(pic, context, slideRels, pkg, parentTransform) {
1644
- const resolved = resolveShapeFrame(pic, context, parentTransform);
1645
- if (resolved === void 0) return;
1646
- const blipFill = childrenWithTag(pic, "p:blipFill")[0];
1647
- const blip = blipFill === void 0 ? void 0 : childrenWithTag(blipFill, "a:blip")[0];
1648
- const rId = blip === void 0 ? void 0 : attr(blip, "r:embed");
1649
- const rel = rId === void 0 ? void 0 : slideRels.get(rId);
1650
- const mediaPart = rel === void 0 ? void 0 : pkg.parts[rel.target];
1651
- const blocks = [];
1652
- if (mediaPart?.kind === "binary") {
1653
- const format = sniffImageFormat(base64ToBytes(mediaPart.base64));
1654
- if (format !== void 0) {
1655
- const image = {
1656
- kind: "image",
1657
- format,
1658
- base64: mediaPart.base64,
1659
- widthPt: resolved.frame.widthPt,
1660
- heightPt: resolved.frame.heightPt
1661
- };
1662
- blocks.push(image);
1663
- }
1664
- }
1665
- return {
1666
- name: shapeName(pic),
1667
- frame: resolved.frame,
1668
- rotationDeg: resolved.rotationDeg,
1669
- ...NO_TEXT_BODY_EXTRAS,
1670
- blocks
1671
- };
1672
- }
1673
- function readTableCell(tc, context, slideRels) {
1674
- const hMerge = attr(tc, "hMerge");
1675
- const vMerge = attr(tc, "vMerge");
1676
- if (hMerge === "1" || vMerge === "1") return { blocks: [] };
1677
- const tcPr = childrenWithTag(tc, "a:tcPr")[0];
1678
- const background = readSolidFillColor(tcPr === void 0 ? void 0 : childrenWithTag(tcPr, "a:solidFill")[0], context.colorMap, context.theme);
1679
- const txBody = childrenWithTag(tc, "a:txBody")[0];
1680
- const gridSpan = attr(tc, "gridSpan");
1681
- const rowSpan = attr(tc, "rowSpan");
1682
- return {
1683
- blocks: textBodyParagraphs(txBody, void 0, context, slideRels),
1684
- colSpan: gridSpan === void 0 ? void 0 : Number(gridSpan),
1685
- rowSpan: rowSpan === void 0 ? void 0 : Number(rowSpan),
1686
- background
1687
- };
1688
- }
1689
- function readTable(tbl, context, slideRels) {
1690
- const tblGrid = childrenWithTag(tbl, "a:tblGrid")[0];
1691
- const columnWidthsPt = tblGrid === void 0 ? [] : childrenWithTag(tblGrid, "a:gridCol").map((col) => emuToPt(Number(attr(col, "w") ?? "0")));
1692
- return {
1693
- kind: "table",
1694
- rows: childrenWithTag(tbl, "a:tr").map((tr) => {
1695
- const h = attr(tr, "h");
1696
- return {
1697
- cells: childrenWithTag(tr, "a:tc").map((tc) => readTableCell(tc, context, slideRels)),
1698
- heightPt: h === void 0 ? void 0 : emuToPt(Number(h))
1699
- };
1700
- }),
1701
- columnWidthsPt
1702
- };
1703
- }
1704
- function readGraphicFrameShape(gf, context, slideRels, parentTransform) {
1705
- const xfrm = readXfrm(childrenWithTag(gf, "p:xfrm")[0]);
1706
- if (xfrm === void 0) return;
1707
- const localFrame = {
1708
- xPt: xfrm.xPt,
1709
- yPt: xfrm.yPt,
1710
- widthPt: xfrm.widthPt,
1711
- heightPt: xfrm.heightPt
1712
- };
1713
- const frame = parentTransform === void 0 ? localFrame : applyGroupTransform(parentTransform, localFrame);
1714
- const rotationDeg = xfrm.rotationDeg === 0 ? void 0 : xfrm.rotationDeg;
1715
- const graphic = childrenWithTag(gf, "a:graphic")[0];
1716
- const graphicData = graphic === void 0 ? void 0 : childrenWithTag(graphic, "a:graphicData")[0];
1717
- const tbl = (graphicData === void 0 ? void 0 : attr(graphicData, "uri")) === TABLE_GRAPHIC_URI && graphicData !== void 0 ? childrenWithTag(graphicData, "a:tbl")[0] : void 0;
1718
- const blocks = tbl === void 0 ? [] : [readTable(tbl, context, slideRels)];
1719
- return {
1720
- name: shapeName(gf),
1721
- frame,
1722
- rotationDeg,
1723
- ...NO_TEXT_BODY_EXTRAS,
1724
- blocks
1725
- };
1726
- }
1727
- function walkShapeTreeChildren(children, parentTransform, context, slideRels, pkg, out) {
1728
- for (const node of children) {
1729
- if (node.type !== "element") continue;
1730
- if (node.tag === "p:sp") {
1731
- const shape = readSpShape(node, context, slideRels, parentTransform);
1732
- if (shape !== void 0) out.push(shape);
1733
- } else if (node.tag === "p:pic") {
1734
- const shape = readPicShape(node, context, slideRels, pkg, parentTransform);
1735
- if (shape !== void 0) out.push(shape);
1736
- } else if (node.tag === "p:graphicFrame") {
1737
- const shape = readGraphicFrameShape(node, context, slideRels, parentTransform);
1738
- if (shape !== void 0) out.push(shape);
1739
- } else if (node.tag === "p:grpSp") {
1740
- const grpSpPr = childrenWithTag(node, "p:grpSpPr")[0];
1741
- const composed = composeGroupTransform(readGroupXfrm(grpSpPr === void 0 ? void 0 : childrenWithTag(grpSpPr, "a:xfrm")[0]), parentTransform);
1742
- walkShapeTreeChildren(node.children, composed, context, slideRels, pkg, out);
1743
- }
1744
- }
1745
- }
1746
- function composeGroupTransform(own, parent) {
1747
- if (own === void 0) return;
1748
- if (parent === void 0) return own;
1749
- const absolute = applyGroupTransform(parent, {
1750
- xPt: own.offXPt,
1751
- yPt: own.offYPt,
1752
- widthPt: own.extWidthPt,
1753
- heightPt: own.extHeightPt
1754
- });
1755
- return {
1756
- ...own,
1757
- offXPt: absolute.xPt,
1758
- offYPt: absolute.yPt,
1759
- extWidthPt: absolute.widthPt,
1760
- extHeightPt: absolute.heightPt
1761
- };
1762
- }
1763
- const NOTES_SLIDE_REL_SUFFIX = "/notesSlide";
1764
- function readNotes(pkg, slidePath) {
1765
- let notesPath;
1766
- for (const rel of resolveRelationships(pkg, slidePath).values()) if (rel.type.endsWith(NOTES_SLIDE_REL_SUFFIX)) {
1767
- notesPath = rel.target;
1768
- break;
1769
- }
1770
- if (notesPath === void 0) return "";
1771
- const notesRoot = rootElement(pkg.parts[notesPath]);
1772
- if (notesRoot === void 0) return "";
1773
- const bodyShape = elementsWithTag([notesRoot], "p:sp").find((shape) => {
1774
- const key = readPlaceholderKey(shape);
1775
- return key !== void 0 && (key.type === void 0 || key.type === "body");
1776
- });
1777
- if (bodyShape !== void 0) {
1778
- const txBody = childrenWithTag(bodyShape, "p:txBody")[0];
1779
- if (txBody !== void 0) return elementsWithTag(txBody.children, "a:t").map(textContent).join("");
1780
- }
1781
- return elementsWithTag([notesRoot], "a:t").map(textContent).join("");
1782
- }
1783
- function readSlide(pkg, slidePath, size) {
1784
- const slideRoot = rootElement(pkg.parts[slidePath]);
1785
- const context = resolveSlideInheritance(pkg, slidePath);
1786
- const slideRels = resolveRelationships(pkg, slidePath);
1787
- const cSld = slideRoot === void 0 ? void 0 : childrenWithTag(slideRoot, "p:cSld")[0];
1788
- const spTree = cSld === void 0 ? void 0 : childrenWithTag(cSld, "p:spTree")[0];
1789
- const shapes = [];
1790
- if (spTree !== void 0) walkShapeTreeChildren(spTree.children, void 0, context, slideRels, pkg, shapes);
1791
- return {
1792
- size,
1793
- shapes,
1794
- notes: readNotes(pkg, slidePath)
1795
- };
1796
- }
1797
- function readPptx(pkg) {
1798
- const presentationRoot = rootElement(pkg.parts[PRESENTATION_PATH]);
1799
- const size = readSlideSize(presentationRoot);
1800
- const slides = readSlidePathsInOrder(pkg, presentationRoot).map((slidePath) => readSlide(pkg, slidePath, size));
1801
- slides.forEach((slide, slideIndex) => {
1802
- slide.shapes.forEach((shape, shapeIndex) => {
1803
- const shapePath = `slides[${slideIndex}].shapes[${shapeIndex}]`;
1804
- shape.sourcePath = shapePath;
1805
- assignSourcePaths(shape.blocks, shapePath);
1806
- });
1807
- });
1808
- return {
1809
- metadata: readCoreProperties(pkg),
1810
- slides
1811
- };
1812
- }
1813
- //#endregion
1814
- //#region src/typed/xlsx/shared-strings.ts
1815
- function loadSharedStrings(pkg) {
1816
- const root = rootElement(pkg.parts["xl/sharedStrings.xml"]);
1817
- if (root === void 0) return [];
1818
- const strings = [];
1819
- for (const si of childrenWithTag(root, "si")) {
1820
- let value = "";
1821
- for (const t of elementsWithTag(si.children, "t")) value += textContent(t);
1822
- strings.push(value);
1823
- }
1824
- return strings;
1825
- }
1826
- var SharedStringTable = class {
1827
- indexByValue = /* @__PURE__ */ new Map();
1828
- values = [];
1829
- intern(value) {
1830
- const existing = this.indexByValue.get(value);
1831
- if (existing !== void 0) return existing;
1832
- const index = this.values.length;
1833
- this.indexByValue.set(value, index);
1834
- this.values.push(value);
1835
- return index;
1836
- }
1837
- entries() {
1838
- return this.values;
1839
- }
1840
- get size() {
1841
- return this.values.length;
1842
- }
1843
- };
1844
- //#endregion
1845
- //#region src/typed/xlsx.ts
1846
- const XlsxCellSchema = z.object({
1847
- reference: z.string(),
1848
- value: z.string(),
1849
- formula: z.string().optional()
1850
- });
1851
- const XlsxSheetSchema = z.object({
1852
- name: z.string(),
1853
- cells: z.array(XlsxCellSchema),
1854
- mergedRanges: z.array(z.string())
1855
- });
1856
- const DefinedNameSchema = z.object({
1857
- name: z.string(),
1858
- refersTo: z.string()
1859
- });
1860
- const XlsxWorkbookSchema = z.object({
1861
- sheets: z.array(XlsxSheetSchema),
1862
- definedNames: z.array(DefinedNameSchema)
1863
- });
1864
- const SHEET_PATH_RE = /^xl\/worksheets\/sheet(\d+)\.xml$/;
1865
- function resolveRelTarget(target) {
1866
- if (target.startsWith("/")) return target.slice(1);
1867
- return `xl/${target}`;
1868
- }
1869
- function relTargets(pkg) {
1870
- const map = /* @__PURE__ */ new Map();
1871
- const rels = rootElement(pkg.parts["xl/_rels/workbook.xml.rels"]);
1872
- if (rels === void 0) return map;
1873
- for (const rel of childrenWithTag(rels, "Relationship")) {
1874
- const id = attr(rel, "Id");
1875
- const target = attr(rel, "Target");
1876
- if (id !== void 0 && target !== void 0) map.set(id, resolveRelTarget(target));
1877
- }
1878
- return map;
1879
- }
1880
- function resolveSheetNames(pkg) {
1881
- const names = /* @__PURE__ */ new Map();
1882
- const workbook = rootElement(pkg.parts["xl/workbook.xml"]);
1883
- if (workbook === void 0) return names;
1884
- const targets = relTargets(pkg);
1885
- for (const sheet of elementsWithTag(workbook.children, "sheet")) {
1886
- const name = attr(sheet, "name");
1887
- const rid = attr(sheet, "r:id");
1888
- if (name !== void 0 && rid !== void 0) {
1889
- const partName = targets.get(rid);
1890
- if (partName !== void 0) names.set(partName, name);
1891
- }
1892
- }
1893
- return names;
1894
- }
1895
- function readDefinedNames(pkg) {
1896
- const names = [];
1897
- const workbook = rootElement(pkg.parts["xl/workbook.xml"]);
1898
- if (workbook === void 0) return names;
1899
- for (const container of elementsWithTag(workbook.children, "definedNames")) for (const definedName of childrenWithTag(container, "definedName")) {
1900
- const name = attr(definedName, "name");
1901
- if (name === void 0) continue;
1902
- names.push({
1903
- name,
1904
- refersTo: textContent(definedName)
1905
- });
1906
- }
1907
- return names;
1908
- }
1909
- function sheetNumberOf(path) {
1910
- const match = SHEET_PATH_RE.exec(path);
1911
- const digits = match === null ? void 0 : match[1];
1912
- if (digits === void 0) return;
1913
- return Number.parseInt(digits, 10);
1914
- }
1915
- function readCell$1(cell, sharedStrings) {
1916
- const reference = attr(cell, "r");
1917
- if (reference === void 0) return;
1918
- const valueEl = childrenWithTag(cell, "v")[0];
1919
- if (valueEl === void 0) return;
1920
- const raw = textContent(valueEl);
1921
- let value;
1922
- if (attr(cell, "t") === "s") {
1923
- const index = Number.parseInt(raw, 10);
1924
- value = Number.isInteger(index) ? sharedStrings[index] : void 0;
1925
- } else value = raw;
1926
- if (value === void 0) return;
1927
- const projected = {
1928
- reference,
1929
- value
1930
- };
1931
- const formulaEl = childrenWithTag(cell, "f")[0];
1932
- if (formulaEl !== void 0) projected.formula = textContent(formulaEl);
1933
- return projected;
1934
- }
1935
- function readCells$1(worksheet, sharedStrings) {
1936
- const cells = [];
1937
- for (const row of elementsWithTag(worksheet.children, "row")) for (const cell of childrenWithTag(row, "c")) {
1938
- const projected = readCell$1(cell, sharedStrings);
1939
- if (projected !== void 0) cells.push(projected);
1940
- }
1941
- return cells;
1942
- }
1943
- function readMergedRanges(worksheet) {
1944
- const ranges = [];
1945
- for (const mergeCells of elementsWithTag(worksheet.children, "mergeCells")) for (const mergeCell of childrenWithTag(mergeCells, "mergeCell")) {
1946
- const ref = attr(mergeCell, "ref");
1947
- if (ref !== void 0) ranges.push(ref);
1948
- }
1949
- return ranges;
1950
- }
1951
- function readXlsx(pkg) {
1952
- const sharedStrings = loadSharedStrings(pkg);
1953
- const names = resolveSheetNames(pkg);
1954
- const definedNames = readDefinedNames(pkg);
1955
- const worksheets = Object.keys(pkg.parts).map((path) => ({
1956
- path,
1957
- number: sheetNumberOf(path)
1958
- })).filter((entry) => entry.number !== void 0).sort((a, b) => a.number - b.number);
1959
- const sheets = [];
1960
- for (const { path, number } of worksheets) {
1961
- const root = rootElement(pkg.parts[path]);
1962
- if (root === void 0) continue;
1963
- const name = names.get(path) ?? `Sheet${number}`;
1964
- sheets.push({
1965
- name,
1966
- cells: readCells$1(root, sharedStrings),
1967
- mergedRanges: readMergedRanges(root)
1968
- });
1969
- }
1970
- return {
1971
- sheets,
1972
- definedNames
1973
- };
1974
- }
1975
- //#endregion
1976
- //#region src/typed/xlsx/a1.ts
1977
- const CELL_REFERENCE_RE = /^([A-Za-z]+)(\d+)$/;
1978
- function columnLettersToIndex(letters) {
1979
- if (letters.length === 0) return;
1980
- let index = 0;
1981
- for (const ch of letters.toUpperCase()) {
1982
- const code = ch.charCodeAt(0);
1983
- if (code < 65 || code > 90) return;
1984
- index = index * 26 + (code - 64);
1985
- }
1986
- return index - 1;
1987
- }
1988
- function columnIndexToLetters(index) {
1989
- let remaining = index + 1;
1990
- let letters = "";
1991
- while (remaining > 0) {
1992
- const digit = (remaining - 1) % 26;
1993
- letters = String.fromCharCode(65 + digit) + letters;
1994
- remaining = Math.trunc((remaining - 1) / 26);
1995
- }
1996
- return letters;
1997
- }
1998
- function parseCellReference(ref) {
1999
- const match = CELL_REFERENCE_RE.exec(ref);
2000
- if (match === null) return;
2001
- const letters = match[1];
2002
- const digits = match[2];
2003
- if (letters === void 0 || digits === void 0) return;
2004
- const column = columnLettersToIndex(letters);
2005
- const rowNumber = Number.parseInt(digits, 10);
2006
- if (column === void 0 || !Number.isInteger(rowNumber) || rowNumber < 1) return;
2007
- return {
2008
- row: rowNumber - 1,
2009
- column
2010
- };
2011
- }
2012
- function cellReference(row, column) {
2013
- return `${columnIndexToLetters(column)}${row + 1}`;
2014
- }
2015
- function parseRangeReference(ref) {
2016
- const separatorIndex = ref.indexOf(":");
2017
- const startRaw = separatorIndex === -1 ? ref : ref.slice(0, separatorIndex);
2018
- const endRaw = separatorIndex === -1 ? ref : ref.slice(separatorIndex + 1);
2019
- const start = parseCellReference(startRaw);
2020
- const end = parseCellReference(endRaw);
2021
- if (start === void 0 || end === void 0) return;
2022
- return {
2023
- startRow: Math.min(start.row, end.row),
2024
- startColumn: Math.min(start.column, end.column),
2025
- endRow: Math.max(start.row, end.row),
2026
- endColumn: Math.max(start.column, end.column)
2027
- };
2028
- }
2029
- function rangeReference(range) {
2030
- return `${cellReference(range.startRow, range.startColumn)}:${cellReference(range.endRow, range.endColumn)}`;
2031
- }
2032
- //#endregion
2033
- //#region src/typed/xlsx/defined-names.ts
2034
- const XLNM_PRINT_AREA = "_xlnm.Print_Area";
2035
- const XLNM_PRINT_TITLES = "_xlnm.Print_Titles";
2036
- function readDefinedNamesBySheet(pkg) {
2037
- const map = /* @__PURE__ */ new Map();
2038
- const workbook = rootElement(pkg.parts["xl/workbook.xml"]);
2039
- if (workbook === void 0) return map;
2040
- const container = childrenWithTag(workbook, "definedNames")[0];
2041
- if (container === void 0) return map;
2042
- for (const definedName of childrenWithTag(container, "definedName")) {
2043
- const name = attr(definedName, "name");
2044
- const localSheetIdRaw = attr(definedName, "localSheetId");
2045
- if (name === void 0 || localSheetIdRaw === void 0) continue;
2046
- if (name !== "_xlnm.Print_Area" && name !== "_xlnm.Print_Titles") continue;
2047
- const sheetIndex = Number.parseInt(localSheetIdRaw, 10);
2048
- if (!Number.isInteger(sheetIndex) || sheetIndex < 0) continue;
2049
- const value = textContent(definedName);
2050
- const existing = map.get(sheetIndex) ?? {};
2051
- if (name === "_xlnm.Print_Area") existing.printArea = value;
2052
- else existing.printTitles = value;
2053
- map.set(sheetIndex, existing);
2054
- }
2055
- return map;
2056
- }
2057
- function stripSheetPrefix(segment) {
2058
- const bang = segment.lastIndexOf("!");
2059
- return bang === -1 ? segment : segment.slice(bang + 1);
2060
- }
2061
- function parsePrintAreaValue(value) {
2062
- const first = value.split(",")[0]?.trim();
2063
- if (first === void 0 || first.length === 0) return;
2064
- return parseRangeReference(stripSheetPrefix(first).replace(/\$/g, ""));
2065
- }
2066
- function parsePrintTitlesValue(value) {
2067
- const result = {};
2068
- for (const rawSegment of value.split(",")) {
2069
- const segment = stripSheetPrefix(rawSegment.trim()).replace(/\$/g, "");
2070
- const separatorIndex = segment.indexOf(":");
2071
- if (separatorIndex === -1) continue;
2072
- const startSpec = segment.slice(0, separatorIndex);
2073
- const endSpec = segment.slice(separatorIndex + 1);
2074
- if (/^[A-Za-z]+$/.test(startSpec) && /^[A-Za-z]+$/.test(endSpec)) {
2075
- const start = columnLettersToIndex(startSpec);
2076
- const end = columnLettersToIndex(endSpec);
2077
- if (start !== void 0 && end !== void 0) result.repeatColumns = {
2078
- start: Math.min(start, end),
2079
- end: Math.max(start, end)
2080
- };
2081
- } else if (/^\d+$/.test(startSpec) && /^\d+$/.test(endSpec)) {
2082
- const start = Number.parseInt(startSpec, 10) - 1;
2083
- const end = Number.parseInt(endSpec, 10) - 1;
2084
- result.repeatRows = {
2085
- start: Math.min(start, end),
2086
- end: Math.max(start, end)
2087
- };
2088
- }
2089
- }
2090
- return result;
2091
- }
2092
- function quoteSheetNameIfNeeded(sheetName) {
2093
- if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(sheetName)) return sheetName;
2094
- return `'${sheetName.replace(/'/g, "''")}'`;
2095
- }
2096
- function buildPrintAreaValue(sheetName, range) {
2097
- const dollared = rangeReference({
2098
- startRow: range.startRow,
2099
- startColumn: range.startColumn,
2100
- endRow: range.endRow,
2101
- endColumn: range.endColumn
2102
- }).replace(/([A-Z]+)(\d+)/g, "$$$1$$$2");
2103
- return `${quoteSheetNameIfNeeded(sheetName)}!${dollared}`;
2104
- }
2105
- function buildPrintTitlesValue(sheetName, repeatRows, repeatColumns) {
2106
- const quotedName = quoteSheetNameIfNeeded(sheetName);
2107
- const segments = [];
2108
- if (repeatColumns !== void 0) segments.push(`${quotedName}!$${columnIndexToLetters(repeatColumns.start)}:$${columnIndexToLetters(repeatColumns.end)}`);
2109
- if (repeatRows !== void 0) segments.push(`${quotedName}!$${repeatRows.start + 1}:$${repeatRows.end + 1}`);
2110
- return segments.length > 0 ? segments.join(",") : void 0;
2111
- }
2112
- //#endregion
2113
- //#region src/typed/xlsx/util.ts
2114
- function readXmlBool(value) {
2115
- return value === "1" || value === "true";
2116
- }
2117
- function writeXmlBool(value) {
2118
- return value ? "true" : "false";
2119
- }
2120
- const UNIVERSAL_MEASURE_RE = /^(-?\d+(?:\.\d+)?)(mm|cm|in|pt|pc|pi)$/;
2121
- function parseUniversalMeasureToPt(value) {
2122
- const match = UNIVERSAL_MEASURE_RE.exec(value.trim());
2123
- if (match === null) return;
2124
- const amountRaw = match[1];
2125
- const unit = match[2];
2126
- if (amountRaw === void 0 || unit === void 0) return;
2127
- const amount = Number(amountRaw);
2128
- switch (unit) {
2129
- case "mm": return amount / 25.4 * 72;
2130
- case "cm": return amount / 2.54 * 72;
2131
- case "in": return amount * 72;
2132
- case "pt": return amount;
2133
- case "pc":
2134
- case "pi": return amount * 12;
2135
- default: return;
2136
- }
2137
- }
2138
- function ptToUniversalMeasure(pt) {
2139
- return `${(pt / 72 * 2.54).toFixed(2)}cm`;
2140
- }
2141
- const PAPER_SIZE_BY_CODE = {
2142
- "1": PAGE_SIZE_LETTER$1,
2143
- "9": PAGE_SIZE_A4$1
2144
- };
2145
- function paperSizeCodeToPageSize(code) {
2146
- return PAPER_SIZE_BY_CODE[code];
2147
- }
2148
- const PAPER_SIZE_TOLERANCE_PT = .5;
2149
- function approximatelyEquals(a, b) {
2150
- return Math.abs(a - b) <= PAPER_SIZE_TOLERANCE_PT;
2151
- }
2152
- function pageSizeToPaperSizeCode(pageSize) {
2153
- if (approximatelyEquals(pageSize.widthPt, PAGE_SIZE_LETTER$1.widthPt) && approximatelyEquals(pageSize.heightPt, PAGE_SIZE_LETTER$1.heightPt)) return "1";
2154
- if (approximatelyEquals(pageSize.widthPt, PAGE_SIZE_A4$1.widthPt) && approximatelyEquals(pageSize.heightPt, PAGE_SIZE_A4$1.heightPt)) return "9";
2155
- }
2156
- //#endregion
2157
- //#region src/typed/xlsx/print-settings.ts
2158
- const DEFAULT_MARGINS = {
2159
- topPt: .75 * 72,
2160
- rightPt: .7 * 72,
2161
- bottomPt: .75 * 72,
2162
- leftPt: .7 * 72
2163
- };
2164
- const DEFAULT_HEADER_FOOTER_MARGIN_PT = .3 * 72;
2165
- const DEFAULT_FIT_TO_PAGES = 1;
2166
- function applyOrientation(pageSize, pageSetup) {
2167
- if ((pageSetup === void 0 ? void 0 : attr(pageSetup, "orientation")) !== "landscape") return pageSize;
2168
- return {
2169
- widthPt: pageSize.heightPt,
2170
- heightPt: pageSize.widthPt
2171
- };
2172
- }
2173
- function readPageSize(pageSetup) {
2174
- if (pageSetup === void 0) return PAGE_SIZE_LETTER$1;
2175
- const paperSize = attr(pageSetup, "paperSize");
2176
- const byCode = paperSize === void 0 ? void 0 : paperSizeCodeToPageSize(paperSize);
2177
- if (byCode !== void 0) return applyOrientation(byCode, pageSetup);
2178
- const paperWidth = attr(pageSetup, "paperWidth");
2179
- const paperHeight = attr(pageSetup, "paperHeight");
2180
- const widthPt = paperWidth === void 0 ? void 0 : parseUniversalMeasureToPt(paperWidth);
2181
- const heightPt = paperHeight === void 0 ? void 0 : parseUniversalMeasureToPt(paperHeight);
2182
- return widthPt === void 0 || heightPt === void 0 ? PAGE_SIZE_LETTER$1 : applyOrientation({
2183
- widthPt,
2184
- heightPt
2185
- }, pageSetup);
2186
- }
2187
- function readMargins(pageMargins) {
2188
- if (pageMargins === void 0) return DEFAULT_MARGINS;
2189
- const top = attr(pageMargins, "top");
2190
- const right = attr(pageMargins, "right");
2191
- const bottom = attr(pageMargins, "bottom");
2192
- const left = attr(pageMargins, "left");
2193
- return {
2194
- topPt: top === void 0 ? DEFAULT_MARGINS.topPt : Number(top) * 72,
2195
- rightPt: right === void 0 ? DEFAULT_MARGINS.rightPt : Number(right) * 72,
2196
- bottomPt: bottom === void 0 ? DEFAULT_MARGINS.bottomPt : Number(bottom) * 72,
2197
- leftPt: left === void 0 ? DEFAULT_MARGINS.leftPt : Number(left) * 72
2198
- };
2199
- }
2200
- function readPageOrder(pageSetup) {
2201
- return (pageSetup === void 0 ? void 0 : attr(pageSetup, "pageOrder")) === "overThenDown" ? "overThenDown" : "downThenOver";
2202
- }
2203
- function readManualBreaks(worksheet) {
2204
- const rowBreaksEl = childrenWithTag(worksheet, "rowBreaks")[0];
2205
- const colBreaksEl = childrenWithTag(worksheet, "colBreaks")[0];
2206
- const rows = rowBreaksEl === void 0 ? [] : readBreakIndices(rowBreaksEl);
2207
- const columns = colBreaksEl === void 0 ? [] : readBreakIndices(colBreaksEl);
2208
- return rows.length > 0 || columns.length > 0 ? {
2209
- rows,
2210
- columns
2211
- } : void 0;
2212
- }
2213
- function readBreakIndices(container) {
2214
- const indices = [];
2215
- for (const brk of childrenWithTag(container, "brk")) {
2216
- const id = attr(brk, "id");
2217
- const index = id === void 0 ? void 0 : Number.parseInt(id, 10);
2218
- if (index !== void 0 && Number.isInteger(index) && index >= 0) indices.push(index);
2219
- }
2220
- return indices;
2221
- }
2222
- function readPrintSettings(worksheet, sheetIndex, definedNamesBySheet) {
2223
- const sheetPr = childrenWithTag(worksheet, "sheetPr")[0];
2224
- const pageSetUpPr = sheetPr === void 0 ? void 0 : childrenWithTag(sheetPr, "pageSetUpPr")[0];
2225
- const fitToPage = readXmlBool(pageSetUpPr === void 0 ? void 0 : attr(pageSetUpPr, "fitToPage"));
2226
- const pageSetup = childrenWithTag(worksheet, "pageSetup")[0];
2227
- const pageMargins = childrenWithTag(worksheet, "pageMargins")[0];
2228
- const printOptions = childrenWithTag(worksheet, "printOptions")[0];
2229
- const manualBreaks = readManualBreaks(worksheet);
2230
- const definedNames = definedNamesBySheet.get(sheetIndex);
2231
- const settings = {
2232
- pageSize: readPageSize(pageSetup),
2233
- margins: readMargins(pageMargins),
2234
- gridlines: readXmlBool(printOptions === void 0 ? void 0 : attr(printOptions, "gridLines")),
2235
- headers: readXmlBool(printOptions === void 0 ? void 0 : attr(printOptions, "headings")),
2236
- pageOrder: readPageOrder(pageSetup)
2237
- };
2238
- if (fitToPage) {
2239
- const fitToWidthRaw = pageSetup === void 0 ? void 0 : attr(pageSetup, "fitToWidth");
2240
- const fitToHeightRaw = pageSetup === void 0 ? void 0 : attr(pageSetup, "fitToHeight");
2241
- settings.fitToPages = {
2242
- width: fitToWidthRaw === void 0 ? DEFAULT_FIT_TO_PAGES : Number(fitToWidthRaw),
2243
- height: fitToHeightRaw === void 0 ? DEFAULT_FIT_TO_PAGES : Number(fitToHeightRaw)
2244
- };
2245
- } else {
2246
- const scaleRaw = pageSetup === void 0 ? void 0 : attr(pageSetup, "scale");
2247
- if (scaleRaw !== void 0) {
2248
- const scale = Number(scaleRaw);
2249
- if (Number.isFinite(scale)) settings.scale = scale;
2250
- }
2251
- }
2252
- if (manualBreaks !== void 0) settings.manualBreaks = manualBreaks;
2253
- if (definedNames?.printArea !== void 0) {
2254
- const range = parsePrintAreaValue(definedNames.printArea);
2255
- if (range !== void 0) settings.printRange = range;
2256
- }
2257
- if (definedNames?.printTitles !== void 0) {
2258
- const titles = parsePrintTitlesValue(definedNames.printTitles);
2259
- if (titles.repeatRows !== void 0) settings.repeatRows = titles.repeatRows;
2260
- if (titles.repeatColumns !== void 0) settings.repeatColumns = titles.repeatColumns;
2261
- }
2262
- return settings;
2263
- }
2264
- function columnWidthCharsToPt(width) {
2265
- const digitWidthAllowance = Math.trunc(128 / 7);
2266
- return Math.trunc((256 * width + digitWidthAllowance) / 256 * 7) / 96 * 72;
2267
- }
2268
- function ptToColumnWidthChars(widthPt) {
2269
- const pixels = widthPt / 72 * 96;
2270
- const digitWidthAllowance = Math.trunc(128 / 7);
2271
- return pixels / 7 - digitWidthAllowance / 256;
2272
- }
2273
- //#endregion
2274
- //#region src/typed/xlsx/content.ts
2275
- const WORKBOOK_PATH = "xl/workbook.xml";
2276
- function resolveSheetEntries(pkg) {
2277
- const workbook = rootElement(pkg.parts[WORKBOOK_PATH]);
2278
- if (workbook === void 0) return [];
2279
- const sheetsEl = childrenWithTag(workbook, "sheets")[0];
2280
- if (sheetsEl === void 0) return [];
2281
- const rels = resolveRelationships(pkg, WORKBOOK_PATH);
2282
- const entries = [];
2283
- for (const sheet of childrenWithTag(sheetsEl, "sheet")) {
2284
- const name = attr(sheet, "name");
2285
- const rId = attr(sheet, "r:id");
2286
- const rel = rId === void 0 ? void 0 : rels.get(rId);
2287
- if (name !== void 0 && rel !== void 0) entries.push({
2288
- name,
2289
- path: rel.target
2290
- });
2291
- }
2292
- return entries;
2293
- }
2294
- function sheetFormatDefaultRowHeightPt(worksheet) {
2295
- const sheetFormatPr = childrenWithTag(worksheet, "sheetFormatPr")[0];
2296
- const raw = sheetFormatPr === void 0 ? void 0 : attr(sheetFormatPr, "defaultRowHeight");
2297
- if (raw === void 0) return 15;
2298
- const parsed = Number(raw);
2299
- return Number.isFinite(parsed) ? parsed : 15;
2300
- }
2301
- function readColumns(worksheet) {
2302
- const colsEl = childrenWithTag(worksheet, "cols")[0];
2303
- if (colsEl === void 0) return [];
2304
- const columns = [];
2305
- for (const col of childrenWithTag(colsEl, "col")) {
2306
- const minRaw = attr(col, "min");
2307
- const min = minRaw === void 0 ? void 0 : Number.parseInt(minRaw, 10);
2308
- if (min === void 0 || !Number.isInteger(min) || min < 1) continue;
2309
- const widthRaw = attr(col, "width");
2310
- const widthPt = widthRaw === void 0 ? 0 : columnWidthCharsToPt(Number(widthRaw));
2311
- const column = {
2312
- index: min - 1,
2313
- widthPt: Number.isFinite(widthPt) ? widthPt : 0
2314
- };
2315
- if (readXmlBool(attr(col, "hidden"))) column.hidden = true;
2316
- columns.push(column);
2317
- }
2318
- return columns;
2319
- }
2320
- function readRows(worksheet) {
2321
- const sheetData = childrenWithTag(worksheet, "sheetData")[0];
2322
- if (sheetData === void 0) return [];
2323
- const fallbackHeightPt = sheetFormatDefaultRowHeightPt(worksheet);
2324
- const rows = [];
2325
- for (const row of childrenWithTag(sheetData, "row")) {
2326
- const rRaw = attr(row, "r");
2327
- const rowNumber = rRaw === void 0 ? void 0 : Number.parseInt(rRaw, 10);
2328
- if (rowNumber === void 0 || !Number.isInteger(rowNumber) || rowNumber < 1) continue;
2329
- const htRaw = attr(row, "ht");
2330
- const heightPt = htRaw === void 0 ? fallbackHeightPt : Number(htRaw);
2331
- const contentRow = {
2332
- index: rowNumber - 1,
2333
- heightPt: Number.isFinite(heightPt) ? heightPt : fallbackHeightPt
2334
- };
2335
- if (readXmlBool(attr(row, "hidden"))) contentRow.hidden = true;
2336
- rows.push(contentRow);
2337
- }
2338
- return rows;
2339
- }
2340
- function readInlineOrSharedStringText(container) {
2341
- let value = "";
2342
- for (const t of elementsWithTag(container.children, "t")) value += textContent(t);
2343
- return value;
2344
- }
2345
- function deriveDisplayText(value) {
2346
- switch (value.kind) {
2347
- case "number": return String(value.value);
2348
- case "boolean": return value.value ? "TRUE" : "FALSE";
2349
- case "string":
2350
- case "error":
2351
- case "date":
2352
- case "time": return value.value;
2353
- case "percentage":
2354
- case "currency": return String(value.value);
2355
- case "empty": return "";
2356
- }
2357
- }
2358
- function readCellValue(cell, sharedStrings) {
2359
- const type = attr(cell, "t");
2360
- if (type === "inlineStr") {
2361
- const is = childrenWithTag(cell, "is")[0];
2362
- const text = is === void 0 ? void 0 : readInlineOrSharedStringText(is);
2363
- return text === void 0 ? void 0 : {
2364
- value: {
2365
- kind: "string",
2366
- value: text
2367
- },
2368
- displayText: text
2369
- };
2370
- }
2371
- const valueEl = childrenWithTag(cell, "v")[0];
2372
- const raw = valueEl === void 0 ? void 0 : textContent(valueEl);
2373
- if (raw === void 0) return;
2374
- if (type === "s") {
2375
- const index = Number.parseInt(raw, 10);
2376
- const text = Number.isInteger(index) ? sharedStrings[index] : void 0;
2377
- return text === void 0 ? void 0 : {
2378
- value: {
2379
- kind: "string",
2380
- value: text
2381
- },
2382
- displayText: text
2383
- };
2384
- }
2385
- if (type === "str") return {
2386
- value: {
2387
- kind: "string",
2388
- value: raw
2389
- },
2390
- displayText: raw
2391
- };
2392
- if (type === "b") {
2393
- const value = {
2394
- kind: "boolean",
2395
- value: raw === "1" || raw.toLowerCase() === "true"
2396
- };
2397
- return {
2398
- value,
2399
- displayText: deriveDisplayText(value)
2400
- };
2401
- }
2402
- if (type === "e") return {
2403
- value: {
2404
- kind: "error",
2405
- value: raw
2406
- },
2407
- displayText: raw
2408
- };
2409
- if (type === "d") return {
2410
- value: {
2411
- kind: "date",
2412
- value: raw
2413
- },
2414
- displayText: raw
2415
- };
2416
- const num = Number(raw);
2417
- if (Number.isNaN(num)) return;
2418
- const value = {
2419
- kind: "number",
2420
- value: num
2421
- };
2422
- return {
2423
- value,
2424
- displayText: deriveDisplayText(value)
2425
- };
2426
- }
2427
- function readCell(cell, sharedStrings) {
2428
- const reference = attr(cell, "r");
2429
- const position = reference === void 0 ? void 0 : parseCellReference(reference);
2430
- if (position === void 0) return;
2431
- const formulaEl = childrenWithTag(cell, "f")[0];
2432
- const formula = formulaEl === void 0 ? void 0 : textContent(formulaEl);
2433
- const resolved = readCellValue(cell, sharedStrings);
2434
- if (resolved === void 0) {
2435
- if (formula === void 0) return;
2436
- return {
2437
- row: position.row,
2438
- column: position.column,
2439
- value: { kind: "empty" },
2440
- formula,
2441
- displayText: ""
2442
- };
2443
- }
2444
- const cellEntry = {
2445
- row: position.row,
2446
- column: position.column,
2447
- value: resolved.value,
2448
- displayText: resolved.displayText
2449
- };
2450
- if (formula !== void 0) cellEntry.formula = formula;
2451
- return cellEntry;
2452
- }
2453
- function applyMergedRanges(worksheet, cells) {
2454
- const mergeCellsEl = childrenWithTag(worksheet, "mergeCells")[0];
2455
- if (mergeCellsEl === void 0) return;
2456
- const byPosition = /* @__PURE__ */ new Map();
2457
- for (const cell of cells) byPosition.set(`${cell.row}:${cell.column}`, cell);
2458
- for (const mergeCell of childrenWithTag(mergeCellsEl, "mergeCell")) {
2459
- const ref = attr(mergeCell, "ref");
2460
- const range = ref === void 0 ? void 0 : parseRangeReference(ref);
2461
- if (range === void 0) continue;
2462
- const anchor = byPosition.get(`${range.startRow}:${range.startColumn}`);
2463
- if (anchor === void 0) continue;
2464
- const colSpan = range.endColumn - range.startColumn + 1;
2465
- const rowSpan = range.endRow - range.startRow + 1;
2466
- if (colSpan > 1) anchor.colSpan = colSpan;
2467
- if (rowSpan > 1) anchor.rowSpan = rowSpan;
2468
- }
2469
- }
2470
- function readCells(worksheet, sharedStrings) {
2471
- const sheetData = childrenWithTag(worksheet, "sheetData")[0];
2472
- if (sheetData === void 0) return [];
2473
- const cells = [];
2474
- for (const row of childrenWithTag(sheetData, "row")) for (const cell of childrenWithTag(row, "c")) {
2475
- const read = readCell(cell, sharedStrings);
2476
- if (read !== void 0) cells.push(read);
2477
- }
2478
- applyMergedRanges(worksheet, cells);
2479
- return cells;
2480
- }
2481
- function readSheet(pkg, entry, sheetIndex, sharedStrings, definedNamesBySheet) {
2482
- const worksheet = rootElement(pkg.parts[entry.path]);
2483
- if (worksheet === void 0) return {
2484
- name: entry.name,
2485
- cells: [],
2486
- columns: [],
2487
- rows: [],
2488
- images: [],
2489
- printSettings: readPrintSettings(fallbackEmptyWorksheet(), sheetIndex, definedNamesBySheet)
2490
- };
2491
- return {
2492
- name: entry.name,
2493
- cells: readCells(worksheet, sharedStrings),
2494
- columns: readColumns(worksheet),
2495
- rows: readRows(worksheet),
2496
- images: [],
2497
- printSettings: readPrintSettings(worksheet, sheetIndex, definedNamesBySheet)
2498
- };
2499
- }
2500
- function fallbackEmptyWorksheet() {
2501
- return {
2502
- type: "element",
2503
- tag: "worksheet",
2504
- attributes: [],
2505
- children: []
2506
- };
2507
- }
2508
- function readXlsxContent(pkg) {
2509
- const sharedStrings = loadSharedStrings(pkg);
2510
- const definedNamesBySheet = readDefinedNamesBySheet(pkg);
2511
- const sheets = resolveSheetEntries(pkg).map((entry, sheetIndex) => readSheet(pkg, entry, sheetIndex, sharedStrings, definedNamesBySheet));
2512
- return {
2513
- kind: "spreadsheet",
2514
- formatVersion: CONTENT_FORMAT_VERSION$1,
2515
- metadata: readCoreProperties(pkg),
2516
- sheets
2517
- };
2518
- }
2519
- //#endregion
2520
- //#region src/typed/xlsx/build.ts
2521
- const SML_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
2522
- const REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
2523
- const PKG_RELS_NS = "http://schemas.openxmlformats.org/package/2006/relationships";
2524
- const CONTENT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types";
2525
- const CORE_PROPS_NS = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
2526
- const DC_NS = "http://purl.org/dc/elements/1.1/";
2527
- const DCTERMS_NS = "http://purl.org/dc/terms/";
2528
- const XSI_NS = "http://www.w3.org/2001/XMLSchema-instance";
2529
- const EXTENDED_PROPS_NS = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";
2530
- const CT_WORKBOOK = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
2531
- const CT_STYLES = "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml";
2532
- const CT_SHARED_STRINGS = "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml";
2533
- const CT_WORKSHEET = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
2534
- const CT_CORE_PROPS = "application/vnd.openxmlformats-package.core-properties+xml";
2535
- const CT_EXTENDED_PROPS = "application/vnd.openxmlformats-officedocument.extended-properties+xml";
2536
- const REL_OFFICE_DOCUMENT = `${REL_NS}/officeDocument`;
2537
- const REL_CORE_PROPS = `${PKG_RELS_NS}/metadata/core-properties`;
2538
- const REL_EXTENDED_PROPS = `${REL_NS}/extended-properties`;
2539
- const REL_WORKSHEET = `${REL_NS}/worksheet`;
2540
- const REL_STYLES = `${REL_NS}/styles`;
2541
- const REL_SHARED_STRINGS = `${REL_NS}/sharedStrings`;
2542
- const MAX_COLUMN_INDEX = 16383;
2543
- const MAX_ROW_INDEX = 1048575;
2544
- function xmlDeclaration() {
2545
- return {
2546
- type: "declaration",
2547
- attributes: [
2548
- {
2549
- name: "version",
2550
- value: "1.0"
2551
- },
2552
- {
2553
- name: "encoding",
2554
- value: "UTF-8"
2555
- },
2556
- {
2557
- name: "standalone",
2558
- value: "yes"
2559
- }
2560
- ]
2561
- };
2562
- }
2563
- function xmlPart(root) {
2564
- return {
2565
- kind: "xml",
2566
- nodes: [xmlDeclaration(), root]
2567
- };
2568
- }
2569
- function buildContentTypesPart(sheetCount) {
2570
- const overrides = [
2571
- el("Override", {
2572
- PartName: "/xl/workbook.xml",
2573
- ContentType: CT_WORKBOOK
2574
- }),
2575
- el("Override", {
2576
- PartName: "/xl/styles.xml",
2577
- ContentType: CT_STYLES
2578
- }),
2579
- el("Override", {
2580
- PartName: "/xl/sharedStrings.xml",
2581
- ContentType: CT_SHARED_STRINGS
2582
- })
2583
- ];
2584
- for (let index = 0; index < sheetCount; index++) overrides.push(el("Override", {
2585
- PartName: `/xl/worksheets/sheet${index + 1}.xml`,
2586
- ContentType: CT_WORKSHEET
2587
- }));
2588
- overrides.push(el("Override", {
2589
- PartName: "/docProps/core.xml",
2590
- ContentType: CT_CORE_PROPS
2591
- }));
2592
- overrides.push(el("Override", {
2593
- PartName: "/docProps/app.xml",
2594
- ContentType: CT_EXTENDED_PROPS
2595
- }));
2596
- return xmlPart(el("Types", { xmlns: CONTENT_TYPES_NS }, [
2597
- el("Default", {
2598
- Extension: "rels",
2599
- ContentType: "application/vnd.openxmlformats-package.relationships+xml"
2600
- }),
2601
- el("Default", {
2602
- Extension: "xml",
2603
- ContentType: "application/xml"
2604
- }),
2605
- ...overrides
2606
- ]));
2607
- }
2608
- function buildPackageRelsPart() {
2609
- return xmlPart(el("Relationships", { xmlns: PKG_RELS_NS }, [
2610
- el("Relationship", {
2611
- Id: "rId1",
2612
- Type: REL_OFFICE_DOCUMENT,
2613
- Target: "xl/workbook.xml"
2614
- }),
2615
- el("Relationship", {
2616
- Id: "rId2",
2617
- Type: REL_CORE_PROPS,
2618
- Target: "docProps/core.xml"
2619
- }),
2620
- el("Relationship", {
2621
- Id: "rId3",
2622
- Type: REL_EXTENDED_PROPS,
2623
- Target: "docProps/app.xml"
2624
- })
2625
- ]));
2626
- }
2627
- function worksheetRelId(sheetIndex) {
2628
- return `rId${sheetIndex + 1}`;
2629
- }
2630
- function buildWorkbookRelsPart(sheetCount) {
2631
- const relationships = [];
2632
- for (let index = 0; index < sheetCount; index++) relationships.push(el("Relationship", {
2633
- Id: worksheetRelId(index),
2634
- Type: REL_WORKSHEET,
2635
- Target: `worksheets/sheet${index + 1}.xml`
2636
- }));
2637
- relationships.push(el("Relationship", {
2638
- Id: `rId${sheetCount + 1}`,
2639
- Type: REL_STYLES,
2640
- Target: "styles.xml"
2641
- }));
2642
- relationships.push(el("Relationship", {
2643
- Id: `rId${sheetCount + 2}`,
2644
- Type: REL_SHARED_STRINGS,
2645
- Target: "sharedStrings.xml"
2646
- }));
2647
- return xmlPart(el("Relationships", { xmlns: PKG_RELS_NS }, relationships));
2648
- }
2649
- function buildDefinedNameElements(sheets) {
2650
- const elements = [];
2651
- sheets.forEach((sheet, sheetIndex) => {
2652
- const { printRange, repeatRows, repeatColumns } = sheet.printSettings;
2653
- if (printRange !== void 0) {
2654
- const value = buildPrintAreaValue(sheet.name, printRange);
2655
- elements.push(el("definedName", {
2656
- name: XLNM_PRINT_AREA,
2657
- localSheetId: String(sheetIndex)
2658
- }, [txt(encodeXmlText(value))]));
2659
- }
2660
- if (repeatRows !== void 0 || repeatColumns !== void 0) {
2661
- const value = buildPrintTitlesValue(sheet.name, repeatRows, repeatColumns);
2662
- if (value !== void 0) elements.push(el("definedName", {
2663
- name: XLNM_PRINT_TITLES,
2664
- localSheetId: String(sheetIndex)
2665
- }, [txt(encodeXmlText(value))]));
2666
- }
2667
- });
2668
- return elements;
2669
- }
2670
- function buildWorkbookPart(sheets) {
2671
- const children = [el("sheets", {}, sheets.map((sheet, index) => el("sheet", {
2672
- name: encodeXmlText(sheet.name),
2673
- sheetId: String(index + 1),
2674
- "r:id": worksheetRelId(index)
2675
- })))];
2676
- const definedNameElements = buildDefinedNameElements(sheets);
2677
- if (definedNameElements.length > 0) children.push(el("definedNames", {}, definedNameElements));
2678
- return xmlPart(el("workbook", {
2679
- xmlns: SML_NS,
2680
- "xmlns:r": REL_NS
2681
- }, children));
2682
- }
2683
- function buildSharedStringsPart(sharedStrings) {
2684
- const entries = sharedStrings.entries();
2685
- const siElements = entries.map((value) => el("si", {}, [el("t", { "xml:space": "preserve" }, [txt(encodeXmlText(value))])]));
2686
- return xmlPart(el("sst", {
2687
- xmlns: SML_NS,
2688
- count: String(entries.length),
2689
- uniqueCount: String(entries.length)
2690
- }, siElements));
2691
- }
2692
- function buildStylesPart() {
2693
- return xmlPart(el("styleSheet", { xmlns: SML_NS }, [
2694
- el("fonts", { count: "1" }, [el("font", {}, [el("sz", { val: "11" }), el("name", { val: "Calibri" })])]),
2695
- el("fills", { count: "2" }, [el("fill", {}, [el("patternFill", { patternType: "none" })]), el("fill", {}, [el("patternFill", { patternType: "gray125" })])]),
2696
- el("borders", { count: "1" }, [el("border", {}, [
2697
- el("left"),
2698
- el("right"),
2699
- el("top"),
2700
- el("bottom"),
2701
- el("diagonal")
2702
- ])]),
2703
- el("cellStyleXfs", { count: "1" }, [el("xf", {
2704
- numFmtId: "0",
2705
- fontId: "0",
2706
- fillId: "0",
2707
- borderId: "0"
2708
- })]),
2709
- el("cellXfs", { count: "1" }, [el("xf", {
2710
- numFmtId: "0",
2711
- fontId: "0",
2712
- fillId: "0",
2713
- borderId: "0",
2714
- xfId: "0"
2715
- })]),
2716
- el("cellStyles", { count: "1" }, [el("cellStyle", {
2717
- name: "Normal",
2718
- xfId: "0",
2719
- builtinId: "0"
2720
- })])
2721
- ]));
2722
- }
2723
- function buildCorePropertiesPart(metadata) {
2724
- const children = [];
2725
- if (metadata.title !== void 0) children.push(el("dc:title", {}, [txt(encodeXmlText(metadata.title))]));
2726
- if (metadata.author !== void 0) children.push(el("dc:creator", {}, [txt(encodeXmlText(metadata.author))]));
2727
- if (metadata.subject !== void 0) children.push(el("dc:subject", {}, [txt(encodeXmlText(metadata.subject))]));
2728
- if (metadata.keywords !== void 0 && metadata.keywords.length > 0) children.push(el("cp:keywords", {}, [txt(encodeXmlText(metadata.keywords.join(", ")))]));
2729
- if (metadata.createdIso !== void 0) children.push(el("dcterms:created", { "xsi:type": "dcterms:W3CDTF" }, [txt(encodeXmlText(metadata.createdIso))]));
2730
- if (metadata.modifiedIso !== void 0) children.push(el("dcterms:modified", { "xsi:type": "dcterms:W3CDTF" }, [txt(encodeXmlText(metadata.modifiedIso))]));
2731
- return xmlPart(el("cp:coreProperties", {
2732
- "xmlns:cp": CORE_PROPS_NS,
2733
- "xmlns:dc": DC_NS,
2734
- "xmlns:dcterms": DCTERMS_NS,
2735
- "xmlns:xsi": XSI_NS
2736
- }, children));
2737
- }
2738
- function buildAppPropertiesPart(metadata) {
2739
- const children = [];
2740
- if (metadata.creator !== void 0) children.push(el("Application", {}, [txt(encodeXmlText(metadata.creator))]));
2741
- return xmlPart(el("Properties", { xmlns: EXTENDED_PROPS_NS }, children));
2742
- }
2743
- function computeDimension(sheet) {
2744
- let maxRow = 0;
2745
- let maxColumn = 0;
2746
- let hasAny = false;
2747
- for (const cell of sheet.cells) {
2748
- hasAny = true;
2749
- maxRow = Math.max(maxRow, cell.row);
2750
- maxColumn = Math.max(maxColumn, cell.column);
2751
- }
2752
- for (const column of sheet.columns) {
2753
- hasAny = true;
2754
- maxColumn = Math.max(maxColumn, column.index);
2755
- }
2756
- for (const row of sheet.rows) {
2757
- hasAny = true;
2758
- maxRow = Math.max(maxRow, row.index);
2759
- }
2760
- return hasAny ? rangeReference({
2761
- startRow: 0,
2762
- startColumn: 0,
2763
- endRow: maxRow,
2764
- endColumn: maxColumn
2765
- }) : "A1";
2766
- }
2767
- function buildColsElement(columns) {
2768
- if (columns.length === 0) return;
2769
- return el("cols", {}, columns.map((column) => {
2770
- const attrs = {
2771
- min: String(column.index + 1),
2772
- max: String(column.index + 1),
2773
- width: ptToColumnWidthChars(column.widthPt).toFixed(2),
2774
- customWidth: "true"
2775
- };
2776
- if (column.hidden === true) attrs.hidden = "true";
2777
- return el("col", attrs);
2778
- }));
2779
- }
2780
- function renderCellValue(value, isFormulaResult, sharedStrings) {
2781
- switch (value.kind) {
2782
- case "string":
2783
- if (isFormulaResult) return {
2784
- type: "str",
2785
- content: encodeXmlText(value.value)
2786
- };
2787
- return {
2788
- type: "s",
2789
- content: String(sharedStrings.intern(value.value))
2790
- };
2791
- case "number":
2792
- case "percentage":
2793
- case "currency": return { content: String(value.value) };
2794
- case "boolean": return {
2795
- type: "b",
2796
- content: value.value ? "1" : "0"
2797
- };
2798
- case "date":
2799
- case "time": return {
2800
- type: "d",
2801
- content: encodeXmlText(value.value)
2802
- };
2803
- case "error": return {
2804
- type: "e",
2805
- content: encodeXmlText(value.value)
2806
- };
2807
- case "empty": return;
2808
- }
2809
- }
2810
- function buildCellElement(cell, sharedStrings) {
2811
- const attrs = {
2812
- r: cellReference(cell.row, cell.column),
2813
- s: "0"
2814
- };
2815
- const children = [];
2816
- if (cell.formula !== void 0) children.push(el("f", {}, [txt(encodeXmlText(cell.formula))]));
2817
- const rendered = renderCellValue(cell.value, cell.formula !== void 0, sharedStrings);
2818
- if (rendered !== void 0) {
2819
- if (rendered.type !== void 0) attrs.t = rendered.type;
2820
- children.push(el("v", {}, [txt(rendered.content)]));
2821
- }
2822
- return el("c", attrs, children);
2823
- }
2824
- function buildSheetDataElement(sheet, sharedStrings) {
2825
- const cellsByRow = /* @__PURE__ */ new Map();
2826
- for (const cell of sheet.cells) {
2827
- const existing = cellsByRow.get(cell.row);
2828
- if (existing === void 0) cellsByRow.set(cell.row, [cell]);
2829
- else existing.push(cell);
2830
- }
2831
- const rowInfoByIndex = /* @__PURE__ */ new Map();
2832
- for (const row of sheet.rows) rowInfoByIndex.set(row.index, row);
2833
- return el("sheetData", {}, Array.from(/* @__PURE__ */ new Set([...cellsByRow.keys(), ...rowInfoByIndex.keys()])).sort((a, b) => a - b).map((rowIndex) => {
2834
- const cells = (cellsByRow.get(rowIndex) ?? []).slice().sort((a, b) => a.column - b.column);
2835
- const rowInfo = rowInfoByIndex.get(rowIndex);
2836
- const attrs = { r: String(rowIndex + 1) };
2837
- if (rowInfo !== void 0) {
2838
- attrs.ht = String(rowInfo.heightPt);
2839
- attrs.customHeight = "true";
2840
- if (rowInfo.hidden === true) attrs.hidden = "true";
2841
- }
2842
- return el("row", attrs, cells.map((cell) => buildCellElement(cell, sharedStrings)));
2843
- }));
2844
- }
2845
- function buildMergeCellsElement(cells) {
2846
- const merges = cells.filter((cell) => (cell.colSpan ?? 1) > 1 || (cell.rowSpan ?? 1) > 1);
2847
- if (merges.length === 0) return;
2848
- const mergeCellElements = merges.map((cell) => {
2849
- const endRow = cell.row + (cell.rowSpan ?? 1) - 1;
2850
- const endColumn = cell.column + (cell.colSpan ?? 1) - 1;
2851
- return el("mergeCell", { ref: rangeReference({
2852
- startRow: cell.row,
2853
- startColumn: cell.column,
2854
- endRow,
2855
- endColumn
2856
- }) });
2857
- });
2858
- return el("mergeCells", { count: String(mergeCellElements.length) }, mergeCellElements);
2859
- }
2860
- function buildSheetPrElement(settings) {
2861
- return el("sheetPr", {}, [el("pageSetUpPr", { fitToPage: writeXmlBool(settings.fitToPages !== void 0) })]);
2862
- }
2863
- function buildPrintOptionsElement(settings) {
2864
- return el("printOptions", {
2865
- gridLines: writeXmlBool(settings.gridlines),
2866
- headings: writeXmlBool(settings.headers)
2867
- });
2868
- }
2869
- function ptToInches(pt) {
2870
- return String(pt / 72);
2871
- }
2872
- function buildPageMarginsElement(settings) {
2873
- const margins = settings.margins;
2874
- return el("pageMargins", {
2875
- left: ptToInches(margins.leftPt),
2876
- right: ptToInches(margins.rightPt),
2877
- top: ptToInches(margins.topPt),
2878
- bottom: ptToInches(margins.bottomPt),
2879
- header: ptToInches(DEFAULT_HEADER_FOOTER_MARGIN_PT),
2880
- footer: ptToInches(DEFAULT_HEADER_FOOTER_MARGIN_PT)
2881
- });
2882
- }
2883
- function buildPageSetupElement(settings) {
2884
- const attrs = {};
2885
- const paperCode = pageSizeToPaperSizeCode(settings.pageSize);
2886
- if (paperCode !== void 0) attrs.paperSize = paperCode;
2887
- else {
2888
- attrs.paperWidth = ptToUniversalMeasure(settings.pageSize.widthPt);
2889
- attrs.paperHeight = ptToUniversalMeasure(settings.pageSize.heightPt);
2890
- }
2891
- attrs.scale = String(settings.scale ?? 100);
2892
- attrs.fitToWidth = String(settings.fitToPages?.width ?? 1);
2893
- attrs.fitToHeight = String(settings.fitToPages?.height ?? 1);
2894
- attrs.pageOrder = settings.pageOrder;
2895
- attrs.orientation = settings.pageSize.widthPt > settings.pageSize.heightPt ? "landscape" : "portrait";
2896
- return el("pageSetup", attrs);
2897
- }
2898
- function buildBreaksElements(settings) {
2899
- const manualBreaks = settings.manualBreaks;
2900
- if (manualBreaks === void 0) return {};
2901
- const result = {};
2902
- if (manualBreaks.rows.length > 0) {
2903
- const breaks = manualBreaks.rows.map((id) => el("brk", {
2904
- id: String(id),
2905
- min: "0",
2906
- max: String(MAX_COLUMN_INDEX),
2907
- man: "1"
2908
- }));
2909
- result.rowBreaks = el("rowBreaks", {
2910
- count: String(breaks.length),
2911
- manualBreakCount: String(breaks.length)
2912
- }, breaks);
2913
- }
2914
- if (manualBreaks.columns.length > 0) {
2915
- const breaks = manualBreaks.columns.map((id) => el("brk", {
2916
- id: String(id),
2917
- min: "0",
2918
- max: String(MAX_ROW_INDEX),
2919
- man: "1"
2920
- }));
2921
- result.colBreaks = el("colBreaks", {
2922
- count: String(breaks.length),
2923
- manualBreakCount: String(breaks.length)
2924
- }, breaks);
2925
- }
2926
- return result;
2927
- }
2928
- function buildWorksheetPart(sheet, sharedStrings) {
2929
- const children = [buildSheetPrElement(sheet.printSettings), el("dimension", { ref: computeDimension(sheet) })];
2930
- const colsElement = buildColsElement(sheet.columns);
2931
- if (colsElement !== void 0) children.push(colsElement);
2932
- children.push(buildSheetDataElement(sheet, sharedStrings));
2933
- const mergeCellsElement = buildMergeCellsElement(sheet.cells);
2934
- if (mergeCellsElement !== void 0) children.push(mergeCellsElement);
2935
- children.push(buildPrintOptionsElement(sheet.printSettings), buildPageMarginsElement(sheet.printSettings), buildPageSetupElement(sheet.printSettings));
2936
- const { rowBreaks, colBreaks } = buildBreaksElements(sheet.printSettings);
2937
- if (rowBreaks !== void 0) children.push(rowBreaks);
2938
- if (colBreaks !== void 0) children.push(colBreaks);
2939
- return xmlPart(el("worksheet", {
2940
- xmlns: SML_NS,
2941
- "xmlns:r": REL_NS
2942
- }, children));
2943
- }
2944
- function buildXlsxPackage(document) {
2945
- if (document.kind !== "spreadsheet") throw new Error(`buildXlsxPackage: expected a ContentDocument of kind "spreadsheet", got "${document.kind}"`);
2946
- const sheets = document.sheets;
2947
- const sharedStrings = new SharedStringTable();
2948
- const worksheetParts = sheets.map((sheet) => buildWorksheetPart(sheet, sharedStrings));
2949
- const parts = {
2950
- "[Content_Types].xml": buildContentTypesPart(sheets.length),
2951
- "_rels/.rels": buildPackageRelsPart(),
2952
- "xl/workbook.xml": buildWorkbookPart(sheets),
2953
- "xl/_rels/workbook.xml.rels": buildWorkbookRelsPart(sheets.length),
2954
- "xl/styles.xml": buildStylesPart(),
2955
- "xl/sharedStrings.xml": buildSharedStringsPart(sharedStrings),
2956
- "docProps/core.xml": buildCorePropertiesPart(document.metadata),
2957
- "docProps/app.xml": buildAppPropertiesPart(document.metadata)
2958
- };
2959
- worksheetParts.forEach((part, index) => {
2960
- parts[`xl/worksheets/sheet${index + 1}.xml`] = part;
2961
- });
2962
- return { parts };
2963
- }
2964
- //#endregion
1
+ import { AttributeSchema, XmlCdataSchema, XmlCommentSchema, XmlDeclarationSchema, XmlElementSchema, XmlNodeSchema, XmlPiSchema, XmlTextSchema, isXmlNode } from "./model/node.js";
2
+ import { BinaryPartSchema, PackageSchema, PartSchema, XmlPartSchema } from "./model/package.js";
3
+ import { base64ToBytes, bytesToBase64 } from "./util/base64.js";
4
+ import { parseXml } from "./xml/parse.js";
5
+ import { unzipPackage, zipPackage } from "./zip.js";
6
+ import { parsePackage } from "./package-io/read.js";
7
+ import { buildXml } from "./xml/build.js";
8
+ import { serializePackage } from "./package-io/write.js";
9
+ import { decodePackage, encodePackage, packageCodec, xmlCodec } from "./codec.js";
10
+ import { CompactPackageSchema, CompactPartSchema, CompactXmlNodeSchema, compactCodec, compactPackageCodec, decodeCompactPackage, encodeCompactPackage, fromCompact, isCompactXmlNode, toCompact } from "./compact.js";
11
+ import { el, txt } from "./xml/fragment.js";
12
+ import { encodeXmlText } from "./xml/entities.js";
13
+ import { attr, childrenWithTag, decodeEntities, elementsWithTag, resolveRelationships, rootElement, textContent, walk } from "./typed/util.js";
14
+ import { applyColorTransforms } from "./typed/shared/color.js";
15
+ import { DocumentMetadataSchema } from "./typed/shared/metadata.js";
16
+ import { sniffImageFormat } from "./image/sniff.js";
17
+ import { CommentSchema, DocxDocumentSchema, FootnoteSchema, readDocx } from "./typed/docx/read.js";
18
+ import { PptxDocumentSchema, readPptx } from "./typed/pptx/read.js";
19
+ import { DefinedNameSchema, XlsxCellSchema, XlsxSheetSchema, XlsxWorkbookSchema, readXlsx } from "./typed/xlsx.js";
20
+ import { readXlsxContent } from "./typed/xlsx/content.js";
21
+ import { buildXlsxPackage } from "./typed/xlsx/build.js";
22
+ import { AlignmentSchema, BoxSchema, COLOR_BLACK, CONTENT_FORMAT_VERSION, ColorSchema, ContentBlockSchema, ContentCellValueSchema, ContentDocumentSchema, ContentImageBlockSchema, ContentListMembershipSchema, ContentPageBreakSchema, ContentParagraphSchema, ContentRunSchema, ContentSectionSchema, ContentShapeSchema, ContentSheetCellSchema, ContentSheetColumnSchema, ContentSheetImageSchema, ContentSheetPrintRangeSchema, ContentSheetPrintSettingsSchema, ContentSheetRepeatRangeSchema, ContentSheetRowSchema, ContentSheetSchema, ContentSlideSchema, ContentTableCellSchema, ContentTableRowSchema, ContentTableSchema, MarginsSchema, PAGE_SIZE_A4, PAGE_SIZE_LETTER, PageSizeSchema, SLIDE_SIZE_STANDARD, SLIDE_SIZE_WIDESCREEN, colorToRgbHex, isContentBlock, rgbHexToColor } from "document-schema.js";
2965
23
  export { AlignmentSchema, AttributeSchema, BinaryPartSchema, BoxSchema, COLOR_BLACK, CONTENT_FORMAT_VERSION, ColorSchema, CommentSchema, CompactPackageSchema, CompactPartSchema, CompactXmlNodeSchema, ContentBlockSchema, ContentCellValueSchema, ContentDocumentSchema, ContentImageBlockSchema, ContentListMembershipSchema, ContentPageBreakSchema, ContentParagraphSchema, ContentRunSchema, ContentSectionSchema, ContentShapeSchema, ContentSheetCellSchema, ContentSheetColumnSchema, ContentSheetImageSchema, ContentSheetPrintRangeSchema, ContentSheetPrintSettingsSchema, ContentSheetRepeatRangeSchema, ContentSheetRowSchema, ContentSheetSchema, ContentSlideSchema, ContentTableCellSchema, ContentTableRowSchema, ContentTableSchema, DefinedNameSchema, DocumentMetadataSchema, DocxDocumentSchema, FootnoteSchema, MarginsSchema, PAGE_SIZE_A4, PAGE_SIZE_LETTER, PackageSchema, PageSizeSchema, PartSchema, PptxDocumentSchema, SLIDE_SIZE_STANDARD, SLIDE_SIZE_WIDESCREEN, XlsxCellSchema, XlsxSheetSchema, XlsxWorkbookSchema, XmlCdataSchema, XmlCommentSchema, XmlDeclarationSchema, XmlElementSchema, XmlNodeSchema, XmlPartSchema, XmlPiSchema, XmlTextSchema, applyColorTransforms, attr, base64ToBytes, buildXlsxPackage, buildXml, bytesToBase64, childrenWithTag, colorToRgbHex, compactCodec, compactPackageCodec, decodeCompactPackage, decodeEntities, decodePackage, el, elementsWithTag, encodeCompactPackage, encodePackage, encodeXmlText, fromCompact, isCompactXmlNode, isContentBlock, isXmlNode, packageCodec, parsePackage, parseXml, readDocx, readPptx, readXlsx, readXlsxContent, resolveRelationships, rgbHexToColor, rootElement, serializePackage, sniffImageFormat, textContent, toCompact, txt, unzipPackage, walk, xmlCodec, zipPackage };