# Check your setup

```bash
npx @sparkletree/cli doctor --url https://yoursite.com/pricing
npx @sparkletree/cli doctor --json        # one JSON document, for an agent or CI
```

`doctor` reads your project and asks the edge whether it would accept your
key from your site. It generates nothing, spends nothing and changes nothing,
and it needs no sign-in. Every check answers `pass`, `warn`, `fail` or `skip`.
Every warning and failure comes with a remedy you can act on as written. The
command exits `1` when a check fails and `0` otherwise; a warning does not
fail.

```
pass  node             Node 20.11.0 meets >=18, >=18.
pass  packages         @sparkletree/core and @sparkletree/react 0.16.0.
pass  env-file         Read .env.local.
pass  key              NEXT_PUBLIC_SPARKLETREE_KEY is a test key for workspace 6f1c2a4e-….
FAIL  origin           https://yoursite.com is not allowed for this key.
                        Register it: sparkletree init --origin https://yoursite.com
skip  csp-frame        The served HTML shows no live player. If the page turns on live, frame-src must allow https://*.cloudflarestream.com.
```

| Option | |
|---|---|
| `--url <https://site/page>` | Also fetch this page: its Content Security Policy and whether it is server-rendered. Redirects are followed. |
| `--origin <https://site>` | The site to check against the key. Default: the origin of `--url`. |
| `--env-file <path>` | Default: the first that exists of `.env.local`, `.env.development.local`, `.env.development`, `.env`. |
| `--campaign <id>` | Default: `SPARKLETREE_CAMPAIGN_ID` from the env file. |
| `--cwd <path>` | The project root. |
| `--json` | `{"ok": …, "checks": [{"id", "status", "message", "remedy"?}, …]}` on stdout. |

`doctor` reads the variables `init` writes, with any of the prefixes
`NEXT_PUBLIC_`, `VITE_`, `PUBLIC_` or none: `SPARKLETREE_KEY` (or
`SPARKLETREE_PUBLISHABLE_KEY`), `SPARKLETREE_API_BASE`, `SPARKLETREE_ORG_ID`
and `SPARKLETREE_CAMPAIGN_ID`. With no env file it reads them from the
environment, when the key is there.

`skip` is never a quiet pass: it means the check could not run, and the
message says why.

## Every check

The checks run in this order. When an earlier one fails, the ones that need
it are skipped with the reason.

### The project

| Check | pass | warn or fail, and the remedy |
|---|---|---|
| `node` | Node meets the `engines` range of the installed `@sparkletree/core` and `@sparkletree/react` (or the CLI's own `>=18` when neither is installed). | **fail**: Node is older. Install a version that meets the range, for example the current LTS. **skip**: the range could not be read. |
| `packages` | `@sparkletree/core` and `@sparkletree/react` are installed at the same version. | **fail**: core is not installed (`npm install @sparkletree/core @sparkletree/react`), or the two versions differ (install both at the react version). **warn**: react is not installed; install it at core's version if the site uses React. |
| `cli-version` | The CLI and the installed packages are the same version. | **warn**: they differ. Run the matching CLI: `npx @sparkletree/cli@<version> doctor`. **skip**: core is not installed. |
| `env-file` | The env file was read, or the variables were read from the environment. | **fail**: no env file. Run `sparkletree init` (with `--env-file` when you named one). |

### The key and the API base

| Check | pass | warn or fail, and the remedy |
|---|---|---|
| `key` | The key decodes; the message names `live` or `test` and the workspace. | **fail**: no `SPARKLETREE_KEY` variable (run `sparkletree init`, or add `NEXT_PUBLIC_SPARKLETREE_KEY=<publishable key>` with your framework's prefix), or the key does not decode (copy it again from Settings > Embedding, or run `init`). **skip**: no env file, or `@sparkletree/core` could not be loaded. |
| `org-id` | Shown only when it warns. | **warn**: `SPARKLETREE_ORG_ID` is not the workspace in the key. Set it to the key's workspace id, or run `init` again. |
| `api-base` | The API base (`SPARKLETREE_API_BASE`, else the one in the key) is `https` and a SparkleTree host. | **fail**: it is not `https`. Use the address `sparkletree whoami` shows. **warn**: it is not a SparkleTree host, so facts, slot reads, `ask` and the setup check send nothing to it and new fragment copy is never written, unless the provider gets `apiBase` and `organizationId` as props. Fragment reads, which carry neither the key nor page text, are still sent. Set the address `whoami` shows, or, for a self-hosted edge, pass both props. A loopback API base (`localhost`, `127.0.0.1`, `[::1]`), such as the mock edge of `sparkletree dev`, is a **pass** in a development env file and a **fail** in a production one (a file name with `prod` in it): visitors cannot reach it. **skip**: no API base. |
| `key-env` | The kind of key fits the file. | **warn**: a test key in a file whose name contains `prod`. Use the live key there and keep the test key for development. |

### The edge

These run only with a key that decodes and a usable API base; otherwise all
four are skipped.

| Check | pass | warn or fail, and the remedy |
|---|---|---|
| `edge` | The edge at the API base answers. | **fail**: no answer, or a 5xx. Check the API base and your network, then try again in a few minutes. |
| `whoami-key` | The edge accepts the key. | **fail** when the edge enforces the check, **warn** while it only logs: the edge does not accept the key. The remedy is the edge's own sentence for the reason (`missing_key`, `malformed_key`, `unsigned`, `bad_signature`, `no_secret`, `org_mismatch`). |
| `origin` | The site is allowed, and the message says by which rule: `registered`, `brand-domain` or `platform`. With a test key the edge answers `test-key` for every site before it looks at the site, so the message says only that the edge accepts this test key from any site, and that whether a page on the site can read the answers is what `browser-read` reports. For a localhost site the message also says that the hosted edge writes no new fragment copy there; against a loopback API base, such as `sparkletree dev`, it does not, because the mock edge writes it. | **fail** when the edge enforces the check, **warn** while it only logs: the site is not allowed. Register it: `sparkletree init --origin <site>`. **skip**: no `--origin` or `--url`, or the edge did not accept the key, so it did not check the site. The key's fix is in `whoami-key`. |
| `browser-read` | A page on the site can read the edge's answers. `doctor` sends the edge the request a browser sends before it reads a stream (a CORS preflight, `OPTIONS` on `/api/embed/v1/islands/stream` with the site as `Origin`) and reads `Access-Control-Allow-Origin` from the answer: the site itself, or `*`, is a **pass**. This is what decides it for a test key, which the edge accepts from any site but answers a browser on only when the site is registered, a verified brand domain or localhost. | **fail**: the edge does not answer a browser on the site, so a page there shows only your fallbacks. Register it: `npx @sparkletree/cli init --origin <site>`. For a localhost site, the edge predates the rule that answers localhost: use the mock edge (`npx @sparkletree/cli dev`) or a registered https site. **skip**: no `--origin` or `--url`, no usable API base, or no answer. |
| `enforcement` | Always passes. It reports what the edge does with a request that fails the key and site check: refuses it (`required`), logs it and serves it (`log`), or does not check (`off`). | |

When the edge has no key check yet, `edge` passes and the other three are
skipped.

### The campaign

| Check | pass | warn or fail, and the remedy |
|---|---|---|
| `campaign` | The campaign resolves and can be served. It is read from the edge's cache, so nothing is generated. | **fail**: it does not resolve for this workspace (not in it, not active, or no active variant), the id is not a campaign id, or the edge refused the key for the read. Check the id with `sparkletree whoami`, which lists the campaigns that can be served, and set it with `sparkletree init --campaign <id>`. **warn**: the edge resolved a different campaign, or refused the read for another reason. **skip**: no campaign, no answer, rate limited, or the read ended before it named a campaign; run `doctor` again. |

### The page (with `--url`)

| Check | pass | warn or fail, and the remedy |
|---|---|---|
| `page` | The page answered 2xx. | **fail**: the address is not http or https, the page answered with an error status (check that it is served without signing in), or it could not be fetched (check that the site is running and reachable from this machine). |
| `csp-connect` | The page sends no Content Security Policy, no policy restricts `connect-src`, or every policy allows the API base. | **fail**: a policy blocks the API base. The remedy names the policy (header or `<meta>`) and the source to add. |
| `csp-frame` | Every policy allows `https://*.cloudflarestream.com` in `frame-src`. | **fail**: a policy blocks the live player; the remedy says what to add. **skip**: the served HTML shows no live player. |
| `server-rendered` | The served HTML holds the copy markers `data-st-slot` or `data-content-source`: the page is server-rendered. | **warn**: it holds none, so the copy is rendered in the browser only. That is fine for a client-rendered app. To have the copy in the HTML, see [Server-rendered pages](https://docs.sparkletree.io/developers/sdk/server-rendering.md). |

Without `--url` these four are skipped.

## The Content Security Policy

If your site sends a Content Security Policy, two directives matter:

| Directive | Must allow | For |
|---|---|---|
| `connect-src` | Your API base (`sparkletree whoami` shows it; for the hosted service it is `https://p.qrtree.ai`) | Content, the copy stream, fragments and the events the SDK sends. |
| `frame-src` | `https://*.cloudflarestream.com` | Only when you turn on the live player. Its iframe is always `https://<one label>.cloudflarestream.com/<id>/iframe`. |

A policy line you can copy, for the hosted service:

```
connect-src 'self' https://p.qrtree.ai; frame-src https://*.cloudflarestream.com
```

Keep your own sources in each directive; the line above adds SparkleTree's.
A directive you do not set falls back to `default-src` (`frame-src` first to
`child-src`), so a strict `default-src` blocks SparkleTree too. When a page
has several policies, from headers and `<meta http-equiv>` tags, the browser
enforces each one, and a request goes through only if all of them allow it.
`doctor --url` reads them all the same way. Images, video and audio need
their own directives; see [Origins, CSP and privacy](https://docs.sparkletree.io/developers/sdk/origins-and-privacy.md#add-three-csp-directives).

## Check a key and a site from code: `checkSetup`

```ts
import { checkSetup } from "@sparkletree/core";

const result = await checkSetup({
  apiBase: "https://p.qrtree.ai",
  publishableKey: process.env.NEXT_PUBLIC_SPARKLETREE_KEY,
  origin: "https://yoursite.com",
});

if (!result.ok) console.warn(`SparkleTree: ${result.reason}. ${result.remedy}`);
```

`checkSetup` asks the edge (`GET /api/embed/v1/whoami`) what it would decide
for this key and site, without generating or spending anything. It never
rejects: when the edge cannot be reached, `reached` is false and `reason`
says why. The edge answers with open CORS, so it also works from a page on a
site that is not registered yet, which is the case it exists to explain.
Without `origin`, the edge reads the request's `Origin` header, so in a
browser it checks the page's own site.

| Option | |
|---|---|
| `apiBase` | Required. `https`, or `http` for `localhost`. |
| `publishableKey` | `st_pk_…`, sent as `Authorization: Bearer`. |
| `organizationId` | When given, it must match the key's workspace. |
| `origin` | The site to check, such as `https://yoursite.com`. |
| `apiBaseProvenance` | `"explicit"` (the default) or `"key"`. With `"key"`, an API base that is not a SparkleTree host is refused without a request. |
| `signal` | An `AbortSignal`. |
| `timeoutMs` | Default 10000. Past it the check stops and is not reached, with `reason: "timeout"`. `0` or `Infinity` turns it off. |
| `fetchImpl` | A `fetch` to use instead of the platform's, for tests. |

| Member | |
|---|---|
| `reached` | True when the edge answered with a whoami document. |
| `ok` | What the edge's key and site check would decide. False when not reached. |
| `organizationId` | The key's workspace, or null. |
| `key` | `{ present, env, valid }`, with `env` `"live"`, `"test"` or null. |
| `origin` | `{ value, allowed, via }`, with `via` `"registered"`, `"brand-domain"`, `"platform"`, `"test-key"` or null. |
| `reason` | Null when `ok`. An edge reason (`missing_key`, `malformed_key`, `unsigned`, `bad_signature`, `no_secret`, `org_mismatch`, `missing_origin`, `origin_not_allowed`) or, when not reached, an SDK reason (`insecure_api_base`, `untrusted_api_base`, `network`, `aborted`, `timeout`, `http_error`, `malformed`). |
| `remedy` | One sentence that fixes `reason`, or null. |
| `enforcement` | `"off"`, `"log"` or `"required"`: what the edge does today with a request that fails the check. Null when not reached. |
| `protocol` | `{ supported, current }`: the protocol versions the edge speaks. |
| `sdk` | `{ vendored }`: the version of `@sparkletree/core` the edge carries. |
| `time` | The edge's clock, ISO 8601. |
| `status` | The HTTP status, when the edge answered. |

A live key from a server, with no `origin`, answers `missing_origin`: live keys
work only from a browser origin. Pass `origin` to check a site from a server.

## From a client you already have: `createClient(...).check()`

```ts
import { createClient } from "@sparkletree/core";

const client = createClient({ publishableKey: process.env.NEXT_PUBLIC_SPARKLETREE_KEY! });

const result = await client.check({ origin: "https://yoursite.com" });
if (!result.ok) console.warn(`SparkleTree: ${result.reason}. ${result.remedy}`);
```

`check()` is `checkSetup` with the client's API base, workspace and key, so
you do not pass them again. It takes three options, `origin`, `signal` and `timeoutMs`, and
answers the same result as `checkSetup`. It never rejects. The API base
keeps where it came from: when the client got it from the key rather than
from an explicit `apiBase`, an API base that is not a SparkleTree host is
refused without a request (`untrusted_api_base`), as with
`apiBaseProvenance: "key"`.
