# @ferret/assets: API

Loading and caching of glTF, KTX2 and packed assets, `.ferret` packages and their security checks.

345 exports. Generated from the source (`packages/assets/src`), so it matches the code.

## Classes

### AssetCache

*class* · `packages/assets/src/cache.ts:32`

```ts
class AssetCache
```

Loads glTF/GLB models once and hands out instances. The source stays in memory (not in the scene) while anything uses it;
each instance is its own copy of the nodes, skeletons and animation groups, with materials and geometry shared.
A URL, a `data:` URL, a blob URL or a File all work. Reference counting: `release` the url when the level that asked for it goes.

- `onProgress?: (p: LoadProgress) => void` — Called with the bytes loaded so far, for a loading screen.
- `constructor(readonly scene: BABYLON.Scene)`
- `get size(): number`
- `has(url: string): boolean`
- `refs(url: string): number`
- `async load(url: string, ext = guessExt(url)): Promise<void>` — Load (or reuse) a model and take a reference to it.
- `async preload(urls: string[]): Promise<void>` — Load several models; resolves when all are in.
- `async instantiate(url: string, name?: string): Promise<ModelInstance>` — A new copy of a loaded model in the scene. The model must have been loaded (`load`).
- `release(url: string): void` — Drop one reference; at zero the source and its instances are freed.
- `dispose(): void`

### AssetStore

*class* · `packages/assets/src/store.ts:69`

```ts
class AssetStore
```

- `constructor(o: StoreOptions = {})`
- `resolve(ref: string): string` — Resolve a ref to an absolute URL and check the rules of section 6. Throws StreamError('origin').
- `require(ref: string, opts: RequireOptions = {}): Promise<Handle>`
- `prefetch(refs: string[], opts: RequireOptions = {}): void` — Ask for files nobody waits for. Failures are kept in `status`, not thrown.
- `stats(): { queued: number; loading: number; done: number; failed: number; bytes: number }` — What the store holds and is doing now: files by state and the bytes in them (for `stream.status`).
- `status(ref: string): StoreStatus`
- `plan(refs: { ref: string; size?: number }[]): { bytes: number; files: number; cached: boolean }` — What asking for these refs would download now: files not yet held, their bytes (sizes given by the caller).
- `release(ref: string): void`
- `progress(group: string): StreamProgress`
- `onProgress(fn: (group: string, p: StreamProgress) => void): () => void`
- `cancelGroup(group: string): void` — Abort everything queued or running that belongs to a group (a travel to another level).
- `async byteSource(ref: string, o: { block?: number; maxBlocks?: number; signal?: AbortSignal } = {}): Promise<ByteSource>` — A ByteSource over a URL read through the store: blocks of `block` bytes (read-ahead merges neighbouring ranges), kept in memory, retried like any file. `FerretPackage.open(source)` then costs the bytes of the entries it reads, not the package.
- `get cache(): PersistentCache | undefined` — The persistent cache this store writes to, if any.
- `async fetchFresh(ref: string, o: { signal?: AbortSignal } = {}): Promise<Uint8Array>` — A mutable file (a catalog, an index): always asked of the server, never from the cache, retried like any file. Not queued, because what a travel needs next must not wait behind downloads.
- `keep(key: string, bytes: Uint8Array, meta: { pkg?: string; version?: string; url?: string } = {}): void` — Keep verified bytes under their hash (or another key) in the persistent cache. Never fails the caller: a full or broken cache is only a missed saving.
- `async flushCache(): Promise<void>` — Resolves when every cache write started so far has finished (tests, and before the page is suspended).
- `cacheInfo(): Promise<CacheInfo | null>`
- `pin(pkg: string): void`
- `unpin(pkg: string): void`
- `async pinPack(name: string, files: { ref: string; sha256: string; size?: number }[], o: { priority?: StreamPriority; signal?: AbortSignal } = {}): Promise<{ ok: number; missing: string[] }>` — A pack of files the game wants always on the device (a transition's images, videos, sounds): fetched at low priority, kept in the cache under the pack's name and pinned there, so the wait of a travel never depends on the network for them. Returns what could not be fetched; `status(ref)` tells later whether one is there.
- `async clear(pkg?: string): Promise<void>` — Forget downloaded content: one package, or everything.

### CacheStorageBackend

*class* · `packages/assets/src/persist.ts:24`

```ts
class CacheStorageBackend implements CacheBackend
```

Cache Storage (`caches`): browsers and the Android WebView. A synthetic URL per key.

- `readonly name: "cache-storage"`
- `constructor(private readonly cache: Cache, private readonly origin = 'https://ferret-cache.invalid/')`
- `static async open(caches: CacheStorage, name = 'ferret-assets'): Promise<CacheStorageBackend>`
- `async get(k: string)`
- `async put(k: string, b: Uint8Array)`
- `async delete(k: string)`
- `async keys()`

### CatalogError

*class* · `packages/assets/src/catalog.ts:136`

```ts
class CatalogError extends Error
```

- `constructor(public readonly code: CatalogFailure, message: string, public readonly issues: PackageIssue[] = [])`

### ChunkedBackend

*class* · `packages/assets/src/persist.ts:64`

```ts
class ChunkedBackend implements CacheBackend
```

Splits big values into parts: Chromium refused a single Cache Storage entry above 128 MB (S0). A value of at most `chunk` bytes is
stored as is; a bigger one as parts `key~0..n` and then a small record `key!m`. The record is written last, so a cut write leaves
no half value visible (the orphan parts are removed by `sweep`).

- `constructor(private readonly inner: CacheBackend, private readonly chunk = 32 * 1048576)`
- `get name()`
- `async get(k: string)`
- `async put(k: string, b: Uint8Array)`
- `async delete(k: string)`
- `async keys()` — Logical keys only.
- `async sweep()` — Remove parts whose record is missing (a write that was cut).

### FerretPackage

*class* · `packages/assets/src/package.ts:544`

```ts
class FerretPackage
```

- `readonly libraryVersion?: string` — the number a library catalog gave the file, when it was opened from one that numbers its files
- `get source(): PackageSource` — the files as they can be read now: decrypted once the package is unlocked
- `get encrypted(): boolean`
- `get dirty(): boolean` — the changes made through `draft()` that are not packed yet
- `draft(): PackageDraft` — Start editing: from now on this package reads through a draft, so writes (`draft().set(path, data)`) show in everything that reads the package (a mounted level reloads with them). `pack` writes the result.
- `async appendSave(base: ByteSource): Promise<{ at: number; tail: Uint8Array; dead: number; changed: string[]; commit(): void }>` — Save a project (`.fprj`) by appending: the files changed through `draft()` since the last save are written after the last byte of the file `base` (the package as it stands on disk, the bytes it was opened from plus the tails appended since), then a new directory and end record. Write `tail` at offset `at`, flush, then call `commit()`; a save cut off anywhere leaves the previous content. `dead` is the share of the file the saves left unused, so a tool can `compactZip` above a half. A project holds no hashes or signature, so nothing else changes. Only a project may be saved this way; any other package is written whole by `pack`.
- `async pack(o: PackOptions = {}): Promise<{ bytes: Uint8Array; manifest: PackageManifest }>` — Build the `.ferret` bytes of the package as it is now. An encrypted package is sealed again with the password or key it was unlocked with (pass `decrypt` for plain files, `encrypt` for another key). The old signature does not survive a change: pass `sign` to sign the new package.
- `get locked(): boolean` — encrypted and the key not given yet: the names can be listed, the files cannot be read
- `static async open(input: PackageInput, o: { fetch?: typeof fetch; /** the file's name (a Blob has none; a URL string is its own): `.fex` must be a game and `.fprj` a project */ fileName?: string } & Partial<KeyInput> = {}): Promise<FerretPackage>` — Open a package: a `.ferret` file (a Blob or File, bytes, or a URL — read by range requests when the server allows), or a folder (a URL ending in `/`, or a PackageSource). Fails when `ferret.json` is missing or invalid.
- `async unlock(input: KeyInput): Promise<void>` — Give the password or key of an encrypted package. Throws WrongKeyError when it does not fit.
- `get id(): string`
- `get version(): string`
- `has(path: string): boolean`
- `read(path: string): Promise<Uint8Array>`
- `async readText(path: string): Promise<string>`
- `async readJson<T = unknown>(path: string): Promise<T>`
- `levels(): string[]` — Ids of the levels: those `provides` names, else every `levels/<id>/manifest.json`.
- `get hasCode(): boolean` — Does the package hold code? (kinds `assets` and `levels` must not.)
- `get codeEntry(): string | undefined` — The module the code loader runs: `code.entry`, else a game's `entry.code`; undefined when the package names none.
- `info(): PackageInfo`
- `async verify(o: { trusted?: Iterable<string>; checksums?: boolean } = {}): Promise<VerifyResult>` — Is the signature there, does it match, and is the key one the reader trusts? (default true) also reads every file and compares it with the manifest, which needs the package unlocked. Unsigned is not a failure here: says so, and what to do about it is the reader's decision.
- `async codeAllowed(policy: CodePolicy = {}): Promise<{ allowed: boolean; reason?: string }>` — May this package's code run? Packages without code always can. Otherwise the code must come from the game's own origin, or the package must carry a valid signature (from a trusted key, if the reader keeps a list). Returns the reason when it may not.
- `async validate(o: { checksums?: boolean; engine?: EngineVersions; engineRequired?: boolean } = {}): Promise<PackageIssue[]>` — Check the package: the manifest, that the files it names exist, that kinds without code hold none, and (`checksums`, default true when the manifest has them) that every file has the sha256 the manifest gives. References between levels and assets are checked by `@ferret/levels` (`validatePackage`), which knows the level manifest.

### IndexedDbBackend

*class* · `packages/assets/src/persist.ts:36`

```ts
class IndexedDbBackend implements CacheBackend
```

IndexedDB blobs: one record per key.

- `readonly name: "indexeddb"`
- `static open(idb: IDBFactory, name = 'ferret-assets'): Promise<IndexedDbBackend>`
- `async get(k: string)`
- `async put(k: string, b: Uint8Array)`
- `async delete(k: string)`
- `async keys()`

### LockedError

*class* · `packages/assets/src/package.ts:525`

```ts
class LockedError extends Error
```

Opening an encrypted package without its key, or reading a file of it.

- `constructor(m = 'the package is encrypted: give its password or key (unlock)')`

### MemoryBackend

*class* · `packages/assets/src/persist.ts:14`

```ts
class MemoryBackend implements CacheBackend
```

- `readonly name: "memory"`
- `async get(k: string)`
- `async put(k: string, b: Uint8Array)`
- `async delete(k: string)`
- `async keys()`

### PackageDraft

*class* · `packages/assets/src/package.ts:478`

```ts
class PackageDraft implements PackageSource
```

A package kept in memory, with changes on top of another source: what the editor works on and `pack` writes.

- `readonly kind: "memory"`
- `constructor(readonly base: PackageSource | null = null)`
- `get changed(): string[]` — the paths changed (written or deleted) since the last `commit`
- `get dirty(): boolean`
- `commit(): void` — Remember that everything now in the draft is kept somewhere (appended to the file): `changed` and `dirty` start again from nothing. The files stay readable.
- `list(): string[]` — every file path (the manifest included)
- `has(p: string): boolean`
- `size(p: string): number` — bytes of the file in the package (uncompressed); 0 when unknown
- `async read(p: string): Promise<Uint8Array>`
- `set(path: string, data: Uint8Array | string): void`
- `delete(path: string): void`

### PackageSet

*class* · `packages/assets/src/package.ts:872`

```ts
class PackageSet
```

The packages that are open together, so `ferret://<id>/<path>` and `dependencies` resolve.

- `add(pkg: FerretPackage): this`
- `remove(id: string): void`
- `get(id: string): FerretPackage | undefined`
- `get all(): FerretPackage[]`
- `resolve(ref: string, from: FerretPackage, base = ''): { pkg: FerretPackage; path: string } | null` — Where a reference points: `ferret://id/path` in another package (which must be a declared dependency of `from`), or a path inside `from`.
- `deps(pkg: FerretPackage, seen = new Set<string>()): DependencyReport[]` — `pkg.deps`: every dependency of a package, found or not, and whether its version fits (and, down the tree, theirs).

### PersistentCache

*class* · `packages/assets/src/persist.ts:133`

```ts
class PersistentCache
```

- `constructor(readonly backend: CacheBackend, private readonly o: PersistentCacheOptions = {})`
- `async flush(): Promise<void>`
- `async has(key: string): Promise<boolean>`
- `async get(key: string): Promise<Uint8Array | null>`
- `async put(key: string, bytes: Uint8Array, meta: { pkg?: string; version?: string; url?: string } = {}): Promise<void>` — Keep verified bytes. The blob goes in first and the index after it, so an interrupted write leaves a blob the index does not know (swept later) and never an entry without bytes. Makes room by evicting the least recently used unpinned packages once; throws QuotaError when that is not enough.
- `pin(pkg: string): void`
- `unpin(pkg: string): void`
- `async clear(pkg?: string): Promise<void>`
- `async info(): Promise<CacheInfo>`
- `async putPartial(key: string, bytes: Uint8Array, etag: string): Promise<void>` — Keep what arrived of a file the network cut, with the validator the server gave, so a later session can resume it.
- `async getPartial(key: string): Promise<{ bytes: Uint8Array; etag: string } | null>`
- `async dropPartial(key: string): Promise<void>`
- `async cleanPartials(): Promise<void>` — Remove old partial files and blobs that no index knows (a write cut between the blob and the index).
- `static async requestPersistence(storage: Pick<StorageManager, 'persist' | 'persisted'> | undefined = (globalThis as { navigator?: Navigator }).navigator?.storage): Promise<boolean>` — Ask the browser not to drop the cache under pressure; call it after the first level loaded.

### QuotaError

*class* · `packages/assets/src/persist.ts:119`

```ts
class QuotaError extends Error
```

- `constructor(public readonly needed: number)`

### Sha256

*class* · `packages/assets/src/sha256.ts:11`

```ts
class Sha256
```

- `update(data: Uint8Array): this`
- `hex(): string` — The digest as hex. The hasher is spent afterwards.

### StreamError

*class* · `packages/assets/src/stream-error.ts:6`

```ts
class StreamError extends Error
```

- `constructor(public readonly ref: string, public readonly reason: StreamFailure, message: string, public readonly status?: number)`

### WrongKeyError

*class* · `packages/assets/src/security.ts:136`

```ts
class WrongKeyError extends Error
```

- `constructor(m = 'wrong password or key')`

### ZipWriter

*class* · `packages/assets/src/zip.ts:305`

```ts
class ZipWriter
```

A zip written to a sink as it goes, so a package bigger than memory (a streamed level of several GB) is written to a file one file at a time. Same records as
`writeZip` (sorted by the caller, no dates, the same bytes every time); the directory goes at the end, in zip64 form when it must (offsets past 4 GB, over 65534
files). One file is held whole while it is written, so it is under 4 GB. `sink` is called in order and awaited.

- `constructor(private readonly sink: (chunk: Uint8Array) => void | Promise<void>)`
- `get size(): number` — the bytes written so far
- `async add(f: ZipFile): Promise<ZipEntryInfo>`
- `async finish(): Promise<number>` — write the directory and the end; returns the size of the whole file

## Functions

### appendToZip

*function* · `packages/assets/src/zip.ts:345`

```ts
async function appendToZip(src: ByteSource, changes: { set?: ZipFile[]; remove?: string[] }): Promise<{ at: number; tail: Uint8Array; entries: Map<string, ZipEntryInfo>; dead: number }>
```

Change a zip by appending: the new and changed files are written after the last byte, then a new directory that
lists every live file, then a new end record. Nothing before them is touched, so the cost of a save is the size of the change, not of the
project, and a save cut off at any byte leaves the previous directory the last complete one (`readZipDirectory` finds it). Replaced and
removed files stay in the file as dead bytes until `compactZip`. Write `tail` at offset `at` (the size of the file now), then flush.
`dead` is the share of the file that no directory entry uses.

### bindLodNames

*function* · `packages/assets/src/lod-names.ts:15`

```ts
function bindLodNames(root: BABYLON.TransformNode, scene: BABYLON.Scene): number
```

`root`'s nodes named by level: shows one level of each group and keeps choosing it while the root lives. Returns the number of groups found.

### blobSource

*function* · `packages/assets/src/zip.ts:15`

```ts
function blobSource(blob: Blob): ByteSource
```

### buildCatalog

*function* · `packages/assets/src/catalog.ts:376`

```ts
async function buildCatalog(i: BuildCatalogInput): Promise<{ catalog: Catalog; files: Record<string, Uint8Array> }>
```

`pkg.catalog` + `pkg.publish`: the catalog, and the files to put on the server, as { path: bytes }.

### bytesSource

*function* · `packages/assets/src/zip.ts:18`

```ts
function bytesSource(bytes: Uint8Array): ByteSource
```

### canonicalJson

*function* · `packages/assets/src/model-resolve.ts:140`

```ts
function canonicalJson(v: unknown): string
```

JSON with the keys sorted and no whitespace: the same value always gives the same text.

### canonicalManifest

*function* · `packages/assets/src/security.ts:71`

```ts
function canonicalManifest(m: object): Uint8Array
```

The bytes that are signed: the manifest without its signature, as JSON with sorted keys.

### catalogAtVersion

*function* · `packages/assets/src/catalog.ts:78`

```ts
function catalogAtVersion(c: Catalog, pkgId: string, version: string = DEFAULT_REF_VERSION): Catalog
```

The catalog seen at one version of a package: the package's entry is that version's (what `openCatalogPackage` opens).

### catalogLoader

*function* · `packages/assets/src/model-resolve.ts:82`

```ts
function catalogLoader(store: AssetStore, catalogs: Catalog[], pins: Record<string, string> = {}): ModelLoader
```

A loader over catalogs (the `catalogs` a package names, in order): the package is opened through the store's cache and its files are checked against the
catalog's hashes. The file is the one the range asks for (`packageForRange`: an exact version is held, however many newer ones there are); `pins` are ranges
that go before the asked one (the exact dependencies of the game that is loading).

### checkCatalog

*function* · `packages/assets/src/catalog.ts:228`

```ts
async function checkCatalog(raw: unknown, policy: CatalogPolicy = {}): Promise<{ catalog: Catalog; unsigned: boolean; keyId?: string }>
```

Validate, check the signature against the keys the game trusts, and the engine range. Throws CatalogError.

### checkComputedPhysics

*function* · `packages/assets/src/model-physics.ts:303`

```ts
async function checkComputedPhysics(r: ResolvedModel, read: Read): Promise<{ path: string; message: string }[]>
```

What `physics.computed` of a model that asks for computed values must hold, or the issues when it is missing or stale. Used by `check` and written by `pack`.

### checkEngine

*function* · `packages/assets/src/package.ts:401`

```ts
function checkEngine(engine: PackageManifest['engine'], running: EngineVersions, o: { required?: boolean } = {}): PackageIssue[]
```

Compare the `engine` field of a manifest with the engine that is running. The ranges are those of
`dependencies`; Babylon is usually an exact version. Only the numbers count: a build stamp after `+` is ignored. A field that
is absent is no problem unless `required` is set (a finished game needs both). Returns the issues; empty means it fits.

### checkFileName

*function* · `packages/assets/src/package.ts:234`

```ts
function checkFileName(name: string, kind: PackageKind): PackageIssue[]
```

Does the file name's extension agree with the package kind? `.fex` is a game, `.fprj` a project and `.fmdl` a model; other names are free.

### checkImpostor

*function* · `packages/assets/src/library.ts:693`

```ts
function checkImpostor(v: unknown, tiers: unknown, bad: (path: string, message: string) => void, file: (path: string, p: unknown) => void, at = '/impostor'): void
```

The problems of an `impostor` entry; the tier it names must be one the item has.

### checkMaterialDef

*function* · `packages/assets/src/library.ts:488`

```ts
function checkMaterialDef(m: Record<string, any>, at: string, bad: (p: string, msg: string) => void, deps?: ReadonlySet<string>, own?: string, baseMasks?: Iterable<string>)
```

The problems of a material definition (`MaterialDef`); `maps` must be `ferret://` references (a `.fmdl` checks its own maps itself).

### checkMaterialProgram

*function* · `packages/assets/src/material-program.ts:62`

```ts
function checkMaterialProgram(p: unknown, at: string, pic: (path: string, ref: unknown) => void, bad: (path: string, message: string) => void): void
```

The problems of a program: unknown operations, wrong argument counts, forward references, bad indices. `pic` checks a texture reference.

### checkModelFolder

*function* · `packages/assets/src/model.ts:826`

```ts
async function checkModelFolder(files: Map<string, Uint8Array>): Promise<PackageIssue[]>
```

The problems of a model folder that has not been packed yet (so no hashes): `check` on a directory.

### checkModelReferences

*function* · `packages/assets/src/model.ts:549`

```ts
function checkModelReferences(m: ModelJson, o: { concrete?: boolean } = {}): PackageIssue[]
```

The references between the names inside a model: a part's material, a collision shape's part and material, the parts of a body and the bodies of
a joint, a moving part's link, the docks an include is placed at, the forms a motion needs. Run on a model that states everything itself (one with
no parent), and by the resolver on the resolved model of any other (stage M2). With `concrete`, also what a model that can be placed must have.

### checkVatBake

*function* · `packages/assets/src/library.ts:678`

```ts
function checkVatBake(v: unknown, tiers: unknown, bad: (path: string, message: string) => void, file: (path: string, p: unknown) => void, at = '/vat'): void
```

The problems of an `impostor` entry; the tier it names must be one the item has.

### cleanPath

*function* · `packages/assets/src/package.ts:342`

```ts
function cleanPath(p: unknown): string | null
```

A path inside a package: `a/b/c.ext`, no `..`, no leading slash. Returns it normalised, or null.

### compactZip

*function* · `packages/assets/src/zip.ts:373`

```ts
async function compactZip(src: ByteSource): Promise<Uint8Array>
```

A zip with only its live files, copied as they are (no recompression), in the order they were first written: drops what appends left behind.

### compareVersions

*function* · `packages/assets/src/package.ts:382`

```ts
function compareVersions(a: string, b: string): number
```

Order of two versions by their numbers (a pre-release tag is ignored): negative when `a` is older.

### computeLevelKey

*function* · `packages/assets/src/model-resolve.ts:505`

```ts
async function computeLevelKey(model: ModelJson, i: number, sources: Sources, includeHashes: string[] = []): Promise<string>
```

SPEC 4.5: the key of what the thresholds of level `i` were measured from: the sha256 of this level's file, the next level's file, every file the node
edits bring and the resolved hashes of the included instances (a level is drawn with its includes). The same bytes and the same includes give the same key.

### computeModelPhysics

*function* · `packages/assets/src/model-physics.ts:272`

```ts
async function computeModelPhysics(r: ResolvedModel, read: Read): Promise<ComputedPhysics & Totals & { sum: MassSum }>
```

The mass, charge, centre of mass and inertia of a resolved model, from its own parts (volume x density of every part whose material states a `density`)
and from its included instances (each one's totals, placed), less the binding energy as a mass (E / c^2). `hash` names what they were computed from, so
a reader can tell that they are stale. Throws when something needed is missing.

### computeResolvedHash

*function* · `packages/assets/src/model-resolve.ts:517`

```ts
async function computeResolvedHash(model: ModelJson, sources: Sources, includeHashes: string[] = []): Promise<string>
```

### configureKtx2

*function* · `packages/assets/src/ktx2.ts:65`

```ts
function configureKtx2(o: Ktx2Options = {}): { base: string; workers: number }
```

Point Babylon's KTX2 decoder at the files of `ktx2/`. Idempotent: the first call wins (the worker pool starts with the first KTX2 texture).

### copyThinInstances

*function* · `packages/assets/src/cache.ts:253`

```ts
function copyThinInstances(from: BABYLON.Mesh, to: BABYLON.Mesh): void
```

Give `to` the thin instances of `from`: the matrices and any per-instance attribute buffers (colours).

### crc32

*function* · `packages/assets/src/zip.ts:217`

```ts
function crc32(data: Uint8Array): number
```

### createEncryption

*function* · `packages/assets/src/security.ts:117`

```ts
async function createEncryption(input: KeyInput, iterations = DEFAULT_ITERATIONS): Promise<{ encryption: PackageEncryption; key: CryptoKey }>
```

Make the encryption block (and the key) for a new encrypted package.

### deflate

*function* · `packages/assets/src/zip.ts:214`

```ts
function deflate: (b: Uint8Array<ArrayBufferLike>) => Promise<Uint8Array<ArrayBufferLike>>
```

Deterministic (see deflate.ts): the platform's CompressionStream gives different bytes in each engine.

### describeResolved

*function* · `packages/assets/src/model-describe.ts:106`

```ts
function describeResolved(r: ResolvedModel): ModelDescription
```

The whole description of a resolved model: what the chain says, with everything the model has, the includes counted by their placed instances.

### detectBackend

*function* · `packages/assets/src/persist.ts:101`

```ts
async function detectBackend(env: CacheEnv = globalThis as unknown as CacheEnv, chunk?: number): Promise<CacheBackend>
```

Pick the first backend that really writes, reads and deletes (a private window may offer the API and refuse the write).

### downloadedContentItem

*function* · `packages/assets/src/cache-menu.ts:18`

```ts
function downloadedContentItem(store: AssetStore, o: { onChange?: () => void; close?: () => void } = {}): CacheMenuItem & { refresh(): Promise<void> }
```

`value()` is read by a menu on every draw, so it shows the last size seen; `refresh()` reads the cache and calls `onChange`.

### etc1sTarget

*function* · `packages/assets/src/ktx2.ts:95`

```ts
function etc1sTarget(caps: Ktx2Caps, alpha = true): Ktx2Target
```

the block format Babylon picks for ETC1S data (the colour maps of `--ktx2`)

### exactVersion

*function* · `packages/assets/src/package.ts:384`

```ts
function exactVersion: (range: string) => string | undefined
```

The version an exact range names (`1.2.0`, `=1.2.0`), or undefined for any other range.

### fitsDependency

*function* · `packages/assets/src/package.ts:386`

```ts
function fitsDependency: (pkg: { version: string; libraryVersion?: string | undefined; }, range: string) => boolean
```

Is an opened package the one a dependency `range` asks for? Its own version fits, or the range is the exact number a library gave the file.

### fitsValueType

*function* · `packages/assets/src/model.ts:160`

```ts
function fitsValueType(v: unknown, type: ModelValueType): boolean
```

is the value of the game language's type

### folderSource

*function* · `packages/assets/src/package.ts:443`

```ts
async function folderSource(io: FolderIO): Promise<PackageSource>
```

### formatBytes

*function* · `packages/assets/src/cache-menu.ts:11`

```ts
function formatBytes(n: number): string
```

### fromBase64

*function* · `packages/assets/src/security.ts:47`

```ts
function fromBase64(b: string): Uint8Array
```

### generateDescription

*function* · `packages/assets/src/model-describe.ts:69`

```ts
function generateDescription(model: ModelJson, author: ModelDescription = {}, counts: Record<string, number> = {}): ModelDescription
```

The description the packer writes for a model package: `author` (its `description.json` as it is) with the structured fields filled from `model.json`.
What the model states itself (a dock's text, a motion's summary) is written exactly as it is, since `check` compares them; the author's words win
for parts, includes, materials, physics and size. `counts` gives the number of places of an include when the model is resolved.

### generateEncryptionKey

*function* · `packages/assets/src/security.ts:106`

```ts
function generateEncryptionKey(): string
```

### generateSigningKey

*function* · `packages/assets/src/security.ts:63`

```ts
async function generateSigningKey(): Promise<SigningKey>
```

### getPointer

*function* · `packages/assets/src/model.ts:534`

```ts
function getPointer(root: unknown, pointer: string): unknown
```

The value a JSON Pointer reaches in `root`, or `undefined`.

### glbBounds

*function* · `packages/assets/src/model-import.ts:75`

```ts
function glbBounds(bytes: Uint8Array): { min: Vec3; max: Vec3 }
```

the bounds of the whole glb

### glbJson

*function* · `packages/assets/src/model-import.ts:25`

```ts
function glbJson(bytes: Uint8Array): any
```

the JSON of a binary glTF file

### glbNodes

*function* · `packages/assets/src/model-import.ts:46`

```ts
function glbNodes(bytes: Uint8Array): GlbNode[]
```

The named nodes of a glb with the world bounds of everything at and below each (from the POSITION accessors' min and max, which glTF requires).

### glbOfMeshes

*function* · `packages/assets/src/model-import.ts:95`

```ts
function glbOfMeshes(meshes: MeshInput[], materials: Record<string, MaterialInput> = {}, generator = '@ferret/assets'): Uint8Array
```

a glb of raw meshes, one node and one primitive each (positions, normals, vertex colours, uvs, 32-bit indices)

### httpFolderSource

*function* · `packages/assets/src/package.ts:459`

```ts
async function httpFolderSource(base: string, fetchFn: typeof fetch = (u, i) => fetch(u, i)): Promise<PackageSource>
```

A folder package on a server. The file names come from `index` (a list of paths) or, when the folder is served with an index
file named `ferret-index.json`, from that; otherwise from the `files` of its `ferret.json`.

### includeLevel

*function* · `packages/assets/src/model-plan.ts:55`

```ts
function includeLevel(level: number, included: { levels?: { maxTier?: ModelTier }[] }, tier: ModelTier = 'desktop'): number
```

The level of an included model drawn on level `level` of the whole: the same index, no finer than the device tier lets the included model go, and no
coarser than its last. An included model is always on the level of the whole (the loader's rule, SPEC 4.1), never one of its own.

### inflate

*function* · `packages/assets/src/zip.ts:212`

```ts
function inflate: (b: Uint8Array<ArrayBufferLike>, max?: number) => Promise<Uint8Array<ArrayBufferLike>>
```

### inRubric

*function* · `packages/assets/src/library.ts:1049`

```ts
function inRubric: (rubric: string | undefined, under: string) => boolean
```

is the rubric `rubric` the rubric `under` or beneath it

### isCompressedFormat

*function* · `packages/assets/src/zip.ts:227`

```ts
function isCompressedFormat(path: string): boolean
```

Files that are compressed already are stored, so a package is read by slices without inflating (PLAN.md 4.9).

### isVersionRange

*function* · `packages/assets/src/package.ts:380`

```ts
function isVersionRange(range: string): boolean
```

Is `range` a version range (`1.2.0`, `^1.2.0`, `~1.2.0`, `>=1.2.0`, `*`)?

### itemPath

*function* · `packages/assets/src/library.ts:957`

```ts
function itemPath: (id: string) => string
```

Path of the item file of an id inside a package.

### joinPath

*function* · `packages/assets/src/package.ts:353`

```ts
function joinPath(base: string, ref: string): string | null
```

Resolve `ref` against the folder `base` (`levels/yard/` + `../../assets/a.glb` = `assets/a.glb`).

### keepContainerInStep

*function* · `packages/assets/src/cache.ts:154`

```ts
function keepContainerInStep(container: BABYLON.AssetContainer): void
```

Keep a container's sources in step with the scene it was loaded for: the lights the scene has now, and every later change of what a shader depends on (an environment, fog,
a material plugin such as the baked light of

### keyIdOf

*function* · `packages/assets/src/security.ts:59`

```ts
async function keyIdOf(spki: Uint8Array): Promise<string>
```

### ktx2Base

*function* · `packages/assets/src/ktx2.ts:49`

```ts
function ktx2Base(o: Ktx2Options = {}): string
```

where the transcoder files are for this page (absolute: Babylon's worker is a blob, which resolves nothing relative)

### ktx2GpuBytes

*function* · `packages/assets/src/ktx2.ts:112`

```ts
function ktx2GpuBytes(width: number, height: number, target: Ktx2Target, mips = true): number
```

Video memory of a texture of `width` x `height` with a full mip chain in `target` (4/3 of the top level, rounded up by the blocks).

### ktx2Targets

*function* · `packages/assets/src/ktx2.ts:105`

```ts
function ktx2Targets(engine: { getCaps(): Ktx2Caps }): { caps: Required<Ktx2Caps>; uastc: Ktx2Target; uastcNonColour: Ktx2Target; etc1s: Ktx2Target }
```

The formats a running engine will transcode to: for logs, tests and the memory estimate (`Engine.getCaps()` is read).

### lazyLoader

*function* · `packages/assets/src/model-resolve.ts:50`

```ts
function lazyLoader(entries: { id: string; version: string; libraryVersion?: string; open: () => Promise<ModelSource | null>; openFiles?: () => Promise<PackageFiles | null> }[]): ModelLoader
```

A loader over packages that are known by id and version and opened on demand (a folder of `.fmdl` files, say). The highest version that fits is opened, once.

### levelIds

*function* · `packages/assets/src/package.ts:762`

```ts
function levelIds(files: string[]): string[]
```

### levelsForTier

*function* · `packages/assets/src/model.ts:26`

```ts
function levelsForTier(levels: readonly ModelLevel[], tier: ModelTier = 'desktop'): { index: number; level: ModelLevel }[]
```

SPEC 4.1: the levels a device of `tier` may load, as `{ index, level }` in order, finest first. `maxTier` of a level is the finest device tier that
may load it, so a device loads from the first level whose `maxTier` is its own tier or a coarser one (a level with none counts as `desktop`); the
levels below that one stay, they are what it draws far away. There is always at least the coarsest level.

### loadCatalog

*function* · `packages/assets/src/catalog.ts:252`

```ts
async function loadCatalog(store: AssetStore, url: string, policy: CatalogPolicy = {}, o: { signal?: AbortSignal } = {}): Promise<LoadedCatalog>
```

Fetch a catalog (never from the HTTP cache) and check it. When the network fails, the last good copy kept in the persistent
cache is used and marked `stale`; with none, the failure is thrown. A good fresh copy replaces the kept one.

### massProperties

*function* · `packages/assets/src/model-physics.ts:157`

```ts
function massProperties(s: MassSum): { mass: number; centerOfMass: Vec3; inertia: Vec3 }
```

The mass, centre of mass and the diagonal of the inertia about it (axes of the model) of a sum.

### mayHoldCode

*function* · `packages/assets/src/package.ts:229`

```ts
function mayHoldCode(m: { kind: PackageKind; docking?: unknown }): boolean
```

May the package hold code: a game, a library, a project, a level docked into a parent (kind `levels` with a `docking` block), or a model (the modules its model.json names).

### measureModelFolder

*function* · `packages/assets/src/model.ts:802`

```ts
async function measureModelFolder(files: Map<string, Uint8Array>): Promise<{ files: Map<string, Uint8Array>; changed: string[]; issues: PackageIssue[] }>
```

The files of a model folder ready to pack: the cost of every level written into `model.json` from its glTF (bytes, triangles, draw calls, bones; what
the packer measures, never typed by hand). Everything else is the author's. Returns the files and what it changed.

### memoryLoader

*function* · `packages/assets/src/model-resolve.ts:70`

```ts
function memoryLoader(sources: ModelSource[]): ModelLoader
```

A loader over model sources already in hand.

### meshVolume

*function* · `packages/assets/src/model-import.ts:131`

```ts
function meshVolume(positions: ArrayLike<number>, indices: ArrayLike<number>): number
```

the volume of a closed triangle mesh, m3 (the divergence theorem); for a mesh that is not closed the number is not a volume

### modelFilesFromGlb

*function* · `packages/assets/src/model-import.ts:171`

```ts
async function modelFilesFromGlb(spec: ImportSpec): Promise<Map<string, Uint8Array>>
```

The files of a model folder for the pack: see the header. Throws, naming it, when something the path has to give is missing or wrong.

### modelSourceOf

*function* · `packages/assets/src/model-resolve.ts:34`

```ts
async function modelSourceOf(source: PackageSource): Promise<ModelSource>
```

Read the model of a package (a folder, a zip, a draft, a catalog package). Throws with the reason when `ferret.json` or `model.json` cannot be read.

### modelSourceOfFiles

*function* · `packages/assets/src/model-resolve.ts:45`

```ts
function modelSourceOfFiles(files: Map<string, Uint8Array>): Promise<ModelSource>
```

The files of a folder (as `readFolder` of the command line gives them) as a model source.

### nodeNamesOf

*function* · `packages/assets/src/model.ts:715`

```ts
function nodeNamesOf(m: ModelJson): { at: string; node: string }[]
```

The node names the model states itself that every level must hold (parts, moving parts, docks, collision, nodes of node edits that are replaced).

### numbersVersions

*function* · `packages/assets/src/catalog.ts:88`

```ts
function numbersVersions: (c: Catalog, pkgId: string) => boolean
```

Whether a catalog numbers the files of a package (the library server does: every version stays).

### openCatalogPackage

*function* · `packages/assets/src/catalog.ts:288`

```ts
async function openCatalogPackage(store: AssetStore, c: Catalog, pkgId: string, o: { tier?: string; signal?: AbortSignal } = {}): Promise<CatalogPackageSource>
```

Open a package of the catalog. `ferret.json` is checked against the catalog's `manifest` hash, and every file read afterwards
against the hash that manifest holds, so nothing the signed catalog does not vouch for is handed on. Files are looked up in the
persistent cache by their hash first; a miss reads the package by range requests (only then is the network used) and keeps the
file. The package's index is cached under the manifest hash, so a package seen once can be opened, and its cached files read,
with the network gone.

### openEncryption

*function* · `packages/assets/src/security.ts:139`

```ts
async function openEncryption(e: PackageEncryption, input: KeyInput): Promise<CryptoKey>
```

The key for an existing encrypted package; throws WrongKeyError when it does not open the package's check value.

### ownGeometry

*function* · `packages/assets/src/cache.ts:220`

```ts
function ownGeometry(mesh: BABYLON.Mesh): void
```

Give a mesh that shares its Geometry (a clone) a Geometry of its own over the SAME vertex and index buffers: no vertex data is copied. Babylon keeps a mesh's thin-instance buffers
(`world0..3`, colours) in its Geometry, so meshes sharing one Geometry share one instance buffer: every streaming cell that placed the same model wrote its matrices there, the last
one to load won, and the other cells drew its instances (or a buffer disposed by it): whole houses gone or drawn in another place. Call it before giving the mesh thin instances.
The new Geometry holds its own references on the shared GPU buffers (Babylon counts them), so the model's file may be released while the mesh still draws, and disposing the
mesh releases only its references and its own instance buffers. Meshes left on the old Geometry get their own instance buffers bound again.

### packageForRange

*function* · `packages/assets/src/catalog.ts:95`

```ts
function packageForRange(c: Catalog, pkgId: string, range: string): CatalogVersion | undefined
```

The file of a package that a dependency `range` asks for. In a catalog that numbers its files an exact version is the library's number of the file, so that a
new version never changes what was made; when no file has that number it is the package's own version. Any other range takes the newest file whose own
version fits. Undefined when there is none.

### packageSetLoader

*function* · `packages/assets/src/model-resolve.ts:74`

```ts
function packageSetLoader(set: PackageSet): ModelLoader
```

A loader over the packages that are open together (`PackageSet`); a package that is encrypted and locked is not found.

### packageUrl

*function* · `packages/assets/src/catalog.ts:271`

```ts
function packageUrl(c: Catalog, pkgId: string, tier?: string): string
```

Absolute URL of a package file for a tier (falls back to the plain one), relative to the catalog's base.

### packageVersion

*function* · `packages/assets/src/catalog.ts:73`

```ts
function packageVersion(c: Catalog, pkgId: string, version: string = DEFAULT_REF_VERSION): CatalogVersion | undefined
```

One version of a package (default 1.0.0); undefined when the catalog has none such.

### packageVersions

*function* · `packages/assets/src/catalog.ts:65`

```ts
function packageVersions(c: Catalog, pkgId: string): CatalogVersion[]
```

The versions of a package, oldest first. A catalog without a `versions` list (every catalog made before this) has one version, 1.0.0, whatever its
package entry says: the packages that were in the library at the move are version 1.0.0.

### packFiles

*function* · `packages/assets/src/package.ts:931`

```ts
async function packFiles(files: { path: string; data: Uint8Array | string }[], o: PackOptions = {}): Promise<{ bytes: Uint8Array; manifest: PackageManifest }>
```

A folder's files (read from disk by the caller) packed into a package (`ferret pack`). The folder must hold `ferret.json`.

### packModelFolder

*function* · `packages/assets/src/model-pack.ts:87`

```ts
async function packModelFolder(input: Map<string, Uint8Array>, loader: ModelLoader, o: PackOptions & PrepareOptions = {}): Promise<{ bytes: Uint8Array; manifest: Awaited<ReturnType<typeof packFiles>>['manifest']; prepared: PreparedModel }>
```

prepare and pack; throws, naming the problems, when the folder is not good

### packPackage

*function* · `packages/assets/src/package.ts:795`

```ts
async function packPackage(source: PackageSource, o: PackOptions = {}): Promise<{ bytes: Uint8Array; manifest: PackageManifest }>
```

### packPackageTo

*function* · `packages/assets/src/package.ts:832`

```ts
async function packPackageTo(source: PackageSource, sink: (chunk: Uint8Array) => void | Promise<void>, o: Omit<PackOptions, 'decrypt'> = {}): Promise<{ size: number; manifest: PackageManifest; manifestBytes: Uint8Array }>
```

`packPackage` for a package that does not fit in memory (a streamed level of several GB): the zip goes to `sink` one file at a time (`ZipWriter`), so only
the biggest file is held. Every file is read twice (once for the hash the manifest holds, once to write it). `encrypt` seals the files as in
`packPackage`. Returns what a
catalog needs: the size of the file, the manifest and its bytes.

### parseFerretRef

*function* · `packages/assets/src/library.ts:482`

```ts
function parseFerretRef(ref: string): { pkg: string; path: string } | null
```

`ferret://<package>/<path>` -> its parts, or null

### parseQualified

*function* · `packages/assets/src/model-resolve.ts:110`

```ts
function parseQualified(p: string): { pkg: string; path: string } | null
```

