### Generate EPUB using Main Entry Point Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/README.md Use the main `epub` function for straightforward EPUB generation. It accepts options and chapter data to produce an EPUB buffer. This is the simplest way to get started. ```typescript import epub from 'epub-gen-memory'; const buffer = await epub(options, chapters); ``` -------------------------------- ### Install epub-gen-memory Source: https://github.com/cpiber/epub-gen-memory/blob/master/README.md Install the library using npm and add it as a project dependency. ```shell npm install epub-gen-memory --save ``` -------------------------------- ### Simple Chapter Example Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/02-types.md A basic example of a chapter object with a title and content. This demonstrates the minimum required fields. ```typescript const chapter: Chapter = { title: 'Introduction', content: '
Welcome to the book.
' }; ``` -------------------------------- ### Full Options Configuration Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/02-types.md Example demonstrating how to set all available options for comprehensive EPUB customization. Includes metadata, styling, and advanced generation settings. ```typescript const options: Options = { title: 'Alice in Wonderland', author: ['Lewis Carroll'], publisher: 'Macmillan & Co.', description: 'A classic children\'s novel', cover: 'http://example.com/cover.jpg', tocTitle: 'Contents', tocInTOC: true, numberChaptersInTOC: true, prependChapterTitles: true, date: '2023-01-01', lang: 'en', version: 3, fetchTimeout: 30000, retryTimes: 5, batchSize: 50, ignoreFailedDownloads: false, verbose: true, fonts: [ { filename: 'Merriweather.ttf', url: 'http://...' } ] }; ``` -------------------------------- ### Example Usage of LogFn Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/02-types.md Demonstrates how to implement a custom logging function for the verbose option, including timestamps and message type handling. ```typescript const options: Options = { title: 'My Book', verbose: (type, ...args) => { const timestamp = new Date().toISOString(); if (type === 'warn') { console.error(`[${timestamp}] WARN:`, ...args); } else { console.log(`[${timestamp}] LOG:`, ...args); } } }; ``` -------------------------------- ### HTML Code Sample Example Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/05-html-content-guide.md Display code samples using the code tag for inline code and pre tags for blocks. Styling can enhance readability. ```htmlTo define a function, use the def keyword:
def hello():
print("Hello, World!")
```
--------------------------------
### Chapter Organization with Metadata
Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/README.md
Provides an example of how to structure chapters for an EPUB, including options for placing chapters before the table of contents (TOC) or excluding them from the TOC.
```typescript
const chapters = [
{ title: 'Preface', content: '...', beforeToc: true }, // Before TOC
{ title: 'Chapter 1', content: '...' }, // Normal
{ title: 'Appendix', content: '...', excludeFromToc: true } // No TOC entry
];
```
--------------------------------
### Generate EPUB with Options Object
Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/01-api-reference.md
This example demonstrates generating an EPUB with detailed options, including title, author, publisher, cover image URL, EPUB version, and verbose logging. Ensure all provided options are correctly formatted.
```typescript
import epub from 'epub-gen-memory';
const options = {
title: 'Alice in Wonderland',
author: 'Lewis Carroll',
publisher: 'Macmillan & Co.',
cover: 'http://example.com/cover.jpg',
version: 3,
verbose: true
};
const content = [
{
title: 'Down the Rabbit Hole',
content: 'Alice was beginning to get very tired...
' } ]; const epubBuffer = await epub(options, content); ``` -------------------------------- ### Font Example Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/02-types.md Shows how to configure font options for an EPUB, including specifying filenames and URLs for multiple fonts, and providing custom CSS. This configuration is passed to the epub() function via the Options object. ```typescript const options: Options = { title: 'Styled Book', fonts: [ { filename: 'Merriweather.ttf', url: 'https://fonts.example.com/Merriweather.ttf' }, { filename: 'Courier.ttf', url: 'https://fonts.example.com/Courier.ttf' } ], css: " @font-face { font-family: 'Merriweather'; src: url(./fonts/Merriweather.ttf); } body { font-family: 'Merriweather', serif; } " }; ``` -------------------------------- ### Minimal Options Configuration Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/02-types.md Example of providing only the required `title` field for EPUB generation. Other fields will use their default values. ```typescript const options: Options = { title: 'My Book' }; ``` -------------------------------- ### Get Default EPUB Options Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/03-configuration.md Retrieve the default configuration options for EPUB 3 or EPUB 2. These defaults can be used as a base for custom configurations. ```typescript import { optionsDefaults } from 'epub-gen-memory'; const defaults = optionsDefaults(3); // EPUB 3 defaults const defaults2 = optionsDefaults(2); // EPUB 2 defaults ``` -------------------------------- ### Configure Fetch Timeout for Large Resources Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/04-errors.md This example shows how to set a `fetchTimeout` option, which can be exceeded if a resource is very large or the server is slow. Increase the timeout or use `ignoreFailedDownloads` to prevent errors. ```typescript const options = { title: 'My Book', fetchTimeout: 5000, // 5 seconds (short!) cover: 'http://example.com/large-cover.jpg' // 10MB file }; await epub(options, chapters); // May timeout ``` -------------------------------- ### optionsDefaults() Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/01-api-reference.md Returns default options for EPUB generation. This function can be used to get a base set of options that can then be customized. ```APIDOC ## optionsDefaults() ### Description Returns default options for EPUB generation. ### Signature ```typescript optionsDefaults(version?: number): OmitChapter content here
' } ]; const buffer = await epub('My Book', content); // Save to file (Node.js) import { writeFile } from 'fs/promises'; await writeFile('book.epub', buffer); ``` -------------------------------- ### Content Example Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/02-types.md Illustrates how to define book content using the Content type, including chapters with titles and HTML content. This structure is passed to the epub() function. ```typescript const content: Content = [ { title: 'Preface', content: 'Preface text
', beforeToc: true }, { title: 'Chapter 1', content: 'Chapter 1 content
' }, { title: 'Chapter 2', content: 'Chapter 2 content
' } ]; const buffer = await epub('My Book', content); ``` -------------------------------- ### Get EPUB Options Defaults Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/01-api-reference.md Use `optionsDefaults` to retrieve default configuration options for EPUB generation. You can specify the EPUB version (2 or 3) to get version-specific defaults. The returned object omits the `title` field, which must be provided separately. ```typescript import { optionsDefaults } from 'epub-gen-memory'; const defaults = optionsDefaults(2); // EPUB 2 defaults const customOptions = { ...defaults, title: 'My Book', author: 'Jane Doe' }; ``` -------------------------------- ### optionsDefaults([version]) Source: https://github.com/cpiber/epub-gen-memory/blob/master/README.md Retrieves the default options for EPUB generation. An optional version number can be provided to get defaults specific to EPUB 2 or 3. ```APIDOC ## optionsDefaults([version]) ### Description Returns the default configuration options for EPUB generation. ### Parameters - **version** (`number`, optional, default `3`): The EPUB version (2 or 3) for which to retrieve defaults. ### Returns - `Options`: An object containing the default options. ``` -------------------------------- ### Manage Retry Exhaustion for Unreliable Resources Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/04-errors.md This example configures `retryTimes` for fetching resources. If all retries fail due to network issues or server unavailability, an error will be thrown. Adjust `retryTimes` or `ignoreFailedDownloads`. ```typescript const options = { title: 'My Book', retryTimes: 3, // Try 3 times total cover: 'http://example.com/unreachable.jpg' // Network error }; await epub(options, chapters); // Logs "Failed to fetch `http://...` 1 time. Retrying..." // Logs "Failed to fetch `http://...` 2 times. Retrying..." // Throws on 3rd attempt ``` -------------------------------- ### Handle HTTP Error Responses During Download Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/04-errors.md This example demonstrates setting options that may lead to an HTTP error response if the provided URLs are invalid or inaccessible. Verify URLs and consider `ignoreFailedDownloads`. ```typescript const options = { title: 'My Book', cover: 'http://example.com/missing-cover.jpg' // 404 }; const chapters = [ { title: 'Ch1', content: '
' // 404
}
];
await epub(options, chapters); // Throws during image download
```
--------------------------------
### Chapter with Author and URL
Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/02-types.md
An example of a chapter object including optional fields like `author` and `url`. The `beforeToc` field is used to place this chapter before the table of contents.
```typescript
const chapter: Chapter = {
title: 'About the Author',
author: 'John Smith',
content: 'John is an author...
', url: 'https://johnsmith.com', beforeToc: true // Put before table of contents }; ``` -------------------------------- ### Inline CSS Styling for HTML Elements Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/05-html-content-guide.md Provides examples of applying CSS styles directly to HTML elements using the `style` attribute for properties like font-weight, color, text-decoration, text-align, and margin. ```htmlBold text
UnderlinedCh1
', beforeToc: false }, { title: 'Preface', content: 'Preface
', beforeToc: true } // Should be first! ]; await epub('My Book', chapters, true); // Logs: "Warning (content[1]): Got `beforeToc=true` after at least one `beforeToc=false`. ..." ``` -------------------------------- ### Handle File Read Errors for Local Resources (Node.js) Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/04-errors.md This example illustrates a scenario where a local file specified with a `file://` URL cannot be read, typically due to incorrect paths or permissions. Ensure the path is correct and accessible. ```typescript const options = { title: 'My Book', // Node.js only cover: 'file:///absolute/path/to/missing-cover.jpg' }; await epub(options, chapters); // Throws ``` -------------------------------- ### Instantiate EPub Class Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/01-api-reference.md Use this constructor to create an EPub instance for manual control over the EPUB generation process. Provide configuration options and an array of chapters. ```typescript import { EPub } from 'epub-gen-memory'; const options = { title: 'My Book', author: 'John Doe' }; const chapters = [ { title: 'Introduction', content: 'Welcome
' } ]; const epub = new EPub(options, chapters); const buffer = await epub.genEpub(); ``` -------------------------------- ### Original HTML Image Tag Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/05-html-content-guide.md Example of an original HTML image tag before processing. ```html
``` -------------------------------- ### Processed HTML Image Tag in EPUB Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/05-html-content-guide.md Example of an HTML image tag after processing and embedding within an EPUB. ```html"The only way to do great work is to love what you do."
— Steve Jobs
Welcome
' } ]; const epub = new EPub(options, chapters); const buffer = await epub.genEpub(); ``` ### Response None ### Response Example None ``` -------------------------------- ### EPUB Generation Data Flow Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/06-module-architecture.md Illustrates the step-by-step process of generating an EPUB file, from initial options and chapters to final file creation and zipping. It highlights key internal functions and data transformations. ```mermaid graph TD epub(options, chapters) ↓ validateIsOptionsOrTitle() + validateIsChapters() ↓ new EPub(options, content) ↓ (constructor) validateAndNormalizeOptions() → NormOptions validateAndNormalizeChapters() → NormChapter[] (images, fonts extracted from content) ↓ await epub.render() ↓ (for each chapter) normalizeHTML() → fixHTML() (parse + validate) → register images for download → return sanitized HTML ↓ await downloadAllFonts() → batch by batchSize → retryFetch() each → write to zip: OEBPS/fonts/ ↓ await downloadAllImages() → batch by batchSize → retryFetch() each → write to zip: OEBPS/images/{uuid}.{ext} ↓ await makeCover() → retryFetch() cover image → write to zip: OEBPS/cover.{ext} ↓ await generateTemplateFiles() → render chapter files via EJS → render content.opf (manifest) → render toc.ncx (EPUB 2 nav) → render toc.xhtml (EPUB 3 nav) → write style.css → write META-INF/container.xml ↓ await genEpub() → (calls render()) → zip.generateAsync() → return Buffer | Blob ``` -------------------------------- ### Import epub-gen-memory using the browserify bundle Source: https://github.com/cpiber/epub-gen-memory/blob/master/README.md Import the UMD bundle for browser usage. The bundle also provides a PromiseOnce upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore—``` ```html
Once upon a midnight dreary,
while I pondered, weak and weary,
Over many a quaint and curious
volume of forgotten lore—
T he story begins...
``` -------------------------------- ### HTML Footnote/Side Note Example Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/05-html-content-guide.md Implement footnotes or side notes using spans for superscripts and styled paragraphs or aside elements for the note content. ```htmlThis is main text[1].
[1] This is a footnote.
``` ```htmlMain paragraph.
``` -------------------------------- ### Browser Bundle Creation Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/06-module-architecture.md Creates a UMD bundle for browsers using browserify, excluding specific entry points, and then minifies it with terser. This process includes mangling and compression for optimization. ```bash browserify -e ./dist/lib/SharedArrayBufferStub.js -e ./dist/lib/index.js ``` ```bash terser --mangle --compress ``` -------------------------------- ### Generate EPUB using EPub Class Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/README.md Instantiate the `EPub` class for more control over the EPUB generation process. This approach allows for creating an EPUB object with specific options and chapters, then calling `genEpub` to create the buffer. Requires importing `EPub`, `optionsDefaults`, and `chapterDefaults`. ```typescript import { EPub, optionsDefaults, chapterDefaults } from 'epub-gen-memory'; const epub = new EPub(options, chapters); const buffer = await epub.genEpub(); ``` -------------------------------- ### EPub.prototype.genEpub() Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/01-api-reference.md Completes the EPUB generation pipeline by calling `render()` internally and then generating the final ZIP archive. ```APIDOC ## EPub.prototype.genEpub() ### Description Complete EPUB generation pipeline. Calls `render()` internally, then generates the final ZIP archive. ### Method `async genEpub(): PromiseText
', filename: 'chapters/ch1.xhtml' // Slashes not allowed }; await epub('My Book', [chapter]); // Throws ``` -------------------------------- ### epub() function Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/MANIFEST.txt The main entry point for generating EPUB files. This function orchestrates the entire process, taking options and content to produce a valid EPUB. ```APIDOC ## epub() ### Description Generates an EPUB file from provided options and content. ### Method ``` function epub(options, content) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (Options) - Required - Configuration object for EPUB generation. - **content** (Chapter[]) - Required - An array of chapter objects defining the EPUB content. ### Request Example ```json { "options": { "version": 3, "title": "My EPUB", "author": "Me" }, "content": [ { "title": "Introduction", "html": "This is the introduction.
" } ] } ``` ### Response #### Success Response (200) - **epubFilePath** (string) - The path to the generated EPUB file. #### Response Example ```json { "epubFilePath": "/path/to/my-epub.epub" } ``` ``` -------------------------------- ### Manual EPUB Control with EPub Class Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/07-quick-start-examples.md Use the EPub class for manual control over the EPUB generation process, including explicit rendering and saving steps. ```typescript import { EPub } from 'epub-gen-memory'; const options = { title: 'Manual EPUB', verbose: true }; const chapters = [ { title: 'Ch1', content: 'Text
' } ]; // Create instance const epubInstance = new EPub(options, chapters); // Manually control rendering console.log('Starting render...'); await epubInstance.render(); console.log('Render complete, fonts and images downloaded'); // Generate final EPUB const buffer = await epubInstance.genEpub(); console.log('EPUB generation complete'); // Save import { writeFile } from 'fs/promises'; await writeFile('manual.epub', buffer); ``` -------------------------------- ### Get Chapter Defaults Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/01-api-reference.md Use `chapterDefaults` to obtain default values for a chapter object. Provide the zero-based index of the chapter to generate default `title` and `id` properties. ```typescript import { chapterDefaults } from 'epub-gen-memory'; const ch = chapterDefaults(0); // { title: 'Chapter 1', id: 'item_0', url: '', excludeFromToc: false, beforeToc: false } ``` -------------------------------- ### Set EPUB Version to 3 (Recommended) Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/03-configuration.md Use the modern EPUB 3 standard for new projects. It supports XHTML 5, toc.xhtml navigation, and offers better media and font support. ```typescript const options = { title: 'My Book', version: 3 // default }; ``` -------------------------------- ### Logging Progress with Verbose Option Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/README.md Shows how to enable detailed logging during the EPUB generation process by providing a verbose callback function in the options. This function will be called with log type and arguments. ```typescript const options = { title: 'My Book', verbose: (type, ...args) => { console.log(`[${type}]`, ...args); } }; ``` -------------------------------- ### Core Classes Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/README.md Instantiate the EPub class with options and chapters to generate an EPUB. The genEpub method returns a Promise resolving to the EPUB data. ```typescript import { EPub, optionsDefaults, chapterDefaults } from 'epub-gen-memory'; const epubInstance = new EPub(options, chapters); const buffer = await epubInstance.genEpub(); ``` -------------------------------- ### Remove Image Tag with Missing Source Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/04-errors.md This example demonstrates the removal of an image tag that lacks a 'src' attribute. The tag is silently removed, and the EPUB generation proceeds without the incomplete image element. ```typescript const chapters = [ { title: 'Ch1', content: 'Text more text
Text more text
``` -------------------------------- ### Import epub-gen-memory for environments without SharedArrayBuffer Source: https://github.com/cpiber/epub-gen-memory/blob/master/README.md Use this import if SharedArrayBuffer is not available in your environment. It includes a non-functional stub. ```javascript import epub from 'epub-gen-memory/sabstub'; ``` -------------------------------- ### Invalid Font Object Example Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/04-errors.md Illustrates an invalid font object within the options, leading to a TypeError. Each font object must include both 'url' and 'filename' as strings, with 'filename' free of path separators. ```typescript const options = { title: 'My Book', fonts: [ { // url missing! filename: 'MyFont.ttf' } ] }; await epub(options, chapters); // Throws ``` -------------------------------- ### EPub.prototype.render() Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/01-api-reference.md Generates all template files, downloads fonts and images, and prepares the cover. This method is called automatically by `genEpub()` but can be invoked separately for manual control. ```APIDOC ## EPub.prototype.render() ### Description Generates all template files, downloads fonts and images, and prepares the cover. This is called automatically by `genEpub()`, but can be called separately for manual control. ### Method `async render(): PromiseText
' // aside not in XHTML 1.1 } ]; const options = { title: 'My Book', version: 2 }; await epub(options, chapters, true); // Logs: "Warning (content[0]): tag aside isn't allowed in EPUB 2/XHTML 1.1 DTD." // Results in:End of Chapter 1
``` -------------------------------- ### Custom Styling with CSS Option Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/README.md Illustrates how to apply custom CSS styling to the generated EPUB by providing a CSS string in the options. This allows for fine-grained control over the appearance of the book. ```typescript const options = { title: 'My Book', css: `body { font-family: Georgia, serif; }` }; ``` -------------------------------- ### Generate EPUB with Uploaded Cover Image Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/07-quick-start-examples.md Generates an EPUB using an image file uploaded by the user as the cover. The generated EPUB is then saved to the user's device. ```html ``` -------------------------------- ### Advanced ZIP Generation with generateAsync Source: https://github.com/cpiber/epub-gen-memory/blob/master/_autodocs/01-api-reference.md For advanced control over ZIP generation, use `generateAsync()`, which delegates to JSZip's `generateAsync()` method. This is useful for custom workflows and allows specifying options like type, mimeType, and compression. ```typescript const epub = new EPub(options, content); await epub.render(); const buffer = await epub.generateAsync({ type: 'nodebuffer', mimeType: 'application/epub+zip', compression: 'DEFLATE' }); ``` -------------------------------- ### Options Schema Source: https://github.com/cpiber/epub-gen-memory/blob/master/README.md Defines the available configuration options for EPUB generation, including title, author, cover, TOC settings, and more. ```APIDOC ## Options ### Properties - **title** (`string`): Title of the book. - **author** (`string | string[]`, optional, default `['anonymous']`): Name of the author(s). - **publisher** (`string`, optional, default `anonymous`): Publisher name. - **description** (`string`, optional): Book description. - **cover** (`string | File`, optional): URL or File object for the book cover image. - **tocTitle** (`string`, optional, default `Table of Contents`): Title for the Table of Contents. - **tocInTOC** (`boolean`, optional, default `true`): Whether to include the TOC entry in the reader's TOC (EPUB2 only). - **numberChaptersInTOC** (`boolean`, optional, default `true`): Automatically number TOC entries. - **prependChapterTitles** (`boolean`, optional, default `true`): Prepend chapter titles before content. - **date** (`string`, optional, default today): Publication date. - **lang** (`string`, optional, default `en`): Language code of the book. - **css** (`string`, optional): Custom CSS string to replace default styles. - **fonts** (`Font[]`, optional): Array of fonts to include in the EPUB. - **version** (`number`, optional, default `3`): EPUB version (2 or 3). - **fetchTimeout** (`number`, optional, default `20000`): Timeout for resource fetching in milliseconds. - **retryTimes** (`number`, optional, default `3`): Number of times to retry fetching resources. - **batchSize** (`number`, optional, default `100`): Batch size for downloading files. - **ignoreFailedDownloads** (`boolean`, optional, default `false`): Ignore errors during downloads and write empty files instead. - **verbose** (`boolean | ((type, ...args) => void)`, optional, default `false`): Enable verbose logging or provide a custom logging function. ```