# jg-render

> Render prepared HTML to exact PNGs in offline Chromium, with verified fonts and images, transparency, and a caller-owned layout check.

- **Version:** `1.0.0`
- **Runtimes:** Node.js
- **Install:** `npm install jg-render`
- **On npm:** [jg-render](https://www.npmjs.com/package/jg-render)
- **Source:** [packages/jg-render](https://github.com/jesusgraterol/jg-packages/tree/main/packages/jg-render)
- **Recipes:** [jg-render recipes](https://jg-packages.jesusgraterol.dev/packages/jg-render/recipes/index.md)

## Usage

`withOfflineRenderer` creates and closes one context for a batch. Chromium itself belongs to the caller. The context disables document JavaScript and service workers, denies network access, reduces motion and renders at one pixel per CSS pixel.

Supply an HTML document with inline styles and data URLs for assets. The renderer waits for declared fonts and decodes image elements. Use the optional layout callback for project-specific checks or adjustments after assets load. Return `'overflow'` from that callback to report a layout that does not fit. The callback receives a live page and should use its caller's cancellation signal for any external work.

Use `renderPng` for PNG bytes and `preparePage` to run a trusted callback on a prepared page, for example to call Playwright's PDF API. Each page closes after its callback settles, times out or is cancelled. A render defaults to 15 seconds and accepts dimensions up to 8192 on either side and a total of 33,554,432 pixels.

## Errors

| Code                          | Message                                |
| ----------------------------- | -------------------------------------- |
| `INVALID_HTML_RENDER_OPTIONS` | The HTML render options are invalid.   |
| `HTML_RENDER_FAILED`          | The HTML could not be rendered to PNG. |

The package's errors carry a fixed `data.reason` without document source, resource URLs or asset bytes. Errors from the caller's session or prepared-page callback propagate to the caller.

## <a id="api-reference"></a>jg-render API reference

Every export of `jg-render@1.0.0`, 6 in all, with its signature, its errors, and an example. It's generated from the package's TSDoc.

- Functions: [`withOfflineRenderer`](#api-withOfflineRenderer)
- Constants: [`ERRORS`](#api-ERRORS)
- Types: [`IHtmlRenderInput`](#api-IHtmlRenderInput), [`IOfflineRenderer`](#api-IOfflineRenderer), [`IOfflineRendererOptions`](#api-IOfflineRendererOptions), [`IRequiredRenderFont`](#api-IRequiredRenderFont)

### <a id="api-functions"></a>Functions

#### <a id="api-withOfflineRenderer"></a>`withOfflineRenderer`

*Function*

Runs one rendering session in a disposable context on caller-owned Chromium. Pages are offline, document JavaScript and service workers are disabled, motion is reduced and the pixel scale is one.

```ts
withOfflineRenderer<T>(
  browser: Browser,
  options: IOfflineRendererOptions,
  work: (renderer: IOfflineRenderer) => Promise<T>,
): Promise<T>
```

**Parameters**

- `browser` `Browser`: The caller's launched Playwright Chromium.
- `options` `IOfflineRendererOptions`: Safe context defaults and optional cancellation.
- `work` `(renderer: IOfflineRenderer) => Promise<T>`: The renders or trusted operations to perform before the session is closed.

**Returns** `Promise<T>`: The caller's result after closing the owned context.

**Throws**

- `INVALID_HTML_RENDER_OPTIONS`: The HTML render options are invalid.
- `HTML_RENDER_FAILED`: The HTML could not be rendered to PNG.

**Example**

```ts
import { chromium } from 'playwright';
import { withOfflineRenderer } from 'jg-render';

const browser = await chromium.launch();
try {
  const png = await withOfflineRenderer(browser, {}, (render) =>
    render.renderPng({
      html: '<!doctype html><svg width="80" height="80"><circle cx="40" cy="40" r="24"/></svg>',
      width: 80,
      height: 80,
      transparent: true,
    }),
  );
  // png contains an 80 by 80 image
  void png;
} finally {
  await browser.close();
}
```

### <a id="api-constants"></a>Constants

#### <a id="api-ERRORS"></a>`ERRORS`

*Constant*

stable public error codes

```ts
const ERRORS: { INVALID_HTML_RENDER_OPTIONS: "INVALID_HTML_RENDER_OPTIONS"; HTML_RENDER_FAILED: "HTML_RENDER_FAILED" }
```

### <a id="api-types"></a>Types

#### <a id="api-IHtmlRenderInput"></a>`IHtmlRenderInput`

*Type*

a prepared HTML document, its exact canvas, and the assets it is expected to use

```ts
type IHtmlRenderInput = {
    html: string;
    width: number;
    height: number;
    requiredFonts?: IRequiredRenderFont[];
    transparent?: boolean;
    colorScheme?: BrowserContextOptions['colorScheme'];
    timeoutMs?: number;
    layout?: (page: Page) => Promise<void | 'overflow'>;
};
```

**Members**

- `html: string` (property)
- `width: number` (property)
- `height: number` (property)
- `requiredFonts: IRequiredRenderFont[]` (property)
- `transparent: boolean` (property)
- `colorScheme: BrowserContextOptions["colorScheme"]` (property)
- `timeoutMs: number` (property)
- `layout: (page: Page) => Promise<void | "overflow">` (property)

#### <a id="api-IOfflineRenderer"></a>`IOfflineRenderer`

*Type*

the browser operations available inside one offline session

```ts
type IOfflineRenderer = {
    preparePage<T>(input: IHtmlRenderInput, usePage: (page: Page) => Promise<T>): Promise<T>;
    renderPng(input: IHtmlRenderInput): Promise<Buffer>;
};
```

**Members**

- `preparePage<T>(input: IHtmlRenderInput, usePage: (page: Page) => Promise<T>): Promise<T>` (method): Prepares a page and passes it to trusted code, such as a PDF producer, until the callback settles.
- `renderPng(input: IHtmlRenderInput): Promise<Buffer<ArrayBufferLike>>` (method): Prepares a page and returns its exact-size PNG bytes.

#### <a id="api-IOfflineRendererOptions"></a>`IOfflineRendererOptions`

*Type*

optional context defaults for trusted callers; offline and pixel settings are owned by the renderer

```ts
type IOfflineRendererOptions = Pick<BrowserContextOptions, 'colorScheme' | 'locale' | 'timezoneId'> & {
    signal?: AbortSignal;
};
```

#### <a id="api-IRequiredRenderFont"></a>`IRequiredRenderFont`

*Type*

each required

```ts
type IRequiredRenderFont = {
    family: string;
    weight?: string;
    style?: string;
};
```

**Members**

- `family: string` (property)
- `weight: string` (property)
- `style: string` (property)
