> ## Documentation Index
> Fetch the complete documentation index at: https://docs.streampixel.io/llms.txt
> Use this file to discover all available pages before exploring further.

# The engine and updates

> How the Streampixel Web SDK loads its engine: what the npm package contains, what create() downloads and from which hosts, how the download is verified, channels, version pinning, preload() and EngineLoadError.

Expert For developers and security reviewers who want to know exactly what code runs in the page and where it comes from. After this page you can explain the download to a reviewer, choose between automatic updates and a pinned version, and handle a download that fails.

The SDK has two parts. You install one. The other is downloaded when a stream starts.

> [card] The loader
>
> What `npm install` puts in your bundle. It finds the engine, proves that it comes from Streampixel, and hands it your options. It decides nothing about streaming. It never changes after you install it.

> [card] The engine
>
> Everything that runs a stream: access, signalling, WebRTC, input, reconnection, telemetry. It is not in the package. `create()` downloads it from Streampixel's servers, so fixes reach your site without a new install or deploy.

When your page calls `Streampixel.create()`, the loader fetches a signed manifest from the engine hosts, checks its signature, expiry and sequence number, and chooses a build: the version you pinned, else the one your channel runs. It then loads the engine script with its integrity hash and hands it your options. Only after these steps does the engine look the project up and ask the platform for a ticket.

## What the npm package contains

`@streampixel/web-sdk` is the loader. It is under 10 KB of minified JavaScript and has no runtime dependencies.

| In the package | Detail |
| - | - |
| `Streampixel.create()` and `Streampixel.preload()` | The two entry points. |
| `AuthError`, `EngineLoadError`, `DisconnectCodes`, `SDK_VERSION` | Error classes, the end code names and the package's own version. |
| TypeScript types | Options, states, events, stats. |
| The entry `@streampixel/web-sdk/voice` | A second small loader, for the chat code. See [Voice chat](https://docs.streampixel.io/resources/web-sdk-v2/voice-chat.md). |
| ESM and CommonJS builds | Importing the package touches no browser globals, so it can be imported during server-side rendering. Only `create()` needs a browser. |
| What the loader trusts | The two engine hosts, the public keys that verify the manifest's signature, and the lowest manifest sequence number it accepts. These are constants in the package. |

The package holds **no engine**, and so no copy to fall back to.

> [!NOTE]
>
> The script-tag build is the same loader, served as `https://js.streampixel.io/v2/loader.js`. It defines `window.StreampixelSDK`. See [Installation](https://docs.streampixel.io/resources/web-sdk-v2/installation.md).

## What `create()` downloads

Two files, both from the same two public hosts. `https://js.streampixel.io` is tried first. `https://js-backup.streampixel.io` is its mirror.

| File | What it is | How it is requested |
| - | - | - |
| The manifest, `/v2/manifest.json` | A signed list of engine builds: which version each channel runs, and the integrity hash of each build's files. | `fetch`, without cookies or credentials and without a referrer. Once per page load. |
| The engine script | One file per engine version. A released file never changes. | A `<script>` element in `document.head` with `integrity`, `crossorigin="anonymous"` and no referrer. |

If your page uses chat, the chat code is a third file. It is loaded the first time you call `VoiceChat.for()`, in the same version as the stream's engine, with the same checks.

In your browser's network panel the requests look like this:

**[https://js.streampixel.io](https://js.streampixel.io)**

**v2**

**manifest.json**

**v2.0.0-beta.2 (one folder per engine version)**

**engine.js**

**voice.js**

The loader keeps what it loaded for the life of the page. A second `create()` with the same `engine` options and `appId` does not download again.

## How the download is verified

The loader trusts a file only after every check below has passed. If one fails, nothing from that answer is run.

**1. The hosts are fixed**

The two hosts are constants in the package. No option, URL parameter or page global can point the loader to another host.

**2. The manifest is signed**

The manifest carries a signature (ECDSA, curve P-256, with SHA-256). The loader verifies it with the browser's WebCrypto against public keys that are built into the package. A manifest without a valid signature is refused: reason `signature`.

This is why the page must be served over `https` or from `localhost`: WebCrypto is not available elsewhere, and `create()` then rejects with reason `no-webcrypto`.

**3. The manifest is current**

| Check | Refused with reason |
| - | - |
| It has a sequence number and an expiry time. | `manifest-incomplete` |
| The expiry time is in the future. | `manifest-expired` |
| Its sequence number is not below the lowest one built into the package. | `manifest-too-old` |
| Its sequence number is not below the newest one this browser has seen. The loader keeps that number in `localStorage`, under the key `spx.sdk.seq`. | `manifest-replayed` |

Together these stop someone from serving an old, validly signed manifest to hold viewers on an old engine.

**4. The engine file matches its hash**

The engine is loaded as a script with [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity). The hash (SHA-384) comes from the signed manifest, so the browser itself refuses a file with other content.

**5. The script registers as the build that was chosen**

After it loaded, the script must report the version and the contract number the loader expects. Otherwise the load fails with reason `engine-register`.

What this means for a reviewer:

| Question | Answer |
| - | - |
| What if one of the two hosts is compromised or impersonated? | It can withhold the engine, so no stream starts. It cannot replace the engine: the manifest would fail the signature check, and a changed engine file would fail the integrity check. |
| Does the loader use `eval` or `blob:` URLs? | No. |
| Does it work with Trusted Types? | Yes. It creates one policy, named `streampixel-sdk`, that accepts only URLs on the two hosts. Allow that policy name. |
| What must my Content-Security-Policy allow? | The two hosts in `script-src` and `connect-src`. See [Content-Security-Policy](https://docs.streampixel.io/resources/web-sdk-v2/installation.md#content-security-policy). |
| Can I host the engine myself? | No. The hosts are fixed. |
| Can I review a build before my viewers get it? | Pin a version: see [Which build runs](#which-build-runs). |
| What does this not cover? | Your own page. A script that already runs in your page can do what your page can do. The checks cover the path from Streampixel to the browser. |

## Which build runs

The loader chooses the build in this order:

1. The version you pinned with `engine.version`.
2. Otherwise, a build that the manifest names for your project. Streampixel can do this for one project that needs a particular engine build.
3. Otherwise, the build of your channel: `engine.channel`, which is `'stable'` unless you set it.

> [tab] Stable (default)
>
> Do nothing. Your page runs the build of the `stable` channel and gets fixes by itself.
>
> ```ts theme={"dark"}
> const stream = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
> ```

> [tab] Beta channel
>
> The next release, for testing. Use it on a test page, so you see a new engine before your viewers do.
>
> ```ts highlight={4} theme={"dark"}
> const stream = await Streampixel.create({
>   appId: 'YOUR_PROJECT_ID',
>   container,
>   engine: { channel: 'beta' },
> });
> ```

> [tab] Pin a version
>
> One exact build, with no automatic updates.
>
> ```ts highlight={4} theme={"dark"}
> const stream = await Streampixel.create({
>   appId: 'YOUR_PROJECT_ID',
>   container,
>   engine: { version: '2.0.0-beta.2' },
> });
> ```

**engine.channel** `'stable' | 'beta'` (default: 'stable')

Which release runs. A channel the manifest does not have rejects with reason `no-channel`.

**engine.version** `string`

One exact engine version, for example `'2.0.0-beta.2'`. It wins over the channel. A string that is not a version rejects with a `TypeError`. A version that does not exist rejects with `EngineLoadError`, reason `no-build`.

> [!WARNING]
>
> A pinned page gets no fixes until you change the pin. Pin when you need change control, and plan how you will move the pin. The manifest is still downloaded and verified on every page load.

> [accordion] Staged releases
>
> A channel can list more than one build, each with a percentage. The loader then draws one random number per page load and takes the build that number falls on. Every stream on the same page load gets the same build. A reload can get the other one.

> [accordion] Which engine is running in my page?
>
> ```ts theme={"dark"}
> import { Streampixel, SDK_VERSION } from '@streampixel/web-sdk';
>
> const stream = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
>
> console.log(SDK_VERSION);          // the package you installed (the loader)
> console.log(stream.engineVersion); // the engine that runs this stream
> console.log(stream.engineSource);  // 'cdn' in every published package
> ```
>
> The two versions can differ: the engine updates by itself, the package does not. Include `stream.engineVersion` in every support request.

## `preload()`

`Streampixel.preload()` downloads and verifies the engine without starting a session. Nothing else happens: no project lookup, no ticket, no GPU. Call it when the page loads, so that `create()` starts faster when the viewer presses Start.

```ts highlight={4} theme={"dark"}
import { Streampixel } from '@streampixel/web-sdk';

// When the page loads. A failed warm-up is not fatal: create() tries again.
Streampixel.preload({ appId: 'YOUR_PROJECT_ID' }).catch(() => undefined);

startButton.addEventListener('click', async () => {
  const stream = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
});
```

**engine** `object`

Optional. Pass the same choices you will pass to `create()`, so that the build `create()` picks is the one already loaded.

**properties**

**channel** `'stable' | 'beta'`

As `engine.channel` in `create()`.

**version** `string`

As `engine.version` in `create()`.

**appId** `string`

Your project ID. The manifest can name a build for one project, so the loader needs the ID to choose the same build as `create()`.

**returns** `Promise\<\{ source, version \}\>`

`version` is the engine version that was loaded. `source` is `'cdn'` in every published package. It rejects with `EngineLoadError` when the engine cannot be loaded.

## Time limits

| Step | Limit per attempt | Attempts | Longest wait |
| - | - | - | - |
| The manifest | 3 seconds per host | The primary host, then the mirror. Then a pause of 0.6 seconds, and both once more. | About 12.6 seconds |
| The engine script | 8 seconds per host | The host that served the manifest, then the other one. | 16 seconds |

A healthy load takes a fraction of these limits. The longest waits apply only when every attempt runs into its limit.

Aborting the `signal` you passed to `create()` does not interrupt the download. `create()` rejects with `AbortError` as soon as the download has finished or failed, and nothing starts.

## When the download fails

`create()` and `preload()` reject with `EngineLoadError`. No stream starts.

```ts highlight={6-8} theme={"dark"}
import { Streampixel, EngineLoadError } from '@streampixel/web-sdk';

try {
  const stream = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
} catch (err) {
  if (err instanceof EngineLoadError) {
    console.warn('engine not loaded:', err.reason, err.message);
    showRetryButton(); // a failed load is not remembered: create() again tries again
  } else {
    throw err;
  }
}
```

`err.reason` says which step failed. The reasons you can act on:

| `reason` | Step | What to check |
| - | - | - |
| `no-webcrypto` | Before any download | The page is not served over `https` or from `localhost`. |
| `manifest-unavailable` | Manifest | Neither host answered in time: the viewer is offline, a firewall or an ad blocker is in the way, or `connect-src` does not allow the hosts. |
| `no-channel`, `no-build` | Choosing the build | The channel or the pinned version does not exist. |
| `needs-newer-loader` | Choosing the build | The chosen engine needs a newer `@streampixel/web-sdk`. Update the package. |
| `trusted-types` | Engine script | Your Trusted Types configuration refused the policy `streampixel-sdk`. |
| `engine-blocked` | Engine script | The script was blocked: the network, your `script-src`, or the integrity check. The browser reports the three in the same way, so open the console to tell them apart. |
| `engine-timeout` | Engine script | The script did not load within 8 seconds. |

The full list, with the manifest checks, is in [Errors and disconnects](https://docs.streampixel.io/resources/web-sdk-v2/errors-and-disconnects.md#engineloaderror).

> [!TIP]
>
> To see what a viewer's network does, open the browser's network panel and filter on `streampixel.io`. A blocked manifest or engine request shows there with the browser's own reason.

## What an update can and cannot change

The split between loader and engine is also a contract.

| | The engine, which updates | The loader, which you installed |
| - | - | - |
| Holds | Every method and event of the stream object, every default, the protocol with the platform. | `create()`, `preload()`, the error classes, the two hosts, the keys and the checks above. |
| Can change | Yes, with an engine release. Within version 2 an engine may **add** options, methods, events, state kinds and error kinds. It does not remove or change an existing one. | Only when you install a newer package. |
| Compatibility | The loader runs an engine only when both speak the same contract number. An engine that needs a newer loader is not run by an older package: `create()` rejects with reason `needs-newer-loader`. | |

Because the engine can add things after you compiled your page, write your code so that additions do not break it:

| Where | What to do |
| - | - |
| `switch (state.kind)` | Keep a `default` branch. A newer engine may add a state. |
| `switch (err.kind)` on an `AuthError` | Keep a `default` branch. A newer engine may add a kind. |
| An event that is not in your installed types yet | Subscribe with `stream.onUnknown(name, fn)`. `stream.on()` accepts only the names in your types, so that a typing mistake does not compile. |
| An option that is not in your installed types yet | Pass it in `advanced.flags`. Names the engine does not know are ignored. |

> [!NOTE]
>
> These pages describe engine 2.0.0-beta.2. A page that pins an older engine does not have everything described here: check `stream.engineVersion`.

## Next steps

> [card] [Reliability](https://docs.streampixel.io/resources/web-sdk-v2/reliability.md)
>
> What the engine does when the network or the app fails, with the timings.

> [card] [Diagnostics](https://docs.streampixel.io/resources/web-sdk-v2/diagnostics.md)
>
> What you can read yourself, and what the SDK reports to Streampixel.

> [card] [Options](https://docs.streampixel.io/resources/web-sdk-v2/options.md)
>
> Reference: `engine.channel`, `engine.version` and every other option.

> [card] [Changelog](https://docs.streampixel.io/resources/web-sdk-v2/changelog.md)
>
> Reference: what changed in each release.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.