@office-open/core 0.5.0 → 0.5.2

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.
@@ -0,0 +1,72 @@
1
+ import hash from "hash.js";
2
+ import { customAlphabet, nanoid } from "nanoid/non-secure";
3
+ //#region src/converters.ts
4
+ /**
5
+ * OOXML unit conversion utilities.
6
+ *
7
+ * @module
8
+ */
9
+ /**
10
+ * Converts millimeters to TWIP (twentieths of a point).
11
+ */
12
+ const convertMillimetersToTwip = (millimeters) => Math.floor(millimeters / 25.4 * 72 * 20);
13
+ /**
14
+ * Converts inches to TWIP (twentieths of a point).
15
+ */
16
+ const convertInchesToTwip = (inches) => Math.floor(inches * 72 * 20);
17
+ /**
18
+ * Converts pixels to EMU (96 DPI).
19
+ */
20
+ const convertPixelsToEmu = (pixels) => Math.round(pixels * 9525);
21
+ /**
22
+ * Converts EMU to pixels (96 DPI).
23
+ */
24
+ const convertEmuToPixels = (emus) => Math.round(emus / 9525);
25
+ /**
26
+ * Converts inches to EMU.
27
+ */
28
+ const convertInchesToEmu = (inches) => Math.round(inches * 914400);
29
+ /**
30
+ * Converts EMU to inches.
31
+ */
32
+ const convertEmuToInches = (emus) => emus / 914400;
33
+ /**
34
+ * Converts points to EMU.
35
+ */
36
+ const convertPointsToEmu = (points) => Math.round(points * 12700);
37
+ /**
38
+ * Converts EMU to points.
39
+ */
40
+ const convertEmuToPoints = (emus) => emus / 12700;
41
+ //#endregion
42
+ //#region src/id-generators.ts
43
+ /**
44
+ * Unique ID generation utilities.
45
+ *
46
+ * @module
47
+ */
48
+ /**
49
+ * Creates a unique numeric ID generator with sequential numbering.
50
+ */
51
+ const uniqueNumericIdCreator = (initial = 0) => {
52
+ let currentCount = initial;
53
+ return () => ++currentCount;
54
+ };
55
+ /**
56
+ * Generates a unique lowercase alphanumeric ID using nanoid.
57
+ */
58
+ const uniqueId = () => nanoid().toLowerCase();
59
+ /**
60
+ * Generates a SHA-1 hash of the provided data.
61
+ */
62
+ const hashedId = (data) => hash.sha1().update(data instanceof ArrayBuffer ? new Uint8Array(data) : data).digest("hex");
63
+ /**
64
+ * Generates a random hexadecimal string of specified length.
65
+ */
66
+ const generateUuidPart = (count) => customAlphabet("1234567890abcdef", count)();
67
+ /**
68
+ * Generates a UUID v4-style unique identifier.
69
+ */
70
+ const uniqueUuid = () => `${generateUuidPart(8)}-${generateUuidPart(4)}-${generateUuidPart(4)}-${generateUuidPart(4)}-${generateUuidPart(12)}`;
71
+ //#endregion
72
+ export { convertEmuToInches as a, convertInchesToEmu as c, convertPixelsToEmu as d, convertPointsToEmu as f, uniqueUuid as i, convertInchesToTwip as l, uniqueId as n, convertEmuToPixels as o, uniqueNumericIdCreator as r, convertEmuToPoints as s, hashedId as t, convertMillimetersToTwip as u };
package/dist/index.d.mts CHANGED
@@ -223,8 +223,8 @@ declare class ParsedDocument {
223
223
  /** Serialize back to a ZIP buffer, merging original zip + modifications. */
224
224
  save(): Uint8Array;
225
225
  }
226
- /** Parse an OOXML file (.docx, .pptx) into a ParsedDocument. */
227
- declare function parseDocument(data: Uint8Array): ParsedDocument;
226
+ /** Parse an OOXML archive (.docx, .pptx, .xlsx) into a ParsedDocument. */
227
+ declare function parseArchive(data: Uint8Array): ParsedDocument;
228
228
  //#endregion
229
229
  //#region src/raw-passthrough.d.ts
230
230
  /**
@@ -271,4 +271,4 @@ interface SmartArtRelOptions {
271
271
  declare function replaceSmartArtPlaceholders(xml: string, keys: readonly string[], dataOffset: number, idFormat?: IdFormat): string;
272
272
  declare function addSmartArtRelationships(keys: readonly string[], addRel: (id: number, type: RelationshipType, target: string, targetMode?: string) => void, baseOffset: number, globalStartIndex: number, options: SmartArtRelOptions): void;
273
273
  //#endregion
274
- export { AppProperties, AttributeData, AttributeMap, AttributePayload, BaseXmlComponent, BuilderElement, COLOR_CATEGORIES, Connection, ContentTypeAttributes, CoreProperties, DEFAULT_DRAWING_XML, DataModel, type DefaultAttributes, EMPTY_OBJECT, EmptyElement, Formatter, HpsMeasureElement, IContext, ISmartArtData, ITreeNode, IXmlAttribute, IXmlableObject, IXmlifyedFile, IdFormat, IgnoreIfEmptyXmlComponent, ImportedRootElementAttributes, ImportedXmlComponent, InitializableXmlComponent, LAYOUT_CATEGORIES, NextAttributeComponent, NumberValueElement, OnOffElement, OoxmlMimeType, OutputByType, OutputType, type OverrideAttributes, ParsedDocument, Percentage, Point, PositivePercentage, PositiveUniversalMeasure, PrettifyType, RawPassthrough, Relationship, type RelationshipType, Relationships, RelativeMeasure, STYLE_CATEGORIES, SmartArtCollection, SmartArtRelOptions, StringContainer, StringEnumValueElement, StringValueElement, TargetModeType, ThemeColor, ThemeFont, TransPoint, UniqueNumericIdCreator, UniversalMeasure, XmlAttributeComponent, XmlComponent, addSmartArtRelationships, buildCorePropertiesXml, chartAttr, collectPlaceholderKeys, convertEmuToInches, convertEmuToPixels, convertEmuToPoints, convertInchesToEmu, convertInchesToTwip, convertMillimetersToTwip, convertOutput, convertPixelsToEmu, convertPointsToEmu, convertPrettifyType, convertToXmlComponent, createDataModel, createDefault, createOverride, dateTimeValue, decimalNumber, eighthPointMeasureValue, elementToCompact, elementToXml, escapeRegex, findRel, findRelsByType, formatId, getColorXml, getImageType, getLayoutXml, getReferencedMedia, getStyleXml, hasPlaceholders, hashedId, hexBinary, hexColorValue, hpsMeasureObj, hpsMeasureValue, listFiles, longHexNumber, measurementOrPercentValue, numberValObj, onOffObj, parseCoreProperties, parseDocument, parseRels, percentageValue, pointMeasureValue, positiveUniversalMeasureValue, readAllXmlParts, readBinaryFromZip, readTextFromZip, readXmlFromZip, replaceChartPlaceholders, replaceImagePlaceholders, replaceSmartArtPlaceholders, shortHexNumber, signedHpsMeasureValue, signedTwipsMeasureValue, stringContainerObj, stringEnumValObj, stringValObj, twipsMeasureValue, uCharHexNumber, uint8ToBase64, uniqueId, uniqueNumericIdCreator, uniqueUuid, universalMeasureValue, unsignedDecimalNumber, unzipToMap, wrapEl, zipToBuffer };
274
+ export { AppProperties, AttributeData, AttributeMap, AttributePayload, BaseXmlComponent, BuilderElement, COLOR_CATEGORIES, Connection, ContentTypeAttributes, CoreProperties, DEFAULT_DRAWING_XML, DataModel, type DefaultAttributes, EMPTY_OBJECT, EmptyElement, Formatter, HpsMeasureElement, IContext, ISmartArtData, ITreeNode, IXmlAttribute, IXmlableObject, IXmlifyedFile, IdFormat, IgnoreIfEmptyXmlComponent, ImportedRootElementAttributes, ImportedXmlComponent, InitializableXmlComponent, LAYOUT_CATEGORIES, NextAttributeComponent, NumberValueElement, OnOffElement, OoxmlMimeType, OutputByType, OutputType, type OverrideAttributes, ParsedDocument, Percentage, Point, PositivePercentage, PositiveUniversalMeasure, PrettifyType, RawPassthrough, Relationship, type RelationshipType, Relationships, RelativeMeasure, STYLE_CATEGORIES, SmartArtCollection, SmartArtRelOptions, StringContainer, StringEnumValueElement, StringValueElement, TargetModeType, ThemeColor, ThemeFont, TransPoint, UniqueNumericIdCreator, UniversalMeasure, XmlAttributeComponent, XmlComponent, addSmartArtRelationships, buildCorePropertiesXml, chartAttr, collectPlaceholderKeys, convertEmuToInches, convertEmuToPixels, convertEmuToPoints, convertInchesToEmu, convertInchesToTwip, convertMillimetersToTwip, convertOutput, convertPixelsToEmu, convertPointsToEmu, convertPrettifyType, convertToXmlComponent, createDataModel, createDefault, createOverride, dateTimeValue, decimalNumber, eighthPointMeasureValue, elementToCompact, elementToXml, escapeRegex, findRel, findRelsByType, formatId, getColorXml, getImageType, getLayoutXml, getReferencedMedia, getStyleXml, hasPlaceholders, hashedId, hexBinary, hexColorValue, hpsMeasureObj, hpsMeasureValue, listFiles, longHexNumber, measurementOrPercentValue, numberValObj, onOffObj, parseArchive, parseCoreProperties, parseRels, percentageValue, pointMeasureValue, positiveUniversalMeasureValue, readAllXmlParts, readBinaryFromZip, readTextFromZip, readXmlFromZip, replaceChartPlaceholders, replaceImagePlaceholders, replaceSmartArtPlaceholders, shortHexNumber, signedHpsMeasureValue, signedTwipsMeasureValue, stringContainerObj, stringEnumValObj, stringValObj, twipsMeasureValue, uCharHexNumber, uint8ToBase64, uniqueId, uniqueNumericIdCreator, uniqueUuid, universalMeasureValue, unsignedDecimalNumber, unzipToMap, wrapEl, zipToBuffer };
package/dist/index.mjs CHANGED
@@ -1 +1,424 @@
1
- import{C as e,E as t,S as n,T as r,_ as i,a,b as o,c as s,d as c,f as l,g as u,h as d,i as ee,l as te,m as ne,n as re,o as ie,p as ae,r as f,s as oe,t as se,u as ce,v as le,w as ue,x as de,y as fe}from"./xml-components-Csq7gWPd.mjs";import{ThemeColor as pe,ThemeFont as me,dateTimeValue as he,decimalNumber as p,eighthPointMeasureValue as m,hexBinary as h,hexColorValue as g,hpsMeasureValue as _,longHexNumber as v,measurementOrPercentValue as y,percentageValue as b,pointMeasureValue as x,positiveUniversalMeasureValue as S,shortHexNumber as C,signedHpsMeasureValue as w,signedTwipsMeasureValue as T,twipsMeasureValue as E,uCharHexNumber as D,universalMeasureValue as O,unsignedDecimalNumber as k}from"./values.mjs";import{a as A,c as j,d as M,f as N,i as P,l as F,n as I,o as L,r as R,s as ge,t as _e,u as ve}from"./id-generators-Dd0w7vti.mjs";import{a as ye,c as be,d as xe,f as Se,i as Ce,l as we,n as Te,o as Ee,p as De,r as Oe,s as ke,t as Ae,u as z}from"./smartart-C-ZIRmWU.mjs";import{elementToXml as je,findRel as Me,findRelsByType as Ne,getImageType as Pe,listFiles as Fe,parseRels as Ie,readAllXmlParts as Le,readBinaryFromZip as Re,readTextFromZip as ze,readXmlFromZip as B,uint8ToBase64 as Be,unzipToMap as V,zipToBuffer as H}from"./archive.mjs";import{js2xml as Ve,textOf as U,xml2js as W}from"@office-open/xml";import{strFromU8 as G,strToU8 as He}from"fflate";const K={DOCX:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,PPTX:`application/vnd.openxmlformats-officedocument.presentationml.presentation`},Ue=(e,t,n=K.DOCX)=>{switch(t){case`nodebuffer`:return Buffer.from(e);case`blob`:return new Blob([e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)],{type:n});case`arraybuffer`:return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);case`uint8array`:return e;case`base64`:return btoa(G(e,!0));case`string`:case`text`:case`binarystring`:return G(e,!0);case`array`:return[...e];default:return e}},q={NONE:``,WITH_2_BLANKS:` `,WITH_4_BLANKS:` `,WITH_TAB:` `},We=e=>e===!0?q.WITH_2_BLANKS:e===!1?void 0:e;var Ge=class e extends f{static instance=f.fromXmlString(`<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"/>`);constructor(){super(`Properties`)}prepForXml(){return e.instance.prepForXml({stack:[]})}};const Ke={EXTERNAL:`External`},qe={_attr:{xmlns:`http://schemas.openxmlformats.org/package/2006/relationships`}};var Je=class extends t{entries=[];constructor(){super(`Relationships`)}addRelationship(e,t,n,r){this.entries.push({id:`rId${e}`,type:t,target:n,targetMode:r})}get RelationshipCount(){return this.entries.length}prepForXml(e){let t=[qe];for(let e of this.entries){let n={Id:e.id,Type:e.type,Target:e.target};e.targetMode&&(n.TargetMode=e.targetMode),t.push({Relationship:{_attr:n}})}return t.length===1&&`_attr`in t[0]?{Relationships:t[0]}:{Relationships:t}}};const Ye=(e,t)=>new a({attributes:{contentType:{key:`ContentType`,value:e},extension:{key:`Extension`,value:t}},name:`Default`}),Xe=(e,t)=>new a({attributes:{contentType:{key:`ContentType`,value:e},partName:{key:`PartName`,value:t}},name:`Override`});var Ze=class extends n{xmlKeys={xmlns:`xmlns`}},Qe=class{format(e,t={stack:[]}){let n=e.prepForXml(t);if(n)return n;throw Error(`XMLComponent did not format correctly`)}formatToXml(e,t,n){let r=e.toXml(t);return n?`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`+r:r}};const $e=[{name:`dc:title`,key:`title`},{name:`dc:subject`,key:`subject`},{name:`dc:creator`,key:`creator`},{name:`dc:description`,key:`description`},{name:`cp:keywords`,key:`keywords`},{name:`cp:lastModifiedBy`,key:`lastModifiedBy`}];function et(e){let t=B(e,`docProps/core.xml`);if(!t)return{};let n={};for(let e of $e){let r=t.elements?.find(t=>t.name===e.name),i=U(r)||void 0;i&&(n[e.key]=i)}let r=t.elements?.find(e=>e.name===`cp:revision`);if(r){let e=U(r);if(e){let t=Number(e);isNaN(t)||(n.revision=e)}}return n}const tt=Object.freeze({_attr:Object.freeze({"xmlns:cp":`http://schemas.openxmlformats.org/package/2006/metadata/core-properties`,"xmlns:dc":`http://purl.org/dc/elements/1.1/`,"xmlns:dcmitype":`http://purl.org/dc/dcmitype/`,"xmlns:dcterms":`http://purl.org/dc/terms/`,"xmlns:xsi":`http://www.w3.org/2001/XMLSchema-instance`})}),J=Object.freeze({_attr:Object.freeze({"xsi:type":`dcterms:W3CDTF`})});function nt(e){let t=[tt];e.title&&t.push({"dc:title":[e.title]}),e.subject&&t.push({"dc:subject":[e.subject]}),e.creator&&t.push({"dc:creator":[e.creator]}),e.keywords&&t.push({"cp:keywords":[e.keywords]}),e.description&&t.push({"dc:description":[e.description]}),e.lastModifiedBy&&t.push({"cp:lastModifiedBy":[e.lastModifiedBy]}),e.revision&&t.push({"cp:revision":[String(e.revision)]});let n=new Date().toISOString();return t.push({"dcterms:created":[J,n]}),t.push({"dcterms:modified":[J,n]}),{"cp:coreProperties":t}}const Y={nativeTypeAttributes:!0,captureSpacesBetweenElements:!0};var X=class{zip;modified=new Map;wrapperCache=new Map;constructor(e){this.zip=e}get(e){let t=this.modified.get(e);if(t){let n=W(G(t),Y);return this.wrapperCache.set(e,n),n.elements?.find(e=>e.type===`element`)}let n=this.zip.get(e);if(n===void 0)return;let r=this.wrapperCache.get(e);if(r)return r.elements?.find(e=>e.type===`element`);let i=W(G(n),Y);return this.wrapperCache.set(e,i),i.elements?.find(e=>e.type===`element`)}set(e,t){let n=this.wrapperCache.get(e),r=Ve(n?{...n,elements:[{...t,type:`element`}]}:{elements:[{...t,type:`element`}]});this.modified.set(e,He(r))}getRaw(e){return this.modified.get(e)??this.zip.get(e)}setRaw(e,t){this.modified.set(e,t),this.wrapperCache.delete(e)}remove(e){return this.wrapperCache.delete(e),this.modified.delete(e)||this.zip.delete(e)}has(e){return this.modified.has(e)||this.zip.has(e)}keys(e){let t=new Set;for(let n of this.zip.keys())(!e||n.startsWith(e))&&t.add(n);for(let n of this.modified.keys())(!e||n.startsWith(e))&&t.add(n);return[...t]}save(){let e=new Map;for(let[t,n]of this.zip)this.modified.has(t)||e.set(t,n);for(let[t,n]of this.modified)e.set(t,n);return H(e)}};function rt(e){return new X(V(e))}function Z(e){let t={};if(e.attributes&&Object.keys(e.attributes).length>0&&(t._attributes=e.attributes),e.cdata?t._cdata=e.cdata:e.text!=null&&(t._text=e.text),e.elements)for(let n of e.elements){let e=n.name??`_unknown`,r=Z(n);t[e]?(Array.isArray(t[e])||(t[e]=[t[e]]),t[e].push(r)):t[e]=r}let n=e.name??`unknown`;return Object.keys(t).length===0?{[n]:{}}:{[n]:t}}var it=class extends t{constructor(e){super(e.name??`unknown`),this.element=e}prepForXml(e){return Z(this.element)}};const Q=(e,t,n)=>n===`rId`?`rId${e+t}`:`${e+t}`;function $(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function at(e){return e.includes(`{`)}function ot(e,t){let n=[],r=`{${t}`,i=0;for(;(i=e.indexOf(r,i))!==-1;){let t=i+r.length,a=e.indexOf(`}`,t);if(a===-1)break;let o=e.substring(t,a);o.length>0&&!n.includes(o)&&n.push(o),i=a+1}return n}function st(e,t,n,r=`rId`){let i=e;return t.forEach((e,t)=>{i=i.replace(RegExp(`\\{${$(e.fileName)}\\}`,`g`),Q(n,t,r))}),i}function ct(e,t){return t.filter(t=>e.includes(`{${t.fileName}}`))}function lt(e,t,n,r=`rId`){let i=e;return t.forEach((e,t)=>{i=i.replace(RegExp(`\\{chart:${$(e)}\\}`,`g`),Q(n,t,r))}),i}function ut(e,t,n,r=`rId`){let i=e,a=t.length,o=n+a,s=o+a,c=s+a;return t.forEach((e,t)=>{i=i.replace(RegExp(`\\{smartart:${$(e)}\\}`,`g`),Q(n,t,r)),i=i.replace(RegExp(`\\{smartart-lo:${$(e)}\\}`,`g`),Q(o,t,r)),i=i.replace(RegExp(`\\{smartart-qs:${$(e)}\\}`,`g`),Q(s,t,r)),i=i.replace(RegExp(`\\{smartart-cs:${$(e)}\\}`,`g`),Q(c,t,r))}),i}function dt(e,t,n,r,i){let{pathPrefix:a,styleRelType:o}=i,s=e.length,c=n+s,l=c+s,u=l+s;e.forEach((e,i)=>{let d=r+i;t(n+i,`http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramData`,`${a}diagrams/data${d+1}.xml`),t(c+i,`http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramLayout`,`${a}diagrams/layout${d+1}.xml`),t(l+i,o,`${a}diagrams/quickStyle${d+1}.xml`),t(u+i,`http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramColors`,`${a}diagrams/colors${d+1}.xml`),t(u+s+i,`http://schemas.microsoft.com/office/2007/relationships/diagramDrawing`,`${a}diagrams/drawing${d+1}.xml`)})}export{Ge as AppProperties,t as BaseXmlComponent,a as BuilderElement,xe as COLOR_CATEGORIES,Ee as Connection,Ze as ContentTypeAttributes,ke as DEFAULT_DRAWING_XML,ye as DataModel,e as EMPTY_OBJECT,ie as EmptyElement,Qe as Formatter,oe as HpsMeasureElement,ue as IgnoreIfEmptyXmlComponent,re as ImportedRootElementAttributes,f as ImportedXmlComponent,se as InitializableXmlComponent,Se as LAYOUT_CATEGORIES,de as NextAttributeComponent,s as NumberValueElement,te as OnOffElement,K as OoxmlMimeType,X as ParsedDocument,Oe as Point,q as PrettifyType,it as RawPassthrough,Je as Relationships,De as STYLE_CATEGORIES,Te as SmartArtCollection,ce as StringContainer,c as StringEnumValueElement,l as StringValueElement,Ke as TargetModeType,pe as ThemeColor,me as ThemeFont,Ce as TransPoint,n as XmlAttributeComponent,r as XmlComponent,dt as addSmartArtRelationships,nt as buildCorePropertiesXml,ae as chartAttr,ot as collectPlaceholderKeys,A as convertEmuToInches,L as convertEmuToPixels,ge as convertEmuToPoints,j as convertInchesToEmu,F as convertInchesToTwip,ve as convertMillimetersToTwip,Ue as convertOutput,M as convertPixelsToEmu,N as convertPointsToEmu,We as convertPrettifyType,ee as convertToXmlComponent,Ae as createDataModel,Ye as createDefault,Xe as createOverride,he as dateTimeValue,p as decimalNumber,m as eighthPointMeasureValue,Z as elementToCompact,je as elementToXml,$ as escapeRegex,Me as findRel,Ne as findRelsByType,Q as formatId,be as getColorXml,Pe as getImageType,we as getLayoutXml,ct as getReferencedMedia,z as getStyleXml,at as hasPlaceholders,_e as hashedId,h as hexBinary,g as hexColorValue,ne as hpsMeasureObj,_ as hpsMeasureValue,Fe as listFiles,v as longHexNumber,y as measurementOrPercentValue,d as numberValObj,u as onOffObj,et as parseCoreProperties,rt as parseDocument,Ie as parseRels,b as percentageValue,x as pointMeasureValue,S as positiveUniversalMeasureValue,Le as readAllXmlParts,Re as readBinaryFromZip,ze as readTextFromZip,B as readXmlFromZip,lt as replaceChartPlaceholders,st as replaceImagePlaceholders,ut as replaceSmartArtPlaceholders,C as shortHexNumber,w as signedHpsMeasureValue,T as signedTwipsMeasureValue,i as stringContainerObj,le as stringEnumValObj,fe as stringValObj,E as twipsMeasureValue,D as uCharHexNumber,Be as uint8ToBase64,I as uniqueId,R as uniqueNumericIdCreator,P as uniqueUuid,O as universalMeasureValue,k as unsignedDecimalNumber,V as unzipToMap,o as wrapEl,H as zipToBuffer};
1
+ import { C as EMPTY_OBJECT, E as BaseXmlComponent, S as XmlAttributeComponent, T as XmlComponent, _ as stringContainerObj, a as BuilderElement, b as wrapEl, c as NumberValueElement, d as StringEnumValueElement, f as StringValueElement, g as onOffObj, h as numberValObj, i as convertToXmlComponent, l as OnOffElement, m as hpsMeasureObj, n as ImportedRootElementAttributes, o as EmptyElement, p as chartAttr, r as ImportedXmlComponent, s as HpsMeasureElement, t as InitializableXmlComponent, u as StringContainer, v as stringEnumValObj, w as IgnoreIfEmptyXmlComponent, x as NextAttributeComponent, y as stringValObj } from "./xml-components-CJKrtCSG.mjs";
2
+ import { ThemeColor, ThemeFont, dateTimeValue, decimalNumber, eighthPointMeasureValue, hexBinary, hexColorValue, hpsMeasureValue, longHexNumber, measurementOrPercentValue, percentageValue, pointMeasureValue, positiveUniversalMeasureValue, shortHexNumber, signedHpsMeasureValue, signedTwipsMeasureValue, twipsMeasureValue, uCharHexNumber, universalMeasureValue, unsignedDecimalNumber } from "./values.mjs";
3
+ import { a as convertEmuToInches, c as convertInchesToEmu, d as convertPixelsToEmu, f as convertPointsToEmu, i as uniqueUuid, l as convertInchesToTwip, n as uniqueId, o as convertEmuToPixels, r as uniqueNumericIdCreator, s as convertEmuToPoints, t as hashedId, u as convertMillimetersToTwip } from "./id-generators-CM3u923a.mjs";
4
+ import { a as DataModel, c as getColorXml, d as COLOR_CATEGORIES, f as LAYOUT_CATEGORIES, i as TransPoint, l as getLayoutXml, n as SmartArtCollection, o as Connection, p as STYLE_CATEGORIES, r as Point, s as DEFAULT_DRAWING_XML, t as createDataModel, u as getStyleXml } from "./smartart-CdBk8E0n.mjs";
5
+ import { elementToXml, findRel, findRelsByType, getImageType, listFiles, parseRels, readAllXmlParts, readBinaryFromZip, readTextFromZip, readXmlFromZip, uint8ToBase64, unzipToMap, zipToBuffer } from "./archive.mjs";
6
+ import { js2xml, textOf, xml2js } from "@office-open/xml";
7
+ import { strFromU8, strToU8 } from "fflate";
8
+ //#region src/output-type.ts
9
+ /**
10
+ * Output type definitions for OOXML document export.
11
+ *
12
+ * @module
13
+ */
14
+ const OoxmlMimeType = {
15
+ DOCX: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
16
+ PPTX: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
17
+ };
18
+ const convertOutput = (data, type, mimeType = OoxmlMimeType.DOCX) => {
19
+ switch (type) {
20
+ case "nodebuffer": return Buffer.from(data);
21
+ case "blob": return new Blob([data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)], { type: mimeType });
22
+ case "arraybuffer": return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
23
+ case "uint8array": return data;
24
+ case "base64": return btoa(strFromU8(data, true));
25
+ case "string":
26
+ case "text":
27
+ case "binarystring": return strFromU8(data, true);
28
+ case "array": return [...data];
29
+ default: return data;
30
+ }
31
+ };
32
+ //#endregion
33
+ //#region src/packer.ts
34
+ const PrettifyType = {
35
+ NONE: "",
36
+ WITH_2_BLANKS: " ",
37
+ WITH_4_BLANKS: " ",
38
+ WITH_TAB: " "
39
+ };
40
+ const convertPrettifyType = (prettify) => prettify === true ? PrettifyType.WITH_2_BLANKS : prettify === false ? void 0 : prettify;
41
+ //#endregion
42
+ //#region src/opc/app-properties.ts
43
+ const APP_PROPS_XML = "<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\" xmlns:vt=\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\"/>";
44
+ var AppProperties = class AppProperties extends ImportedXmlComponent {
45
+ static instance = ImportedXmlComponent.fromXmlString(APP_PROPS_XML);
46
+ constructor() {
47
+ super("Properties");
48
+ }
49
+ prepForXml() {
50
+ return AppProperties.instance.prepForXml({ stack: [] });
51
+ }
52
+ };
53
+ //#endregion
54
+ //#region src/opc/relationships.ts
55
+ const TargetModeType = { EXTERNAL: "External" };
56
+ const RELS_ATTRS = { _attr: { xmlns: "http://schemas.openxmlformats.org/package/2006/relationships" } };
57
+ var Relationships = class extends BaseXmlComponent {
58
+ entries = [];
59
+ constructor() {
60
+ super("Relationships");
61
+ }
62
+ addRelationship(id, type, target, targetMode) {
63
+ this.entries.push({
64
+ id: `rId${id}`,
65
+ type,
66
+ target,
67
+ targetMode
68
+ });
69
+ }
70
+ get RelationshipCount() {
71
+ return this.entries.length;
72
+ }
73
+ prepForXml(_context) {
74
+ const children = [RELS_ATTRS];
75
+ for (const e of this.entries) {
76
+ const attrs = {
77
+ Id: e.id,
78
+ Type: e.type,
79
+ Target: e.target
80
+ };
81
+ if (e.targetMode) attrs.TargetMode = e.targetMode;
82
+ children.push({ Relationship: { _attr: attrs } });
83
+ }
84
+ if (children.length === 1 && "_attr" in children[0]) return { Relationships: children[0] };
85
+ return { Relationships: children };
86
+ }
87
+ };
88
+ //#endregion
89
+ //#region src/opc/content-types.ts
90
+ /**
91
+ * Content Types components for OPC (Open Packaging Convention).
92
+ *
93
+ * Provides Default and Override elements used in [Content_Types].xml
94
+ * to map file extensions and part paths to MIME content types.
95
+ *
96
+ * Reference: ECMA-376 Part 2, Section 10.1
97
+ *
98
+ * @module
99
+ */
100
+ /**
101
+ * Creates a Default element mapping a file extension to a MIME content type.
102
+ */
103
+ const createDefault = (contentType, extension) => new BuilderElement({
104
+ attributes: {
105
+ contentType: {
106
+ key: "ContentType",
107
+ value: contentType
108
+ },
109
+ extension: {
110
+ key: "Extension",
111
+ value: extension
112
+ }
113
+ },
114
+ name: "Default"
115
+ });
116
+ /**
117
+ * Creates an Override element mapping a specific part path to a MIME content type.
118
+ */
119
+ const createOverride = (contentType, partName) => new BuilderElement({
120
+ attributes: {
121
+ contentType: {
122
+ key: "ContentType",
123
+ value: contentType
124
+ },
125
+ partName: {
126
+ key: "PartName",
127
+ value: partName
128
+ }
129
+ },
130
+ name: "Override"
131
+ });
132
+ /**
133
+ * Attributes for the Types (Content Types) root element.
134
+ * Declares the XML namespace for the content types part.
135
+ */
136
+ var ContentTypeAttributes = class extends XmlAttributeComponent {
137
+ xmlKeys = { xmlns: "xmlns" };
138
+ };
139
+ //#endregion
140
+ //#region src/formatter.ts
141
+ const XML_DECL = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
142
+ /**
143
+ * Converts an XmlComponent tree into a serializable XML object.
144
+ */
145
+ var Formatter = class {
146
+ format(input, context = { stack: [] }) {
147
+ const output = input.prepForXml(context);
148
+ if (output) return output;
149
+ throw new Error("XMLComponent did not format correctly");
150
+ }
151
+ formatToXml(input, context, declaration) {
152
+ const str = input.toXml(context);
153
+ return declaration ? XML_DECL + str : str;
154
+ }
155
+ };
156
+ //#endregion
157
+ //#region src/core-properties.ts
158
+ const FIELD_MAP = [
159
+ {
160
+ name: "dc:title",
161
+ key: "title"
162
+ },
163
+ {
164
+ name: "dc:subject",
165
+ key: "subject"
166
+ },
167
+ {
168
+ name: "dc:creator",
169
+ key: "creator"
170
+ },
171
+ {
172
+ name: "dc:description",
173
+ key: "description"
174
+ },
175
+ {
176
+ name: "cp:keywords",
177
+ key: "keywords"
178
+ },
179
+ {
180
+ name: "cp:lastModifiedBy",
181
+ key: "lastModifiedBy"
182
+ }
183
+ ];
184
+ function parseCoreProperties(zip) {
185
+ const xml = readXmlFromZip(zip, "docProps/core.xml");
186
+ if (!xml) return {};
187
+ const props = {};
188
+ for (const field of FIELD_MAP) {
189
+ const el = xml.elements?.find((e) => e.name === field.name);
190
+ const value = textOf(el) || void 0;
191
+ if (value) props[field.key] = value;
192
+ }
193
+ const revEl = xml.elements?.find((e) => e.name === "cp:revision");
194
+ if (revEl) {
195
+ const rev = textOf(revEl);
196
+ if (rev) {
197
+ const n = Number(rev);
198
+ if (!isNaN(n)) props.revision = rev;
199
+ }
200
+ }
201
+ return props;
202
+ }
203
+ const CORE_PROPS_NS = Object.freeze({ _attr: Object.freeze({
204
+ "xmlns:cp": "http://schemas.openxmlformats.org/package/2006/metadata/core-properties",
205
+ "xmlns:dc": "http://purl.org/dc/elements/1.1/",
206
+ "xmlns:dcmitype": "http://purl.org/dc/dcmitype/",
207
+ "xmlns:dcterms": "http://purl.org/dc/terms/",
208
+ "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance"
209
+ }) });
210
+ const W3CDTF_ATTR = Object.freeze({ _attr: Object.freeze({ "xsi:type": "dcterms:W3CDTF" }) });
211
+ /**
212
+ * Build a cp:coreProperties XML object from metadata.
213
+ *
214
+ * Shared by docx and pptx to avoid duplicating namespace declarations
215
+ * and Dublin Core property construction.
216
+ */
217
+ function buildCorePropertiesXml(opts) {
218
+ const children = [CORE_PROPS_NS];
219
+ if (opts.title) children.push({ "dc:title": [opts.title] });
220
+ if (opts.subject) children.push({ "dc:subject": [opts.subject] });
221
+ if (opts.creator) children.push({ "dc:creator": [opts.creator] });
222
+ if (opts.keywords) children.push({ "cp:keywords": [opts.keywords] });
223
+ if (opts.description) children.push({ "dc:description": [opts.description] });
224
+ if (opts.lastModifiedBy) children.push({ "cp:lastModifiedBy": [opts.lastModifiedBy] });
225
+ if (opts.revision) children.push({ "cp:revision": [String(opts.revision)] });
226
+ const now = (/* @__PURE__ */ new Date()).toISOString();
227
+ children.push({ "dcterms:created": [W3CDTF_ATTR, now] });
228
+ children.push({ "dcterms:modified": [W3CDTF_ATTR, now] });
229
+ return { "cp:coreProperties": children };
230
+ }
231
+ //#endregion
232
+ //#region src/parser.ts
233
+ const XML_PARSE_OPTIONS = {
234
+ nativeTypeAttributes: true,
235
+ captureSpacesBetweenElements: true
236
+ };
237
+ /**
238
+ * Parsed OOXML document backed by an unzipped ZIP map.
239
+ *
240
+ * Provides unstorage-style API (get/set/getRaw/setRaw/remove/has/keys)
241
+ * for reading and modifying individual parts, then serializing back to a ZIP buffer.
242
+ */
243
+ var ParsedDocument = class {
244
+ zip;
245
+ modified = /* @__PURE__ */ new Map();
246
+ wrapperCache = /* @__PURE__ */ new Map();
247
+ constructor(zip) {
248
+ this.zip = zip;
249
+ }
250
+ /** Read an XML part as an Element tree. */
251
+ get(path) {
252
+ const modData = this.modified.get(path);
253
+ if (modData) {
254
+ const wrapper = xml2js(strFromU8(modData), XML_PARSE_OPTIONS);
255
+ this.wrapperCache.set(path, wrapper);
256
+ return wrapper.elements?.find((e) => e.type === "element");
257
+ }
258
+ const data = this.zip.get(path);
259
+ if (data === void 0) return void 0;
260
+ const cached = this.wrapperCache.get(path);
261
+ if (cached) return cached.elements?.find((e) => e.type === "element");
262
+ const wrapper = xml2js(strFromU8(data), XML_PARSE_OPTIONS);
263
+ this.wrapperCache.set(path, wrapper);
264
+ return wrapper.elements?.find((e) => e.type === "element");
265
+ }
266
+ /** Write an XML part (Element → XML string). */
267
+ set(path, element) {
268
+ const wrapper = this.wrapperCache.get(path);
269
+ const xml = js2xml(wrapper ? {
270
+ ...wrapper,
271
+ elements: [{
272
+ ...element,
273
+ type: "element"
274
+ }]
275
+ } : { elements: [{
276
+ ...element,
277
+ type: "element"
278
+ }] });
279
+ this.modified.set(path, strToU8(xml));
280
+ }
281
+ /** Read raw binary data (images, media, etc.). */
282
+ getRaw(path) {
283
+ return this.modified.get(path) ?? this.zip.get(path);
284
+ }
285
+ /** Write raw binary data. */
286
+ setRaw(path, data) {
287
+ this.modified.set(path, data);
288
+ this.wrapperCache.delete(path);
289
+ }
290
+ /** Remove a part. Returns true if it existed. */
291
+ remove(path) {
292
+ this.wrapperCache.delete(path);
293
+ return this.modified.delete(path) || this.zip.delete(path);
294
+ }
295
+ /** Check if a part exists. */
296
+ has(path) {
297
+ return this.modified.has(path) || this.zip.has(path);
298
+ }
299
+ /** List all paths matching an optional prefix. */
300
+ keys(prefix) {
301
+ const all = /* @__PURE__ */ new Set();
302
+ for (const key of this.zip.keys()) if (!prefix || key.startsWith(prefix)) all.add(key);
303
+ for (const key of this.modified.keys()) if (!prefix || key.startsWith(prefix)) all.add(key);
304
+ return [...all];
305
+ }
306
+ /** Serialize back to a ZIP buffer, merging original zip + modifications. */
307
+ save() {
308
+ const files = /* @__PURE__ */ new Map();
309
+ for (const [path, data] of this.zip) if (!this.modified.has(path)) files.set(path, data);
310
+ for (const [path, data] of this.modified) files.set(path, data);
311
+ return zipToBuffer(files);
312
+ }
313
+ };
314
+ /** Parse an OOXML archive (.docx, .pptx, .xlsx) into a ParsedDocument. */
315
+ function parseArchive(data) {
316
+ return new ParsedDocument(unzipToMap(data));
317
+ }
318
+ //#endregion
319
+ //#region src/raw-passthrough.ts
320
+ /**
321
+ * Convert an Element tree to xml-js compact format (IXmlableObject).
322
+ * Always wraps in a named key so the element name is preserved even for empty elements.
323
+ */
324
+ function elementToCompact(el) {
325
+ const inner = {};
326
+ if (el.attributes && Object.keys(el.attributes).length > 0) inner._attributes = el.attributes;
327
+ if (el.cdata) inner._cdata = el.cdata;
328
+ else if (el.text != null) inner._text = el.text;
329
+ if (el.elements) for (const child of el.elements) {
330
+ const key = child.name ?? "_unknown";
331
+ const compactChild = elementToCompact(child);
332
+ if (inner[key]) {
333
+ if (!Array.isArray(inner[key])) inner[key] = [inner[key]];
334
+ inner[key].push(compactChild);
335
+ } else inner[key] = compactChild;
336
+ }
337
+ const name = el.name ?? "unknown";
338
+ if (Object.keys(inner).length === 0) return { [name]: {} };
339
+ return { [name]: inner };
340
+ }
341
+ /**
342
+ * Thin wrapper that passes a raw Element tree through the XML serialization pipeline.
343
+ * Used to include parsed-but-unrecognized XML in generated documents.
344
+ */
345
+ var RawPassthrough = class extends BaseXmlComponent {
346
+ constructor(element) {
347
+ super(element.name ?? "unknown");
348
+ this.element = element;
349
+ }
350
+ prepForXml(_context) {
351
+ return elementToCompact(this.element);
352
+ }
353
+ };
354
+ //#endregion
355
+ //#region src/placeholder.ts
356
+ const formatId = (offset, index, style) => style === "rId" ? `rId${offset + index}` : `${offset + index}`;
357
+ function escapeRegex(str) {
358
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
359
+ }
360
+ function hasPlaceholders(xml) {
361
+ return xml.includes("{");
362
+ }
363
+ function collectPlaceholderKeys(xml, prefix) {
364
+ const keys = [];
365
+ const search = `{${prefix}`;
366
+ let pos = 0;
367
+ while ((pos = xml.indexOf(search, pos)) !== -1) {
368
+ const keyStart = pos + search.length;
369
+ const keyEnd = xml.indexOf("}", keyStart);
370
+ if (keyEnd === -1) break;
371
+ const key = xml.substring(keyStart, keyEnd);
372
+ if (key.length > 0 && !keys.includes(key)) keys.push(key);
373
+ pos = keyEnd + 1;
374
+ }
375
+ return keys;
376
+ }
377
+ function replaceImagePlaceholders(xml, mediaData, offset, idFormat = "rId") {
378
+ let result = xml;
379
+ mediaData.forEach((image, i) => {
380
+ result = result.replace(new RegExp(`\\{${escapeRegex(image.fileName)}\\}`, "g"), formatId(offset, i, idFormat));
381
+ });
382
+ return result;
383
+ }
384
+ function getReferencedMedia(xml, mediaArray) {
385
+ return mediaArray.filter((image) => xml.includes(`{${image.fileName}}`));
386
+ }
387
+ function replaceChartPlaceholders(xml, chartKeys, offset, idFormat = "rId") {
388
+ let result = xml;
389
+ chartKeys.forEach((key, i) => {
390
+ result = result.replace(new RegExp(`\\{chart:${escapeRegex(key)}\\}`, "g"), formatId(offset, i, idFormat));
391
+ });
392
+ return result;
393
+ }
394
+ function replaceSmartArtPlaceholders(xml, keys, dataOffset, idFormat = "rId") {
395
+ let result = xml;
396
+ const count = keys.length;
397
+ const loOffset = dataOffset + count;
398
+ const qsOffset = loOffset + count;
399
+ const csOffset = qsOffset + count;
400
+ keys.forEach((key, i) => {
401
+ result = result.replace(new RegExp(`\\{smartart:${escapeRegex(key)}\\}`, "g"), formatId(dataOffset, i, idFormat));
402
+ result = result.replace(new RegExp(`\\{smartart-lo:${escapeRegex(key)}\\}`, "g"), formatId(loOffset, i, idFormat));
403
+ result = result.replace(new RegExp(`\\{smartart-qs:${escapeRegex(key)}\\}`, "g"), formatId(qsOffset, i, idFormat));
404
+ result = result.replace(new RegExp(`\\{smartart-cs:${escapeRegex(key)}\\}`, "g"), formatId(csOffset, i, idFormat));
405
+ });
406
+ return result;
407
+ }
408
+ function addSmartArtRelationships(keys, addRel, baseOffset, globalStartIndex, options) {
409
+ const { pathPrefix, styleRelType } = options;
410
+ const count = keys.length;
411
+ const loOffset = baseOffset + count;
412
+ const qsOffset = loOffset + count;
413
+ const csOffset = qsOffset + count;
414
+ keys.forEach((_key, i) => {
415
+ const gi = globalStartIndex + i;
416
+ addRel(baseOffset + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramData", `${pathPrefix}diagrams/data${gi + 1}.xml`);
417
+ addRel(loOffset + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramLayout", `${pathPrefix}diagrams/layout${gi + 1}.xml`);
418
+ addRel(qsOffset + i, styleRelType, `${pathPrefix}diagrams/quickStyle${gi + 1}.xml`);
419
+ addRel(csOffset + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramColors", `${pathPrefix}diagrams/colors${gi + 1}.xml`);
420
+ addRel(csOffset + count + i, "http://schemas.microsoft.com/office/2007/relationships/diagramDrawing", `${pathPrefix}diagrams/drawing${gi + 1}.xml`);
421
+ });
422
+ }
423
+ //#endregion
424
+ export { AppProperties, BaseXmlComponent, BuilderElement, COLOR_CATEGORIES, Connection, ContentTypeAttributes, DEFAULT_DRAWING_XML, DataModel, EMPTY_OBJECT, EmptyElement, Formatter, HpsMeasureElement, IgnoreIfEmptyXmlComponent, ImportedRootElementAttributes, ImportedXmlComponent, InitializableXmlComponent, LAYOUT_CATEGORIES, NextAttributeComponent, NumberValueElement, OnOffElement, OoxmlMimeType, ParsedDocument, Point, PrettifyType, RawPassthrough, Relationships, STYLE_CATEGORIES, SmartArtCollection, StringContainer, StringEnumValueElement, StringValueElement, TargetModeType, ThemeColor, ThemeFont, TransPoint, XmlAttributeComponent, XmlComponent, addSmartArtRelationships, buildCorePropertiesXml, chartAttr, collectPlaceholderKeys, convertEmuToInches, convertEmuToPixels, convertEmuToPoints, convertInchesToEmu, convertInchesToTwip, convertMillimetersToTwip, convertOutput, convertPixelsToEmu, convertPointsToEmu, convertPrettifyType, convertToXmlComponent, createDataModel, createDefault, createOverride, dateTimeValue, decimalNumber, eighthPointMeasureValue, elementToCompact, elementToXml, escapeRegex, findRel, findRelsByType, formatId, getColorXml, getImageType, getLayoutXml, getReferencedMedia, getStyleXml, hasPlaceholders, hashedId, hexBinary, hexColorValue, hpsMeasureObj, hpsMeasureValue, listFiles, longHexNumber, measurementOrPercentValue, numberValObj, onOffObj, parseArchive, parseCoreProperties, parseRels, percentageValue, pointMeasureValue, positiveUniversalMeasureValue, readAllXmlParts, readBinaryFromZip, readTextFromZip, readXmlFromZip, replaceChartPlaceholders, replaceImagePlaceholders, replaceSmartArtPlaceholders, shortHexNumber, signedHpsMeasureValue, signedTwipsMeasureValue, stringContainerObj, stringEnumValObj, stringValObj, twipsMeasureValue, uCharHexNumber, uint8ToBase64, uniqueId, uniqueNumericIdCreator, uniqueUuid, universalMeasureValue, unsignedDecimalNumber, unzipToMap, wrapEl, zipToBuffer };
@@ -1 +1,2 @@
1
- import{a as e,c as t,d as n,f as r,i,l as a,n as o,o as s,p as c,r as l,s as u,t as d,u as f}from"../smartart-C-ZIRmWU.mjs";export{n as COLOR_CATEGORIES,s as Connection,u as DEFAULT_DRAWING_XML,e as DataModel,r as LAYOUT_CATEGORIES,l as Point,c as STYLE_CATEGORIES,o as SmartArtCollection,i as TransPoint,d as createDataModel,t as getColorXml,a as getLayoutXml,f as getStyleXml};
1
+ import { a as DataModel, c as getColorXml, d as COLOR_CATEGORIES, f as LAYOUT_CATEGORIES, i as TransPoint, l as getLayoutXml, n as SmartArtCollection, o as Connection, p as STYLE_CATEGORIES, r as Point, s as DEFAULT_DRAWING_XML, t as createDataModel, u as getStyleXml } from "../smartart-CdBk8E0n.mjs";
2
+ export { COLOR_CATEGORIES, Connection, DEFAULT_DRAWING_XML, DataModel, LAYOUT_CATEGORIES, Point, STYLE_CATEGORIES, SmartArtCollection, TransPoint, createDataModel, getColorXml, getLayoutXml, getStyleXml };