# Node API

Use favseed from your own scripts. build() writes the set to disk, buildFiles() returns the bytes, and the portable core exposes the pieces for custom hosts.

## build()

Use named imports from `favseed` in an ES module (`.mjs`, or a project with `"type": "module"`). The default export is the [Astro integration](https://favseed.cevdet.ch/docs/astro).

```js
import { build, FavseedError } from 'favseed'

try {
  const result = await build({
    input: 'src/logo.svg',
    out: 'public',
    bg: '#0E1C28',
    base: '/blog/',
    manifest: { name: 'Example', short_name: 'Ex' },
    onWarn: message => console.warn(message),
  })
  console.log(result.links)
  for (const name of result.files) {
    console.log(name, result.bytes[name])
  }
} catch (error) {
  if (!(error instanceof FavseedError)) throw error
  console.error(error.message)
  process.exitCode = 1
}
```

`build()` writes the complete set into `out`, the working directory by default. It stages and recovers files as described in [How files are written](https://favseed.cevdet.ch/docs/cli#how-files-are-written). Its result contains:

| Field | Value |
|---|---|
| `files` | Filenames in write order. |
| `bytes` | Byte count by filename. |
| `dir` | Absolute output directory, with symlinks resolved. |
| `links` | HTML `<link>` block with `base` applied. |
| `animated` | Whether `icon.svg` preserves animation. |
| `fit` | Placement measurements for `apple` and `icons[size]`; numbered icons have `null` placement with `bg: null`. |
| `quality` | Per raster file (`favicon.ico`, `apple-touch-icon.png`, `icon-<size>.png`): the `setting` chosen, `{ quality, colors }`, and its accuracy-bar measurement, `pct`, `edge` and `pass`. The three are `null` when nothing was gated: effort `fast` with no pinned setting. |

## buildFiles()

To get the generated bytes without writing any files, use `buildFiles()`:

```js
import { buildFiles } from 'favseed'

const result = await buildFiles({
  input: 'src/logo.svg',
  bg: '#0E1C28',
  manifest: true,
  onWarn: message => console.warn(message),
})

for (const { name, bytes } of result.files) {
  // bytes is a Uint8Array, ready for your asset emitter or storage API.
  console.log(name, bytes.byteLength)
}
console.log(result.links)
```

`buildFiles()` returns `files: { name, bytes }[]` plus `links`, `animated`, `fit` and `quality`. It has no `dir` and no separate byte-count map. It still reads `input` from disk and validates the same options as `build()`, including `out` if you supply it.

## Options and errors

Both functions accept the [config options](https://favseed.cevdet.ch/docs/cli#a-config-file) plus `onWarn`. Paths are relative to the process working directory.

They do not discover config files. Import your config and pass it explicitly, for example `build({ ...config, input: 'src/logo.svg', onWarn: console.warn })`.

Warnings are silent unless you supply `onWarn`. Neither function prints a summary or exits the process: await the result and handle a rejected promise in your caller. `FavseedError.message` holds a readable diagnostic.

## TypeScript

The TypeScript exports include `FavseedConfig`, `BuildOptions`, `BuildResult`, `BuildFilesResult` and `Placement`. Node, Vite and Astro share the `ImageOptions` declarations. `vars` accepts an object or a `Map<string, string | number>`.

The declarations check shapes; builds enforce ranges and option combinations at runtime. `defineConfig()` returns its argument unchanged and neither validates it nor fills in defaults. The root and core types work without the optional Astro or Vite peers installed.

## Advanced helpers

Use `build()` or `buildFiles()` for a complete favicon set. These helpers are also available as named imports from `favseed`:

| Export | Contract |
|---|---|
| `optimiseSvg(source, options?)` | Synchronous SVG optimisation; returns `{ data, animated }`. Options are `animation` (default `true`), `vars` and `name`. `animation: false` is the static pass `--no-animation` runs: it strips motion and accessibility. |
| `loadEngine()` | Loads and caches the native engine on first use. Returns a promise for `render`, `renderRgba`, `probe`, `encode`, `decode`, `search` and `finish`. Rendering needs a square SVG with a valid viewBox; encoding, decoding and finishing take PNG bytes. `search(raw, reference, { effort, pinned?, seed?, onProbe? })` is the build's per-raster search for the smallest encode that passes the accuracy bar, against a decoded `reference` (`null` only with effort `fast` or a pinned setting). Each method is asynchronous. |
| `engineVersions()` | Returns the image, Zopfli build and SVGO identities without loading the rendering or SVG optimiser modules. |
| `loadConfigFile(dir?)` | Imports the first config in `dir` (default: the working directory). Returns `{ config, file, ignored }`; filenames are basenames, and `file` is `null` when there is no config. Checks object shape and known keys only. Field values stay `unknown` in TypeScript until narrowed. |
| `CONFIG_FILES` | Config discovery order: `.js`, `.mjs`, `.ts`. Treat this shared array as read-only. |
| `cli(argv)` | Runs CLI parsing and output. Resolves to an exit code on success; errors may terminate the process. Use the build APIs inside an application. |

`optimiseSvg()` performs one configured optimisation. It does not run the full build's measured SVG precision selection, raster encoding or output publishing; use the build APIs for those guarantees.

The engine's `encode()` defaults to quality `100` when you omit it; full builds choose each raster's setting by effort, or use the pinned one. `finish()` uses the iteration count you supply, and `0` skips Zopfli.

```js
import { optimiseSvg } from 'favseed'

const { data, animated } = optimiseSvg(source, {
  vars: { brand: '#123456' },
  animation: false,
})
```

## Portable core

`favseed/core` imports no Node modules or rendering libraries. It exposes these helpers for custom hosts; its declaration file describes the callbacks and return values.

| Export | Contract |
|---|---|
| `createSvgStage({ optimize })` | Inject an SVGO-compatible implementation; returns `{ optimiseSvg }` with the same options and result as the root helper. |
| `normaliseVars(vars?)` | Returns a `Map<string, string>` with `--`-prefixed names and stringified values. |
| `icoWrap(png, px)` | Returns `Uint8Array` ICO bytes for one square PNG. Checks that its dimensions match `px`, from 1 to 256. |
| `maskableFit({ width, height, rgba })` | Measures the mark and returns `{ radius, scale, fullBleed }`; rejects an empty mark. RGBA data has four bytes per pixel. |
| `nestForMask(svg, box, canvas)` | Centres the SVG viewport on a square canvas and returns SVG text. |
| `placeInSafeZone(svg, render, canvas, padding?)` | Returns a promise for `{ svg, box, scale, snapped, radius, fullBleed, padding }`. The renderer supplies transparent RGBA pixels, synchronously or asynchronously. The canvas size must be positive and even; padding defaults to `'auto'`. Unlike the build's placement metadata, this result has no `canvas` field. |
| `squareIconSvg(svg)` | Frames a rectangular viewport; returns `{ data, warning }`, with `warning: null` when no warning applies. |
| `mapImages(items, sizeOf, work, options?)` | Runs image work in a bounded sliding window, in the order given, and returns results in input order. `sizeOf` supplies canvas pixels; `serial: true` runs one at a time. After a failure no item starts, and running items finish before the promise rejects. |
| `linkTags(base?, manifest?)`, `declaresIcon(html)` | Generate the link block, or detect an existing icon link. |
| `manifestIcons({ sizes, base?, purpose? })`, `manifestJson({ sizes, base?, purpose?, extra? })` | Generate icon entries or manifest text. `extra.icons` is replaced with the generated entries. |
| `FavseedError` | The same error class as the root export. |

The low-level link and manifest helpers concatenate `base` as supplied, so include a trailing slash, such as `/blog/`. Full builds normalise `base` for you. The low-level helpers do not apply the full build-option validation.

Core also exports `ICO_SIZE`, `APPLE_SIZE`, `DEFAULT_QUALITY`, `DEFAULT_COLORS`, `DEFAULT_SIZES`, `DEFAULT_BG`, `DEFAULT_EFFORT`, `EFFORT_ITERATIONS`, `ACCURACY_PCT`, `EDGE_GATE`, `SEARCH_QUALITIES`, `SEARCH_COLORS` and `MASK_SAFE_RADIUS`. Treat `DEFAULT_SIZES` as read-only. The current values describe the engine, and output policy can change in a release that allows byte changes. Import through `favseed/core`; other `lib/` paths are package internals.

Full builds normalise variable names in objects and Maps. When you call `optimiseSvg()` directly, pass an object, or normalise a Map with `normaliseVars()` first: that helper's Map path expects keys such as `--brand` and uses them as supplied.
