@office-open/core 0.10.11 → 0.10.13

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 (62) hide show
  1. package/README.md +10 -9
  2. package/dist/chart/index.d.mts +1 -1
  3. package/dist/chart/index.mjs +1 -1
  4. package/dist/{chart-DwE8FCFk.mjs → chart-DOO1st0K.mjs} +3 -1
  5. package/dist/chart-DOO1st0K.mjs.map +1 -0
  6. package/dist/converters-C_Y2QX1w.mjs +1789 -0
  7. package/dist/converters-C_Y2QX1w.mjs.map +1 -0
  8. package/dist/data-type-CZMKVaaT.d.mts +10 -0
  9. package/dist/data-type-CZMKVaaT.d.mts.map +1 -0
  10. package/dist/descriptor/index.d.mts +2 -2
  11. package/dist/descriptor/index.mjs +2 -2
  12. package/dist/{descriptor-DAER86Rt.mjs → descriptor-BjNkn5jo.mjs} +3 -33
  13. package/dist/descriptor-BjNkn5jo.mjs.map +1 -0
  14. package/dist/drawingml/index.d.mts +2 -2
  15. package/dist/drawingml/index.mjs +2 -2
  16. package/dist/{src-zBJYrHrv.mjs → drawingml-sj1J3lb0.mjs} +22 -3728
  17. package/dist/drawingml-sj1J3lb0.mjs.map +1 -0
  18. package/dist/index-BVK2dv6C.d.mts +63 -0
  19. package/dist/index-BVK2dv6C.d.mts.map +1 -0
  20. package/dist/index-BfHfKuKy.d.mts +275 -0
  21. package/dist/index-BfHfKuKy.d.mts.map +1 -0
  22. package/dist/index-CE53SwpZ.d.mts +1463 -0
  23. package/dist/index-CE53SwpZ.d.mts.map +1 -0
  24. package/dist/{index-3STznXzZ.d.mts → index-D6VE-MnJ.d.mts} +3 -15
  25. package/dist/index-D6VE-MnJ.d.mts.map +1 -0
  26. package/dist/{index-CN0YjNSx.d.mts → index-DDyd2ErZ.d.mts} +3 -15
  27. package/dist/index-DDyd2ErZ.d.mts.map +1 -0
  28. package/dist/{index-CsQP7Cl4.d.mts → index-DlPA26cw.d.mts} +2 -47
  29. package/dist/index-DlPA26cw.d.mts.map +1 -0
  30. package/dist/index-k8WKLXnA.d.mts +150 -0
  31. package/dist/index-k8WKLXnA.d.mts.map +1 -0
  32. package/dist/index.d.mts +650 -8
  33. package/dist/index.d.mts.map +1 -0
  34. package/dist/index.mjs +1271 -7
  35. package/dist/index.mjs.map +1 -0
  36. package/dist/output-D_G_JR_8.d.mts +24 -0
  37. package/dist/output-D_G_JR_8.d.mts.map +1 -0
  38. package/dist/patch/index.d.mts +2 -2
  39. package/dist/patch/index.mjs +1 -1
  40. package/dist/{patch-DEPPafeB.mjs → patch-BmRfghOo.mjs} +67 -86
  41. package/dist/patch-BmRfghOo.mjs.map +1 -0
  42. package/dist/smartart/index.d.mts +1 -1
  43. package/dist/smartart/index.mjs +1 -1
  44. package/dist/{smartart-DCY-Vdv7.mjs → smartart-B7ukZ-Tw.mjs} +5 -3
  45. package/dist/smartart-B7ukZ-Tw.mjs.map +1 -0
  46. package/dist/theme/index.d.mts +1 -1
  47. package/dist/theme-CiNzdl-9.mjs +2 -0
  48. package/dist/theme-CiNzdl-9.mjs.map +1 -0
  49. package/dist/util/index.d.mts +4 -0
  50. package/dist/util/index.mjs +3 -0
  51. package/dist/util-Tq9PSjK0.mjs +1113 -0
  52. package/dist/util-Tq9PSjK0.mjs.map +1 -0
  53. package/dist/values-8di32lIe.d.mts +56 -0
  54. package/dist/values-8di32lIe.d.mts.map +1 -0
  55. package/package.json +7 -6
  56. package/dist/index-CHGFwCCQ.d.mts +0 -266
  57. package/dist/index-CpNwAcem.d.mts +0 -169
  58. package/dist/index-DdXU1_sq.d.mts +0 -5029
  59. package/dist/util/values.d.mts +0 -2
  60. package/dist/util/values.mjs +0 -2
  61. package/dist/values-CVIZcTRw.mjs +0 -371
  62. package/dist/values-DQfI1FSg.d.mts +0 -426
@@ -1,2957 +1,6 @@
1
- import "./patch-DEPPafeB.mjs";
2
- import "./smartart-DCY-Vdv7.mjs";
3
- import "./chart-DwE8FCFk.mjs";
4
- import { d as stringify$1, u as parse$1 } from "./descriptor-DAER86Rt.mjs";
5
- import "./theme-CiNzdl-9.mjs";
6
- import { attr, attrMeasure, attrNum, element, escapeXml, findChild, js2xml, stringify, textOf, xml2js } from "@office-open/xml";
7
- import { AsyncZipDeflate, Zip, ZipPassThrough, strFromU8, strFromU8 as strFromU8$1, strToU8, unzipSync, unzipSync as unzipSync$1, zip, zipSync } from "fflate";
8
- import { sha1 } from "@noble/hashes/legacy.js";
9
- import { bytesToHex } from "@noble/hashes/utils.js";
10
- import { sha512 } from "@noble/hashes/sha2.js";
11
- //#region src/opc/relationships.ts
12
- const TargetModeType = { EXTERNAL: "External" };
13
- /**
14
- * Manages OOXML relationship entries and serializes to XML.
15
- *
16
- * Standalone class — no XmlComponent inheritance.
17
- * Pure string concatenation for zero-allocation XML output.
18
- */
19
- var Relationships = class {
20
- entries = [];
21
- addRelationship(id, type, target, targetMode) {
22
- this.entries.push({
23
- id: `rId${id}`,
24
- type,
25
- target,
26
- targetMode
27
- });
28
- }
29
- get relationshipCount() {
30
- return this.entries.length;
31
- }
32
- /** Directly builds XML string — zero intermediate tree allocation. */
33
- serialize() {
34
- const p = ["<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"];
35
- for (const e of this.entries) {
36
- const tm = e.targetMode ? ` TargetMode="${escapeXml(e.targetMode)}"` : "";
37
- p.push(`<Relationship Id="${escapeXml(e.id)}" Type="${escapeXml(e.type)}" Target="${escapeXml(e.target)}"${tm}/>`);
38
- }
39
- p.push("</Relationships>");
40
- return p.join("");
41
- }
42
- };
43
- /**
44
- * Serialize a Relationships part only when it carries at least one
45
- * relationship. Optional parts (fontTable, headers, footers, charts, drawings,
46
- * worksheets, …) emit no .rels part when empty — Office strips empty rels
47
- * shells when re-saving, so skipping them keeps generated packages free of
48
- * redundant empty parts and matches Office's normalized output.
49
- *
50
- * Always-on parts (the package `_rels/.rels` and the main
51
- * document/presentation/workbook parts) carry relationships by construction
52
- * and must NOT use this gate.
53
- */
54
- function optionalRelsPart(rel, xmlDeclaration, path) {
55
- return rel.relationshipCount > 0 ? {
56
- data: xmlDeclaration + rel.serialize(),
57
- path
58
- } : void 0;
59
- }
60
- //#endregion
61
- //#region src/opc/media.ts
62
- /**
63
- * FNV-1a hash is a pure function of the bytes, so memoize it across
64
- * {@link Media} instances — repeated `generate()` calls that reuse the same
65
- * buffer objects (the common case) skip recomputation entirely.
66
- */
67
- const hashKeyCache = /* @__PURE__ */ new WeakMap();
68
- /**
69
- * Shared media collection for docx/pptx/xlsx. Generic over the package's entry
70
- * type so each package keeps its own metadata while sharing the registration +
71
- * dedup logic.
72
- */
73
- var Media = class {
74
- map = /* @__PURE__ */ new Map();
75
- /** FNV-1a content key ("len:hash") -> canonical file name, for cross-object dedup. */
76
- byContent = /* @__PURE__ */ new Map();
77
- /** Memoized result per input buffer — the repeated-reference hot path. */
78
- verified = /* @__PURE__ */ new WeakMap();
79
- counter = 0;
80
- /**
81
- * Register media, reusing the existing entry when the bytes already exist.
82
- * Returns the canonical entry (shared across all identical references) —
83
- * callers read `entry.fileName` for placeholders/relationship targets or use
84
- * the whole entry (e.g. drawing XML). The `build` callback constructs the
85
- * package-specific entry from the allocated file name.
86
- *
87
- * Pass `fileName` to pin the name (round-trip scenarios preserving a source
88
- * file name); omit it to allocate the next sequential `imageN.ext`.
89
- */
90
- addMedia(data, type, build, fileName) {
91
- const verifiedName = this.verified.get(data);
92
- if (verifiedName !== void 0) {
93
- const existing = this.map.get(verifiedName);
94
- if (existing.type === type) return existing;
95
- }
96
- const key = `${type}:${this.contentKey(data)}`;
97
- const existingName = this.byContent.get(key);
98
- if (existingName !== void 0) {
99
- const existing = this.map.get(existingName);
100
- if (existing.type === type && this.byteEqual(existing.data, data)) {
101
- this.verified.set(data, existingName);
102
- return existing;
103
- }
104
- }
105
- const resolvedName = fileName ?? this.nextName(type);
106
- const finalName = this.map.has(resolvedName) ? this.nextName(type) : resolvedName;
107
- const entry = build(finalName);
108
- this.map.set(finalName, entry);
109
- this.byContent.set(key, finalName);
110
- this.verified.set(data, finalName);
111
- return entry;
112
- }
113
- /** Next sequential `imageN.${type}` that isn't already in use. */
114
- nextName(type) {
115
- let name = `image${++this.counter}.${type}`;
116
- while (this.map.has(name)) name = `image${++this.counter}.${type}`;
117
- return name;
118
- }
119
- /** "length:hash" content key for `data` (FNV-1a over the raw bytes), memoized. */
120
- contentKey(data) {
121
- const cached = hashKeyCache.get(data);
122
- if (cached !== void 0) return cached;
123
- let hash = 2166136261;
124
- for (let i = 0; i < data.length; i++) {
125
- hash ^= data[i];
126
- hash = Math.imul(hash, 16777619);
127
- }
128
- const key = `${data.length}:${(hash >>> 0).toString(16)}`;
129
- hashKeyCache.set(data, key);
130
- return key;
131
- }
132
- /** Structural equality with early exit on the first mismatch. */
133
- byteEqual(a, b) {
134
- if (a.length !== b.length) return false;
135
- for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
136
- return true;
137
- }
138
- /** All registered media entries. */
139
- get array() {
140
- return [...this.map.values()];
141
- }
142
- };
143
- //#endregion
144
- //#region src/opc/content-types.ts
145
- /**
146
- * Creates a Default element mapping a file extension to a MIME content type.
147
- */
148
- const createDefault = (contentType, extension) => extension !== void 0 ? `<Default ContentType="${contentType}" Extension="${extension}"/>` : `<Default ContentType="${contentType}"/>`;
149
- /**
150
- * Creates an Override element mapping a specific part path to a MIME content type.
151
- */
152
- const createOverride = (contentType, partName) => partName !== void 0 ? `<Override ContentType="${contentType}" PartName="${partName}"/>` : `<Override ContentType="${contentType}"/>`;
153
- //#endregion
154
- //#region src/opc/app-properties.ts
155
- /**
156
- * Extended (App) Properties module — shared OPC part (docProps/app.xml).
157
- *
158
- * Format-agnostic: CT_Properties (ISO-IEC29500-2_2016 shared-documentPropertiesExtended.xsd)
159
- * is identical across docx/pptx/xlsx. Each package surfaces only the fields it populates
160
- * (Pages/Words for docx, Slides for pptx, etc.) — all fields are optional.
161
- *
162
- * @module
163
- */
164
- /** xsd:boolean lexical form — spec canonical form is "true"/"false" (Word's convention). */
165
- const xsdBoolean = (value) => value ? "true" : "false";
166
- const appPropertiesDesc = {
167
- kind: "custom",
168
- stringify(opts, _ctx) {
169
- const p = ["<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\" xmlns:vt=\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\">"];
170
- if (opts.template !== void 0) p.push(`<Template>${escapeXml(opts.template)}</Template>`);
171
- if (opts.manager !== void 0) p.push(`<Manager>${escapeXml(opts.manager)}</Manager>`);
172
- if (opts.company !== void 0) p.push(`<Company>${escapeXml(opts.company)}</Company>`);
173
- if (opts.pages !== void 0) p.push(`<Pages>${opts.pages}</Pages>`);
174
- if (opts.words !== void 0) p.push(`<Words>${opts.words}</Words>`);
175
- if (opts.characters !== void 0) p.push(`<Characters>${opts.characters}</Characters>`);
176
- if (opts.lines !== void 0) p.push(`<Lines>${opts.lines}</Lines>`);
177
- if (opts.paragraphs !== void 0) p.push(`<Paragraphs>${opts.paragraphs}</Paragraphs>`);
178
- if (opts.slides !== void 0) p.push(`<Slides>${opts.slides}</Slides>`);
179
- if (opts.notes !== void 0) p.push(`<Notes>${opts.notes}</Notes>`);
180
- if (opts.totalTime !== void 0) p.push(`<TotalTime>${opts.totalTime}</TotalTime>`);
181
- if (opts.hiddenSlides !== void 0) p.push(`<HiddenSlides>${opts.hiddenSlides}</HiddenSlides>`);
182
- if (opts.mmClips !== void 0) p.push(`<MMClips>${opts.mmClips}</MMClips>`);
183
- if (opts.scaleCrop !== void 0) p.push(`<ScaleCrop>${xsdBoolean(opts.scaleCrop)}</ScaleCrop>`);
184
- if (opts.linksUpToDate !== void 0) p.push(`<LinksUpToDate>${xsdBoolean(opts.linksUpToDate)}</LinksUpToDate>`);
185
- if (opts.charactersWithSpaces !== void 0) p.push(`<CharactersWithSpaces>${opts.charactersWithSpaces}</CharactersWithSpaces>`);
186
- if (opts.sharedDoc !== void 0) p.push(`<SharedDoc>${xsdBoolean(opts.sharedDoc)}</SharedDoc>`);
187
- if (opts.hyperlinkBase !== void 0) p.push(`<HyperlinkBase>${escapeXml(opts.hyperlinkBase)}</HyperlinkBase>`);
188
- if (opts.hyperlinksChanged !== void 0) p.push(`<HyperlinksChanged>${xsdBoolean(opts.hyperlinksChanged)}</HyperlinksChanged>`);
189
- if (opts.application !== void 0) p.push(`<Application>${escapeXml(opts.application)}</Application>`);
190
- if (opts.appVersion !== void 0) p.push(`<AppVersion>${escapeXml(opts.appVersion)}</AppVersion>`);
191
- if (opts.docSecurity !== void 0) p.push(`<DocSecurity>${opts.docSecurity}</DocSecurity>`);
192
- p.push("</Properties>");
193
- return p.join("");
194
- },
195
- parse(el, _ctx) {
196
- const result = {};
197
- for (const child of el.elements ?? []) {
198
- if (typeof child.name !== "string") continue;
199
- const text = child.elements?.[0]?.text;
200
- switch (child.name) {
201
- case "Template":
202
- if (typeof text === "string") result.template = text;
203
- break;
204
- case "Manager":
205
- if (typeof text === "string") result.manager = text;
206
- break;
207
- case "Company":
208
- if (typeof text === "string") result.company = text;
209
- break;
210
- case "Pages":
211
- if (typeof text === "string") result.pages = Number(text);
212
- break;
213
- case "Words":
214
- if (typeof text === "string") result.words = Number(text);
215
- break;
216
- case "Characters":
217
- if (typeof text === "string") result.characters = Number(text);
218
- break;
219
- case "Lines":
220
- if (typeof text === "string") result.lines = Number(text);
221
- break;
222
- case "Paragraphs":
223
- if (typeof text === "string") result.paragraphs = Number(text);
224
- break;
225
- case "Slides":
226
- if (typeof text === "string") result.slides = Number(text);
227
- break;
228
- case "Notes":
229
- if (typeof text === "string") result.notes = Number(text);
230
- break;
231
- case "TotalTime":
232
- if (typeof text === "string") result.totalTime = Number(text);
233
- break;
234
- case "HiddenSlides":
235
- if (typeof text === "string") result.hiddenSlides = Number(text);
236
- break;
237
- case "MMClips":
238
- if (typeof text === "string") result.mmClips = Number(text);
239
- break;
240
- case "ScaleCrop":
241
- if (typeof text === "string") result.scaleCrop = text === "1" || text === "true";
242
- break;
243
- case "LinksUpToDate":
244
- if (typeof text === "string") result.linksUpToDate = text === "1" || text === "true";
245
- break;
246
- case "CharactersWithSpaces":
247
- if (typeof text === "string") result.charactersWithSpaces = Number(text);
248
- break;
249
- case "SharedDoc":
250
- if (typeof text === "string") result.sharedDoc = text === "1" || text === "true";
251
- break;
252
- case "HyperlinkBase":
253
- if (typeof text === "string") result.hyperlinkBase = text;
254
- break;
255
- case "HyperlinksChanged":
256
- if (typeof text === "string") result.hyperlinksChanged = text === "1" || text === "true";
257
- break;
258
- case "Application":
259
- if (typeof text === "string") result.application = text;
260
- break;
261
- case "AppVersion":
262
- if (typeof text === "string") result.appVersion = text;
263
- break;
264
- case "DocSecurity":
265
- if (typeof text === "string") result.docSecurity = Number(text);
266
- break;
267
- }
268
- }
269
- return result;
270
- }
271
- };
272
- //#endregion
273
- //#region src/opc/custom-properties.ts
274
- /**
275
- * Custom Properties module — shared OPC part (docProps/custom.xml).
276
- *
277
- * Format-agnostic: CT_CustomProperties (ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd)
278
- * is identical across docx/pptx/xlsx.
279
- *
280
- * @module
281
- */
282
- const customPropertiesDesc = {
283
- kind: "custom",
284
- stringify(opts, _ctx) {
285
- const p = ["<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/custom-properties\" xmlns:vt=\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\">"];
286
- let pid = 2;
287
- for (const prop of opts.properties) {
288
- p.push(`<property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="${pid}" name="${escapeXml(prop.name)}"><vt:lpwstr>${escapeXml(prop.value)}</vt:lpwstr></property>`);
289
- pid++;
290
- }
291
- p.push("</Properties>");
292
- return p.join("");
293
- },
294
- parse(el, _ctx) {
295
- const properties = [];
296
- for (const child of el.elements ?? []) {
297
- if (child.name !== "property") continue;
298
- const name = attr(child, "name");
299
- if (!name) continue;
300
- const valueEl = child.elements?.find((e) => e.name?.startsWith("vt:"));
301
- const value = valueEl ? textOf(valueEl) ?? "" : "";
302
- properties.push({
303
- name,
304
- value
305
- });
306
- }
307
- return { properties };
308
- }
309
- };
310
- //#endregion
311
- //#region \0polyfill-node.global.js
312
- var _polyfill_node_global_default = typeof _polyfill_node_global_default !== "undefined" ? _polyfill_node_global_default : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
313
- //#endregion
314
- //#region \0polyfill-node.buffer.js
315
- var lookup = [];
316
- var revLookup = [];
317
- var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
318
- var inited = false;
319
- function init() {
320
- inited = true;
321
- var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
322
- for (var i = 0, len = code.length; i < len; ++i) {
323
- lookup[i] = code[i];
324
- revLookup[code.charCodeAt(i)] = i;
325
- }
326
- revLookup["-".charCodeAt(0)] = 62;
327
- revLookup["_".charCodeAt(0)] = 63;
328
- }
329
- function toByteArray(b64) {
330
- if (!inited) init();
331
- var i, j, l, tmp, placeHolders, arr;
332
- var len = b64.length;
333
- if (len % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4");
334
- placeHolders = b64[len - 2] === "=" ? 2 : b64[len - 1] === "=" ? 1 : 0;
335
- arr = new Arr(len * 3 / 4 - placeHolders);
336
- l = placeHolders > 0 ? len - 4 : len;
337
- var L = 0;
338
- for (i = 0, j = 0; i < l; i += 4, j += 3) {
339
- tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
340
- arr[L++] = tmp >> 16 & 255;
341
- arr[L++] = tmp >> 8 & 255;
342
- arr[L++] = tmp & 255;
343
- }
344
- if (placeHolders === 2) {
345
- tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
346
- arr[L++] = tmp & 255;
347
- } else if (placeHolders === 1) {
348
- tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
349
- arr[L++] = tmp >> 8 & 255;
350
- arr[L++] = tmp & 255;
351
- }
352
- return arr;
353
- }
354
- function tripletToBase64(num) {
355
- return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
356
- }
357
- function encodeChunk(uint8, start, end) {
358
- var tmp;
359
- var output = [];
360
- for (var i = start; i < end; i += 3) {
361
- tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
362
- output.push(tripletToBase64(tmp));
363
- }
364
- return output.join("");
365
- }
366
- function fromByteArray(uint8) {
367
- if (!inited) init();
368
- var tmp;
369
- var len = uint8.length;
370
- var extraBytes = len % 3;
371
- var output = "";
372
- var parts = [];
373
- var maxChunkLength = 16383;
374
- for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
375
- if (extraBytes === 1) {
376
- tmp = uint8[len - 1];
377
- output += lookup[tmp >> 2];
378
- output += lookup[tmp << 4 & 63];
379
- output += "==";
380
- } else if (extraBytes === 2) {
381
- tmp = (uint8[len - 2] << 8) + uint8[len - 1];
382
- output += lookup[tmp >> 10];
383
- output += lookup[tmp >> 4 & 63];
384
- output += lookup[tmp << 2 & 63];
385
- output += "=";
386
- }
387
- parts.push(output);
388
- return parts.join("");
389
- }
390
- function read(buffer, offset, isLE, mLen, nBytes) {
391
- var e, m;
392
- var eLen = nBytes * 8 - mLen - 1;
393
- var eMax = (1 << eLen) - 1;
394
- var eBias = eMax >> 1;
395
- var nBits = -7;
396
- var i = isLE ? nBytes - 1 : 0;
397
- var d = isLE ? -1 : 1;
398
- var s = buffer[offset + i];
399
- i += d;
400
- e = s & (1 << -nBits) - 1;
401
- s >>= -nBits;
402
- nBits += eLen;
403
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
404
- m = e & (1 << -nBits) - 1;
405
- e >>= -nBits;
406
- nBits += mLen;
407
- for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
408
- if (e === 0) e = 1 - eBias;
409
- else if (e === eMax) return m ? NaN : (s ? -1 : 1) * Infinity;
410
- else {
411
- m = m + Math.pow(2, mLen);
412
- e = e - eBias;
413
- }
414
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
415
- }
416
- function write(buffer, value, offset, isLE, mLen, nBytes) {
417
- var e, m, c;
418
- var eLen = nBytes * 8 - mLen - 1;
419
- var eMax = (1 << eLen) - 1;
420
- var eBias = eMax >> 1;
421
- var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
422
- var i = isLE ? 0 : nBytes - 1;
423
- var d = isLE ? 1 : -1;
424
- var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
425
- value = Math.abs(value);
426
- if (isNaN(value) || value === Infinity) {
427
- m = isNaN(value) ? 1 : 0;
428
- e = eMax;
429
- } else {
430
- e = Math.floor(Math.log(value) / Math.LN2);
431
- if (value * (c = Math.pow(2, -e)) < 1) {
432
- e--;
433
- c *= 2;
434
- }
435
- if (e + eBias >= 1) value += rt / c;
436
- else value += rt * Math.pow(2, 1 - eBias);
437
- if (value * c >= 2) {
438
- e++;
439
- c /= 2;
440
- }
441
- if (e + eBias >= eMax) {
442
- m = 0;
443
- e = eMax;
444
- } else if (e + eBias >= 1) {
445
- m = (value * c - 1) * Math.pow(2, mLen);
446
- e = e + eBias;
447
- } else {
448
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
449
- e = 0;
450
- }
451
- }
452
- for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8);
453
- e = e << mLen | m;
454
- eLen += mLen;
455
- for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8);
456
- buffer[offset + i - d] |= s * 128;
457
- }
458
- var toString = {}.toString;
459
- var isArray = Array.isArray || function(arr) {
460
- return toString.call(arr) == "[object Array]";
461
- };
462
- /*!
463
- * The buffer module from node.js, for the browser.
464
- *
465
- * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
466
- * @license MIT
467
- */
468
- /**
469
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
470
- * === true Use Uint8Array implementation (fastest)
471
- * === false Use Object implementation (most compatible, even IE6)
472
- *
473
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
474
- * Opera 11.6+, iOS 4.2+.
475
- *
476
- * Due to various browser bugs, sometimes the Object implementation will be used even
477
- * when the browser supports typed arrays.
478
- *
479
- * Note:
480
- *
481
- * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
482
- * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
483
- *
484
- * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
485
- *
486
- * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
487
- * incorrect length in some situations.
488
-
489
- * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
490
- * get the Object implementation, which is slower but behaves correctly.
491
- */
492
- Buffer.TYPED_ARRAY_SUPPORT = _polyfill_node_global_default.TYPED_ARRAY_SUPPORT !== void 0 ? _polyfill_node_global_default.TYPED_ARRAY_SUPPORT : true;
493
- kMaxLength();
494
- function kMaxLength() {
495
- return Buffer.TYPED_ARRAY_SUPPORT ? 2147483647 : 1073741823;
496
- }
497
- function createBuffer(that, length) {
498
- if (kMaxLength() < length) throw new RangeError("Invalid typed array length");
499
- if (Buffer.TYPED_ARRAY_SUPPORT) {
500
- that = new Uint8Array(length);
501
- that.__proto__ = Buffer.prototype;
502
- } else {
503
- if (that === null) that = new Buffer(length);
504
- that.length = length;
505
- }
506
- return that;
507
- }
508
- /**
509
- * The Buffer constructor returns instances of `Uint8Array` that have their
510
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
511
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
512
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
513
- * returns a single octet.
514
- *
515
- * The `Uint8Array` prototype remains unmodified.
516
- */
517
- function Buffer(arg, encodingOrOffset, length) {
518
- if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) return new Buffer(arg, encodingOrOffset, length);
519
- if (typeof arg === "number") {
520
- if (typeof encodingOrOffset === "string") throw new Error("If encoding is specified then the first argument must be a string");
521
- return allocUnsafe(this, arg);
522
- }
523
- return from(this, arg, encodingOrOffset, length);
524
- }
525
- Buffer.poolSize = 8192;
526
- Buffer._augment = function(arr) {
527
- arr.__proto__ = Buffer.prototype;
528
- return arr;
529
- };
530
- function from(that, value, encodingOrOffset, length) {
531
- if (typeof value === "number") throw new TypeError("\"value\" argument must not be a number");
532
- if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) return fromArrayBuffer(that, value, encodingOrOffset, length);
533
- if (typeof value === "string") return fromString(that, value, encodingOrOffset);
534
- return fromObject(that, value);
535
- }
536
- /**
537
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
538
- * if value is a number.
539
- * Buffer.from(str[, encoding])
540
- * Buffer.from(array)
541
- * Buffer.from(buffer)
542
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
543
- **/
544
- Buffer.from = function(value, encodingOrOffset, length) {
545
- return from(null, value, encodingOrOffset, length);
546
- };
547
- if (Buffer.TYPED_ARRAY_SUPPORT) {
548
- Buffer.prototype.__proto__ = Uint8Array.prototype;
549
- Buffer.__proto__ = Uint8Array;
550
- if (typeof Symbol !== "undefined" && Symbol.species && Buffer[Symbol.species] === Buffer);
551
- }
552
- function assertSize(size) {
553
- if (typeof size !== "number") throw new TypeError("\"size\" argument must be a number");
554
- else if (size < 0) throw new RangeError("\"size\" argument must not be negative");
555
- }
556
- function alloc(that, size, fill, encoding) {
557
- assertSize(size);
558
- if (size <= 0) return createBuffer(that, size);
559
- if (fill !== void 0) return typeof encoding === "string" ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill);
560
- return createBuffer(that, size);
561
- }
562
- /**
563
- * Creates a new filled Buffer instance.
564
- * alloc(size[, fill[, encoding]])
565
- **/
566
- Buffer.alloc = function(size, fill, encoding) {
567
- return alloc(null, size, fill, encoding);
568
- };
569
- function allocUnsafe(that, size) {
570
- assertSize(size);
571
- that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
572
- if (!Buffer.TYPED_ARRAY_SUPPORT) for (var i = 0; i < size; ++i) that[i] = 0;
573
- return that;
574
- }
575
- /**
576
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
577
- * */
578
- Buffer.allocUnsafe = function(size) {
579
- return allocUnsafe(null, size);
580
- };
581
- /**
582
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
583
- */
584
- Buffer.allocUnsafeSlow = function(size) {
585
- return allocUnsafe(null, size);
586
- };
587
- function fromString(that, string, encoding) {
588
- if (typeof encoding !== "string" || encoding === "") encoding = "utf8";
589
- if (!Buffer.isEncoding(encoding)) throw new TypeError("\"encoding\" must be a valid string encoding");
590
- var length = byteLength(string, encoding) | 0;
591
- that = createBuffer(that, length);
592
- var actual = that.write(string, encoding);
593
- if (actual !== length) that = that.slice(0, actual);
594
- return that;
595
- }
596
- function fromArrayLike(that, array) {
597
- var length = array.length < 0 ? 0 : checked(array.length) | 0;
598
- that = createBuffer(that, length);
599
- for (var i = 0; i < length; i += 1) that[i] = array[i] & 255;
600
- return that;
601
- }
602
- function fromArrayBuffer(that, array, byteOffset, length) {
603
- array.byteLength;
604
- if (byteOffset < 0 || array.byteLength < byteOffset) throw new RangeError("'offset' is out of bounds");
605
- if (array.byteLength < byteOffset + (length || 0)) throw new RangeError("'length' is out of bounds");
606
- if (byteOffset === void 0 && length === void 0) array = new Uint8Array(array);
607
- else if (length === void 0) array = new Uint8Array(array, byteOffset);
608
- else array = new Uint8Array(array, byteOffset, length);
609
- if (Buffer.TYPED_ARRAY_SUPPORT) {
610
- that = array;
611
- that.__proto__ = Buffer.prototype;
612
- } else that = fromArrayLike(that, array);
613
- return that;
614
- }
615
- function fromObject(that, obj) {
616
- if (internalIsBuffer(obj)) {
617
- var len = checked(obj.length) | 0;
618
- that = createBuffer(that, len);
619
- if (that.length === 0) return that;
620
- obj.copy(that, 0, 0, len);
621
- return that;
622
- }
623
- if (obj) {
624
- if (typeof ArrayBuffer !== "undefined" && obj.buffer instanceof ArrayBuffer || "length" in obj) {
625
- if (typeof obj.length !== "number" || isnan(obj.length)) return createBuffer(that, 0);
626
- return fromArrayLike(that, obj);
627
- }
628
- if (obj.type === "Buffer" && isArray(obj.data)) return fromArrayLike(that, obj.data);
629
- }
630
- throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.");
631
- }
632
- function checked(length) {
633
- if (length >= kMaxLength()) throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + kMaxLength().toString(16) + " bytes");
634
- return length | 0;
635
- }
636
- Buffer.isBuffer = isBuffer;
637
- function internalIsBuffer(b) {
638
- return !!(b != null && b._isBuffer);
639
- }
640
- Buffer.compare = function compare(a, b) {
641
- if (!internalIsBuffer(a) || !internalIsBuffer(b)) throw new TypeError("Arguments must be Buffers");
642
- if (a === b) return 0;
643
- var x = a.length;
644
- var y = b.length;
645
- for (var i = 0, len = Math.min(x, y); i < len; ++i) if (a[i] !== b[i]) {
646
- x = a[i];
647
- y = b[i];
648
- break;
649
- }
650
- if (x < y) return -1;
651
- if (y < x) return 1;
652
- return 0;
653
- };
654
- Buffer.isEncoding = function isEncoding(encoding) {
655
- switch (String(encoding).toLowerCase()) {
656
- case "hex":
657
- case "utf8":
658
- case "utf-8":
659
- case "ascii":
660
- case "latin1":
661
- case "binary":
662
- case "base64":
663
- case "ucs2":
664
- case "ucs-2":
665
- case "utf16le":
666
- case "utf-16le": return true;
667
- default: return false;
668
- }
669
- };
670
- Buffer.concat = function concat(list, length) {
671
- if (!isArray(list)) throw new TypeError("\"list\" argument must be an Array of Buffers");
672
- if (list.length === 0) return Buffer.alloc(0);
673
- var i;
674
- if (length === void 0) {
675
- length = 0;
676
- for (i = 0; i < list.length; ++i) length += list[i].length;
677
- }
678
- var buffer = Buffer.allocUnsafe(length);
679
- var pos = 0;
680
- for (i = 0; i < list.length; ++i) {
681
- var buf = list[i];
682
- if (!internalIsBuffer(buf)) throw new TypeError("\"list\" argument must be an Array of Buffers");
683
- buf.copy(buffer, pos);
684
- pos += buf.length;
685
- }
686
- return buffer;
687
- };
688
- function byteLength(string, encoding) {
689
- if (internalIsBuffer(string)) return string.length;
690
- if (typeof ArrayBuffer !== "undefined" && typeof ArrayBuffer.isView === "function" && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) return string.byteLength;
691
- if (typeof string !== "string") string = "" + string;
692
- var len = string.length;
693
- if (len === 0) return 0;
694
- var loweredCase = false;
695
- for (;;) switch (encoding) {
696
- case "ascii":
697
- case "latin1":
698
- case "binary": return len;
699
- case "utf8":
700
- case "utf-8":
701
- case void 0: return utf8ToBytes(string).length;
702
- case "ucs2":
703
- case "ucs-2":
704
- case "utf16le":
705
- case "utf-16le": return len * 2;
706
- case "hex": return len >>> 1;
707
- case "base64": return base64ToBytes(string).length;
708
- default:
709
- if (loweredCase) return utf8ToBytes(string).length;
710
- encoding = ("" + encoding).toLowerCase();
711
- loweredCase = true;
712
- }
713
- }
714
- Buffer.byteLength = byteLength;
715
- function slowToString(encoding, start, end) {
716
- var loweredCase = false;
717
- if (start === void 0 || start < 0) start = 0;
718
- if (start > this.length) return "";
719
- if (end === void 0 || end > this.length) end = this.length;
720
- if (end <= 0) return "";
721
- end >>>= 0;
722
- start >>>= 0;
723
- if (end <= start) return "";
724
- if (!encoding) encoding = "utf8";
725
- while (true) switch (encoding) {
726
- case "hex": return hexSlice(this, start, end);
727
- case "utf8":
728
- case "utf-8": return utf8Slice(this, start, end);
729
- case "ascii": return asciiSlice(this, start, end);
730
- case "latin1":
731
- case "binary": return latin1Slice(this, start, end);
732
- case "base64": return base64Slice(this, start, end);
733
- case "ucs2":
734
- case "ucs-2":
735
- case "utf16le":
736
- case "utf-16le": return utf16leSlice(this, start, end);
737
- default:
738
- if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
739
- encoding = (encoding + "").toLowerCase();
740
- loweredCase = true;
741
- }
742
- }
743
- Buffer.prototype._isBuffer = true;
744
- function swap(b, n, m) {
745
- var i = b[n];
746
- b[n] = b[m];
747
- b[m] = i;
748
- }
749
- Buffer.prototype.swap16 = function swap16() {
750
- var len = this.length;
751
- if (len % 2 !== 0) throw new RangeError("Buffer size must be a multiple of 16-bits");
752
- for (var i = 0; i < len; i += 2) swap(this, i, i + 1);
753
- return this;
754
- };
755
- Buffer.prototype.swap32 = function swap32() {
756
- var len = this.length;
757
- if (len % 4 !== 0) throw new RangeError("Buffer size must be a multiple of 32-bits");
758
- for (var i = 0; i < len; i += 4) {
759
- swap(this, i, i + 3);
760
- swap(this, i + 1, i + 2);
761
- }
762
- return this;
763
- };
764
- Buffer.prototype.swap64 = function swap64() {
765
- var len = this.length;
766
- if (len % 8 !== 0) throw new RangeError("Buffer size must be a multiple of 64-bits");
767
- for (var i = 0; i < len; i += 8) {
768
- swap(this, i, i + 7);
769
- swap(this, i + 1, i + 6);
770
- swap(this, i + 2, i + 5);
771
- swap(this, i + 3, i + 4);
772
- }
773
- return this;
774
- };
775
- Buffer.prototype.toString = function toString() {
776
- var length = this.length | 0;
777
- if (length === 0) return "";
778
- if (arguments.length === 0) return utf8Slice(this, 0, length);
779
- return slowToString.apply(this, arguments);
780
- };
781
- Buffer.prototype.equals = function equals(b) {
782
- if (!internalIsBuffer(b)) throw new TypeError("Argument must be a Buffer");
783
- if (this === b) return true;
784
- return Buffer.compare(this, b) === 0;
785
- };
786
- Buffer.prototype.inspect = function inspect() {
787
- var str = "";
788
- var max = 50;
789
- if (this.length > 0) {
790
- str = this.toString("hex", 0, max).match(/.{2}/g).join(" ");
791
- if (this.length > max) str += " ... ";
792
- }
793
- return "<Buffer " + str + ">";
794
- };
795
- Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
796
- if (!internalIsBuffer(target)) throw new TypeError("Argument must be a Buffer");
797
- if (start === void 0) start = 0;
798
- if (end === void 0) end = target ? target.length : 0;
799
- if (thisStart === void 0) thisStart = 0;
800
- if (thisEnd === void 0) thisEnd = this.length;
801
- if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) throw new RangeError("out of range index");
802
- if (thisStart >= thisEnd && start >= end) return 0;
803
- if (thisStart >= thisEnd) return -1;
804
- if (start >= end) return 1;
805
- start >>>= 0;
806
- end >>>= 0;
807
- thisStart >>>= 0;
808
- thisEnd >>>= 0;
809
- if (this === target) return 0;
810
- var x = thisEnd - thisStart;
811
- var y = end - start;
812
- var len = Math.min(x, y);
813
- var thisCopy = this.slice(thisStart, thisEnd);
814
- var targetCopy = target.slice(start, end);
815
- for (var i = 0; i < len; ++i) if (thisCopy[i] !== targetCopy[i]) {
816
- x = thisCopy[i];
817
- y = targetCopy[i];
818
- break;
819
- }
820
- if (x < y) return -1;
821
- if (y < x) return 1;
822
- return 0;
823
- };
824
- function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
825
- if (buffer.length === 0) return -1;
826
- if (typeof byteOffset === "string") {
827
- encoding = byteOffset;
828
- byteOffset = 0;
829
- } else if (byteOffset > 2147483647) byteOffset = 2147483647;
830
- else if (byteOffset < -2147483648) byteOffset = -2147483648;
831
- byteOffset = +byteOffset;
832
- if (isNaN(byteOffset)) byteOffset = dir ? 0 : buffer.length - 1;
833
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
834
- if (byteOffset >= buffer.length) if (dir) return -1;
835
- else byteOffset = buffer.length - 1;
836
- else if (byteOffset < 0) if (dir) byteOffset = 0;
837
- else return -1;
838
- if (typeof val === "string") val = Buffer.from(val, encoding);
839
- if (internalIsBuffer(val)) {
840
- if (val.length === 0) return -1;
841
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
842
- } else if (typeof val === "number") {
843
- val = val & 255;
844
- if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === "function") if (dir) return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
845
- else return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
846
- return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
847
- }
848
- throw new TypeError("val must be string, number or Buffer");
849
- }
850
- function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
851
- var indexSize = 1;
852
- var arrLength = arr.length;
853
- var valLength = val.length;
854
- if (encoding !== void 0) {
855
- encoding = String(encoding).toLowerCase();
856
- if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
857
- if (arr.length < 2 || val.length < 2) return -1;
858
- indexSize = 2;
859
- arrLength /= 2;
860
- valLength /= 2;
861
- byteOffset /= 2;
862
- }
863
- }
864
- function read(buf, i) {
865
- if (indexSize === 1) return buf[i];
866
- else return buf.readUInt16BE(i * indexSize);
867
- }
868
- var i;
869
- if (dir) {
870
- var foundIndex = -1;
871
- for (i = byteOffset; i < arrLength; i++) if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
872
- if (foundIndex === -1) foundIndex = i;
873
- if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
874
- } else {
875
- if (foundIndex !== -1) i -= i - foundIndex;
876
- foundIndex = -1;
877
- }
878
- } else {
879
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
880
- for (i = byteOffset; i >= 0; i--) {
881
- var found = true;
882
- for (var j = 0; j < valLength; j++) if (read(arr, i + j) !== read(val, j)) {
883
- found = false;
884
- break;
885
- }
886
- if (found) return i;
887
- }
888
- }
889
- return -1;
890
- }
891
- Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
892
- return this.indexOf(val, byteOffset, encoding) !== -1;
893
- };
894
- Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
895
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
896
- };
897
- Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
898
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
899
- };
900
- function hexWrite(buf, string, offset, length) {
901
- offset = Number(offset) || 0;
902
- var remaining = buf.length - offset;
903
- if (!length) length = remaining;
904
- else {
905
- length = Number(length);
906
- if (length > remaining) length = remaining;
907
- }
908
- var strLen = string.length;
909
- if (strLen % 2 !== 0) throw new TypeError("Invalid hex string");
910
- if (length > strLen / 2) length = strLen / 2;
911
- for (var i = 0; i < length; ++i) {
912
- var parsed = parseInt(string.substr(i * 2, 2), 16);
913
- if (isNaN(parsed)) return i;
914
- buf[offset + i] = parsed;
915
- }
916
- return i;
917
- }
918
- function utf8Write(buf, string, offset, length) {
919
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
920
- }
921
- function asciiWrite(buf, string, offset, length) {
922
- return blitBuffer(asciiToBytes(string), buf, offset, length);
923
- }
924
- function latin1Write(buf, string, offset, length) {
925
- return asciiWrite(buf, string, offset, length);
926
- }
927
- function base64Write(buf, string, offset, length) {
928
- return blitBuffer(base64ToBytes(string), buf, offset, length);
929
- }
930
- function ucs2Write(buf, string, offset, length) {
931
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
932
- }
933
- Buffer.prototype.write = function write(string, offset, length, encoding) {
934
- if (offset === void 0) {
935
- encoding = "utf8";
936
- length = this.length;
937
- offset = 0;
938
- } else if (length === void 0 && typeof offset === "string") {
939
- encoding = offset;
940
- length = this.length;
941
- offset = 0;
942
- } else if (isFinite(offset)) {
943
- offset = offset | 0;
944
- if (isFinite(length)) {
945
- length = length | 0;
946
- if (encoding === void 0) encoding = "utf8";
947
- } else {
948
- encoding = length;
949
- length = void 0;
950
- }
951
- } else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
952
- var remaining = this.length - offset;
953
- if (length === void 0 || length > remaining) length = remaining;
954
- if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) throw new RangeError("Attempt to write outside buffer bounds");
955
- if (!encoding) encoding = "utf8";
956
- var loweredCase = false;
957
- for (;;) switch (encoding) {
958
- case "hex": return hexWrite(this, string, offset, length);
959
- case "utf8":
960
- case "utf-8": return utf8Write(this, string, offset, length);
961
- case "ascii": return asciiWrite(this, string, offset, length);
962
- case "latin1":
963
- case "binary": return latin1Write(this, string, offset, length);
964
- case "base64": return base64Write(this, string, offset, length);
965
- case "ucs2":
966
- case "ucs-2":
967
- case "utf16le":
968
- case "utf-16le": return ucs2Write(this, string, offset, length);
969
- default:
970
- if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
971
- encoding = ("" + encoding).toLowerCase();
972
- loweredCase = true;
973
- }
974
- };
975
- Buffer.prototype.toJSON = function toJSON() {
976
- return {
977
- type: "Buffer",
978
- data: Array.prototype.slice.call(this._arr || this, 0)
979
- };
980
- };
981
- function base64Slice(buf, start, end) {
982
- if (start === 0 && end === buf.length) return fromByteArray(buf);
983
- else return fromByteArray(buf.slice(start, end));
984
- }
985
- function utf8Slice(buf, start, end) {
986
- end = Math.min(buf.length, end);
987
- var res = [];
988
- var i = start;
989
- while (i < end) {
990
- var firstByte = buf[i];
991
- var codePoint = null;
992
- var bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
993
- if (i + bytesPerSequence <= end) {
994
- var secondByte, thirdByte, fourthByte, tempCodePoint;
995
- switch (bytesPerSequence) {
996
- case 1:
997
- if (firstByte < 128) codePoint = firstByte;
998
- break;
999
- case 2:
1000
- secondByte = buf[i + 1];
1001
- if ((secondByte & 192) === 128) {
1002
- tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
1003
- if (tempCodePoint > 127) codePoint = tempCodePoint;
1004
- }
1005
- break;
1006
- case 3:
1007
- secondByte = buf[i + 1];
1008
- thirdByte = buf[i + 2];
1009
- if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
1010
- tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
1011
- if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) codePoint = tempCodePoint;
1012
- }
1013
- break;
1014
- case 4:
1015
- secondByte = buf[i + 1];
1016
- thirdByte = buf[i + 2];
1017
- fourthByte = buf[i + 3];
1018
- if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
1019
- tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
1020
- if (tempCodePoint > 65535 && tempCodePoint < 1114112) codePoint = tempCodePoint;
1021
- }
1022
- }
1023
- }
1024
- if (codePoint === null) {
1025
- codePoint = 65533;
1026
- bytesPerSequence = 1;
1027
- } else if (codePoint > 65535) {
1028
- codePoint -= 65536;
1029
- res.push(codePoint >>> 10 & 1023 | 55296);
1030
- codePoint = 56320 | codePoint & 1023;
1031
- }
1032
- res.push(codePoint);
1033
- i += bytesPerSequence;
1034
- }
1035
- return decodeCodePointsArray(res);
1036
- }
1037
- var MAX_ARGUMENTS_LENGTH = 4096;
1038
- function decodeCodePointsArray(codePoints) {
1039
- var len = codePoints.length;
1040
- if (len <= MAX_ARGUMENTS_LENGTH) return String.fromCharCode.apply(String, codePoints);
1041
- var res = "";
1042
- var i = 0;
1043
- while (i < len) res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
1044
- return res;
1045
- }
1046
- function asciiSlice(buf, start, end) {
1047
- var ret = "";
1048
- end = Math.min(buf.length, end);
1049
- for (var i = start; i < end; ++i) ret += String.fromCharCode(buf[i] & 127);
1050
- return ret;
1051
- }
1052
- function latin1Slice(buf, start, end) {
1053
- var ret = "";
1054
- end = Math.min(buf.length, end);
1055
- for (var i = start; i < end; ++i) ret += String.fromCharCode(buf[i]);
1056
- return ret;
1057
- }
1058
- function hexSlice(buf, start, end) {
1059
- var len = buf.length;
1060
- if (!start || start < 0) start = 0;
1061
- if (!end || end < 0 || end > len) end = len;
1062
- var out = "";
1063
- for (var i = start; i < end; ++i) out += toHex(buf[i]);
1064
- return out;
1065
- }
1066
- function utf16leSlice(buf, start, end) {
1067
- var bytes = buf.slice(start, end);
1068
- var res = "";
1069
- for (var i = 0; i < bytes.length; i += 2) res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
1070
- return res;
1071
- }
1072
- Buffer.prototype.slice = function slice(start, end) {
1073
- var len = this.length;
1074
- start = ~~start;
1075
- end = end === void 0 ? len : ~~end;
1076
- if (start < 0) {
1077
- start += len;
1078
- if (start < 0) start = 0;
1079
- } else if (start > len) start = len;
1080
- if (end < 0) {
1081
- end += len;
1082
- if (end < 0) end = 0;
1083
- } else if (end > len) end = len;
1084
- if (end < start) end = start;
1085
- var newBuf;
1086
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1087
- newBuf = this.subarray(start, end);
1088
- newBuf.__proto__ = Buffer.prototype;
1089
- } else {
1090
- var sliceLen = end - start;
1091
- newBuf = new Buffer(sliceLen, void 0);
1092
- for (var i = 0; i < sliceLen; ++i) newBuf[i] = this[i + start];
1093
- }
1094
- return newBuf;
1095
- };
1096
- function checkOffset(offset, ext, length) {
1097
- if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
1098
- if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
1099
- }
1100
- Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
1101
- offset = offset | 0;
1102
- byteLength = byteLength | 0;
1103
- if (!noAssert) checkOffset(offset, byteLength, this.length);
1104
- var val = this[offset];
1105
- var mul = 1;
1106
- var i = 0;
1107
- while (++i < byteLength && (mul *= 256)) val += this[offset + i] * mul;
1108
- return val;
1109
- };
1110
- Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
1111
- offset = offset | 0;
1112
- byteLength = byteLength | 0;
1113
- if (!noAssert) checkOffset(offset, byteLength, this.length);
1114
- var val = this[offset + --byteLength];
1115
- var mul = 1;
1116
- while (byteLength > 0 && (mul *= 256)) val += this[offset + --byteLength] * mul;
1117
- return val;
1118
- };
1119
- Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
1120
- if (!noAssert) checkOffset(offset, 1, this.length);
1121
- return this[offset];
1122
- };
1123
- Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
1124
- if (!noAssert) checkOffset(offset, 2, this.length);
1125
- return this[offset] | this[offset + 1] << 8;
1126
- };
1127
- Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
1128
- if (!noAssert) checkOffset(offset, 2, this.length);
1129
- return this[offset] << 8 | this[offset + 1];
1130
- };
1131
- Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
1132
- if (!noAssert) checkOffset(offset, 4, this.length);
1133
- return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
1134
- };
1135
- Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
1136
- if (!noAssert) checkOffset(offset, 4, this.length);
1137
- return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
1138
- };
1139
- Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
1140
- offset = offset | 0;
1141
- byteLength = byteLength | 0;
1142
- if (!noAssert) checkOffset(offset, byteLength, this.length);
1143
- var val = this[offset];
1144
- var mul = 1;
1145
- var i = 0;
1146
- while (++i < byteLength && (mul *= 256)) val += this[offset + i] * mul;
1147
- mul *= 128;
1148
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1149
- return val;
1150
- };
1151
- Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
1152
- offset = offset | 0;
1153
- byteLength = byteLength | 0;
1154
- if (!noAssert) checkOffset(offset, byteLength, this.length);
1155
- var i = byteLength;
1156
- var mul = 1;
1157
- var val = this[offset + --i];
1158
- while (i > 0 && (mul *= 256)) val += this[offset + --i] * mul;
1159
- mul *= 128;
1160
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1161
- return val;
1162
- };
1163
- Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
1164
- if (!noAssert) checkOffset(offset, 1, this.length);
1165
- if (!(this[offset] & 128)) return this[offset];
1166
- return (255 - this[offset] + 1) * -1;
1167
- };
1168
- Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
1169
- if (!noAssert) checkOffset(offset, 2, this.length);
1170
- var val = this[offset] | this[offset + 1] << 8;
1171
- return val & 32768 ? val | 4294901760 : val;
1172
- };
1173
- Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
1174
- if (!noAssert) checkOffset(offset, 2, this.length);
1175
- var val = this[offset + 1] | this[offset] << 8;
1176
- return val & 32768 ? val | 4294901760 : val;
1177
- };
1178
- Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
1179
- if (!noAssert) checkOffset(offset, 4, this.length);
1180
- return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
1181
- };
1182
- Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
1183
- if (!noAssert) checkOffset(offset, 4, this.length);
1184
- return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
1185
- };
1186
- Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
1187
- if (!noAssert) checkOffset(offset, 4, this.length);
1188
- return read(this, offset, true, 23, 4);
1189
- };
1190
- Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
1191
- if (!noAssert) checkOffset(offset, 4, this.length);
1192
- return read(this, offset, false, 23, 4);
1193
- };
1194
- Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
1195
- if (!noAssert) checkOffset(offset, 8, this.length);
1196
- return read(this, offset, true, 52, 8);
1197
- };
1198
- Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
1199
- if (!noAssert) checkOffset(offset, 8, this.length);
1200
- return read(this, offset, false, 52, 8);
1201
- };
1202
- function checkInt(buf, value, offset, ext, max, min) {
1203
- if (!internalIsBuffer(buf)) throw new TypeError("\"buffer\" argument must be a Buffer instance");
1204
- if (value > max || value < min) throw new RangeError("\"value\" argument is out of bounds");
1205
- if (offset + ext > buf.length) throw new RangeError("Index out of range");
1206
- }
1207
- Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
1208
- value = +value;
1209
- offset = offset | 0;
1210
- byteLength = byteLength | 0;
1211
- if (!noAssert) {
1212
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1213
- checkInt(this, value, offset, byteLength, maxBytes, 0);
1214
- }
1215
- var mul = 1;
1216
- var i = 0;
1217
- this[offset] = value & 255;
1218
- while (++i < byteLength && (mul *= 256)) this[offset + i] = value / mul & 255;
1219
- return offset + byteLength;
1220
- };
1221
- Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
1222
- value = +value;
1223
- offset = offset | 0;
1224
- byteLength = byteLength | 0;
1225
- if (!noAssert) {
1226
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1227
- checkInt(this, value, offset, byteLength, maxBytes, 0);
1228
- }
1229
- var i = byteLength - 1;
1230
- var mul = 1;
1231
- this[offset + i] = value & 255;
1232
- while (--i >= 0 && (mul *= 256)) this[offset + i] = value / mul & 255;
1233
- return offset + byteLength;
1234
- };
1235
- Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
1236
- value = +value;
1237
- offset = offset | 0;
1238
- if (!noAssert) checkInt(this, value, offset, 1, 255, 0);
1239
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
1240
- this[offset] = value & 255;
1241
- return offset + 1;
1242
- };
1243
- function objectWriteUInt16(buf, value, offset, littleEndian) {
1244
- if (value < 0) value = 65535 + value + 1;
1245
- for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) buf[offset + i] = (value & 255 << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8;
1246
- }
1247
- Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
1248
- value = +value;
1249
- offset = offset | 0;
1250
- if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
1251
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1252
- this[offset] = value & 255;
1253
- this[offset + 1] = value >>> 8;
1254
- } else objectWriteUInt16(this, value, offset, true);
1255
- return offset + 2;
1256
- };
1257
- Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
1258
- value = +value;
1259
- offset = offset | 0;
1260
- if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
1261
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1262
- this[offset] = value >>> 8;
1263
- this[offset + 1] = value & 255;
1264
- } else objectWriteUInt16(this, value, offset, false);
1265
- return offset + 2;
1266
- };
1267
- function objectWriteUInt32(buf, value, offset, littleEndian) {
1268
- if (value < 0) value = 4294967295 + value + 1;
1269
- for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 255;
1270
- }
1271
- Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
1272
- value = +value;
1273
- offset = offset | 0;
1274
- if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
1275
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1276
- this[offset + 3] = value >>> 24;
1277
- this[offset + 2] = value >>> 16;
1278
- this[offset + 1] = value >>> 8;
1279
- this[offset] = value & 255;
1280
- } else objectWriteUInt32(this, value, offset, true);
1281
- return offset + 4;
1282
- };
1283
- Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
1284
- value = +value;
1285
- offset = offset | 0;
1286
- if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
1287
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1288
- this[offset] = value >>> 24;
1289
- this[offset + 1] = value >>> 16;
1290
- this[offset + 2] = value >>> 8;
1291
- this[offset + 3] = value & 255;
1292
- } else objectWriteUInt32(this, value, offset, false);
1293
- return offset + 4;
1294
- };
1295
- Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
1296
- value = +value;
1297
- offset = offset | 0;
1298
- if (!noAssert) {
1299
- var limit = Math.pow(2, 8 * byteLength - 1);
1300
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
1301
- }
1302
- var i = 0;
1303
- var mul = 1;
1304
- var sub = 0;
1305
- this[offset] = value & 255;
1306
- while (++i < byteLength && (mul *= 256)) {
1307
- if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) sub = 1;
1308
- this[offset + i] = (value / mul >> 0) - sub & 255;
1309
- }
1310
- return offset + byteLength;
1311
- };
1312
- Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
1313
- value = +value;
1314
- offset = offset | 0;
1315
- if (!noAssert) {
1316
- var limit = Math.pow(2, 8 * byteLength - 1);
1317
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
1318
- }
1319
- var i = byteLength - 1;
1320
- var mul = 1;
1321
- var sub = 0;
1322
- this[offset + i] = value & 255;
1323
- while (--i >= 0 && (mul *= 256)) {
1324
- if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) sub = 1;
1325
- this[offset + i] = (value / mul >> 0) - sub & 255;
1326
- }
1327
- return offset + byteLength;
1328
- };
1329
- Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
1330
- value = +value;
1331
- offset = offset | 0;
1332
- if (!noAssert) checkInt(this, value, offset, 1, 127, -128);
1333
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
1334
- if (value < 0) value = 255 + value + 1;
1335
- this[offset] = value & 255;
1336
- return offset + 1;
1337
- };
1338
- Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
1339
- value = +value;
1340
- offset = offset | 0;
1341
- if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
1342
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1343
- this[offset] = value & 255;
1344
- this[offset + 1] = value >>> 8;
1345
- } else objectWriteUInt16(this, value, offset, true);
1346
- return offset + 2;
1347
- };
1348
- Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
1349
- value = +value;
1350
- offset = offset | 0;
1351
- if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
1352
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1353
- this[offset] = value >>> 8;
1354
- this[offset + 1] = value & 255;
1355
- } else objectWriteUInt16(this, value, offset, false);
1356
- return offset + 2;
1357
- };
1358
- Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
1359
- value = +value;
1360
- offset = offset | 0;
1361
- if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
1362
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1363
- this[offset] = value & 255;
1364
- this[offset + 1] = value >>> 8;
1365
- this[offset + 2] = value >>> 16;
1366
- this[offset + 3] = value >>> 24;
1367
- } else objectWriteUInt32(this, value, offset, true);
1368
- return offset + 4;
1369
- };
1370
- Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
1371
- value = +value;
1372
- offset = offset | 0;
1373
- if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
1374
- if (value < 0) value = 4294967295 + value + 1;
1375
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1376
- this[offset] = value >>> 24;
1377
- this[offset + 1] = value >>> 16;
1378
- this[offset + 2] = value >>> 8;
1379
- this[offset + 3] = value & 255;
1380
- } else objectWriteUInt32(this, value, offset, false);
1381
- return offset + 4;
1382
- };
1383
- function checkIEEE754(buf, value, offset, ext, max, min) {
1384
- if (offset + ext > buf.length) throw new RangeError("Index out of range");
1385
- if (offset < 0) throw new RangeError("Index out of range");
1386
- }
1387
- function writeFloat(buf, value, offset, littleEndian, noAssert) {
1388
- if (!noAssert) checkIEEE754(buf, value, offset, 4);
1389
- write(buf, value, offset, littleEndian, 23, 4);
1390
- return offset + 4;
1391
- }
1392
- Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
1393
- return writeFloat(this, value, offset, true, noAssert);
1394
- };
1395
- Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
1396
- return writeFloat(this, value, offset, false, noAssert);
1397
- };
1398
- function writeDouble(buf, value, offset, littleEndian, noAssert) {
1399
- if (!noAssert) checkIEEE754(buf, value, offset, 8);
1400
- write(buf, value, offset, littleEndian, 52, 8);
1401
- return offset + 8;
1402
- }
1403
- Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
1404
- return writeDouble(this, value, offset, true, noAssert);
1405
- };
1406
- Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
1407
- return writeDouble(this, value, offset, false, noAssert);
1408
- };
1409
- Buffer.prototype.copy = function copy(target, targetStart, start, end) {
1410
- if (!start) start = 0;
1411
- if (!end && end !== 0) end = this.length;
1412
- if (targetStart >= target.length) targetStart = target.length;
1413
- if (!targetStart) targetStart = 0;
1414
- if (end > 0 && end < start) end = start;
1415
- if (end === start) return 0;
1416
- if (target.length === 0 || this.length === 0) return 0;
1417
- if (targetStart < 0) throw new RangeError("targetStart out of bounds");
1418
- if (start < 0 || start >= this.length) throw new RangeError("sourceStart out of bounds");
1419
- if (end < 0) throw new RangeError("sourceEnd out of bounds");
1420
- if (end > this.length) end = this.length;
1421
- if (target.length - targetStart < end - start) end = target.length - targetStart + start;
1422
- var len = end - start;
1423
- var i;
1424
- if (this === target && start < targetStart && targetStart < end) for (i = len - 1; i >= 0; --i) target[i + targetStart] = this[i + start];
1425
- else if (len < 1e3 || !Buffer.TYPED_ARRAY_SUPPORT) for (i = 0; i < len; ++i) target[i + targetStart] = this[i + start];
1426
- else Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart);
1427
- return len;
1428
- };
1429
- Buffer.prototype.fill = function fill(val, start, end, encoding) {
1430
- if (typeof val === "string") {
1431
- if (typeof start === "string") {
1432
- encoding = start;
1433
- start = 0;
1434
- end = this.length;
1435
- } else if (typeof end === "string") {
1436
- encoding = end;
1437
- end = this.length;
1438
- }
1439
- if (val.length === 1) {
1440
- var code = val.charCodeAt(0);
1441
- if (code < 256) val = code;
1442
- }
1443
- if (encoding !== void 0 && typeof encoding !== "string") throw new TypeError("encoding must be a string");
1444
- if (typeof encoding === "string" && !Buffer.isEncoding(encoding)) throw new TypeError("Unknown encoding: " + encoding);
1445
- } else if (typeof val === "number") val = val & 255;
1446
- if (start < 0 || this.length < start || this.length < end) throw new RangeError("Out of range index");
1447
- if (end <= start) return this;
1448
- start = start >>> 0;
1449
- end = end === void 0 ? this.length : end >>> 0;
1450
- if (!val) val = 0;
1451
- var i;
1452
- if (typeof val === "number") for (i = start; i < end; ++i) this[i] = val;
1453
- else {
1454
- var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString());
1455
- var len = bytes.length;
1456
- for (i = 0; i < end - start; ++i) this[i + start] = bytes[i % len];
1457
- }
1458
- return this;
1459
- };
1460
- var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
1461
- function base64clean(str) {
1462
- str = stringtrim(str).replace(INVALID_BASE64_RE, "");
1463
- if (str.length < 2) return "";
1464
- while (str.length % 4 !== 0) str = str + "=";
1465
- return str;
1466
- }
1467
- function stringtrim(str) {
1468
- if (str.trim) return str.trim();
1469
- return str.replace(/^\s+|\s+$/g, "");
1470
- }
1471
- function toHex(n) {
1472
- if (n < 16) return "0" + n.toString(16);
1473
- return n.toString(16);
1474
- }
1475
- function utf8ToBytes(string, units) {
1476
- units = units || Infinity;
1477
- var codePoint;
1478
- var length = string.length;
1479
- var leadSurrogate = null;
1480
- var bytes = [];
1481
- for (var i = 0; i < length; ++i) {
1482
- codePoint = string.charCodeAt(i);
1483
- if (codePoint > 55295 && codePoint < 57344) {
1484
- if (!leadSurrogate) {
1485
- if (codePoint > 56319) {
1486
- if ((units -= 3) > -1) bytes.push(239, 191, 189);
1487
- continue;
1488
- } else if (i + 1 === length) {
1489
- if ((units -= 3) > -1) bytes.push(239, 191, 189);
1490
- continue;
1491
- }
1492
- leadSurrogate = codePoint;
1493
- continue;
1494
- }
1495
- if (codePoint < 56320) {
1496
- if ((units -= 3) > -1) bytes.push(239, 191, 189);
1497
- leadSurrogate = codePoint;
1498
- continue;
1499
- }
1500
- codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
1501
- } else if (leadSurrogate) {
1502
- if ((units -= 3) > -1) bytes.push(239, 191, 189);
1503
- }
1504
- leadSurrogate = null;
1505
- if (codePoint < 128) {
1506
- if ((units -= 1) < 0) break;
1507
- bytes.push(codePoint);
1508
- } else if (codePoint < 2048) {
1509
- if ((units -= 2) < 0) break;
1510
- bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);
1511
- } else if (codePoint < 65536) {
1512
- if ((units -= 3) < 0) break;
1513
- bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
1514
- } else if (codePoint < 1114112) {
1515
- if ((units -= 4) < 0) break;
1516
- bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
1517
- } else throw new Error("Invalid code point");
1518
- }
1519
- return bytes;
1520
- }
1521
- function asciiToBytes(str) {
1522
- var byteArray = [];
1523
- for (var i = 0; i < str.length; ++i) byteArray.push(str.charCodeAt(i) & 255);
1524
- return byteArray;
1525
- }
1526
- function utf16leToBytes(str, units) {
1527
- var c, hi, lo;
1528
- var byteArray = [];
1529
- for (var i = 0; i < str.length; ++i) {
1530
- if ((units -= 2) < 0) break;
1531
- c = str.charCodeAt(i);
1532
- hi = c >> 8;
1533
- lo = c % 256;
1534
- byteArray.push(lo);
1535
- byteArray.push(hi);
1536
- }
1537
- return byteArray;
1538
- }
1539
- function base64ToBytes(str) {
1540
- return toByteArray(base64clean(str));
1541
- }
1542
- function blitBuffer(src, dst, offset, length) {
1543
- for (var i = 0; i < length; ++i) {
1544
- if (i + offset >= dst.length || i >= src.length) break;
1545
- dst[i + offset] = src[i];
1546
- }
1547
- return i;
1548
- }
1549
- function isnan(val) {
1550
- return val !== val;
1551
- }
1552
- function isBuffer(obj) {
1553
- return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj));
1554
- }
1555
- function isFastBuffer(obj) {
1556
- return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
1557
- }
1558
- function isSlowBuffer(obj) {
1559
- return typeof obj.readFloatLE === "function" && typeof obj.slice === "function" && isFastBuffer(obj.slice(0, 0));
1560
- }
1561
- //#endregion
1562
- //#region src/util/base64.ts
1563
- /**
1564
- * Shared base64 encode/decode helpers.
1565
- *
1566
- * Both prefer the native `Uint8Array` base64 methods (Node 22+, modern
1567
- * browsers): they avoid the intermediate binary string that `btoa`/`atob`
1568
- * materialize and cannot stack-overflow on large buffers. Node `Buffer` is the
1569
- * secondary path; a manual loop covers older runtimes.
1570
- *
1571
- * @module
1572
- */
1573
- /**
1574
- * Decode a base64 string into a `Uint8Array`.
1575
- *
1576
- * Prefers native `Uint8Array.fromBase64` (no intermediate binary string), then
1577
- * Node `Buffer` (zero-copy), then `atob`.
1578
- */
1579
- function decodeBase64(input) {
1580
- const fromBase64 = Uint8Array.fromBase64;
1581
- if (typeof fromBase64 === "function") return fromBase64.call(Uint8Array, input);
1582
- if (typeof Buffer !== "undefined") return Buffer.from(input, "base64");
1583
- return Uint8Array.from(atob(input), (c) => c.codePointAt(0));
1584
- }
1585
- /**
1586
- * Encode a `Uint8Array` into a base64 string.
1587
- *
1588
- * Prefers native `Uint8Array.prototype.toBase64` (no intermediate binary
1589
- * string), then Node `Buffer` (zero-copy), then a `btoa` fallback.
1590
- *
1591
- * The fallback builds the binary string in a loop rather than
1592
- * `String.fromCharCode(...bytes)` — the spread form places every byte on the
1593
- * call stack and overflows for large buffers (V8 caps function arguments near
1594
- * ~65k).
1595
- */
1596
- function encodeBase64(bytes) {
1597
- const toBase64 = Uint8Array.prototype.toBase64;
1598
- if (typeof toBase64 === "function") return toBase64.call(bytes);
1599
- if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
1600
- let binary = "";
1601
- for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1602
- return btoa(binary);
1603
- }
1604
- //#endregion
1605
- //#region src/opc/output.ts
1606
- /**
1607
- * Output type definitions for OOXML document export.
1608
- *
1609
- * @module
1610
- */
1611
- const OoxmlMimeType = {
1612
- DOCX: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1613
- PPTX: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1614
- XLSX: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
1615
- };
1616
- const convertOutput = (data, type, mimeType = OoxmlMimeType.DOCX) => {
1617
- switch (type) {
1618
- case "nodebuffer": return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
1619
- case "blob": return new Blob([data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)], { type: mimeType });
1620
- case "arraybuffer": return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
1621
- case "uint8array": return data;
1622
- case "base64": return encodeBase64(data);
1623
- case "string":
1624
- case "text":
1625
- case "binarystring": return strFromU8(data, true);
1626
- case "array": return [...data];
1627
- default: return data;
1628
- }
1629
- };
1630
- //#endregion
1631
- //#region src/zip-native.ts
1632
- const CRC_TABLE = new Int32Array(256);
1633
- for (let i = 0; i < 256; i++) {
1634
- let c = i;
1635
- for (let k = 0; k < 8; k++) c = c & 1 ? c >>> 1 ^ -306674912 : c >>> 1;
1636
- CRC_TABLE[i] = c;
1637
- }
1638
- function computeCrc32(data) {
1639
- let crc = -1;
1640
- for (let i = 0; i < data.length; i++) crc = CRC_TABLE[(crc ^ data[i]) & 255] ^ crc >>> 8;
1641
- return ~crc;
1642
- }
1643
- let _nativeDeflate;
1644
- let _nativeDeflateAsync;
1645
- let _nativeCrc32;
1646
- try {
1647
- const zlib = await import("node:zlib");
1648
- if (typeof zlib.deflateRawSync !== "function") throw new Error("no native deflate");
1649
- _nativeDeflate = (data, level) => zlib.deflateRawSync(data, { level });
1650
- _nativeDeflateAsync = (data, level) => new Promise((resolve, reject) => zlib.deflateRaw(data, { level }, (err, result) => {
1651
- if (err) reject(err);
1652
- else resolve(result);
1653
- }));
1654
- _nativeCrc32 = typeof zlib.crc32 === "function" ? (data) => zlib.crc32(data) : computeCrc32;
1655
- } catch {}
1656
- const hasNativeDeflate = () => _nativeDeflate !== void 0;
1657
- function wU16(b, o, v) {
1658
- b[o] = v & 255;
1659
- b[o + 1] = v >> 8 & 255;
1660
- }
1661
- function wU32(b, o, v) {
1662
- b[o] = v & 255;
1663
- b[o + 1] = v >> 8 & 255;
1664
- b[o + 2] = v >> 16 & 255;
1665
- b[o + 3] = v >> 24 & 255;
1666
- }
1667
- function resolveEntryData(raw, defaultLevel) {
1668
- if (Array.isArray(raw)) return {
1669
- data: raw[0],
1670
- level: raw[1].level ?? defaultLevel
1671
- };
1672
- return {
1673
- data: raw,
1674
- level: defaultLevel
1675
- };
1676
- }
1677
- function compressOne(data, level, method, deflate) {
1678
- if (level === 0) return {
1679
- compressed: data,
1680
- method: 0
1681
- };
1682
- const compressed = deflate(data, level);
1683
- if (compressed.length >= data.length) return {
1684
- compressed: data,
1685
- method: 0
1686
- };
1687
- return {
1688
- compressed,
1689
- method: 8
1690
- };
1691
- }
1692
- async function compressOneAsync(data, level, deflate) {
1693
- if (level === 0) return {
1694
- compressed: data,
1695
- method: 0
1696
- };
1697
- const compressed = await deflate(data, level);
1698
- if (compressed.length >= data.length) return {
1699
- compressed: data,
1700
- method: 0
1701
- };
1702
- return {
1703
- compressed,
1704
- method: 8
1705
- };
1706
- }
1707
- function writeZipBuffer(entries) {
1708
- let totalSize = 0;
1709
- for (let i = 0; i < entries.length; i++) totalSize += 30 + entries[i].filename.length + entries[i].data.length;
1710
- const cdOffset = totalSize;
1711
- let cdSize = 0;
1712
- for (let i = 0; i < entries.length; i++) cdSize += 46 + entries[i].filename.length;
1713
- totalSize += cdSize + 22;
1714
- const buf = new Uint8Array(totalSize);
1715
- let offset = 0;
1716
- for (let i = 0; i < entries.length; i++) {
1717
- const e = entries[i];
1718
- e.localOffset = offset;
1719
- wU32(buf, offset, 67324752);
1720
- wU16(buf, offset + 4, 20);
1721
- wU16(buf, offset + 6, 0);
1722
- wU16(buf, offset + 8, e.method);
1723
- wU16(buf, offset + 10, 0);
1724
- wU16(buf, offset + 12, 0);
1725
- wU32(buf, offset + 14, e.crc);
1726
- wU32(buf, offset + 18, e.data.length);
1727
- wU32(buf, offset + 22, e.uncompressedSize);
1728
- wU16(buf, offset + 26, e.filename.length);
1729
- wU16(buf, offset + 28, 0);
1730
- offset += 30;
1731
- buf.set(e.filename, offset);
1732
- offset += e.filename.length;
1733
- buf.set(e.data, offset);
1734
- offset += e.data.length;
1735
- }
1736
- for (let i = 0; i < entries.length; i++) {
1737
- const e = entries[i];
1738
- wU32(buf, offset, 33639248);
1739
- wU16(buf, offset + 4, 20);
1740
- wU16(buf, offset + 6, 20);
1741
- wU16(buf, offset + 8, 0);
1742
- wU16(buf, offset + 10, e.method);
1743
- wU16(buf, offset + 12, 0);
1744
- wU16(buf, offset + 14, 0);
1745
- wU32(buf, offset + 16, e.crc);
1746
- wU32(buf, offset + 20, e.data.length);
1747
- wU32(buf, offset + 24, e.uncompressedSize);
1748
- wU16(buf, offset + 28, e.filename.length);
1749
- wU16(buf, offset + 30, 0);
1750
- wU16(buf, offset + 32, 0);
1751
- wU16(buf, offset + 34, 0);
1752
- wU16(buf, offset + 36, 0);
1753
- wU32(buf, offset + 38, 0);
1754
- wU32(buf, offset + 42, e.localOffset);
1755
- offset += 46;
1756
- buf.set(e.filename, offset);
1757
- offset += e.filename.length;
1758
- }
1759
- wU32(buf, offset, 101010256);
1760
- wU16(buf, offset + 4, 0);
1761
- wU16(buf, offset + 6, 0);
1762
- wU16(buf, offset + 8, entries.length);
1763
- wU16(buf, offset + 10, entries.length);
1764
- wU32(buf, offset + 12, cdSize);
1765
- wU32(buf, offset + 16, cdOffset);
1766
- wU16(buf, offset + 20, 0);
1767
- return buf;
1768
- }
1769
- const textEncoder = new TextEncoder();
1770
- function nativeZip(files, level = 6) {
1771
- if (!_nativeDeflate) throw new Error("Native deflate not available");
1772
- const crc = _nativeCrc32 ?? computeCrc32;
1773
- const keys = Object.keys(files);
1774
- const entries = Array.from({ length: keys.length });
1775
- for (let i = 0; i < keys.length; i++) {
1776
- const { data, level: entryLevel } = resolveEntryData(files[keys[i]], level);
1777
- const c = crc(data);
1778
- const { compressed, method } = compressOne(data, entryLevel, 8, _nativeDeflate);
1779
- entries[i] = {
1780
- filename: textEncoder.encode(keys[i]),
1781
- data: compressed,
1782
- uncompressedSize: data.length,
1783
- crc: c,
1784
- method,
1785
- localOffset: 0
1786
- };
1787
- }
1788
- return writeZipBuffer(entries);
1789
- }
1790
- async function nativeZipAsync(files, level = 6) {
1791
- if (!_nativeDeflateAsync) throw new Error("Native async deflate not available");
1792
- const crc = _nativeCrc32 ?? computeCrc32;
1793
- const keys = Object.keys(files);
1794
- const entries = Array.from({ length: keys.length });
1795
- for (let i = 0; i < keys.length; i++) {
1796
- const { data, level: entryLevel } = resolveEntryData(files[keys[i]], level);
1797
- const c = crc(data);
1798
- const { compressed, method } = await compressOneAsync(data, entryLevel, _nativeDeflateAsync);
1799
- entries[i] = {
1800
- filename: textEncoder.encode(keys[i]),
1801
- data: compressed,
1802
- uncompressedSize: data.length,
1803
- crc: c,
1804
- method,
1805
- localOffset: 0
1806
- };
1807
- }
1808
- return writeZipBuffer(entries);
1809
- }
1810
- //#endregion
1811
- //#region src/opc/packer.ts
1812
- /**
1813
- * Shared packer utilities for OOXML document generation.
1814
- *
1815
- * @module
1816
- */
1817
- /** Default DEFLATE level for XML entries (SuperFast, matching MS Office). */
1818
- const ZIP_DEFLATE_LEVEL = 1;
1819
- /** Level for already-compressed media — STORE (no compression). */
1820
- const ZIP_STORED_LEVEL = 0;
1821
- /**
1822
- * Media formats already compressed internally (DEFLATE for PNG, DCT for JPEG,
1823
- * LZW for GIF). Re-compressing via zip DEFLATE wastes CPU and often inflates
1824
- * the data, so MS Office STORE-s these (CompressionOption.NotCompressed → zip
1825
- * method 0). Everything else (EMF/WMF/BMP/TIFF/SVG/…) is compressible → DEFLATE.
1826
- */
1827
- const PRECOMPRESSED_MEDIA_EXT = new Set([
1828
- "jpg",
1829
- "jpeg",
1830
- "png",
1831
- "gif"
1832
- ]);
1833
- /**
1834
- * Resolve the ZIP level for a media entry by file-name extension, matching MS
1835
- * Office: already-compressed raster formats → STORE (0), everything else →
1836
- * DEFLATE (`mediaLevel`, default Normal). A `compression.media` override
1837
- * therefore applies only to compressible formats, never forcing DEFLATE onto
1838
- * pre-compressed assets.
1839
- */
1840
- const levelForMediaName = (fileName, mediaLevel) => {
1841
- const dot = fileName.lastIndexOf(".");
1842
- const ext = dot < 0 ? "" : fileName.slice(dot + 1).toLowerCase();
1843
- return PRECOMPRESSED_MEDIA_EXT.has(ext) ? 0 : mediaLevel;
1844
- };
1845
- /**
1846
- * Asynchronously compress files and convert to the requested output format.
1847
- *
1848
- * Uses fflate Web Workers for non-blocking DEFLATE compression.
1849
- * XML entries use DEFLATE level 1 (SuperFast) by default. Media entries are
1850
- * split by type, matching MS Office: already-compressed formats (PNG/JPEG/GIF)
1851
- * are STOREd, everything else uses the `media` level (default Normal).
1852
- * Set `{ media: ZIP_STORED_LEVEL }` to STORE all compressible media too.
1853
- */
1854
- const zipAndConvert = async (files, type, mimeType, level = 1) => {
1855
- return convertOutput(hasNativeDeflate() ? await nativeZipAsync(files, level) : await new Promise((resolve, reject) => {
1856
- zip(files, {
1857
- level,
1858
- consume: true
1859
- }, (err, data) => {
1860
- if (err) reject(err);
1861
- else resolve(data);
1862
- });
1863
- }), type, mimeType);
1864
- };
1865
- /**
1866
- * Synchronously compress files and convert to the requested output format.
1867
- *
1868
- * Uses synchronous DEFLATE compression for maximum throughput.
1869
- * Blocks the event loop — prefer {@link zipAndConvert} in server contexts.
1870
- */
1871
- const zipSyncAndConvert = (files, type, mimeType, level = 1) => {
1872
- return convertOutput(hasNativeDeflate() ? nativeZip(files, level) : zipSync(files, { level }), type, mimeType);
1873
- };
1874
- /**
1875
- * Create a `ReadableStream<Uint8Array>` from compressed file entries.
1876
- *
1877
- * Uses fflate's `AsyncZipDeflate` for non-blocking DEFLATE compression.
1878
- * `STORED` entries (media) pass through synchronously.
1879
- * Works in both Node.js and browsers (Web Streams API).
1880
- */
1881
- const createZipStream = (files, defaultLevel = 1) => {
1882
- return new ReadableStream({ start(controller) {
1883
- try {
1884
- const zip = new Zip((err, chunk, _final) => {
1885
- if (err) {
1886
- controller.error(err);
1887
- return;
1888
- }
1889
- controller.enqueue(chunk);
1890
- if (_final) controller.close();
1891
- });
1892
- for (const [name, data] of Object.entries(files)) {
1893
- const raw = Array.isArray(data) ? data[0] : data;
1894
- const level = Array.isArray(data) ? data[1].level ?? defaultLevel : defaultLevel;
1895
- const entry = level === 0 ? new ZipPassThrough(name) : new AsyncZipDeflate(name, { level });
1896
- zip.add(entry);
1897
- entry.push(raw, true);
1898
- }
1899
- zip.end();
1900
- } catch (err) {
1901
- controller.error(err instanceof Error ? err : new Error(String(err)));
1902
- }
1903
- } });
1904
- };
1905
- /**
1906
- * Create a Packer object with all output format methods.
1907
- *
1908
- * Centralises the ZIP → convert pipeline and the streaming implementation
1909
- * so that each OOXML package only needs to provide a `compile` function and
1910
- * a MIME type.
1911
- */
1912
- const createPacker = (options) => {
1913
- const { compile, mimeType } = options;
1914
- const pack = async (file, opts) => {
1915
- const type = opts?.type ?? "nodebuffer";
1916
- return zipAndConvert(compile(file, opts?.overrides ?? [], opts?.compression?.media ?? 6), type, mimeType, opts?.compression?.xml ?? 1);
1917
- };
1918
- const toBytes = (file, opts) => pack(file, {
1919
- ...opts,
1920
- type: "uint8array"
1921
- });
1922
- const toString = (file, opts) => pack(file, {
1923
- ...opts,
1924
- type: "string"
1925
- });
1926
- const toBuffer = (file, opts) => pack(file, {
1927
- ...opts,
1928
- type: "nodebuffer"
1929
- });
1930
- const toBase64 = (file, opts) => pack(file, {
1931
- ...opts,
1932
- type: "base64"
1933
- });
1934
- const toBlob = (file, opts) => pack(file, {
1935
- ...opts,
1936
- type: "blob"
1937
- });
1938
- const toArrayBuffer = (file, opts) => pack(file, {
1939
- ...opts,
1940
- type: "arraybuffer"
1941
- });
1942
- const packSync = (file, opts) => {
1943
- const type = opts?.type ?? "nodebuffer";
1944
- return zipSyncAndConvert(compile(file, opts?.overrides ?? [], opts?.compression?.media ?? 6), type, mimeType, opts?.compression?.xml ?? 1);
1945
- };
1946
- const toBytesSync = (file, opts) => packSync(file, {
1947
- ...opts,
1948
- type: "uint8array"
1949
- });
1950
- const toStringSync = (file, opts) => packSync(file, {
1951
- ...opts,
1952
- type: "string"
1953
- });
1954
- const toBufferSync = (file, opts) => packSync(file, {
1955
- ...opts,
1956
- type: "nodebuffer"
1957
- });
1958
- const toBase64Sync = (file, opts) => packSync(file, {
1959
- ...opts,
1960
- type: "base64"
1961
- });
1962
- const toBlobSync = (file, opts) => packSync(file, {
1963
- ...opts,
1964
- type: "blob"
1965
- });
1966
- const toArrayBufferSync = (file, opts) => packSync(file, {
1967
- ...opts,
1968
- type: "arraybuffer"
1969
- });
1970
- const toStream = (file, opts) => {
1971
- const mediaLevel = opts?.compression?.media ?? 6;
1972
- let files;
1973
- try {
1974
- files = compile(file, opts?.overrides ?? [], mediaLevel);
1975
- } catch (err) {
1976
- return new ReadableStream({ start(controller) {
1977
- controller.error(err instanceof Error ? err : new Error(String(err)));
1978
- } });
1979
- }
1980
- return createZipStream(files, opts?.compression?.xml ?? 1);
1981
- };
1982
- return {
1983
- compile,
1984
- pack,
1985
- packSync,
1986
- toBytes,
1987
- toBytesSync,
1988
- toString,
1989
- toStringSync,
1990
- toBuffer,
1991
- toBufferSync,
1992
- toBase64,
1993
- toBase64Sync,
1994
- toBlob,
1995
- toBlobSync,
1996
- toArrayBuffer,
1997
- toArrayBufferSync,
1998
- toStream
1999
- };
2000
- };
2001
- //#endregion
2002
- //#region src/opc/parser.ts
2003
- const XML_PARSE_OPTIONS = {
2004
- nativeTypeAttributes: true,
2005
- captureSpacesBetweenElements: true
2006
- };
2007
- /**
2008
- * Parsed OOXML archive backed by an unzipped ZIP map.
2009
- *
2010
- * Provides unstorage-style API (get/set/getRaw/setRaw/remove/has/keys)
2011
- * for reading and modifying individual parts, then serializing back to a ZIP buffer.
2012
- */
2013
- var ParsedArchive = class {
2014
- zip;
2015
- modified = /* @__PURE__ */ new Map();
2016
- wrapperCache = /* @__PURE__ */ new Map();
2017
- constructor(data) {
2018
- this.zip = new Map(Object.entries(unzipSync(data)));
2019
- }
2020
- /** Read an XML part as an Element tree. */
2021
- get(path) {
2022
- const modData = this.modified.get(path);
2023
- if (modData) {
2024
- const wrapper = xml2js(strFromU8(modData), XML_PARSE_OPTIONS);
2025
- this.wrapperCache.set(path, wrapper);
2026
- return wrapper.elements?.find((e) => e.type === "element");
2027
- }
2028
- const data = this.zip.get(path);
2029
- if (data === void 0) return void 0;
2030
- const cached = this.wrapperCache.get(path);
2031
- if (cached) return cached.elements?.find((e) => e.type === "element");
2032
- const wrapper = xml2js(strFromU8(data), XML_PARSE_OPTIONS);
2033
- this.wrapperCache.set(path, wrapper);
2034
- return wrapper.elements?.find((e) => e.type === "element");
2035
- }
2036
- /** Write an XML part (Element → XML string). */
2037
- set(path, element) {
2038
- const wrapper = this.wrapperCache.get(path);
2039
- const xml = js2xml(wrapper ? {
2040
- ...wrapper,
2041
- elements: [{
2042
- ...element,
2043
- type: "element"
2044
- }]
2045
- } : { elements: [{
2046
- ...element,
2047
- type: "element"
2048
- }] });
2049
- this.modified.set(path, strToU8(xml));
2050
- }
2051
- /** Read raw binary data (images, media, etc.). */
2052
- getRaw(path) {
2053
- return this.modified.get(path) ?? this.zip.get(path);
2054
- }
2055
- /** Write raw binary data. */
2056
- setRaw(path, data) {
2057
- this.modified.set(path, data);
2058
- this.wrapperCache.delete(path);
2059
- }
2060
- /** Remove a part. Returns true if it existed. */
2061
- remove(path) {
2062
- this.wrapperCache.delete(path);
2063
- return this.modified.delete(path) || this.zip.delete(path);
2064
- }
2065
- /** Check if a part exists. */
2066
- has(path) {
2067
- return this.modified.has(path) || this.zip.has(path);
2068
- }
2069
- /** List all paths matching an optional prefix. */
2070
- keys(prefix) {
2071
- const all = /* @__PURE__ */ new Set();
2072
- for (const key of this.zip.keys()) if (!prefix || key.startsWith(prefix)) all.add(key);
2073
- for (const key of this.modified.keys()) if (!prefix || key.startsWith(prefix)) all.add(key);
2074
- return [...all];
2075
- }
2076
- /** Serialize back to a ZIP buffer, merging original zip + modifications. */
2077
- save() {
2078
- const files = {};
2079
- for (const [path, data] of this.zip) if (!this.modified.has(path)) files[path] = isMediaPath(path) ? [data, { level: MEDIA_STORED_LEVEL }] : data;
2080
- for (const [path, data] of this.modified) files[path] = isMediaPath(path) ? [data, { level: MEDIA_STORED_LEVEL }] : data;
2081
- return zipSync(files);
2082
- }
2083
- };
2084
- /** Media file extensions that should use STORE (no compression). */
2085
- const MEDIA_EXTENSIONS = new Set([
2086
- ".png",
2087
- ".jpg",
2088
- ".jpeg",
2089
- ".gif",
2090
- ".wmf",
2091
- ".emf",
2092
- ".tif",
2093
- ".tiff",
2094
- ".avi",
2095
- ".mp4",
2096
- ".mp3",
2097
- ".wav"
2098
- ]);
2099
- /** Check if a file path has a media extension that should use STORE (no compression). */
2100
- function isMediaPath(path) {
2101
- const dot = path.lastIndexOf(".");
2102
- if (dot === -1) return false;
2103
- return MEDIA_EXTENSIONS.has(path.slice(dot).toLowerCase());
2104
- }
2105
- /** STORE level for already-compressed media formats. */
2106
- const MEDIA_STORED_LEVEL = 0;
2107
- /** Parse an OOXML archive (.docx, .pptx, .xlsx) into a ParsedArchive. */
2108
- function parseArchive(data) {
2109
- return new ParsedArchive(data);
2110
- }
2111
- //#endregion
2112
- //#region src/opc/opc-consistency.ts
2113
- /**
2114
- * OPC (Open Packaging Convention) consistency validator.
2115
- *
2116
- * Pure function operating on an already-unzipped part map. Detects the three
2117
- * classes of cross-part breakage that single-part XSD validation cannot see:
2118
- *
2119
- * - relationship integrity — dangling targets, duplicate rIds (O3/O7)
2120
- * - content-type integrity — parts with no Override/Default, stale
2121
- * Overrides pointing at absent parts (O5/O6)
2122
- * - structural integrity — missing `always` parts, undeclared orphans
2123
- * (O1/O2)
2124
- *
2125
- * O3/O5/O6/O7 are derived directly from the ZIP + `.rels` + `[Content_Types].xml`
2126
- * and need no registry. O1/O2 consult {@link PackagePartRegistry}.
2127
- *
2128
- * Reference: ECMA-376 Part 2 (OPC).
2129
- *
2130
- * @module
2131
- */
2132
- function rootElement(xml) {
2133
- try {
2134
- return xml2js(xml).elements?.find((e) => e.type === "element");
2135
- } catch {
2136
- return;
2137
- }
2138
- }
2139
- function parseContentTypes(entries) {
2140
- const defaults = /* @__PURE__ */ new Map();
2141
- const overrides = /* @__PURE__ */ new Map();
2142
- const xml = entries.get("[Content_Types].xml");
2143
- const root = xml ? rootElement(xml) : void 0;
2144
- if (!root) return {
2145
- defaults,
2146
- overrides
2147
- };
2148
- for (const child of root.elements ?? []) {
2149
- if (child.type !== "element") continue;
2150
- if (child.name === "Default") {
2151
- const ext = String(child.attributes?.Extension ?? "").toLowerCase();
2152
- const ct = String(child.attributes?.ContentType ?? "");
2153
- if (ext && ct) defaults.set(ext, ct);
2154
- } else if (child.name === "Override") {
2155
- const partName = normalizePartName(String(child.attributes?.PartName ?? ""));
2156
- const ct = String(child.attributes?.ContentType ?? "");
2157
- if (partName && ct) overrides.set(partName, ct);
2158
- }
2159
- }
2160
- return {
2161
- defaults,
2162
- overrides
2163
- };
2164
- }
2165
- function parseAllRels(entries) {
2166
- const out = [];
2167
- for (const [relsPath, xml] of entries) {
2168
- if (!relsPath.endsWith(".rels")) continue;
2169
- const root = rootElement(xml);
2170
- if (!root) continue;
2171
- const list = [];
2172
- for (const child of root.elements ?? []) {
2173
- if (child.type !== "element" || child.name !== "Relationship") continue;
2174
- list.push({
2175
- id: String(child.attributes?.Id ?? ""),
2176
- type: String(child.attributes?.Type ?? ""),
2177
- target: String(child.attributes?.Target ?? ""),
2178
- targetMode: child.attributes?.TargetMode ? String(child.attributes?.TargetMode) : void 0
2179
- });
2180
- }
2181
- out.push({
2182
- relsPath,
2183
- entries: list
2184
- });
2185
- }
2186
- return out;
2187
- }
2188
- /** Strip the leading slash OPC uses on `PartName` to align with ZIP paths. */
2189
- function normalizePartName(partName) {
2190
- return partName.startsWith("/") ? partName.slice(1) : partName;
2191
- }
2192
- /**
2193
- * Resolve a relationship `Target` (relative to its owning `.rels`) against the
2194
- * ZIP root. Handles the `..` segments slides/masters use to reference siblings.
2195
- */
2196
- function resolveRelTarget(relsPath, target) {
2197
- const slash = relsPath.lastIndexOf("/");
2198
- const relsDir = slash === -1 ? "" : relsPath.slice(0, slash);
2199
- const base = relsDir === "_rels" ? "" : relsDir.endsWith("/_rels") ? relsDir.slice(0, -6) : relsDir;
2200
- const segments = (base ? base.split("/") : []).concat(target.split("/"));
2201
- const resolved = [];
2202
- for (const seg of segments) {
2203
- if (seg === "" || seg === ".") continue;
2204
- if (seg === "..") resolved.pop();
2205
- else resolved.push(seg);
2206
- }
2207
- return resolved.join("/");
2208
- }
2209
- /** Compile a registry path template (with `${i}`) into an anchored matcher. */
2210
- function pathMatcher(template) {
2211
- const pattern = template.replace(/\$\{i\}/g, "\0").replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(//g, "(\\d+)");
2212
- return new RegExp(`^${pattern}$`);
2213
- }
2214
- function extensionOf(path) {
2215
- const dot = path.lastIndexOf(".");
2216
- return dot === -1 ? "" : path.slice(dot + 1).toLowerCase();
2217
- }
2218
- /**
2219
- * Validate OPC consistency of an unzipped package.
2220
- *
2221
- * @param entries ZIP path → decoded XML/binary text. Binary parts (media,
2222
- * fonts) are never parsed here — only their presence matters.
2223
- * @param registry Declarative part expectations for the package format.
2224
- * @returns Issues sorted by code then part. Empty array = consistent.
2225
- */
2226
- function validateOpcConsistency(entries, registry) {
2227
- const issues = [];
2228
- const contentTypes = parseContentTypes(entries);
2229
- const relsFiles = parseAllRels(entries);
2230
- for (const def of registry.parts) {
2231
- if (def.presence.kind !== "always" || def.path.includes("${i}")) continue;
2232
- if (!entries.has(def.path)) issues.push({
2233
- code: "O2",
2234
- severity: "error",
2235
- part: def.path,
2236
- message: `required ${registry.format} part is absent from the package`
2237
- });
2238
- }
2239
- const matchers = registry.parts.map((def) => pathMatcher(def.path));
2240
- for (const path of entries.keys()) {
2241
- if (path === "[Content_Types].xml") continue;
2242
- if (path.endsWith(".rels")) continue;
2243
- if (registry.orphanWhitelist.some((prefix) => path.startsWith(prefix))) continue;
2244
- if (matchers.some((re) => re.test(path))) continue;
2245
- issues.push({
2246
- code: "O1",
2247
- severity: "warn",
2248
- part: path,
2249
- message: `part not declared in the ${registry.format} registry (possible orphan)`
2250
- });
2251
- }
2252
- for (const rf of relsFiles) for (const rel of rf.entries) {
2253
- if (rel.targetMode === "External") continue;
2254
- if (/^https?:\/\//i.test(rel.target)) continue;
2255
- const resolved = resolveRelTarget(rf.relsPath, rel.target);
2256
- if (!resolved || entries.has(resolved)) continue;
2257
- issues.push({
2258
- code: "O3",
2259
- severity: "error",
2260
- part: rf.relsPath,
2261
- message: `relationship ${rel.id || "(no Id)"} (${rel.type}) Target "${rel.target}" resolves to absent part "${resolved}"`
2262
- });
2263
- }
2264
- for (const path of entries.keys()) {
2265
- if (path === "[Content_Types].xml" || path.endsWith(".rels")) continue;
2266
- if (contentTypes.overrides.has(path)) continue;
2267
- const ext = extensionOf(path);
2268
- if (ext && contentTypes.defaults.has(ext)) continue;
2269
- issues.push({
2270
- code: "O5",
2271
- severity: "error",
2272
- part: path,
2273
- message: `part has no [Content_Types] Override and no Default covers extension "${ext || "(none)"}"`
2274
- });
2275
- }
2276
- for (const partName of contentTypes.overrides.keys()) {
2277
- if (entries.has(partName)) continue;
2278
- issues.push({
2279
- code: "O6",
2280
- severity: "error",
2281
- part: `/${partName}`,
2282
- message: `[Content_Types] Override references absent part "${partName}"`
2283
- });
2284
- }
2285
- for (const rf of relsFiles) {
2286
- const counts = /* @__PURE__ */ new Map();
2287
- for (const rel of rf.entries) {
2288
- if (!rel.id) continue;
2289
- counts.set(rel.id, (counts.get(rel.id) ?? 0) + 1);
2290
- }
2291
- for (const [id, count] of counts) {
2292
- if (count <= 1) continue;
2293
- issues.push({
2294
- code: "O7",
2295
- severity: "warn",
2296
- part: rf.relsPath,
2297
- message: `duplicate relationship Id "${id}" appears ${count} times`
2298
- });
2299
- }
2300
- }
2301
- return issues.sort((a, b) => a.code === b.code ? a.part.localeCompare(b.part) : a.code.localeCompare(b.code));
2302
- }
2303
- function summarizeOpcIssues(issues) {
2304
- let errors = 0;
2305
- let warnings = 0;
2306
- for (const i of issues) if (i.severity === "error") errors++;
2307
- else warnings++;
2308
- return {
2309
- errors,
2310
- warnings
2311
- };
2312
- }
2313
- //#endregion
2314
- //#region src/opc/part-registry.ts
2315
- const DOCX_PARTS = {
2316
- format: "docx",
2317
- orphanWhitelist: [
2318
- "word/media/",
2319
- "word/fonts/",
2320
- "word/embeddings/",
2321
- "word/afchunks/",
2322
- "customXml/",
2323
- "_rels/",
2324
- "word/_rels/",
2325
- "docProps/",
2326
- "[Content_Types].xml"
2327
- ],
2328
- parts: [
2329
- {
2330
- path: "[Content_Types].xml",
2331
- presence: { kind: "always" }
2332
- },
2333
- {
2334
- path: "_rels/.rels",
2335
- presence: { kind: "always" }
2336
- },
2337
- {
2338
- path: "word/document.xml",
2339
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
2340
- presence: { kind: "always" }
2341
- },
2342
- {
2343
- path: "word/styles.xml",
2344
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml",
2345
- presence: {
2346
- kind: "conditional",
2347
- flag: "freshCompile"
2348
- }
2349
- },
2350
- {
2351
- path: "word/numbering.xml",
2352
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",
2353
- presence: {
2354
- kind: "conditional",
2355
- flag: "freshCompile"
2356
- }
2357
- },
2358
- {
2359
- path: "word/footnotes.xml",
2360
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml",
2361
- presence: {
2362
- kind: "conditional",
2363
- flag: "freshCompile"
2364
- }
2365
- },
2366
- {
2367
- path: "word/endnotes.xml",
2368
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml",
2369
- presence: {
2370
- kind: "conditional",
2371
- flag: "freshCompile"
2372
- }
2373
- },
2374
- {
2375
- path: "word/settings.xml",
2376
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml",
2377
- presence: {
2378
- kind: "conditional",
2379
- flag: "freshCompile"
2380
- }
2381
- },
2382
- {
2383
- path: "word/fontTable.xml",
2384
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml",
2385
- presence: {
2386
- kind: "conditional",
2387
- flag: "freshCompile"
2388
- }
2389
- },
2390
- {
2391
- path: "docProps/core.xml",
2392
- contentType: "application/vnd.openxmlformats-package.core-properties+xml",
2393
- presence: {
2394
- kind: "conditional",
2395
- flag: "freshCompile"
2396
- }
2397
- },
2398
- {
2399
- path: "docProps/app.xml",
2400
- contentType: "application/vnd.openxmlformats-officedocument.extended-properties+xml",
2401
- presence: {
2402
- kind: "conditional",
2403
- flag: "freshCompile"
2404
- }
2405
- },
2406
- {
2407
- path: "docProps/custom.xml",
2408
- contentType: "application/vnd.openxmlformats-officedocument.custom-properties+xml",
2409
- presence: {
2410
- kind: "conditional",
2411
- flag: "freshCompile"
2412
- }
2413
- },
2414
- {
2415
- path: "word/comments.xml",
2416
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",
2417
- presence: {
2418
- kind: "conditional",
2419
- flag: "hasComments"
2420
- }
2421
- },
2422
- {
2423
- path: "word/header${i}.xml",
2424
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
2425
- presence: {
2426
- kind: "repeated",
2427
- countFrom: "headerCount"
2428
- }
2429
- },
2430
- {
2431
- path: "word/footer${i}.xml",
2432
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
2433
- presence: {
2434
- kind: "repeated",
2435
- countFrom: "footerCount"
2436
- }
2437
- },
2438
- {
2439
- path: "word/charts/chart${i}.xml",
2440
- contentType: "application/vnd.openxmlformats-officedocument.drawingml.chart+xml",
2441
- presence: {
2442
- kind: "repeated",
2443
- countFrom: "chartCount"
2444
- }
2445
- },
2446
- {
2447
- path: "word/diagrams/data${i}.xml",
2448
- contentType: "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml",
2449
- presence: {
2450
- kind: "repeated",
2451
- countFrom: "smartArtCount"
2452
- }
2453
- },
2454
- {
2455
- path: "word/diagrams/layout${i}.xml",
2456
- contentType: "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml",
2457
- presence: {
2458
- kind: "repeated",
2459
- countFrom: "smartArtCount"
2460
- }
2461
- },
2462
- {
2463
- path: "word/diagrams/quickStyle${i}.xml",
2464
- contentType: "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml",
2465
- presence: {
2466
- kind: "repeated",
2467
- countFrom: "smartArtCount"
2468
- }
2469
- },
2470
- {
2471
- path: "word/diagrams/colors${i}.xml",
2472
- contentType: "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml",
2473
- presence: {
2474
- kind: "repeated",
2475
- countFrom: "smartArtCount"
2476
- }
2477
- },
2478
- {
2479
- path: "word/diagrams/drawing${i}.xml",
2480
- contentType: "application/vnd.ms-office.drawingml.diagramDrawing+xml",
2481
- presence: {
2482
- kind: "repeated",
2483
- countFrom: "smartArtCount"
2484
- }
2485
- },
2486
- {
2487
- path: "word/bibliography.xml",
2488
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.bibliography+xml",
2489
- presence: {
2490
- kind: "conditional",
2491
- flag: "hasBibliography"
2492
- }
2493
- },
2494
- {
2495
- path: "word/glossary/document.xml",
2496
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.glossary+xml",
2497
- presence: {
2498
- kind: "conditional",
2499
- flag: "hasGlossary"
2500
- }
2501
- },
2502
- {
2503
- path: "word/webSettings.xml",
2504
- contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml",
2505
- presence: {
2506
- kind: "conditional",
2507
- flag: "hasWebSettings"
2508
- }
2509
- },
2510
- {
2511
- path: "word/theme/theme1.xml",
2512
- contentType: "application/vnd.openxmlformats-officedocument.theme+xml",
2513
- presence: {
2514
- kind: "conditional",
2515
- flag: "freshCompile"
2516
- }
2517
- }
2518
- ]
2519
- };
2520
- const PPTX_PARTS = {
2521
- format: "pptx",
2522
- orphanWhitelist: [
2523
- "ppt/media/",
2524
- "ppt/embeddings/",
2525
- "_rels/",
2526
- "ppt/_rels/",
2527
- "ppt/slideMasters/_rels/",
2528
- "ppt/slideLayouts/_rels/",
2529
- "ppt/slides/_rels/",
2530
- "ppt/notesMasters/_rels/",
2531
- "ppt/notesSlides/_rels/",
2532
- "ppt/charts/_rels/",
2533
- "ppt/diagrams/_rels/",
2534
- "docProps/",
2535
- "[Content_Types].xml"
2536
- ],
2537
- parts: [
2538
- {
2539
- path: "[Content_Types].xml",
2540
- presence: { kind: "always" }
2541
- },
2542
- {
2543
- path: "_rels/.rels",
2544
- presence: { kind: "always" }
2545
- },
2546
- {
2547
- path: "ppt/presentation.xml",
2548
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml",
2549
- presence: { kind: "always" }
2550
- },
2551
- {
2552
- path: "docProps/core.xml",
2553
- contentType: "application/vnd.openxmlformats-package.core-properties+xml",
2554
- presence: {
2555
- kind: "conditional",
2556
- flag: "freshCompile"
2557
- }
2558
- },
2559
- {
2560
- path: "docProps/app.xml",
2561
- contentType: "application/vnd.openxmlformats-officedocument.extended-properties+xml",
2562
- presence: {
2563
- kind: "conditional",
2564
- flag: "freshCompile"
2565
- }
2566
- },
2567
- {
2568
- path: "ppt/theme/theme${i}.xml",
2569
- contentType: "application/vnd.openxmlformats-officedocument.theme+xml",
2570
- presence: {
2571
- kind: "repeated",
2572
- countFrom: "masters + notes/handout masters"
2573
- }
2574
- },
2575
- {
2576
- path: "ppt/presProps.xml",
2577
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.presProps+xml",
2578
- presence: {
2579
- kind: "conditional",
2580
- flag: "freshCompile"
2581
- }
2582
- },
2583
- {
2584
- path: "ppt/viewProps.xml",
2585
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml",
2586
- presence: {
2587
- kind: "conditional",
2588
- flag: "freshCompile"
2589
- }
2590
- },
2591
- {
2592
- path: "ppt/tableStyles.xml",
2593
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml",
2594
- presence: {
2595
- kind: "conditional",
2596
- flag: "freshCompile"
2597
- }
2598
- },
2599
- {
2600
- path: "ppt/slideMasters/slideMaster${i}.xml",
2601
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml",
2602
- presence: {
2603
- kind: "repeated",
2604
- countFrom: "masters.length"
2605
- }
2606
- },
2607
- {
2608
- path: "ppt/slideLayouts/slideLayout${i}.xml",
2609
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml",
2610
- presence: {
2611
- kind: "repeated",
2612
- countFrom: "layouts.length"
2613
- }
2614
- },
2615
- {
2616
- path: "ppt/slides/slide${i}.xml",
2617
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.slide+xml",
2618
- presence: {
2619
- kind: "repeated",
2620
- countFrom: "slides.length"
2621
- }
2622
- },
2623
- {
2624
- path: "ppt/notesMasters/notesMaster1.xml",
2625
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml",
2626
- presence: {
2627
- kind: "conditional",
2628
- flag: "any slide has notes"
2629
- }
2630
- },
2631
- {
2632
- path: "ppt/handoutMasters/handoutMaster1.xml",
2633
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.handoutMaster+xml",
2634
- presence: {
2635
- kind: "conditional",
2636
- flag: "includeHandoutMaster"
2637
- }
2638
- },
2639
- {
2640
- path: "ppt/notesSlides/notesSlide${i}.xml",
2641
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml",
2642
- presence: {
2643
- kind: "repeated",
2644
- countFrom: "slides with notes"
2645
- }
2646
- },
2647
- {
2648
- path: "ppt/commentAuthors.xml",
2649
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.commentAuthors+xml",
2650
- presence: {
2651
- kind: "conditional",
2652
- flag: "any slide has comments"
2653
- }
2654
- },
2655
- {
2656
- path: "ppt/comments/comment${i}.xml",
2657
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.comments+xml",
2658
- presence: {
2659
- kind: "repeated",
2660
- countFrom: "slides with comments"
2661
- }
2662
- },
2663
- {
2664
- path: "ppt/charts/chart${i}.xml",
2665
- contentType: "application/vnd.openxmlformats-officedocument.drawingml.chart+xml",
2666
- presence: {
2667
- kind: "repeated",
2668
- countFrom: "charts"
2669
- }
2670
- },
2671
- {
2672
- path: "ppt/diagrams/data${i}.xml",
2673
- contentType: "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml",
2674
- presence: {
2675
- kind: "repeated",
2676
- countFrom: "smartArts"
2677
- }
2678
- },
2679
- {
2680
- path: "ppt/diagrams/layout${i}.xml",
2681
- contentType: "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml",
2682
- presence: {
2683
- kind: "repeated",
2684
- countFrom: "smartArts"
2685
- }
2686
- },
2687
- {
2688
- path: "ppt/diagrams/quickStyle${i}.xml",
2689
- contentType: "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml",
2690
- presence: {
2691
- kind: "repeated",
2692
- countFrom: "smartArts"
2693
- }
2694
- },
2695
- {
2696
- path: "ppt/diagrams/colors${i}.xml",
2697
- contentType: "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml",
2698
- presence: {
2699
- kind: "repeated",
2700
- countFrom: "smartArts"
2701
- }
2702
- },
2703
- {
2704
- path: "ppt/diagrams/drawing${i}.xml",
2705
- contentType: "application/vnd.ms-office.drawingml.diagramDrawing+xml",
2706
- presence: {
2707
- kind: "repeated",
2708
- countFrom: "smartArts"
2709
- }
2710
- },
2711
- {
2712
- path: "ppt/slideSyncPr/slideSyncPr${i}.xml",
2713
- contentType: "application/vnd.openxmlformats-officedocument.presentationml.slideSyncProperties+xml",
2714
- presence: {
2715
- kind: "repeated",
2716
- countFrom: "slides with slideSync"
2717
- }
2718
- }
2719
- ]
2720
- };
2721
- const XLSX_PARTS = {
2722
- format: "xlsx",
2723
- orphanWhitelist: [
2724
- "xl/media/",
2725
- "xl/embeddings/",
2726
- "_rels/",
2727
- "xl/_rels/",
2728
- "xl/worksheets/_rels/",
2729
- "xl/chartsheets/_rels/",
2730
- "xl/drawings/_rels/",
2731
- "xl/pivotTables/_rels/",
2732
- "xl/pivotCache/_rels/",
2733
- "xl/externalLinks/_rels/",
2734
- "docProps/",
2735
- "[Content_Types].xml"
2736
- ],
2737
- parts: [
2738
- {
2739
- path: "[Content_Types].xml",
2740
- presence: { kind: "always" }
2741
- },
2742
- {
2743
- path: "_rels/.rels",
2744
- presence: { kind: "always" }
2745
- },
2746
- {
2747
- path: "xl/workbook.xml",
2748
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
2749
- presence: { kind: "always" }
2750
- },
2751
- {
2752
- path: "docProps/core.xml",
2753
- contentType: "application/vnd.openxmlformats-package.core-properties+xml",
2754
- presence: {
2755
- kind: "conditional",
2756
- flag: "freshCompile"
2757
- }
2758
- },
2759
- {
2760
- path: "docProps/app.xml",
2761
- contentType: "application/vnd.openxmlformats-officedocument.extended-properties+xml",
2762
- presence: {
2763
- kind: "conditional",
2764
- flag: "freshCompile"
2765
- }
2766
- },
2767
- {
2768
- path: "xl/styles.xml",
2769
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
2770
- presence: {
2771
- kind: "conditional",
2772
- flag: "freshCompile"
2773
- }
2774
- },
2775
- {
2776
- path: "xl/theme/theme1.xml",
2777
- contentType: "application/vnd.openxmlformats-officedocument.theme+xml",
2778
- presence: {
2779
- kind: "conditional",
2780
- flag: "freshCompile"
2781
- }
2782
- },
2783
- {
2784
- path: "xl/sharedStrings.xml",
2785
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
2786
- presence: {
2787
- kind: "conditional",
2788
- flag: "sharedStrings.count > 0"
2789
- }
2790
- },
2791
- {
2792
- path: "xl/worksheets/sheet${i}.xml",
2793
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
2794
- presence: {
2795
- kind: "repeated",
2796
- countFrom: "worksheets.length"
2797
- }
2798
- },
2799
- {
2800
- path: "xl/chartsheets/sheet${i}.xml",
2801
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml",
2802
- presence: {
2803
- kind: "repeated",
2804
- countFrom: "chartsheets.length"
2805
- }
2806
- },
2807
- {
2808
- path: "xl/drawings/drawing${i}.xml",
2809
- contentType: "application/vnd.openxmlformats-officedocument.drawing+xml",
2810
- presence: {
2811
- kind: "conditional",
2812
- flag: "worksheet has drawing"
2813
- }
2814
- },
2815
- {
2816
- path: "xl/comments${i}.xml",
2817
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
2818
- presence: {
2819
- kind: "conditional",
2820
- flag: "worksheet.comments.length > 0"
2821
- }
2822
- },
2823
- {
2824
- path: "xl/drawings/vmlDrawing${i}.vml",
2825
- presence: {
2826
- kind: "conditional",
2827
- flag: "worksheet.comments (legacy VML)"
2828
- }
2829
- },
2830
- {
2831
- path: "xl/charts/chart${i}.xml",
2832
- contentType: "application/vnd.openxmlformats-officedocument.drawingml.chart+xml",
2833
- presence: {
2834
- kind: "repeated",
2835
- countFrom: "charts"
2836
- }
2837
- },
2838
- {
2839
- path: "xl/pivotTables/pivotTable${i}.xml",
2840
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml",
2841
- presence: {
2842
- kind: "repeated",
2843
- countFrom: "pivotTables"
2844
- }
2845
- },
2846
- {
2847
- path: "xl/pivotCache/pivotCacheDefinition${i}.xml",
2848
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml",
2849
- presence: {
2850
- kind: "repeated",
2851
- countFrom: "pivotCaches"
2852
- }
2853
- },
2854
- {
2855
- path: "xl/pivotCache/pivotCacheRecords${i}.xml",
2856
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml",
2857
- presence: {
2858
- kind: "repeated",
2859
- countFrom: "pivotCaches"
2860
- }
2861
- },
2862
- {
2863
- path: "xl/tables/table${i}.xml",
2864
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
2865
- presence: {
2866
- kind: "repeated",
2867
- countFrom: "tables"
2868
- }
2869
- },
2870
- {
2871
- path: "xl/externalLinks/externalLink${i}.xml",
2872
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml",
2873
- presence: {
2874
- kind: "repeated",
2875
- countFrom: "externalLinks.length"
2876
- }
2877
- },
2878
- {
2879
- path: "xl/calcChain.xml",
2880
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml",
2881
- presence: {
2882
- kind: "conditional",
2883
- flag: "any formula cell"
2884
- }
2885
- },
2886
- {
2887
- path: "xl/revisionHeaders.xml",
2888
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml",
2889
- presence: {
2890
- kind: "conditional",
2891
- flag: "revisionLog"
2892
- }
2893
- },
2894
- {
2895
- path: "xl/revisions/revision${i}.xml",
2896
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml",
2897
- presence: {
2898
- kind: "repeated",
2899
- countFrom: "revisionLog.logs.length"
2900
- }
2901
- },
2902
- {
2903
- path: "xl/users.xml",
2904
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.users+xml",
2905
- presence: {
2906
- kind: "conditional",
2907
- flag: "revisionLog.users"
2908
- }
2909
- }
2910
- ]
2911
- };
2912
- const PART_REGISTRIES = {
2913
- docx: DOCX_PARTS,
2914
- pptx: PPTX_PARTS,
2915
- xlsx: XLSX_PARTS
2916
- };
2917
- //#endregion
2918
- //#region src/opc/content-type-overrides.ts
2919
- /** Ensure a part path carries the leading slash an Override PartName requires. */
2920
- function withLeadingSlash(partPath) {
2921
- return partPath.startsWith("/") ? partPath : `/${partPath}`;
2922
- }
2923
- /**
2924
- * Derive [Content_Types].xml Override entries for every registry part present
2925
- * under `facts`. The `facts` keys mirror the registry's `flag` / `countFrom`
2926
- * tokens: a boolean for `conditional` parts, a count for `repeated` parts.
2927
- * Order follows `registry.parts`; OPC does not mandate Override order.
2928
- */
2929
- function buildContentTypeOverrides(registry, facts) {
2930
- const overrides = [];
2931
- for (const part of registry.parts) {
2932
- if (!part.contentType) continue;
2933
- const presence = part.presence;
2934
- if (presence.kind === "always") {
2935
- if (!part.path.includes("${i}")) overrides.push({
2936
- partName: withLeadingSlash(part.path),
2937
- contentType: part.contentType
2938
- });
2939
- } else if (presence.kind === "conditional") {
2940
- if (facts.get(presence.flag)) overrides.push({
2941
- partName: withLeadingSlash(part.path),
2942
- contentType: part.contentType
2943
- });
2944
- } else {
2945
- const count = Number(facts.get(presence.countFrom) ?? 0);
2946
- for (let i = 1; i <= count; i++) overrides.push({
2947
- partName: withLeadingSlash(part.path.replace("${i}", String(i))),
2948
- contentType: part.contentType
2949
- });
2950
- }
2951
- }
2952
- return overrides;
2953
- }
2954
- //#endregion
1
+ import { C as xsdLineEndSize, D as xsdPenAlignment, E as xsdPattern, L as uniqueId, O as xsdPresetShadow, S as xsdLineCap, T as xsdPathFillMode, V as toUint8Array, b as xsdCompoundLine, k as xsdRectAlignment, l as convertToEmu, w as xsdMaterialType, x as xsdEffectContainer, y as xsdBlendMode } from "./converters-C_Y2QX1w.mjs";
2
+ import { o as parse$1, s as stringify$1 } from "./descriptor-BjNkn5jo.mjs";
3
+ import { attr, attrMeasure, attrNum, element, escapeXml, findChild, stringify } from "@office-open/xml";
2955
4
  //#region src/drawingml/color/color-transform.ts
2956
5
  /**
2957
6
  * Creates color transform child elements as XML strings.
@@ -3527,74 +576,6 @@ const createColorElement = (color) => {
3527
576
  */
3528
577
  const createSolidFill = (options) => element("a:solidFill", void 0, [createColorElement(options)]);
3529
578
  //#endregion
3530
- //#region src/util/data-type.ts
3531
- /**
3532
- * Binary input normalization.
3533
- *
3534
- * Accepts the full range of binary inputs (Buffer/Uint8Array/ArrayBuffer/
3535
- * DataView/number[]/string/base64 data URL/…) and normalizes to `Uint8Array`.
3536
- * Centralized here so every entry point (packer, patch, descriptor helpers)
3537
- * shares one definition instead of re-declaring per module.
3538
- *
3539
- * @module
3540
- */
3541
- const DATA_URL_RE = /^data:([\w.+-]+\/[\w.+-]+)?;base64,/;
3542
- /** Test whether a string is a base64 data URL (`data:[mime];base64,...`). */
3543
- function isBase64DataURL(input) {
3544
- return DATA_URL_RE.test(input);
3545
- }
3546
- /** Normalize any supported binary input to a `Uint8Array`. */
3547
- function toUint8Array(data, options) {
3548
- if (data instanceof Uint8Array) return data;
3549
- if (data instanceof ArrayBuffer) return new Uint8Array(data);
3550
- if (data instanceof DataView) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
3551
- if (typeof data === "string") {
3552
- const match = data.match(DATA_URL_RE);
3553
- if (match) return decodeBase64(data.slice(match[0].length));
3554
- if (options?.encoding === "base64") return decodeBase64(data);
3555
- return new TextEncoder().encode(data);
3556
- }
3557
- if (Array.isArray(data)) return new Uint8Array(data);
3558
- if (data instanceof Blob) throw new TypeError("Blob input requires async processing");
3559
- if (data instanceof ReadableStream) throw new TypeError("ReadableStream input requires async processing");
3560
- throw new TypeError(`Unsupported data type: ${typeof data}`);
3561
- }
3562
- //#endregion
3563
- //#region src/util/generators.ts
3564
- /**
3565
- * Unique ID generation utilities.
3566
- *
3567
- * @module
3568
- */
3569
- /**
3570
- * Creates a unique numeric ID generator with sequential numbering.
3571
- */
3572
- const uniqueNumericIdCreator = (initial = 0) => {
3573
- let currentCount = initial;
3574
- return () => ++currentCount;
3575
- };
3576
- const URL_ALPHABET = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
3577
- /**
3578
- * Generates a unique lowercase alphanumeric ID using crypto.getRandomValues.
3579
- */
3580
- const uniqueId = () => {
3581
- const bytes = new Uint8Array(21);
3582
- crypto.getRandomValues(bytes);
3583
- let id = "";
3584
- for (let i = 0; i < 21; i++) id += URL_ALPHABET[bytes[i] & 63];
3585
- return id.toLowerCase();
3586
- };
3587
- /**
3588
- * Generates a SHA-1 hash of the provided data.
3589
- */
3590
- const hashedId = (data) => {
3591
- return bytesToHex(sha1(data instanceof ArrayBuffer ? new Uint8Array(data) : typeof data === "string" ? new TextEncoder().encode(data) : data));
3592
- };
3593
- /**
3594
- * Generates a UUID v4-style unique identifier using crypto.randomUUID.
3595
- */
3596
- const uniqueUuid = () => crypto.randomUUID();
3597
- //#endregion
3598
579
  //#region src/drawingml/blip/blip-effects.ts
3599
580
  /**
3600
581
  * Blip image adjustment effects for DrawingML.
@@ -3705,215 +686,6 @@ const createSourceRectangle = (options) => {
3705
686
  return element("a:srcRect", attrs);
3706
687
  };
3707
688
  //#endregion
3708
- //#region src/util/mappings.ts
3709
- /**
3710
- * Bidirectional mappings between user-friendly values and XSD abbreviated values.
3711
- *
3712
- * When XSD uses full English words (e.g. "center", "start"), values are used directly — no mapping needed.
3713
- * When XSD uses abbreviations (e.g. "ctr", "l", "rnd"), this module maps them to full words.
3714
- *
3715
- * Usage in generation (Options → XML): xsdAlign.to("center") → "ctr"
3716
- * Usage in parsing (XML → Options): xsdAlign.from("ctr") → "center"
3717
- */
3718
- /** Invert a Record<K, V> into Record<V, K>. */
3719
- function invertMap(map) {
3720
- const result = {};
3721
- for (const key of Object.keys(map)) result[map[key]] = key;
3722
- return result;
3723
- }
3724
- /** Create a bidirectional mapping helper from a single forward map. */
3725
- function bidi(forward) {
3726
- const reverse = invertMap(forward);
3727
- return {
3728
- /** User-friendly value → XSD value */
3729
- to: (key) => forward[key] ?? key,
3730
- /** XSD value → user-friendly value */
3731
- from: (xsd) => reverse[xsd] ?? xsd,
3732
- /** The forward map (user → XSD) */
3733
- forward,
3734
- /** The reverse map (XSD → user) */
3735
- reverse
3736
- };
3737
- }
3738
- const xsdRectAlignment = bidi({
3739
- topLeft: "tl",
3740
- top: "t",
3741
- topRight: "tr",
3742
- left: "l",
3743
- center: "ctr",
3744
- right: "r",
3745
- bottomLeft: "bl",
3746
- bottom: "b",
3747
- bottomRight: "br"
3748
- });
3749
- const xsdTextAlign = bidi({
3750
- left: "l",
3751
- center: "ctr",
3752
- right: "r",
3753
- justify: "just"
3754
- });
3755
- const xsdTextAnchor = bidi({
3756
- top: "t",
3757
- center: "ctr",
3758
- bottom: "b",
3759
- justify: "just",
3760
- distribute: "dist"
3761
- });
3762
- const xsdLineCap = bidi({
3763
- round: "rnd",
3764
- square: "sq",
3765
- flat: "flat"
3766
- });
3767
- const xsdCompoundLine = bidi({
3768
- single: "sng",
3769
- double: "dbl",
3770
- thickThin: "thickThin",
3771
- thinThick: "thinThick",
3772
- triple: "tri"
3773
- });
3774
- const xsdPenAlignment = bidi({
3775
- center: "ctr",
3776
- inside: "in"
3777
- });
3778
- const xsdLineEndSize = bidi({
3779
- small: "sm",
3780
- medium: "med",
3781
- large: "lg"
3782
- });
3783
- const xsdBlendMode = bidi({
3784
- over: "over",
3785
- multiply: "mult",
3786
- screen: "screen",
3787
- darken: "darken",
3788
- lighten: "lighten"
3789
- });
3790
- const xsdPathFillMode = bidi({
3791
- none: "none",
3792
- normal: "norm",
3793
- lighten: "lighten",
3794
- lightenLess: "lightenLess",
3795
- darken: "darken",
3796
- darkenLess: "darkenLess"
3797
- });
3798
- const xsdEffectContainer = bidi({
3799
- sibling: "sib",
3800
- tree: "tree"
3801
- });
3802
- const xsdPresetShadow = bidi({
3803
- shadow1: "shdw1",
3804
- shadow2: "shdw2",
3805
- shadow3: "shdw3",
3806
- shadow4: "shdw4",
3807
- shadow5: "shdw5",
3808
- shadow6: "shdw6",
3809
- shadow7: "shdw7",
3810
- shadow8: "shdw8",
3811
- shadow9: "shdw9",
3812
- shadow10: "shdw10",
3813
- shadow11: "shdw11",
3814
- shadow12: "shdw12",
3815
- shadow13: "shdw13",
3816
- shadow14: "shdw14",
3817
- shadow15: "shdw15",
3818
- shadow16: "shdw16",
3819
- shadow17: "shdw17",
3820
- shadow18: "shdw18",
3821
- shadow19: "shdw19",
3822
- shadow20: "shdw20"
3823
- });
3824
- const xsdMaterialType = bidi({
3825
- legacyMatte: "legacyMatte",
3826
- legacyPlastic: "legacyPlastic",
3827
- legacyMetal: "legacyMetal",
3828
- legacyWireframe: "legacyWireframe",
3829
- matte: "matte",
3830
- plastic: "plastic",
3831
- metal: "metal",
3832
- warmMatte: "warmMatte",
3833
- translucentPowder: "translucentPowder",
3834
- powder: "powder",
3835
- darkEdge: "dkEdge",
3836
- softEdge: "softEdge",
3837
- clear: "clear",
3838
- flat: "flat",
3839
- softMetal: "softmetal"
3840
- });
3841
- const xsdPattern = bidi({
3842
- percent5: "pct5",
3843
- percent10: "pct10",
3844
- percent20: "pct20",
3845
- percent25: "pct25",
3846
- percent30: "pct30",
3847
- percent40: "pct40",
3848
- percent50: "pct50",
3849
- percent60: "pct60",
3850
- percent70: "pct70",
3851
- percent75: "pct75",
3852
- percent80: "pct80",
3853
- percent90: "pct90",
3854
- horizontal: "horz",
3855
- vertical: "vert",
3856
- lightHorizontal: "ltHorz",
3857
- lightVertical: "ltVert",
3858
- darkHorizontal: "dkHorz",
3859
- darkVertical: "dkVert",
3860
- narrowHorizontal: "narHorz",
3861
- narrowVertical: "narVert",
3862
- dashedHorizontal: "dashHorz",
3863
- dashedVertical: "dashVert",
3864
- cross: "cross",
3865
- downDiagonal: "dnDiag",
3866
- upDiagonal: "upDiag",
3867
- lightDownDiagonal: "ltDnDiag",
3868
- lightUpDiagonal: "ltUpDiag",
3869
- darkDownDiagonal: "dkDnDiag",
3870
- darkUpDiagonal: "dkUpDiag",
3871
- wideDownDiagonal: "wdDnDiag",
3872
- wideUpDiagonal: "wdUpDiag",
3873
- dashedDownDiagonal: "dashDnDiag",
3874
- dashedUpDiagonal: "dashUpDiag",
3875
- diagonalCross: "diagCross",
3876
- smallChecker: "smCheck",
3877
- largeChecker: "lgCheck",
3878
- smallGrid: "smGrid",
3879
- largeGrid: "lgGrid",
3880
- dotGrid: "dotGrid",
3881
- smallConfetti: "smConfetti",
3882
- largeConfetti: "lgConfetti",
3883
- horizontalBrick: "horzBrick",
3884
- diagonalBrick: "diagBrick",
3885
- solidDiamond: "solidDmnd",
3886
- openDiamond: "openDmnd",
3887
- dottedDiamond: "dotDmnd",
3888
- plaid: "plaid",
3889
- sphere: "sphere",
3890
- weave: "weave",
3891
- divot: "divot",
3892
- shingle: "shingle",
3893
- wave: "wave",
3894
- trellis: "trellis",
3895
- zigZag: "zigZag"
3896
- });
3897
- const xsdVerticalMergeRev = bidi({
3898
- continue: "cont",
3899
- restart: "rest"
3900
- });
3901
- const xsdUnderlineStyle = bidi({
3902
- single: "sng",
3903
- double: "dbl",
3904
- none: "none"
3905
- });
3906
- const xsdStrikeStyle = bidi({
3907
- singleStrike: "sngStrike",
3908
- doubleStrike: "dblStrike",
3909
- noStrike: "noStrike"
3910
- });
3911
- const xsdTextCaps = bidi({
3912
- none: "none",
3913
- all: "all",
3914
- small: "small"
3915
- });
3916
- //#endregion
3917
689
  //#region src/drawingml/blip/tile.ts
3918
690
  /**
3919
691
  * Tile fill module for blip fills.
@@ -5618,7 +2390,7 @@ const createCustomGeometry = (options) => {
5618
2390
  return element("a:custGeom", void 0, children);
5619
2391
  };
5620
2392
  //#endregion
5621
- //#region src/drawingml/blip/blip-extentions.ts
2393
+ //#region src/drawingml/blip/blip-extensions.ts
5622
2394
  /**
5623
2395
  * Blip extensions module for SVG support.
5624
2396
  *
@@ -5650,7 +2422,7 @@ const createSvgBlip = (svgReferenceId) => `<asvg:svgBlip xmlns:asvg="http://sche
5650
2422
  * @returns An XML string representing the extension element
5651
2423
  * @internal
5652
2424
  */
5653
- const createExtention = (svgReferenceId) => element("a:ext", { uri: "{96DAC541-7B7A-43D3-8B79-37D633B846F1}" }, [createSvgBlip(svgReferenceId)]);
2425
+ const createExtension = (svgReferenceId) => element("a:ext", { uri: "{96DAC541-7B7A-43D3-8B79-37D633B846F1}" }, [createSvgBlip(svgReferenceId)]);
5654
2426
  /**
5655
2427
  * Creates an extension list for SVG images.
5656
2428
  *
@@ -5669,7 +2441,7 @@ const createExtention = (svgReferenceId) => element("a:ext", { uri: "{96DAC541-7
5669
2441
  * @param svgReferenceId - The reference ID for the SVG image
5670
2442
  * @returns An XML string representing the extension list
5671
2443
  */
5672
- const createExtentionList = (svgReferenceId) => element("a:extLst", void 0, [createExtention(svgReferenceId)]);
2444
+ const createExtensionList = (svgReferenceId) => element("a:extLst", void 0, [createExtension(svgReferenceId)]);
5673
2445
  //#endregion
5674
2446
  //#region src/drawingml/blip/blip.ts
5675
2447
  /**
@@ -5729,7 +2501,7 @@ const createExtentionList = (svgReferenceId) => element("a:extLst", void 0, [cre
5729
2501
  const createBlip = (options, blipEffects) => {
5730
2502
  const children = [];
5731
2503
  if (blipEffects) children.push(...createBlipEffects(blipEffects));
5732
- if (options.type === "svg" && options.fallbackFileName) children.push(createExtentionList(options.referenceId));
2504
+ if (options.type === "svg" && options.fallbackFileName) children.push(createExtensionList(options.referenceId));
5733
2505
  return element("a:blip", {
5734
2506
  cstate: "none",
5735
2507
  "r:embed": `{${options.type === "svg" && options.fallbackFileName ? options.fallbackFileName : options.referenceId}}`
@@ -6922,9 +3694,10 @@ function readBlipEffects(el, ctx) {
6922
3694
  const sf = findChild(child, "a:solidFill");
6923
3695
  if (sf) fills.push(parse$1(solidFillDesc, sf, ctx));
6924
3696
  }
6925
- if (fills.length >= 2) result.duotone = {
6926
- color1: fills[0],
6927
- color2: fills[1]
3697
+ const [color1, color2] = fills;
3698
+ if (color1 && color2) result.duotone = {
3699
+ color1,
3700
+ color2
6928
3701
  };
6929
3702
  }
6930
3703
  return Object.keys(result).length > 0 ? result : void 0;
@@ -7205,217 +3978,6 @@ function readDirectColor(el, ctx) {
7205
3978
  return { value: "" };
7206
3979
  }
7207
3980
  //#endregion
7208
- //#region src/util/converters.ts
7209
- /**
7210
- * OOXML unit conversion utilities.
7211
- *
7212
- * @module
7213
- */
7214
- /**
7215
- * Converts millimeters to TWIP (twentieths of a point).
7216
- */
7217
- const convertMillimetersToTwip = (millimeters) => Math.floor(millimeters / 25.4 * 72 * 20);
7218
- /**
7219
- * Converts inches to TWIP (twentieths of a point).
7220
- */
7221
- const convertInchesToTwip = (inches) => Math.floor(inches * 72 * 20);
7222
- /**
7223
- * Converts pixels to EMU (96 DPI).
7224
- */
7225
- const convertPixelsToEmu = (pixels) => Math.round(pixels * 9525);
7226
- /**
7227
- * Converts EMU to pixels (96 DPI).
7228
- *
7229
- * Returns a possibly fractional (sub-pixel) value. The integer rounding that
7230
- * lived here before permanently discarded sub-pixel precision, which made an
7231
- * EMU → pixel → EMU round-trip lossy (e.g. 5521960 EMU → 580 px → 5524500 EMU).
7232
- * Keeping the fraction lets convertPixelsToEmu restore the exact original EMU.
7233
- * Callers needing an integer pixel for display should Math.round the result.
7234
- */
7235
- const convertEmuToPixels = (emus) => emus / 9525;
7236
- /**
7237
- * Converts inches to EMU.
7238
- */
7239
- const convertInchesToEmu = (inches) => Math.round(inches * 914400);
7240
- /**
7241
- * Converts EMU to inches.
7242
- */
7243
- const convertEmuToInches = (emus) => emus / 914400;
7244
- /**
7245
- * Converts points to EMU.
7246
- */
7247
- const convertPointsToEmu = (points) => Math.round(points * 12700);
7248
- /**
7249
- * Converts EMU to points.
7250
- */
7251
- const convertEmuToPoints = (emus) => emus / 12700;
7252
- /**
7253
- * Parse a UniversalMeasure string into its numeric value and unit.
7254
- *
7255
- * @param measure - A universal measure string like "2.54cm", "-10mm", "1in"
7256
- * @returns The parsed value and unit
7257
- * @throws Error if the format is invalid
7258
- *
7259
- * @example
7260
- * ```typescript
7261
- * parseUniversalMeasure("2.54cm"); // { value: 2.54, unit: "cm" }
7262
- * parseUniversalMeasure("-10mm"); // { value: -10, unit: "mm" }
7263
- * ```
7264
- */
7265
- const parseUniversalMeasure = (measure) => {
7266
- const match = measure.match(/^(-?[0-9]+(?:\.[0-9]+)?)(mm|cm|in|pt|pc|pi|px)$/);
7267
- if (!match) throw new Error(`Invalid universal measure: '${measure}'`);
7268
- return {
7269
- value: parseFloat(match[1]),
7270
- unit: match[2]
7271
- };
7272
- };
7273
- /**
7274
- * Converts a UniversalMeasure string to TWIP (twentieths of a point).
7275
- *
7276
- * Supports units: mm, cm, in, pt, pc (picas, 1pc = 12pt), pi (alias for pc).
7277
- *
7278
- * @param measure - A universal measure string like "2.54cm", "1in", "12pt"
7279
- * @returns The value in TWIP
7280
- *
7281
- * @example
7282
- * ```typescript
7283
- * convertUniversalMeasureToTwip("1in"); // 1440
7284
- * convertUniversalMeasureToTwip("2.54cm"); // ~1440 (1 inch)
7285
- * convertUniversalMeasureToTwip("72pt"); // 1440 (1 inch = 72pt = 1440 twips)
7286
- * ```
7287
- */
7288
- const convertUniversalMeasureToTwip = (measure) => {
7289
- const { value, unit } = parseUniversalMeasure(measure);
7290
- switch (unit) {
7291
- case "mm": return convertMillimetersToTwip(value);
7292
- case "cm": return convertMillimetersToTwip(value * 10);
7293
- case "in": return convertInchesToTwip(value);
7294
- case "pt": return Math.floor(value * 20);
7295
- case "pc":
7296
- case "pi": return Math.floor(value * 12 * 20);
7297
- case "px": return Math.round(value * 15);
7298
- }
7299
- };
7300
- /**
7301
- * Converts a measurement value (number or UniversalMeasure) to TWIP.
7302
- *
7303
- * If the value is already a number, it is returned as-is (assumed to be in twips).
7304
- * If the value is a UniversalMeasure string, it is converted to twips.
7305
- *
7306
- * Useful for accepting both `number` and `UniversalMeasure` inputs where
7307
- * the XSD type is a union (e.g., ST_TwipsMeasure, ST_SignedTwipsMeasure).
7308
- *
7309
- * @param val - A numeric twip value or a universal measure string
7310
- * @returns The value in TWIP
7311
- *
7312
- * @example
7313
- * ```typescript
7314
- * convertToTwip(1440); // 1440 (already twips)
7315
- * convertToTwip("1in"); // 1440
7316
- * convertToTwip("2.54cm"); // ~1440
7317
- * ```
7318
- */
7319
- const convertToTwip = (val) => typeof val === "string" ? convertUniversalMeasureToTwip(val) : val;
7320
- /**
7321
- * Converts a UniversalMeasure string to EMU (English Metric Units).
7322
- *
7323
- * Supports units: mm, cm, in, pt, pc (picas, 1pc = 12pt), pi (alias for pc).
7324
- *
7325
- * @param measure - A universal measure string like "2.54cm", "1in", "12pt"
7326
- * @returns The value in EMU
7327
- *
7328
- * @example
7329
- * ```typescript
7330
- * convertUniversalMeasureToEmu("1in"); // 914400
7331
- * convertUniversalMeasureToEmu("2.54cm"); // 914400
7332
- * convertUniversalMeasureToEmu("12pt"); // 152400
7333
- * ```
7334
- */
7335
- const convertUniversalMeasureToEmu = (measure) => {
7336
- const { value, unit } = parseUniversalMeasure(measure);
7337
- switch (unit) {
7338
- case "mm": return Math.round(value * 36e3);
7339
- case "cm": return Math.round(value * 36e4);
7340
- case "in": return convertInchesToEmu(value);
7341
- case "pt": return convertPointsToEmu(value);
7342
- case "pc":
7343
- case "pi": return convertPointsToEmu(value * 12);
7344
- case "px": return convertPixelsToEmu(value);
7345
- }
7346
- };
7347
- /**
7348
- * Converts a measurement value (number or UniversalMeasure) to EMU.
7349
- *
7350
- * Numbers are returned as-is (assumed EMU). Strings are parsed as
7351
- * UniversalMeasure via {@link convertUniversalMeasureToEmu} — including the
7352
- * project-only `px` unit (96 DPI). The result is always an EMU number written to
7353
- * XML, so px never appears verbatim in the document.
7354
- *
7355
- * Useful for DrawingML fields where the XSD type is a union (e.g., ST_Coordinate).
7356
- *
7357
- * @param val - A numeric EMU value, or a UniversalMeasure string (incl. `${n}px`)
7358
- * @returns The value in EMU
7359
- *
7360
- * @example
7361
- * ```typescript
7362
- * convertToEmu(914400); // 914400 (already EMU)
7363
- * convertToEmu("1in"); // 914400
7364
- * convertToEmu("2.54cm"); // 914400
7365
- * convertToEmu("200px"); // 1905000 (200 * 9525)
7366
- * ```
7367
- */
7368
- const convertToEmu = (val) => typeof val === "string" ? convertUniversalMeasureToEmu(val) : val;
7369
- /**
7370
- * Converts a UniversalMeasure string to points (1pt = 1/72 inch).
7371
- *
7372
- * Supports units: mm, cm, in, pt, pc (picas, 1pc = 12pt), pi (alias for pc),
7373
- * px (96 DPI).
7374
- */
7375
- const convertUniversalMeasureToPt = (measure) => {
7376
- const { value, unit } = parseUniversalMeasure(measure);
7377
- switch (unit) {
7378
- case "mm": return value / 25.4 * 72;
7379
- case "cm": return value * 10 / 25.4 * 72;
7380
- case "in": return value * 72;
7381
- case "pt": return value;
7382
- case "pc":
7383
- case "pi": return value * 12;
7384
- case "px": return value / 96 * 72;
7385
- }
7386
- };
7387
- /**
7388
- * Converts a measurement value (number or UniversalMeasure) to points.
7389
- *
7390
- * Numbers are returned as-is (assumed to be in points). Strings are parsed as
7391
- * UniversalMeasure. Useful for SpreadsheetML fields where a number is points.
7392
- */
7393
- const convertToPt = (val) => typeof val === "string" ? convertUniversalMeasureToPt(val) : val;
7394
- /**
7395
- * Converts a UniversalMeasure string to inches.
7396
- *
7397
- * Supports units: mm, cm, in, pt, pc, pi, px (96 DPI).
7398
- */
7399
- const convertUniversalMeasureToInch = (measure) => {
7400
- const { value, unit } = parseUniversalMeasure(measure);
7401
- switch (unit) {
7402
- case "mm": return value / 25.4;
7403
- case "cm": return value * 10 / 25.4;
7404
- case "in": return value;
7405
- case "pt": return value / 72;
7406
- case "pc":
7407
- case "pi": return value * 12 / 72;
7408
- case "px": return value / 96;
7409
- }
7410
- };
7411
- /**
7412
- * Converts a measurement value (number or UniversalMeasure) to inches.
7413
- *
7414
- * Numbers are returned as-is (assumed to be in inches). Useful for SpreadsheetML
7415
- * page-margin fields where a number is inches.
7416
- */
7417
- const convertToInch = (val) => typeof val === "string" ? convertUniversalMeasureToInch(val) : val;
7418
- //#endregion
7419
3981
  //#region src/drawingml/outline/outline-descriptors.ts
7420
3982
  /**
7421
3983
  * Outline descriptor for DrawingML shapes.
@@ -7868,22 +4430,22 @@ function readPathCommand(tag, el) {
7868
4430
  };
7869
4431
  }
7870
4432
  case "a:quadBezTo": {
7871
- const points = (el.elements ?? []).filter((c) => c.name === "a:pt").map(readAdjustPoint).filter((p) => p !== void 0);
7872
- if (points.length < 2) return void 0;
4433
+ const [p0, p1] = (el.elements ?? []).filter((c) => c.name === "a:pt").map(readAdjustPoint).filter((p) => p !== void 0);
4434
+ if (!p0 || !p1) return void 0;
7873
4435
  return {
7874
4436
  command: "quadBezTo",
7875
- points: [points[0], points[1]]
4437
+ points: [p0, p1]
7876
4438
  };
7877
4439
  }
7878
4440
  case "a:cubicBezTo": {
7879
- const points = (el.elements ?? []).filter((c) => c.name === "a:pt").map(readAdjustPoint).filter((p) => p !== void 0);
7880
- if (points.length < 3) return void 0;
4441
+ const [p0, p1, p2] = (el.elements ?? []).filter((c) => c.name === "a:pt").map(readAdjustPoint).filter((p) => p !== void 0);
4442
+ if (!p0 || !p1 || !p2) return void 0;
7881
4443
  return {
7882
4444
  command: "cubicBezTo",
7883
4445
  points: [
7884
- points[0],
7885
- points[1],
7886
- points[2]
4446
+ p0,
4447
+ p1,
4448
+ p2
7887
4449
  ]
7888
4450
  };
7889
4451
  }
@@ -8465,274 +5027,6 @@ const diagramExtensionListDesc = {
8465
5027
  }
8466
5028
  };
8467
5029
  //#endregion
8468
- //#region src/util/compile.ts
8469
- /**
8470
- * Shared compiler utilities for OOXML document generation.
8471
- *
8472
- * @module
8473
- */
8474
- /** Reusable TextEncoder instance (stateless, safe to share). */
8475
- const encoder = new TextEncoder();
8476
- /**
8477
- * Convert a mapping of XML files + overrides + media into a Zippable structure.
8478
- *
8479
- * Centralises the mapping→Zippable conversion shared by all three compilers.
8480
- */
8481
- function compileMapping(mapping, overrides, media, mediaLevel = 0) {
8482
- const files = {};
8483
- for (const entry of Object.values(mapping)) files[entry.path] = encoder.encode(entry.data);
8484
- if (overrides) for (const o of overrides) files[o.path] = typeof o.data === "string" ? encoder.encode(o.data) : o.data;
8485
- if (media) for (const m of media) files[m.path] = [m.data, { level: levelForMediaName(m.path, mediaLevel) }];
8486
- return files;
8487
- }
8488
- //#endregion
8489
- //#region src/util/crypto.ts
8490
- /**
8491
- * Password hashing utilities for OOXML document protection.
8492
- *
8493
- * Implements ECMA-376 Agile Encryption password derivation.
8494
- * Passwords are encoded as UTF-16LE per the OOXML specification.
8495
- *
8496
- * Uses @noble/hashes for SHA-512 — audited, cross-platform,
8497
- * and comparable in speed to node:crypto for this workload.
8498
- *
8499
- * @module
8500
- */
8501
- function utf16leEncode(str) {
8502
- const bytes = new Uint8Array(str.length * 2);
8503
- for (let i = 0; i < str.length; i++) {
8504
- const code = str.charCodeAt(i);
8505
- bytes[i * 2] = code & 255;
8506
- bytes[i * 2 + 1] = code >> 8 & 255;
8507
- }
8508
- return bytes;
8509
- }
8510
- function randomBytes(length) {
8511
- const bytes = new Uint8Array(length);
8512
- if (typeof crypto !== "undefined" && crypto.getRandomValues) crypto.getRandomValues(bytes);
8513
- else for (let i = 0; i < length; i++) bytes[i] = Math.floor(Math.random() * 256);
8514
- return bytes;
8515
- }
8516
- /**
8517
- * Computes the ECMA-376 Agile Encryption hash for a password.
8518
- *
8519
- * Algorithm: SHA-512(salt + UTF-16LE(password)), then iterate
8520
- * SHA-512(hash + i.toUint32LE()) spinCount times.
8521
- */
8522
- function hashPasswordAgile(password, salt, spinCount) {
8523
- const pwBytes = utf16leEncode(password);
8524
- const initial = new Uint8Array(salt.length + pwBytes.length);
8525
- initial.set(salt, 0);
8526
- initial.set(pwBytes, salt.length);
8527
- let h = sha512(initial);
8528
- for (let i = 0; i < spinCount; i++) {
8529
- const buf = new Uint8Array(h.length + 4);
8530
- buf.set(h, 0);
8531
- buf[h.length] = i & 255;
8532
- buf[h.length + 1] = i >> 8 & 255;
8533
- buf[h.length + 2] = i >> 16 & 255;
8534
- buf[h.length + 3] = i >> 24 & 255;
8535
- h = sha512(buf);
8536
- }
8537
- return encodeBase64(new Uint8Array(h));
8538
- }
8539
- /**
8540
- * Derives a password hash for OOXML document protection.
8541
- *
8542
- * Returns base64-encoded hashValue, saltValue, spinCount, and algorithmName
8543
- * suitable for direct use in document protection options.
8544
- */
8545
- function derivePasswordHash(password, spinCount = 1e5) {
8546
- const salt = randomBytes(16);
8547
- return {
8548
- hashValue: hashPasswordAgile(password, salt, spinCount),
8549
- saltValue: encodeBase64(salt),
8550
- spinCount,
8551
- algorithmName: "SHA-512"
8552
- };
8553
- }
8554
- //#endregion
8555
- //#region src/util/placeholder.ts
8556
- const formatId = (offset, index, style) => style === "rId" ? `rId${offset + index}` : `${offset + index}`;
8557
- /** Single-pass regex replacement for `{key}` placeholders using a Map lookup. */
8558
- const PLACEHOLDER_RE = /\{([^{}]+)\}/g;
8559
- function replacePlaceholders(xml, map) {
8560
- const parts = [];
8561
- let last = 0;
8562
- for (const m of xml.matchAll(PLACEHOLDER_RE)) {
8563
- const replacement = map.get(m[1]);
8564
- if (replacement !== void 0) {
8565
- parts.push(xml.substring(last, m.index), replacement);
8566
- last = m.index + m[0].length;
8567
- }
8568
- }
8569
- if (last === 0) return xml;
8570
- parts.push(xml.substring(last));
8571
- return parts.join("");
8572
- }
8573
- function hasPlaceholders(xml) {
8574
- return xml.includes("{");
8575
- }
8576
- function collectPlaceholderKeys(xml, prefix) {
8577
- const keys = /* @__PURE__ */ new Set();
8578
- const search = `{${prefix}`;
8579
- let pos = 0;
8580
- while ((pos = xml.indexOf(search, pos)) !== -1) {
8581
- const keyStart = pos + search.length;
8582
- const keyEnd = xml.indexOf("}", keyStart);
8583
- if (keyEnd === -1) break;
8584
- const key = xml.substring(keyStart, keyEnd);
8585
- if (key.length > 0) keys.add(key);
8586
- pos = keyEnd + 1;
8587
- }
8588
- return [...keys];
8589
- }
8590
- function replaceImagePlaceholders(xml, mediaData, offset, idFormat = "rId") {
8591
- if (mediaData.length === 0) return xml;
8592
- const map = /* @__PURE__ */ new Map();
8593
- for (let i = 0; i < mediaData.length; i++) map.set(mediaData[i].fileName, formatId(offset, i, idFormat));
8594
- return replacePlaceholders(xml, map);
8595
- }
8596
- function getReferencedMedia(xml, mediaArray) {
8597
- return mediaArray.filter((image) => xml.includes(`{${image.fileName}}`));
8598
- }
8599
- /**
8600
- * Combined find + replace for image placeholders in a single pass.
8601
- *
8602
- * Scans XML for `{fileName}` placeholders, replaces them with formatted IDs,
8603
- * and returns the list of referenced media items for relationship registration.
8604
- * More efficient than calling getReferencedMedia() + replaceImagePlaceholders() separately.
8605
- */
8606
- function findAndReplaceImagePlaceholders(xml, mediaArray, offset, idFormat = "rId") {
8607
- if (mediaArray.length === 0 || !hasPlaceholders(xml)) return {
8608
- xml,
8609
- referenced: []
8610
- };
8611
- const itemMap = /* @__PURE__ */ new Map();
8612
- for (let i = 0; i < mediaArray.length; i++) itemMap.set(mediaArray[i].fileName, mediaArray[i]);
8613
- const referenced = [];
8614
- const replaceMap = /* @__PURE__ */ new Map();
8615
- const parts = [];
8616
- let last = 0;
8617
- for (const m of xml.matchAll(PLACEHOLDER_RE)) {
8618
- const key = m[1];
8619
- const item = itemMap.get(key);
8620
- if (item !== void 0) {
8621
- if (!replaceMap.has(key)) {
8622
- replaceMap.set(key, formatId(offset, referenced.length, idFormat));
8623
- referenced.push(item);
8624
- }
8625
- parts.push(xml.substring(last, m.index), replaceMap.get(key));
8626
- last = m.index + m[0].length;
8627
- }
8628
- }
8629
- if (last === 0) return {
8630
- xml,
8631
- referenced: []
8632
- };
8633
- parts.push(xml.substring(last));
8634
- return {
8635
- xml: parts.join(""),
8636
- referenced
8637
- };
8638
- }
8639
- /**
8640
- * Replace all placeholder types in a single pass.
8641
- *
8642
- * Combines image, chart, smartart, and arbitrary key-value replacements
8643
- * into one regex scan of the XML string. Used by compilers to avoid
8644
- * multiple full-string passes on large documents.
8645
- */
8646
- function replaceAllPlaceholders(xml, entries) {
8647
- if (entries.length === 0 || !hasPlaceholders(xml)) return xml;
8648
- const map = /* @__PURE__ */ new Map();
8649
- for (const { prefix, key, value } of entries) map.set(prefix ? `${prefix}${key}` : key, value);
8650
- return replacePlaceholders(xml, map);
8651
- }
8652
- function replaceChartPlaceholders(xml, chartKeys, offset, idFormat = "rId") {
8653
- if (chartKeys.length === 0) return xml;
8654
- const map = /* @__PURE__ */ new Map();
8655
- for (let i = 0; i < chartKeys.length; i++) map.set(`chart:${chartKeys[i]}`, formatId(offset, i, idFormat));
8656
- return replacePlaceholders(xml, map);
8657
- }
8658
- function replaceSmartArtPlaceholders(xml, keys, dataOffset, idFormat = "rId") {
8659
- if (keys.length === 0) return xml;
8660
- const count = keys.length;
8661
- const loOffset = dataOffset + count;
8662
- const qsOffset = loOffset + count;
8663
- const csOffset = qsOffset + count;
8664
- const map = /* @__PURE__ */ new Map();
8665
- for (let i = 0; i < count; i++) {
8666
- map.set(`smartart:${keys[i]}`, formatId(dataOffset, i, idFormat));
8667
- map.set(`smartart-lo:${keys[i]}`, formatId(loOffset, i, idFormat));
8668
- map.set(`smartart-qs:${keys[i]}`, formatId(qsOffset, i, idFormat));
8669
- map.set(`smartart-cs:${keys[i]}`, formatId(csOffset, i, idFormat));
8670
- }
8671
- return replacePlaceholders(xml, map);
8672
- }
8673
- function addSmartArtRelationships(keys, addRel, baseOffset, globalStartIndex, options) {
8674
- const { pathPrefix, styleRelType } = options;
8675
- const count = keys.length;
8676
- const loOffset = baseOffset + count;
8677
- const qsOffset = loOffset + count;
8678
- const csOffset = qsOffset + count;
8679
- for (let i = 0; i < keys.length; i++) {
8680
- const gi = globalStartIndex + i;
8681
- addRel(baseOffset + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramData", `${pathPrefix}diagrams/data${gi + 1}.xml`);
8682
- addRel(loOffset + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramLayout", `${pathPrefix}diagrams/layout${gi + 1}.xml`);
8683
- addRel(qsOffset + i, styleRelType, `${pathPrefix}diagrams/quickStyle${gi + 1}.xml`);
8684
- addRel(csOffset + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramColors", `${pathPrefix}diagrams/colors${gi + 1}.xml`);
8685
- addRel(csOffset + count + i, "http://schemas.microsoft.com/office/2007/relationships/diagramDrawing", `${pathPrefix}diagrams/drawing${gi + 1}.xml`);
8686
- }
8687
- }
8688
- /** Replace `{reference-instance}` placeholders with numId values. */
8689
- function replaceNumberingPlaceholders(xml, concreteNumberings) {
8690
- if (concreteNumberings.length === 0) return xml;
8691
- const map = /* @__PURE__ */ new Map();
8692
- for (const { reference, instance, numId } of concreteNumberings) map.set(`${reference}-${instance}`, numId.toString());
8693
- return replacePlaceholders(xml, map);
8694
- }
8695
- /** Replace `{media:fileName}` placeholders with relationship IDs. */
8696
- function replaceMediaPlaceholders(xml, mediaData, offset) {
8697
- if (mediaData.length === 0) return xml;
8698
- const map = /* @__PURE__ */ new Map();
8699
- for (let i = 0; i < mediaData.length; i++) map.set(`media:${mediaData[i].fileName}`, formatId(offset, i, "rId"));
8700
- return replacePlaceholders(xml, map);
8701
- }
8702
- /** Replace `{video:fileName}` placeholders with relationship IDs. */
8703
- function replaceVideoPlaceholders(xml, mediaData, offset) {
8704
- if (mediaData.length === 0) return xml;
8705
- const map = /* @__PURE__ */ new Map();
8706
- for (let i = 0; i < mediaData.length; i++) map.set(`video:${mediaData[i].fileName}`, formatId(offset, i, "rId"));
8707
- return replacePlaceholders(xml, map);
8708
- }
8709
- /** Collect media items referenced by `{media:...}` placeholders in XML. */
8710
- function getMediaRefs(xml, mediaArray) {
8711
- return collectPrefixedRefs(xml, "media:", mediaArray);
8712
- }
8713
- /** Collect media items referenced by `{video:...}` placeholders in XML. */
8714
- function getVideoRefs(xml, mediaArray) {
8715
- return collectPrefixedRefs(xml, "video:", mediaArray);
8716
- }
8717
- function collectPrefixedRefs(xml, prefix, mediaArray) {
8718
- const keys = /* @__PURE__ */ new Set();
8719
- const search = `{${prefix}`;
8720
- let pos = 0;
8721
- while ((pos = xml.indexOf(search, pos)) !== -1) {
8722
- const keyStart = pos + search.length;
8723
- const keyEnd = xml.indexOf("}", keyStart);
8724
- if (keyEnd === -1) break;
8725
- keys.add(xml.substring(keyStart, keyEnd));
8726
- pos = keyEnd + 1;
8727
- }
8728
- return mediaArray.filter((m) => keys.has(m.fileName));
8729
- }
8730
- /** Replace `{hlink:key}` placeholders with relationship IDs. */
8731
- function replaceHyperlinkPlaceholders(xml, hyperlinks, offset) {
8732
- if (hyperlinks.length === 0) return xml;
8733
- const map = /* @__PURE__ */ new Map();
8734
- for (let i = 0; i < hyperlinks.length; i++) map.set(`hlink:${hyperlinks[i].key}`, formatId(offset, i, "rId"));
8735
- return replacePlaceholders(xml, map);
8736
- }
8737
- //#endregion
8738
- export { convertUniversalMeasureToTwip as $, createGradientStop as $n, levelForMediaName as $r, createGroupLocking as $t, customGeometryDesc as A, createGlowEffect as An, SystemColor as Ar, createStyleLabel as At, convertEmuToPoints as B, LineEndType as Bn, buildContentTypeOverrides as Br, AnimateOneByOneValue as Bt, diagramStyleDesc as C, createSoftEdgeEffect as Cn, uniqueId as Cr, FontCollectionIndex as Ct, shape3DDesc as D, RectAlignment as Dn, toUint8Array as Dr, createEffectColorList as Dt, scene3DDesc as E, createPresetShadowEffect as En, isBase64DataURL as Er, createDiagramStyle as Et, shapeLockingDesc as F, LineJoin as Fn, createRgbColor as Fr, createColorsDefinitionHeaderList as Ft, convertPointsToEmu as G, createNoFill as Gn, summarizeOpcIssues as Gr, createAnimateOneByOne as Gt, convertInchesToTwip as H, createLineEnd as Hn, PART_REGISTRIES as Hr, HierBranchStyle as Ht, effectListDesc as I, PenAlignment as In, PresetColor as Ir, createLayoutDefinitionHeader as It, convertToPt as J, PresetPattern as Jn, parseArchive as Jr, createMaxChildren as Jt, convertToEmu as K, buildFill as Kn, validateOpcConsistency as Kr, createAnimationLevel as Kt, outlineDesc as L, PresetDash as Ln, createPresetColor as Lr, createLayoutDefinitionHeaderList as Lt, graphicFrameLockingDesc as M, createFillOverlayEffect as Mn, SchemeColor as Mr, createTextFillColorList as Mt, groupLockingDesc as N, CompoundLine as Nn, createSchemeColor as Nr, createTextLineColorList as Nt, groupTransform2DDesc as O, createOuterShadowEffect as On, createColorElement as Or, createFillColorList as Ot, pictureLockingDesc as P, LineCap as Pn, createScRgbColor as Pr, createColorsDefinitionHeader as Pt, convertUniversalMeasureToPt as Q, createGradientFill as Qn, createZipStream as Qr, createGraphicFrameLocking as Qt, convertEmuToInches as R, createOutline as Rn, createHslColor as Rr, createStyleDefinitionHeader as Rt, diagramRelationshipIdsDesc as S, createEffectList as Sn, hashedId as Sr, ColorMethod as St, bevelDesc as T, PresetShadowVal as Tn, uniqueUuid as Tr, StyleMatrixIndex as Tt, convertMillimetersToTwip as U, createCustomDash as Un, PPTX_PARTS as Ur, createAdjust as Ut, convertInchesToEmu as V, LineEndWidth as Vn, DOCX_PARTS as Vr, AnimationLevelValue as Vt, convertPixelsToEmu as W, createGroupFill as Wn, XLSX_PARTS as Wr, createAdjustList as Wt, convertUniversalMeasureToEmu as X, PathShadeType as Xn, ZIP_STORED_LEVEL as Xr, createPreferredChildren as Xt, convertToTwip as Y, createPatternFill as Yn, ZIP_DEFLATE_LEVEL as Yr, createOrgChart as Yt, convertUniversalMeasureToInch as Z, TileFlipMode as Zn, createPacker as Zr, createPresentationLayoutVariables as Zt, derivePasswordHash as _, createBevel as _n, xsdTextCaps as _r, systemColorDesc as _t, getMediaRefs as a, convertOutput as ai, createGroupTransform2D as an, xsdEffectContainer as ar, blipFillDesc as at, compileMapping as b, createEffectDag as bn, createSourceRectangle as br, createDiagramTextProperties as bt, hasPlaceholders as c, customPropertiesDesc as ci, createBlipFill as cn, xsdMaterialType as cr, tileDesc as ct, replaceHyperlinkPlaceholders as d, createOverride as di, createCustomGeometry as dn, xsdPenAlignment as dr, presetColorDesc as dt, strFromU8$1 as ei, createPictureLocking as en, TileAlignment as er, parseUniversalMeasure as et, replaceImagePlaceholders as f, Media as fi, stringifyPresetGeometry as fn, xsdPresetShadow as fr, rgbColorDesc as ft, replaceVideoPlaceholders as g, BevelPresetType as gn, xsdTextAnchor as gr, stringifyColorChoice as gt, replaceSmartArtPlaceholders as h, optionalRelsPart as hi, createShape3D as hn, xsdTextAlign as hr, solidFillDesc as ht, formatId as i, OoxmlMimeType as ii, parseTableStyleList as in, xsdCompoundLine as ir, blipDesc as it, presetGeometryDesc as j, BlendMode as jn, createSystemColor as jr, createTextEffectColorList as jt, transform2DDesc as k, createInnerShadowEffect as kn, createSolidFill as kr, createLineColorList as kt, replaceAllPlaceholders as l, appPropertiesDesc as li, createBlip as ln, xsdPathFillMode as lr, hslColorDesc as lt, replaceNumberingPlaceholders as m, TargetModeType as mi, PresetMaterialType as mn, xsdStrikeStyle as mr, schemeColorDesc as mt, collectPlaceholderKeys as n, zipAndConvert as ni, createTableStyle as nn, invertMap as nr, gradientFillDesc as nt, getReferencedMedia as o, decodeBase64 as oi, createTransform2D as on, xsdLineCap as or, sourceRectangleDesc as ot, replaceMediaPlaceholders as p, Relationships as pi, stringifyAdjustmentValues as pn, xsdRectAlignment as pr, scRgbColorDesc as pt, convertToInch as q, extractBlipFillMedia as qn, ParsedArchive as qr, createHierBranch as qt, findAndReplaceImagePlaceholders as r, zipSyncAndConvert as ri, createTableStyleList as rn, xsdBlendMode as rr, patternFillDesc as rt, getVideoRefs as s, encodeBase64 as si, stringifyStretch as sn, xsdLineEndSize as sr, stretchDesc as st, addSmartArtRelationships as t, unzipSync$1 as ti, createShapeLocking as tn, createTileInfo as tr, fillDesc as tt, replaceChartPlaceholders as u, createDefault as ui, createExtentionList as un, xsdPattern as ur, parseColorChoice as ut, hashPasswordAgile as v, createBottomBevel as vn, xsdUnderlineStyle as vr, createDiagramExtensionList as vt, presentationLayoutVariablesDesc as w, createReflectionEffect as wn, uniqueNumericIdCreator as wr, HueDirection as wt, diagramExtensionListDesc as x, calculateEffectExtent as xn, createBlipEffects as xr, createDiagramRelationshipIds as xt, randomBytes as y, createScene3D as yn, xsdVerticalMergeRev as yr, createDiagramShape3D as yt, convertEmuToPixels as z, LineEndLength as zn, createColorTransforms as zr, createStyleDefinitionHeaderList as zt };
5030
+ export { createLayoutDefinitionHeader as $, PenAlignment as $t, scRgbColorDesc as A, createPresetColor as An, stringifyAdjustmentValues as At, FontCollectionIndex as B, createSoftEdgeEffect as Bt, sourceRectangleDesc as C, SystemColor as Cn, createTransform2D as Ct, parseColorChoice as D, createScRgbColor as Dn, createExtensionList as Dt, hslColorDesc as E, createSchemeColor as En, createBlip as Et, createDiagramExtensionList as F, createBottomBevel as Ft, createFillColorList as G, createOuterShadowEffect as Gt, StyleMatrixIndex as H, PresetShadowVal as Ht, createDiagramShape3D as I, createScene3D as It, createTextEffectColorList as J, BlendMode as Jt, createLineColorList as K, createInnerShadowEffect as Kt, createDiagramTextProperties as L, createEffectDag as Lt, solidFillDesc as M, createColorTransforms as Mn, createShape3D as Mt, stringifyColorChoice as N, BevelPresetType as Nt, presetColorDesc as O, createRgbColor as On, createCustomGeometry as Ot, systemColorDesc as P, createBevel as Pt, createColorsDefinitionHeaderList as Q, LineJoin as Qt, createDiagramRelationshipIds as R, calculateEffectExtent as Rt, blipFillDesc as S, createSolidFill as Sn, createGroupTransform2D as St, tileDesc as T, SchemeColor as Tn, createBlipFill as Tt, createDiagramStyle as U, createPresetShadowEffect as Ut, HueDirection as V, createReflectionEffect as Vt, createEffectColorList as W, RectAlignment as Wt, createTextLineColorList as X, CompoundLine as Xt, createTextFillColorList as Y, createFillOverlayEffect as Yt, createColorsDefinitionHeader as Z, LineCap as Zt, outlineDesc as _, TileAlignment as _n, createPictureLocking as _t, bevelDesc as a, createLineEnd as an, HierBranchStyle as at, patternFillDesc as b, createBlipEffects as bn, createTableStyleList as bt, groupTransform2DDesc as c, createNoFill as cn, createAnimateOneByOne as ct, presetGeometryDesc as d, PresetPattern as dn, createMaxChildren as dt, PresetDash as en, createLayoutDefinitionHeaderList as et, graphicFrameLockingDesc as f, createPatternFill as fn, createOrgChart as ft, effectListDesc as g, createGradientStop as gn, createGroupLocking as gt, shapeLockingDesc as h, createGradientFill as hn, createGraphicFrameLocking as ht, presentationLayoutVariablesDesc as i, LineEndWidth as in, AnimationLevelValue as it, schemeColorDesc as j, createHslColor as jn, PresetMaterialType as jt, rgbColorDesc as k, PresetColor as kn, stringifyPresetGeometry as kt, transform2DDesc as l, buildFill as ln, createAnimationLevel as lt, pictureLockingDesc as m, TileFlipMode as mn, createPresentationLayoutVariables as mt, diagramRelationshipIdsDesc as n, LineEndLength as nn, createStyleDefinitionHeaderList as nt, scene3DDesc as o, createCustomDash as on, createAdjust as ot, groupLockingDesc as p, PathShadeType as pn, createPreferredChildren as pt, createStyleLabel as q, createGlowEffect as qt, diagramStyleDesc as r, LineEndType as rn, AnimateOneByOneValue as rt, shape3DDesc as s, createGroupFill as sn, createAdjustList as st, diagramExtensionListDesc as t, createOutline as tn, createStyleDefinitionHeader as tt, customGeometryDesc as u, extractBlipFillMedia as un, createHierBranch as ut, fillDesc as v, createTileInfo as vn, createShapeLocking as vt, stretchDesc as w, createSystemColor as wn, stringifyStretch as wt, blipDesc as x, createColorElement as xn, parseTableStyleList as xt, gradientFillDesc as y, createSourceRectangle as yn, createTableStyle as yt, ColorMethod as z, createEffectList as zt };
5031
+
5032
+ //# sourceMappingURL=drawingml-sj1J3lb0.mjs.map