8000 Percent-encode and decode PartName in [Content_Types].xml by DominikPalo · Pull Request #4 · DominikPalo/OOXML-Toolkit · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Dif 10BC8 f view
25 changes: 23 additions & 2 deletions src/core/package/opc.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** Open Packaging Conventions: content types, relationships, package family detection. */
import type { PartSource } from './model';
import { decodeEntities, tryParseXml } from '../xml/parser';
import { decodeEntities, tryParseXml, type XmlDocument } from '../xml/parser';

export const CONTENT_TYPES_PART = '[Content_Types].xml';
export const PACKAGE_RELS_PART = '_rels/.rels';
Expand All @@ -22,12 +22,33 @@ export function parseContentTypes(xml: string): ContentTypes {
if (ext) out.defaults.set(ext.toLowerCase(), ct);
} else if (el.local === 'Override') {
const pn = el.attrs.find((a) => a.name === 'PartName')?.value;
if (pn) out.overrides.set(pn.replace(/^\//, ''), ct);
if (pn) out.overrides.set(partNameOfUri(pn), ct);
}
}
return out;
}

/**
* Point the `Override` for part `from` at part `to`, as a text splice of `doc.source`.
* `undefined` when `[Content_Types].xml` has no override for `from`.
*/
export function renameOverride(doc: XmlDocument, from: string, to: string): string | undefined {
for (const el of doc.root.elements) {
if (el.local !== 'Override') continue;
const pn = el.attrs.find((a) => a.name === 'PartName');
if (!pn || partNameOfUri(pn.value) !== from) continue;
return (
doc.source.slice(0, pn.valueStart) + '/' + encodePartUri(to) + doc.source.slice(pn.valueEnd)
);
}
return undefined;
}

/** The part name a `PartName` URI refers to: no leading slash, percent-escapes decoded. */
function partNameOfUri(uri: string): string {
return safeDecode(uri.replace(/^\//, ''));
}

export function contentTypeOf(types: ContentTypes, partName: string): string | undefined {
const o = types.overrides.get(partName);
if (o) return o;
Expand Down
29 changes: 13 additions & 16 deletions src/renderer/src/store/actions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
/** Application behaviour: everything the UI can ask for lives here, never inside components. */
import { PackageModel, type PartSource } from '@core/package/model';
import { baseName, extensionOf, partKind } from '@core/package/kinds';
import { contentTypeOf, encodePartUri, partNameProblem, relativeTarget } from '@core/package/opc';
import {
contentTypeOf,
encodePartUri,
partNameProblem,
relativeTarget,
renameOverride,
} from '@core/package/opc';
import { validatePackage } from '@core/package/validate';
import { comparePackages, type DiffStatus } from '@core/compare/compare';
import { formatXml, minifyXml } from '@core/xml/format';
Expand Down Expand Up @@ -767,21 +773,12 @@ export async function renamePart(id: string, part: string): Promise<void> {
const ct = tab.model.has('[Content_Types].xml')
? tab.model.getXml('[Content_Types].xml').doc
: undefined;
const ov = ct?.root.elements.find(
(e) =>
e.local === 'Override' &&
e.attrs.some((a) => a.name === 'PartName' && a.value.replace(/^\//, '') === part),
);
const pn = ov?.attrs.find((a) => a.name === 'PartName');
if (ct && pn) {
tab.model.setText(
'[Content_Types].xml',
ct.source.slice(0, pn.valueStart) + '/' + next + ct.source.slice(pn.valueEnd),
{
label: 'Update content types',
coalesceKey: undefined,
},
);
const text = ct && renameOverride(ct, part, next);
if (text !== undefined) {
tab.model.setText('[Content_Types].xml', text, {
label: 'Update content types',
coalesceKey: undefined,
});
}
});
navigate(id, { part: next }, { record: false });
Expand Down
87 changes: 87 additions & 0 deletions tests/package.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ import {
analyzePackage,
contentTypeOf,
encodePartUri,
parseContentTypes,
parseRelationships,
partNameProblem,
relativeTarget,
relsPartFor,
renameOverride,
resolveTarget,
sourceOfRels,
} from '@core/package/opc';
import { parseXml } from '@core/xml/parser';
import { buildFolderTree } from '@core/package/tree';
import { partKind } from '@core/package/kinds';
import { validatePackage } from '@core/package/validate';
Expand Down Expand Up @@ -43,6 +46,90 @@ describe('opc helpers', () => {
});
});

describe('content type part names', () => {
const CT = 'application/x-test';
const typesXml = (...partNames: string[]) =>
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
partNames.map((p) => `<Override PartName="${p}" ContentType="${CT}"/>`).join('') +
'</Types>';
const rename = (xml: string, from: string, to: string) => renameOverride(parseXml(xml), from, to);

it('matches a percent-encoded PartName to the real part name', () => {
const types = parseContentTypes(typesXml('/xl/embeddings/Dokument%20Word.docx'));
expect([...types.overrides.keys()]).toEqual(['xl/embeddings/Dokument Word.docx']);
expect(contentTypeOf(types, 'xl/embeddings/Dokument Word.docx')).toBe(CT);
});

it('encodes the PartName it writes on rename', () => {
const text = rename(
typesXml('/ppt/slides/slide1.xml'),
'ppt/slides/slide1.xml',
'ppt/slides/my slide.xml',
);
expect(text).toBe(typesXml('/ppt/slides/my%20slide.xml'));
});

it('round-trips names with spaces, % and non-ASCII characters', () => {
const next = 'xl/embeddings/Dokument 100% čeština.docx';
const text = rename(typesXml('/xl/embeddings/old.docx'), 'xl/embeddings/old.docx', next)!;
expect(text).toContain('PartName="/xl/embeddings/Dokument%20100%25%20%C4%8De%C5%A1tina.docx"');
const types = parseContentTypes(text);
expect([...types.overrides.keys()]).toEqual([next]);
expect(contentTypeOf(types, next)).toBe(CT);
// ...and back again, now that the existing PartName is encoded.
const back = rename(text, next, 'xl/embeddings/old.docx');
expect(back).toBe(typesXml('/xl/embeddings/old.docx'));
});

it('still finds an unencoded PartName written by another tool', () => {
const text = rename(
typesXml('/ppt/slides/my slide.xml', '/ppt/slides/slide2.xml'),
'ppt/slides/my slide.xml',
'ppt/slides/other.xml',
);
expect(text).toBe(typesXml('/ppt/slides/other.xml', '/ppt/slides/slide2.xml'));
});

it('only touches the matching PartName and leaves the rest of the source alone', () => {
const xml =
'<?xml version="1.0"?>\n<Types xmlns="x">\n <Override ContentType="a" PartName="/a%20b.xml" />\n' +
' <Override PartName="/c.xml" ContentType="b"/>\n</Types>';
expect(rename(xml, 'a b.xml', 'd.xml')).toBe(xml.replace('/a%20b.xml', '/d.xml'));
expect(rename(xml, 'missing.xml', 'd.xml')).toBeUndefined();
expect(rename('<Types/>', 'a.xml', 'b.xml')).toBeUndefined();
});

it('does not throw on malformed percent sequences', () => {
const bad = ['/a/100%.xml', '/a/%E0%A4%A.xml', '/a/%zz.xml', '/a/%.xml'];
const types = parseContentTypes(typesXml(...bad));
// Not decodable: kept as written (minus the leading slash).
expect([...types.overrides.keys()]).toEqual(bad.map((p) => p.slice(1)));
expect(contentTypeOf(types, 'a/100%.xml')).toBe(CT);
const text = rename(typesXml(...bad), 'a/%zz.xml', 'a/b.xml');
expect(text).toBe(typesXml('/a/100%.xml', '/a/%E0%A4%A.xml', '/a/b.xml', '/a/%.xml'));
});

it('does not report a false missing content type for an encoded override', async () => {
const m = PackageModel.open(buildXlsx());
m.addPart('xl/embeddings/Dokument Word.docx', 'x');
m.setText(
'[Content_Types].xml',
m
.getText('[Content_Types].xml')
.text.replace(
'</Types>',
`<Override PartName="/xl/embeddings/Dokument%20Word.docx" ContentType="${CT}"/></Types>`,
),
);
const codes = (await validatePackage(m)).map((p) => p.code);
expect(codes).not.toContain('no-content-type');
expect(codes).not.toContain('override-missing');
expect(contentTypeOf(analyzePackage(m).contentTypes, 'xl/embeddings/Dokument Word.docx')).toBe(
CT,
);
});
});

describe('package analysis', () => {
it.each([
['docx', buildDocx(), 'word', 'word/document.xml'],
Expand Down
Loading
0