Skip to content
Open
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
Diff view
33 changes: 33 additions & 0 deletions src/utils/pdf/__fixtures__/fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Stand-ins for fetch(). A response offers arrayBuffer() and blob() the way a
* browser's does. jsdom's Blob has no arrayBuffer(), so blob() gives a plain
* object with one. Its type is generic, as servers often send it.
*/
const response = (bytes, { ok = true, status = 200 } = {}) => {
const data = Uint8Array.from(bytes);
return {
ok,
status,
arrayBuffer: () => Promise.resolve(data.buffer),
blob: () => Promise.resolve({
type: 'application/octet-stream',
arrayBuffer: () => Promise.resolve(data.buffer),
}),
};
};

// Answer every URL with these bytes.
export const serveBytes = (bytes, options) =>
jest.fn(() => Promise.resolve(response(bytes, options)));

// Answer each URL with its bytes, and with a 404 for a URL not listed.
export const serveFiles = (filesByUrl) =>
jest.fn((url) => Promise.resolve(
filesByUrl[url] ? response(filesByUrl[url]) : response([], { ok: false, status: 404 }),
));

// A server that never answers: the fetch rejects only when it is aborted.
export const neverAnswers = () =>
jest.fn((url, { signal }) => new Promise((resolve, reject) => {
signal.addEventListener('abort', () => reject(new Error('aborted')));
}));
129 changes: 129 additions & 0 deletions src/utils/pdf/__fixtures__/font-files.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/* eslint-disable no-magic-numbers */
// Font files built byte by byte, at their OpenType and WOFF offsets.
import { deflateSync } from 'zlib';

// A table of `size` bytes, filled in by `write`.
const table = (size, write) => {
const bytes = new Uint8Array(size);
write(new DataView(bytes.buffer));
return bytes;
};
const head = (unitsPerEm) => table(54, (v) => v.setUint16(18, unitsPerEm));
const hhea = (ascender) => table(36, (v) => v.setInt16(4, ascender));
const os2 = (version, capHeight) =>
table(96, (v) => {
v.setUint16(0, version);
v.setInt16(88, capHeight);
});
// A Unicode format 4 cmap that maps "H" (0x48) to glyph 1.
const cmapH = () =>
table(44, (v) => {
v.setUint16(2, 1); // one subtable
v.setUint16(4, 3); // platform: Windows
v.setUint16(6, 1); // encoding: Unicode BMP
v.setUint32(8, 12); // subtable offset
v.setUint16(12, 4); // format 4
v.setUint16(18, 4); // two segments: "H" and the closing 0xFFFF one
v.setUint16(26, 0x48); // end codes
v.setUint16(28, 0xffff);
v.setUint16(32, 0x48); // start codes
v.setUint16(34, 0xffff);
v.setUint16(36, 0x10000 + 1 - 0x48); // id deltas: "H" + delta wraps to 1
v.setUint16(38, 1);
});
// Short loca offsets: glyph 0 is empty, glyph 1 takes 12 bytes.
const loca = () => table(6, (v) => v.setUint16(4, 6));
const glyf = (yMax) => table(12, (v) => v.setInt16(8, yMax));

// A font with a cap height in OS/2, and one that needs the "H" glyph.
export const modernTables = () => ({
head: head(2048),
hhea: hhea(2070),
'OS/2': os2(4, 1434),
});
export const oldTables = () => ({
head: head(1000),
hhea: hhea(1011),
'OS/2': os2(1, 0),
cmap: cmapH(),
loca: loca(),
glyf: glyf(705),
});
export const MODERN = { ascender: 2070 / 2048, capHeight: 1434 / 2048 };
export const OLD = { ascender: 1.011, capHeight: 0.705 };

// Helvetica's metrics for every style, as loadFont gives them.
const HELVETICA = { ascender: 0.718, capHeight: 0.718 };
export const HELVETICA_FONT_METRICS = {
normal: HELVETICA,
bold: HELVETICA,
italics: HELVETICA,
bolditalics: HELVETICA,
};

// Lay out a file: a header, one directory entry per table, then the tables.
const pack = (tables, headerSize, entrySize, writeHeader, writeEntry) => {
const tags = Object.keys(tables);
let end = headerSize + tags.length * entrySize;
const offsets = tags.map((tag) => {
const offset = end;
end += tables[tag].length;
return offset;
});
const bytes = new Uint8Array(end);
const view = new DataView(bytes.buffer);
writeHeader(view, tags.length, end);
tags.forEach((tag, i) => {
const entry = headerSize + i * entrySize;
for (let c = 0; c < 4; c++) bytes[entry + c] = tag.charCodeAt(c);
writeEntry(view, entry, tag, offsets[i]);
bytes.set(tables[tag], offsets[i]);
});
return bytes;
};

// A TTF file, or an OTF one with version 0x4f54544f ("OTTO").
export const ttf = (tables, version = 0x00010000) =>
pack(
tables,
12,
16,
(view, numTables) => {
view.setUint32(0, version);
view.setUint16(4, numTables);
},
(view, entry, tag, offset) => {
view.setUint32(entry + 8, offset);
view.setUint32(entry + 12, tables[tag].length);
},
);

// A WOFF file. Each table is compressed with zlib, unless that doesn't make
// it smaller: then it is stored as it is, as WOFF requires. The tiny loca and
// glyf tables here are stored that way.
export const woff = (tables) => {
const stored = {};
Object.keys(tables).forEach((tag) => {
const packed = new Uint8Array(deflateSync(tables[tag]));
stored[tag] = packed.length < tables[tag].length ? packed : tables[tag];
});
return pack(
stored,
44,
20,
(view, numTables, length) => {
view.setUint32(0, 0x774f4646); // "wOFF"
view.setUint32(4, 0x00010000);
view.setUint32(8, length);
view.setUint16(12, numTables);
},
(view, entry, tag, offset) => {
view.setUint32(entry + 4, offset);
view.setUint32(entry + 8, stored[tag].length);
view.setUint32(entry + 12, tables[tag].length);
},
);
};

// The first bytes of a WOFF2 file; enough for a signature check.
export const woff2 = () => Uint8Array.from([0x77, 0x4f, 0x46, 0x32, 0, 1, 0, 0]);
24 changes: 24 additions & 0 deletions src/utils/pdf/__tests__/base64.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* @jest-environment node
*/
/* eslint-disable no-magic-numbers */
import { bytesToBase64, base64ToBytes } from '../base64';

describe('base64', () => {
// Longer than one 0x8000-byte chunk, with every byte value.
const bytes = Uint8Array.from({ length: 0x8000 * 2 + 7 }, (_, i) => i % 256);

it('encodes bytes the way Node does, across chunks', () => {
expect(bytesToBase64(bytes)).toBe(Buffer.from(bytes).toString('base64'));
expect(bytesToBase64(new Uint8Array(0))).toBe('');
});

it('encodes only the bytes a view covers', () => {
const view = bytes.subarray(10, 20);
expect(bytesToBase64(view)).toBe(Buffer.from(view).toString('base64'));
});

it('decodes what it encodes', () => {
expect(base64ToBytes(bytesToBase64(bytes))).toEqual(bytes);
});
});
8 changes: 6 additions & 2 deletions src/utils/pdf/__tests__/create-document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/
import { createDocument } from '../create-document';
import { createFakePdfMake } from '../__fixtures__/fake-pdfmake';
import { HELVETICA_FONT_METRICS } from '../__fixtures__/font-files';

describe('createDocument', () => {
beforeEach(() => {
Expand All @@ -11,13 +12,16 @@ describe('createDocument', () => {
});
afterEach(() => jest.restoreAllMocks());

it('resolves font, runs the template with it, and sets defaultStyle.font', async () => {
it('resolves font, runs the template with it and its metrics, and sets defaultStyle.font', async () => {
const { pdfMake } = createFakePdfMake();
const template = jest.fn((data, ctx) => ({ content: [{ text: data.t }], _ctxFont: ctx.font }));

const api = await createDocument({ pdfMake, font: 'Helvetica', template, data: { t: 'hi' } });

expect(template).toHaveBeenCalledWith({ t: 'hi' }, { font: 'Helvetica' });
expect(template).toHaveBeenCalledWith({ t: 'hi' }, {
font: 'Helvetica',
fontMetrics: HELVETICA_FONT_METRICS,
});
const doc = pdfMake.createPdf.mock.calls[0][0];
expect(doc.defaultStyle.font).toBe('Helvetica');
expect(typeof api.download).toBe('function');
Expand Down
96 changes: 96 additions & 0 deletions src/utils/pdf/__tests__/font-metrics.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/**
* @jest-environment node
*/
// Node has DecompressionStream, Blob and Response, which jsdom lacks.
/* eslint-disable no-magic-numbers */
import { fontFormat, isCompleteFontFile, readFontMetrics } from '../font-metrics';
import {
modernTables, oldTables, ttf, woff, woff2, MODERN, OLD,
} from '../__fixtures__/font-files';

const html = new TextEncoder().encode('<!doctype html><html></html>');

describe('fontFormat', () => {
it('tells the format from the first four bytes', () => {
expect(fontFormat(ttf(modernTables()))).toBe('sfnt');
expect(fontFormat(ttf(modernTables(), 0x4f54544f))).toBe('sfnt'); // OTF
expect(fontFormat(ttf(modernTables(), 0x74727565))).toBe('sfnt'); // "true"
expect(fontFormat(woff(modernTables()))).toBe('woff');
expect(fontFormat(woff2())).toBe('woff2');
});

it('gives null for other files and files under four bytes', () => {
expect(fontFormat(html)).toBeNull();
expect(fontFormat(new Uint8Array([0, 1, 0]))).toBeNull();
});
});

describe('isCompleteFontFile', () => {
it('accepts TTF and WOFF files whose tables lie inside them', () => {
expect(isCompleteFontFile(ttf(oldTables()))).toBe(true);
expect(isCompleteFontFile(woff(oldTables()))).toBe(true);
});

it('rejects a file cut short in its tables or in its table directory', () => {
const file = ttf(oldTables());
expect(isCompleteFontFile(file.slice(0, file.length - 1))).toBe(false);
expect(isCompleteFontFile(file.slice(0, 20))).toBe(false);
const packed = woff(oldTables());
expect(isCompleteFontFile(packed.slice(0, packed.length - 1))).toBe(false);
});

it('rejects other formats', () => {
expect(isCompleteFontFile(woff2())).toBe(false);
expect(isCompleteFontFile(html)).toBe(false);
});
});

describe('readFontMetrics', () => {
it('reads the ascender from hhea and the cap height from OS/2', async () => {
await expect(readFontMetrics(ttf(modernTables()))).resolves.toEqual(MODERN);
// OpenType with CFF outlines has the same tables.
await expect(readFontMetrics(ttf(modernTables(), 0x4f54544f))).resolves.toEqual(MODERN);
});

it('measures the H glyph when OS/2 has no cap height', async () => {
await expect(readFontMetrics(ttf(oldTables()))).resolves.toEqual(OLD);
});

it("returns null when it can't find a cap height", async () => {
const tables = oldTables();
delete tables.glyf;
await expect(readFontMetrics(ttf(tables))).resolves.toBeNull();
});

it('inflates the tables of a WOFF file', async () => {
await expect(readFontMetrics(woff(modernTables()))).resolves.toEqual(MODERN);
});

it('reads WOFF tables stored compressed or as they are', async () => {
await expect(readFontMetrics(woff(oldTables()))).resolves.toEqual(OLD);
});

it("returns null for WOFF where the browser can't inflate it", async () => {
const { DecompressionStream } = global;
delete global.DecompressionStream;
try {
await expect(readFontMetrics(woff(modernTables()))).resolves.toBeNull();
} finally {
global.DecompressionStream = DecompressionStream;
}
});

it("returns null for formats it can't read", async () => {
await expect(readFontMetrics(woff2())).resolves.toBeNull();
await expect(
readFontMetrics(new TextEncoder().encode('<!doctype html><html></html>')),
).resolves.toBeNull();
});

it('rejects for a damaged file', async () => {
await expect(readFontMetrics(ttf(modernTables()).slice(0, 40))).rejects.toThrow();
const broken = woff(modernTables());
broken.fill(0xff, 44 + 3 * 20); // tables that don't inflate
await expect(readFontMetrics(broken)).rejects.toThrow();
});
});
Loading
Loading