pulpweaver4-epub 0.0.0-stage → 0.0.7

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.
package/LICENSE ADDED
@@ -0,0 +1,121 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # pulpweaver4-epub
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [pulpweaver4](https://gitlab.com/inkylabs/pulpweaver4)'s EPUB 3 output: a
4
+ book's screen edition as an EPUB, with its package document, its navigation
5
+ (the contents, landmarks and a page list taken from a print edition's
6
+ layout) and its accessibility metadata, checked by EPUBCheck in CI.
7
+
8
+ ```sh
9
+ npm install pulpweaver4-epub
10
+ ```
11
+
12
+ ```toml
13
+ # pulpweaver4.toml
14
+ [plugins]
15
+ pulpweaver4-epub = {}
16
+
17
+ [editions.epub]
18
+ media = "screen"
19
+ output = "epub"
20
+ page-list = "paperback" # the print edition whose pages it lists
21
+ ```
22
+
23
+ `pw build --edition epub` writes `dist/epub/epub.epub`. The guide is
24
+ [docs/guide.md](docs/guide.md); the options and the output's reference are
25
+ generated into `docs/reference/` at each release, and published at
26
+ https://pulpweaver.inkylabs.com.
27
+
28
+ ## Licence
29
+
30
+ [CC0 1.0](LICENSE): no rights reserved.
@@ -0,0 +1,6 @@
1
+ export { epubFile, epubOutput, writeEpub } from './output.js';
2
+ export { NAME, OPTIONS_SCHEMA, OUTPUT_DESCRIPTION, readOptions, type EpubOptions } from './options.js';
3
+ export { pageStarts, placePageBreaks, type PageStart } from './page-list.js';
4
+ export { PROBLEMS, type ProblemCode } from './problems.js';
5
+ declare const _default: import("pulpweaver4").Plugin;
6
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * pulpweaver4-epub, pulpweaver4's EPUB 3 output
3
+ * (https://plans.inkylabs.com/pulpweaver#repositories): an edition whose
4
+ * `output` is `epub` is written as `<edition>.epub`, the book's screen
5
+ * edition as XHTML with its package document, its navigation (the
6
+ * contents, landmarks, and a page list from the print edition its
7
+ * `page-list` names) and its accessibility metadata.
8
+ */
9
+ import { definePlugin } from 'pulpweaver4';
10
+ import { NAME, OPTIONS_SCHEMA, OUTPUT_DESCRIPTION } from './options.js';
11
+ import { epubOutput } from './output.js';
12
+ export { epubFile, epubOutput, writeEpub } from './output.js';
13
+ export { NAME, OPTIONS_SCHEMA, OUTPUT_DESCRIPTION, readOptions } from './options.js';
14
+ export { pageStarts, placePageBreaks } from './page-list.js';
15
+ export { PROBLEMS } from './problems.js';
16
+ export default definePlugin({
17
+ name: NAME,
18
+ api: 1,
19
+ url: import.meta.url,
20
+ description: 'EPUB 3 output: the package document, navigation with a page list from a print edition, and accessibility metadata.',
21
+ options: OPTIONS_SCHEMA,
22
+ output: {
23
+ epub: {
24
+ description: OUTPUT_DESCRIPTION,
25
+ write: (ctx) => epubOutput.write(ctx),
26
+ },
27
+ },
28
+ });
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The plugin's options, `[plugins] pulpweaver4-epub = { … }` in
3
+ * `pulpweaver4.toml`: the book's metadata that the core's configuration
4
+ * doesn't hold and an EPUB's package document does. The reference's page
5
+ * for them is made from this schema (`scripts/reference.mjs`).
6
+ */
7
+ import type { Schema } from 'pulpweaver4';
8
+ /** The plugin's name, as `pulpweaver4.toml`'s `[plugins]` names it. */
9
+ export declare const NAME = "pulpweaver4-epub";
10
+ /** What the `epub` output writes, for the docs and messages. */
11
+ export declare const OUTPUT_DESCRIPTION = "An EPUB 3 of the book\u2019s screen edition, `<edition>.epub`: its text as XHTML, a document per chapter\u2019s file, with its contents, landmarks and accessibility metadata, and a page list of the print edition its `page-list` names.";
12
+ export declare const OPTIONS_SCHEMA: Schema;
13
+ /** The options, read from what `pulpweaver4.toml` gave, which the core has checked against the schema. */
14
+ export interface EpubOptions {
15
+ readonly identifier?: string;
16
+ readonly creators: readonly string[];
17
+ readonly publisher?: string;
18
+ readonly pageSource?: string;
19
+ readonly accessibilitySummary?: string;
20
+ }
21
+ /** The options from `[plugins]`'s table for the plugin. */
22
+ export declare function readOptions(given?: Readonly<Record<string, unknown>>): EpubOptions;
@@ -0,0 +1,55 @@
1
+ /** The plugin's name, as `pulpweaver4.toml`'s `[plugins]` names it. */
2
+ export const NAME = 'pulpweaver4-epub';
3
+ /** What the `epub` output writes, for the docs and messages. */
4
+ export const OUTPUT_DESCRIPTION = 'An EPUB 3 of the book’s screen edition, `<edition>.epub`: its text as XHTML, a document per chapter’s file, with its contents, landmarks and accessibility metadata, and a page list of the print edition its `page-list` names.';
5
+ export const OPTIONS_SCHEMA = {
6
+ type: 'object',
7
+ additionalProperties: false,
8
+ properties: {
9
+ identifier: {
10
+ type: 'string',
11
+ minLength: 1,
12
+ description: 'The EPUB’s unique identifier, its `dc:identifier`: its ISBN as a URN, a DOI or a UUID. By default a UUID made from the book’s title and language, the same at every build, which a book with an ISBN should replace.',
13
+ examples: ['urn:isbn:9780000000002'],
14
+ },
15
+ creators: {
16
+ type: 'array',
17
+ items: { type: 'string', minLength: 1 },
18
+ description: 'The book’s authors, in order, each a `dc:creator`.',
19
+ default: [],
20
+ examples: [['The pulpweaver4 Project']],
21
+ },
22
+ publisher: {
23
+ type: 'string',
24
+ minLength: 1,
25
+ description: 'Its publisher, the `dc:publisher`.',
26
+ examples: ['Inky Labs'],
27
+ },
28
+ 'page-source': {
29
+ type: 'string',
30
+ minLength: 1,
31
+ description: 'The printed book whose pages the page list gives (an edition’s `page-list`), as the package’s `dc:source`: the print edition’s ISBN as a URN, or its name. By default the book’s title and the edition’s name.',
32
+ examples: ['urn:isbn:9780000000019'],
33
+ },
34
+ 'accessibility-summary': {
35
+ type: 'string',
36
+ minLength: 1,
37
+ description: 'The `schema:accessibilitySummary`, a sentence or two on how accessible the book is. By default one made from what the EPUB has: its structure, its navigation and page list, alternative text and MathML.',
38
+ },
39
+ },
40
+ };
41
+ /** The options from `[plugins]`'s table for the plugin. */
42
+ export function readOptions(given = {}) {
43
+ const text = (key) => (typeof given[key] === 'string' ? given[key] : undefined);
44
+ const identifier = text('identifier');
45
+ const publisher = text('publisher');
46
+ const pageSource = text('page-source');
47
+ const accessibilitySummary = text('accessibility-summary');
48
+ return {
49
+ creators: Array.isArray(given['creators']) ? given['creators'].filter((c) => typeof c === 'string') : [],
50
+ ...(identifier !== undefined ? { identifier } : {}),
51
+ ...(publisher !== undefined ? { publisher } : {}),
52
+ ...(pageSource !== undefined ? { pageSource } : {}),
53
+ ...(accessibilitySummary !== undefined ? { accessibilitySummary } : {}),
54
+ };
55
+ }
@@ -0,0 +1,13 @@
1
+ import { type Output, type OutputContext, type OutputResult } from 'pulpweaver4';
2
+ /** The EPUB an edition writes, in its folder. */
3
+ export declare function epubFile(edition: string): string;
4
+ /** The plugin's `epub` output. */
5
+ export declare const epubOutput: Output;
6
+ /** Writes an EPUB edition. */
7
+ export declare function writeEpub(ctx: OutputContext): Promise<OutputResult>;
8
+ /**
9
+ * The web edition's stylesheet as the EPUB's: without its `@page` rules,
10
+ * which a reflowable EPUB has no pages for and whose margin boxes EPUB's
11
+ * CSS doesn't take.
12
+ */
13
+ export declare function epubStylesheet(css: string): string;
package/dist/output.js ADDED
@@ -0,0 +1,356 @@
1
+ import { BookCitations, CONFIG_FILE, citesAnything, epochMilliseconds, htmlToDom, MathTypesetter, MemoryFS, positionOptions, projectCitations, renderHtml, sitePages, TomlDocument, webHast, webOutput, } from 'pulpweaver4';
2
+ import postcss from 'postcss';
3
+ import { NAME, readOptions } from './options.js';
4
+ import { mediaType, NAV_FILE, navDocument, PACKAGE_FILE, packageDocument, zipEpub } from './package.js';
5
+ import { pageStarts, placePageBreaks } from './page-list.js';
6
+ import { documentProperties, epubNotes, relink, setEpubType, xhtmlDocument, XHTML } from './xhtml.js';
7
+ /** The EPUB an edition writes, in its folder. */
8
+ export function epubFile(edition) {
9
+ return `${edition}.epub`;
10
+ }
11
+ /** The plugin's `epub` output. */
12
+ export const epubOutput = { name: 'epub', write: writeEpub };
13
+ const STYLESHEET = 'style.css';
14
+ const LABELS = { contents: 'Contents', pages: 'Pages', landmarks: 'Landmarks', start: 'Start of content' };
15
+ /** Writes an EPUB edition. */
16
+ export async function writeEpub(ctx) {
17
+ const { project, edition, manuscript, out } = ctx;
18
+ const { config } = project;
19
+ const options = readOptions(config.plugins[NAME]);
20
+ const problems = [];
21
+ const at = (key, code, message, fix) => TomlDocument.parse(project.configText, CONFIG_FILE).problem(['editions', edition.name, key], 'value', code, message, fix);
22
+ if (!ctx.date) {
23
+ problems.push(at('output', 'epub-date', 'an EPUB must say when it was modified, and the build has no date', 'set date in pulpweaver4.toml, or SOURCE_DATE_EPOCH'));
24
+ return { files: [], problems };
25
+ }
26
+ const mtime = epochMilliseconds(ctx.date);
27
+ // The web edition, in memory: its stylesheet, fonts and images, and what it finds wrong, which the EPUB shares.
28
+ const site = new MemoryFS();
29
+ const web = await webOutput.write({ ...ctx, edition: { ...edition, split: 'chapter' }, out: site });
30
+ problems.push(...web.problems);
31
+ const documents = await contentDocuments(ctx, new Set(web.files));
32
+ // The print edition's pages, each marked where it begins.
33
+ let breaks = [];
34
+ if (edition.pageList !== undefined && ctx.layOut) {
35
+ const starts = await printPageStarts(ctx.layOut, edition.pageList);
36
+ breaks = placePageBreaks(documents, starts, (start) => pageBreak(documents[0].root.ownerDocument, start));
37
+ }
38
+ else if (edition.pageList !== undefined) {
39
+ problems.push(at('page-list', 'epub-page-list', `the page list needs the ${edition.pageList} edition’s pages, and this build can’t lay them out`, 'build with pulpweaver4 0.0.93 or later'));
40
+ }
41
+ // The navigation, whose contents give the headings they link to ids; a book without headings lists its documents.
42
+ const headings = contents(documents);
43
+ const toc = headings.length ? headings : documentContents(documents, config.title);
44
+ const pages = breaks.map((b) => ({ title: b.start.label, href: `${documents[b.document].file}#${b.marker.id}` }));
45
+ // The book's own contents page; the navigation document's contents can't be a landmark, as it isn't in the spine.
46
+ const own = bookContents(documents);
47
+ const landmarks = own ? [{ title: LABELS.contents, href: own, type: 'toc' }] : [];
48
+ const start = bodyMatter(documents, breaks);
49
+ if (start)
50
+ landmarks.push({ title: LABELS.start, href: start, type: 'bodymatter' });
51
+ const files = [{
52
+ path: NAV_FILE,
53
+ data: navDocument({ title: config.title, language: config.language, labels: LABELS, toc, landmarks, ...(pages.length ? { pages } : {}) }),
54
+ properties: ['nav'],
55
+ }];
56
+ const pagesByFile = new Map(documents.map((x) => [x.file.replace(/\.xhtml$/, '.html'), x.file]));
57
+ for (const d of documents) {
58
+ epubNotes(d.root);
59
+ relink(d.root, pagesByFile, documents[0].file);
60
+ files.push({
61
+ path: d.file,
62
+ data: xhtmlDocument({ title: d.title, language: config.language, stylesheets: [STYLESHEET], body: [d.root] }),
63
+ properties: documentProperties(d.root),
64
+ });
65
+ }
66
+ for (const path of web.files) {
67
+ if (path.endsWith('.html') || path.startsWith('pw/'))
68
+ continue;
69
+ if (mediaType(path) === undefined) {
70
+ problems.push(at('output', 'epub-media-type', `${path} isn’t a type an EPUB can hold without a fallback, and is left out`));
71
+ continue;
72
+ }
73
+ const data = await site.readFile(path);
74
+ files.push({ path, data: path === STYLESHEET ? epubStylesheet(new TextDecoder().decode(data)) : data });
75
+ }
76
+ const accessibility = accessibilityOf(documents, files, options, edition.pageList, headings.length > 0);
77
+ const identifier = options.identifier ?? (await titleUuid(config.title, config.language));
78
+ const pageSource = edition.pageList === undefined ? undefined : (options.pageSource ?? `${config.title}, the ${edition.pageList} edition`);
79
+ files.push({
80
+ path: PACKAGE_FILE,
81
+ data: packageDocument({
82
+ identifier, title: config.title, language: config.language, modified: new Date(mtime), creators: options.creators,
83
+ ...(options.publisher !== undefined ? { publisher: options.publisher } : {}), ...(pageSource !== undefined ? { pageSource } : {}), accessibility,
84
+ }, files, documents.map((d) => ({ path: d.file }))),
85
+ });
86
+ const file = epubFile(edition.name);
87
+ await out.writeFile(file, zipEpub(files, mtime));
88
+ return { files: [file], problems };
89
+ }
90
+ /**
91
+ * The book's content documents: the web output's pages, rendered as it
92
+ * renders them, but for the contents page the site adds (the EPUB's
93
+ * navigation is the contents), each its `div.pw-document` in the page's DOM,
94
+ * with each image pointed at the file the site has.
95
+ */
96
+ async function contentDocuments(ctx, siteFiles) {
97
+ const { project, edition, manuscript } = ctx;
98
+ const { config } = project;
99
+ const citations = citesAnything(manuscript)
100
+ ? new BookCitations(manuscript, {
101
+ processor: ctx.citations ?? (await projectCitations(project, edition.name)).processor,
102
+ edition: { name: edition.name, media: 'screen' },
103
+ nocite: config.nocite,
104
+ ...positionOptions(project, edition.name),
105
+ })
106
+ : undefined;
107
+ const math = new MathTypesetter({ language: config.language, speech: false });
108
+ await math.prepare(manuscript, ['mathml']);
109
+ const rendering = renderHtml(manuscript, {
110
+ edition: { name: edition.name, media: 'screen' },
111
+ math,
112
+ ...(ctx.renderers ? { renderers: ctx.renderers } : {}),
113
+ ...(citations ? { citations } : {}),
114
+ language: config.language,
115
+ title: config.title,
116
+ });
117
+ // Its problems are the web output's, which has reported them.
118
+ webHast(rendering.tree, { manuscript });
119
+ const pages = sitePages(rendering.tree, { title: config.title, language: config.language, split: 'chapter' });
120
+ const host = ctx.document ?? document;
121
+ const out = [];
122
+ for (const page of pages) {
123
+ const content = findElement(page.body, (el) => el.tagName === 'div' && classes(el).includes('pw-document'));
124
+ if (!content || page.file === 'index.html')
125
+ continue;
126
+ const dom = htmlToDom({ ...rendering, tree: { type: 'root', children: [content] } }, host);
127
+ pointImages(dom.element, project.files, siteFiles);
128
+ out.push({ file: page.file.replace(/\.html$/, '.xhtml'), title: page.title, root: dom.element, elementsOf: (node) => dom.elementsOf(node) });
129
+ }
130
+ return out;
131
+ }
132
+ /** The first element under `el`, or `el`, that `test` takes, in document order. */
133
+ function findElement(el, test) {
134
+ if (test(el))
135
+ return el;
136
+ for (const c of el.children) {
137
+ const found = c.type === 'element' ? findElement(c, test) : undefined;
138
+ if (found)
139
+ return found;
140
+ }
141
+ return undefined;
142
+ }
143
+ function classes(el) {
144
+ const c = el.properties['className'];
145
+ return Array.isArray(c) ? c.map(String) : typeof c === 'string' ? c.split(/\s+/) : [];
146
+ }
147
+ /**
148
+ * Points each image at its file as the web output wrote it: its path in the
149
+ * project, from its chapter's folder or the project's root, as the web
150
+ * output finds it.
151
+ */
152
+ function pointImages(root, projectFiles, siteFiles) {
153
+ const have = new Set(projectFiles);
154
+ for (const img of root.querySelectorAll('img[src]')) {
155
+ const src = img.getAttribute('src');
156
+ if (/^[a-z][a-z0-9+.-]*:/i.test(src) || src.startsWith('//') || src.startsWith('#'))
157
+ continue;
158
+ const chapter = img.closest('[data-pw-file]')?.getAttribute('data-pw-file') ?? '';
159
+ const path = decodeURI(src.split(/[?#]/)[0]);
160
+ const fromChapter = normalize(`${chapter.slice(0, chapter.lastIndexOf('/') + 1)}${path}`);
161
+ const fromRoot = normalize(path.replace(/^\/+/, ''));
162
+ const found = [fromChapter, fromRoot].find((p) => p !== undefined && have.has(p) && siteFiles.has(p));
163
+ if (found !== undefined)
164
+ img.setAttribute('src', encodeURI(found));
165
+ }
166
+ }
167
+ /** A relative path with its `.` and `..` resolved; undefined if it climbs out of the root. */
168
+ function normalize(path) {
169
+ const parts = [];
170
+ for (const part of path.split('/')) {
171
+ if (part === '' || part === '.')
172
+ continue;
173
+ if (part === '..') {
174
+ if (!parts.length)
175
+ return undefined;
176
+ parts.pop();
177
+ }
178
+ else {
179
+ parts.push(part);
180
+ }
181
+ }
182
+ return parts.join('/');
183
+ }
184
+ /** Where each page of the print edition `name` begins, laid out as its own output lays it out, from the same manuscript. */
185
+ async function printPageStarts(layOut, name) {
186
+ const book = await layOut(name);
187
+ try {
188
+ return pageStarts(book);
189
+ }
190
+ finally {
191
+ book.dispose();
192
+ }
193
+ }
194
+ /** A page break, as EPUB and DPUB-ARIA mark one: named by its page's label. */
195
+ function pageBreak(doc, start) {
196
+ const span = doc.createElementNS(XHTML, 'span');
197
+ span.id = `pw-page-${start.number}`;
198
+ span.setAttribute('role', 'doc-pagebreak');
199
+ span.setAttribute('aria-label', start.label);
200
+ setEpubType(span, 'pagebreak');
201
+ return span;
202
+ }
203
+ /** The contents: each document's headings, nested by level, to the third. */
204
+ function contents(documents) {
205
+ const root = [];
206
+ const top = [];
207
+ let n = 0;
208
+ for (const d of documents) {
209
+ for (const h of d.root.querySelectorAll('h1, h2, h3')) {
210
+ if (h.closest('aside, nav, [role="doc-footnote"]'))
211
+ continue;
212
+ const title = (h.textContent ?? '').replace(/\s+/g, ' ').trim();
213
+ if (!title)
214
+ continue;
215
+ const level = Number(h.localName[1]);
216
+ // A section's first heading is linked by the section's id, which the source gave.
217
+ const parent = h.parentElement;
218
+ const section = parent?.localName === 'section' && [...parent.children].find((c) => /^h[1-6]$/.test(c.localName)) === h ? parent : undefined;
219
+ let id = h.id || section?.id;
220
+ if (!id) {
221
+ id = `pw-heading-${++n}`;
222
+ h.id = id;
223
+ }
224
+ const entry = { title, href: `${d.file}#${id}`, children: [] };
225
+ while (root.length && root[root.length - 1].level >= level)
226
+ root.pop();
227
+ if (root.length)
228
+ root[root.length - 1].entry.children.push(entry);
229
+ else
230
+ top.push(entry);
231
+ root.push({ level, entry });
232
+ }
233
+ }
234
+ return top;
235
+ }
236
+ /**
237
+ * The contents of a book without headings, as EPUB requires contents: an
238
+ * entry per document, titled by its first text, or by the book's title if it
239
+ * is the only document or has no text.
240
+ */
241
+ function documentContents(documents, title) {
242
+ return documents.map((d) => ({ title: (documents.length > 1 && firstText(d.root)) || title, href: d.file, children: [] }));
243
+ }
244
+ /** An element's first text, from its first block with any, without generated text, to its first ten words. */
245
+ function firstText(root) {
246
+ for (const block of root.querySelectorAll('p, li, dt, dd, td, th, blockquote, figcaption, caption, pre')) {
247
+ if (block.closest('aside, nav, [role="doc-footnote"]'))
248
+ continue;
249
+ const copy = block.cloneNode(true);
250
+ for (const g of copy.querySelectorAll('[data-pw-generated], aside, a[role="doc-noteref"]'))
251
+ g.remove();
252
+ const words = (copy.textContent ?? '').split(/\s+/).filter(Boolean);
253
+ if (words.length)
254
+ return words.length > 10 ? `${words.slice(0, 10).join(' ')}…` : words.join(' ');
255
+ }
256
+ return undefined;
257
+ }
258
+ /**
259
+ * The book's own contents (`::: contents`, which the renderer makes a
260
+ * `doc-toc` navigation), by an id it or its section has, given one if
261
+ * neither has.
262
+ */
263
+ function bookContents(documents) {
264
+ for (const d of documents) {
265
+ const nav = d.root.querySelector('[role="doc-toc"]');
266
+ if (!nav)
267
+ continue;
268
+ const section = nav.closest('section[id]');
269
+ if (!nav.id && !section)
270
+ nav.id = 'pw-contents';
271
+ return `${d.file}#${nav.id || section.id}`;
272
+ }
273
+ return undefined;
274
+ }
275
+ /**
276
+ * The web edition's stylesheet as the EPUB's: without its `@page` rules,
277
+ * which a reflowable EPUB has no pages for and whose margin boxes EPUB's
278
+ * CSS doesn't take.
279
+ */
280
+ export function epubStylesheet(css) {
281
+ const root = postcss.parse(css);
282
+ root.walkAtRules('page', (rule) => {
283
+ rule.remove();
284
+ });
285
+ return root.toString();
286
+ }
287
+ /** Where the body of the book begins: the page numbered 1 in print, else its first chapter that isn't front matter. */
288
+ function bodyMatter(documents, breaks) {
289
+ const one = breaks.find((b) => b.start.label === '1');
290
+ if (one)
291
+ return `${documents[one.document].file}#${one.marker.id}`;
292
+ for (const d of documents) {
293
+ const chapter = d.root.querySelector('section.chapter:not(.unnumbered)[id]');
294
+ if (chapter)
295
+ return `${d.file}#${chapter.id}`;
296
+ }
297
+ return undefined;
298
+ }
299
+ /** What the EPUB is, for its accessibility metadata. */
300
+ function accessibilityOf(documents, files, options, pageList, headings) {
301
+ const images = documents.flatMap((d) => [...d.root.querySelectorAll('img')]);
302
+ const figures = documents.flatMap((d) => [...d.root.querySelectorAll('svg[role="img"]:not(.math)')]);
303
+ const visual = images.length > 0 || figures.length > 0;
304
+ const described = images.every((img) => img.hasAttribute('alt')) && figures.every((svg) => svg.hasAttribute('aria-label') || svg.querySelector('title'));
305
+ const math = documents.some((d) => documentProperties(d.root).includes('mathml'));
306
+ // Headings are its structure; a book without them has contents of its documents alone.
307
+ const features = [...(headings ? ['structuralNavigation'] : []), 'tableOfContents', 'readingOrder'];
308
+ if (pageList !== undefined)
309
+ features.push('pageBreakMarkers', 'pageNavigation');
310
+ if (visual && described)
311
+ features.push('alternativeText');
312
+ if (math)
313
+ features.push('MathML');
314
+ // An animated image could flash; anything else a book holds can't.
315
+ const animated = files.some((f) => /\.(gif|webp)$/i.test(f.path) || (/\.png$/i.test(f.path) && typeof f.data !== 'string' && hasChunk(f.data, 'acTL')));
316
+ const summary = options.accessibilitySummary ?? [
317
+ headings ? 'The book is structured by its headings, with a table of contents and landmarks' : 'The book has no headings; its table of contents lists its documents',
318
+ pageList !== undefined ? `, and its pages are those of the ${pageList} edition, marked in the text and listed for navigation` : '',
319
+ '.',
320
+ visual ? (described ? ' Its images have text alternatives.' : ' Some of its images have no text alternative.') : '',
321
+ math ? ' Its mathematics is MathML.' : '',
322
+ ].join('');
323
+ return {
324
+ accessModes: visual ? ['textual', 'visual'] : ['textual'],
325
+ accessModesSufficient: visual && !described ? [['textual', 'visual']] : [['textual']],
326
+ features,
327
+ hazards: animated ? ['unknown'] : ['none'],
328
+ summary,
329
+ };
330
+ }
331
+ /** Whether a PNG has a chunk of the type (`acTL`, an animation's). */
332
+ function hasChunk(png, type) {
333
+ const view = new DataView(png.buffer, png.byteOffset, png.byteLength);
334
+ for (let i = 8; i + 8 <= png.length;) {
335
+ const length = view.getUint32(i);
336
+ if (String.fromCharCode(...png.subarray(i + 4, i + 8)) === type)
337
+ return true;
338
+ i += 12 + length;
339
+ }
340
+ return false;
341
+ }
342
+ /**
343
+ * A UUID made from the book's title and language, as RFC 9562's version 5
344
+ * makes one from a name: the same at every build, for a book whose author
345
+ * gave no identifier.
346
+ */
347
+ async function titleUuid(title, language) {
348
+ // The URL namespace's UUID, as RFC 9562 gives it, and the name as a URL of its own.
349
+ const namespace = [0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8];
350
+ const name = new TextEncoder().encode(`https://pulpweaver.inkylabs.com/epub/${encodeURIComponent(language)}/${encodeURIComponent(title)}`);
351
+ const hash = new Uint8Array(await crypto.subtle.digest('SHA-1', new Uint8Array([...namespace, ...name])));
352
+ hash[6] = (hash[6] & 0x0f) | 0x50;
353
+ hash[8] = (hash[8] & 0x3f) | 0x80;
354
+ const hex = [...hash.subarray(0, 16)].map((b) => b.toString(16).padStart(2, '0')).join('');
355
+ return `urn:uuid:${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
356
+ }