# Show prices and other facts

A stated fact is a value your workspace has on record: a product's name, its
price, whether it is in stock. The SDK reads facts from the edge and never
generates or adapts them. Put one in the page with `<Fact>`:

```tsx
import { Fact, SparkletreeProvider } from "@sparkletree/react";

<SparkletreeProvider publishableKey={KEY}>
  <p className="price">
    <Fact product="stoneware-mug" fact="price" fallback="249,00 kr" />
  </p>
</SparkletreeProvider>
```

`product` is the product's id or its shop handle. `fallback` is the text the
page shows when the fact is not stated or cannot be read, and it sets the
space the fact may take.

There are three ways to show facts:

| Way | Use it for |
|---|---|
| A `fact` field in a fragments declaration | A fact next to adapted copy, under the same hold and in the same draw. |
| `<Fact>` (React) or `<sparkletree-fact>` (any framework) | One fact on its own, inside your own element. |
| `fetchFacts`, or `useFacts` in React | The whole facts document as data, for markup you render yourself or for a server. |

## A fact next to adapted copy

A fragments declaration takes `kind: "fact"` fields next to generated ones.
All of them resolve under one hold, in one round of requests:

```tsx
import { FragmentGroup, FragmentText, useFragments } from "@sparkletree/react";

function MugCard() {
  const f = useFragments({
    context: { page: "product", intent: "convert" },
    fields: {
      pitch: { kind: "body", fallback: "A heavy mug that keeps coffee warm." },
      name:  { kind: "fact", product: "stoneware-mug", fact: "name",  fallback: "Stoneware mug" },
      price: { kind: "fact", product: "stoneware-mug", fact: "price", fallback: "249,00 kr" },
    },
  });

  return (
    <FragmentGroup fragments={f} as="article">
      <h3><FragmentText field={f.name} /></h3>
      <p><FragmentText field={f.pitch} /></p>
      <p className="price"><FragmentText field={f.price} /></p>
    </FragmentGroup>
  );
}
```

`<Fact>` is exactly this with one field. Every rule of
[fragments](https://docs.sparkletree.io/developers/sdk/fragments.md) applies to a fact field: it holds
with its fallback keeping its space, it lands once if it arrives inside the
hold and fits, and text the visitor has seen is never replaced.

When a stated value is the same text as its fallback, nothing on the page
changes: the text stays exactly as it is. The field still counts as stated,
so it carries `stated: true` and `data-content-source="stated"`, because the
workspace stated that value. That stamp needs the value to land: the answer arrives while the field
still holds and fits its space. When the hold has already ended, when there
is no hold (`holdMs: 0`, or the group was shown earlier in the page view),
or when the fit check refuses it, the fallback is shown as your own text,
with no stamp. When a fact is not stated, the fallback stays
and is your own copy (`source: "static"`, no `stated`).

## The facts you can name

| `fact` | Returns |
|---|---|
| `name` | The product's name. |
| `price` | The amount formatted with its currency for the page language, for example `249,00 kr` for `sv-SE`. |
| `amount` | The amount as stored, as a decimal string, for example `249.00`. Never formatted. |
| `currency` | The ISO 4217 code, for example `SEK`. |
| `availability` | Your words for the stated state, from `labels` (see below). `unknown` counts as not stated, so the fallback stays. |
| `sku` | The stock keeping unit. |
| `description` | The product's description as stored. |

A fact the workspace has not stated leaves the fallback in place. The edge
reports availability as `in_stock` or `out_of_stock` only when the product's
inventory is tracked; otherwise it is `unknown`.

## Availability in your own words

The edge states availability as a code, `in_stock` or `out_of_stock`. A
code is not text for a visitor, so an availability field shows the words
you give it for each state:

```tsx
<p className="stock">
  <Fact
    product="stoneware-mug"
    fact="availability"
    labels={{ in_stock: "In stock", out_of_stock: "Sold out" }}
    fallback="In stock"
  />
</p>
```

In a fragments declaration the same field is
`{ kind: "fact", product: "stoneware-mug", fact: "availability", labels: { in_stock: "In stock", out_of_stock: "Sold out" }, fallback: "In stock" }`.
In the custom elements the words are attributes on the text:
`<sparkletree-fact product="stoneware-mug" fact="availability" in-stock="In stock" out-of-stock="Sold out">In stock</sparkletree-fact>`.

The field lands the label for the stated state. It keeps its fallback when
there is no label for that state, when it has no labels at all, and when
the state is `unknown`. Development builds warn once when an availability
field has no labels. `labels` is read only for `availability`.

Each label must fit the fallback's space like any other value: it is held
to the fallback's character budget and measured in place. Make the fallback
the longest label, so every state fits. As with any fact, a label equal to
the fallback changes no text on the page; the field is still stamped
`stated`.

The code itself is still data: `useFacts` and `fetchFacts` return it as
`product.availability`.

## Prices and the page language

`price` is formatted with
`Intl.NumberFormat(language, { style: "currency", currency })`. The same
amount reads differently per language:

| Language | `249.00` in `SEK` |
|---|---|
| `en` | `SEK 249.00` |
| `sv-SE` | `249,00 kr` |
| `de-DE` | `249,00 SEK` |

Where the language comes from:

- **React:** the provider's language. That is the `language` in the
  provider's `context` when you set one, else the language of the server
  read (`serverContext`), else the browser's (`navigator.language`).
- **Custom elements:** the nearest `lang` attribute, else the document's,
  else `en`.
- **Core:** the `language` option of `fetchFragments` or
  `client.fragments`. Core never reads it from the browser and defaults to
  `en`, so a server and a browser that pass the same value format the same
  string.

When the currency is not known, the amount is not a plain decimal, or the
runtime cannot format the language or currency, `price` is the raw amount.

Write the fallback as the formatted price will read for the page language,
at least as long. The fallback sets the space: a formatted price longer than
its fallback can be refused (see below).

## Unknown products and values that do not fit

Every failure leaves the fallback in place, and development builds say why:

- **A product the workspace does not have** (by id or by handle, matched
  without regard to case): the edge leaves it out of its answer, and the
  field keeps its fallback.
- **A value longer than its budget.** A fact gets the same character budget
  a generated field with that fallback gets: `name` is sized as a
  `headline`, `description` as a `body`, every other fact as a `label`.
  A longer value is refused.
- **A value that would not fit the space.** As with every fragment, the
  renderer measures the value in place before it is painted. In React,
  shorter text lands pinned to the box the fallback held, and text that
  would make the element larger is refused. The custom elements are
  stricter; see [Use it in any framework](https://docs.sparkletree.io/developers/sdk/elements.md).
- **More than 20 products in one declaration.** One facts request names at
  most 20 products. Fields for the others keep their fallbacks.
- **The request fails** (network, an error status, a malformed answer, an
  aborted request): every fact field keeps its fallback. `fetchFacts`
  resolves `{ ok: false, reason }` and never rejects.

## A fact is never adapted copy

A landed fact has `source: "static"` and `stated: true`. The renderers stamp
it `data-content-source="stated"`, so it can be told apart from your own
copy (`static`) and from adapted copy (`generated`, `cached`).

`source` keeps its three values, so a fact never makes a group count as
adapted: `$group.marked` stays false for a group whose only landed text is
facts, and `FragmentGroup` stamps the group with the strongest source among
its other fields. If your site labels AI-generated copy, a fact needs no
label.

## Facts requests made together are sent as one

Fact fields that start in the same frame share one request to
`GET /api/embed/v1/facts`, when they use the same API base, workspace, key
and page language. A product card with `<Fact>` for the name, the price and
the availability makes one request, not three. Each request names at most
20 products; more start a second request.

`fetchFacts` and `useFacts` make their own request each time.

## The whole document as data

`useFacts` returns the facts document for a campaign, a surface or named
products:

```tsx
import { useFacts } from "@sparkletree/react";

function LowStockNote() {
  const { facts } = useFacts({ products: ["stoneware-mug"] });
  const soldOut = facts?.products[0]?.availability === "out_of_stock";
  // A fixed box: the note appearing later cannot move the page.
  return (
    <span className="stock-note" style={{ display: "inline-block", width: "16em" }}>
      {soldOut ? "Back in stock soon" : ""}
    </span>
  );
}
```

`useFacts` holds nothing and renders nothing. While its request runs,
`facts` is `null`, `ok` is false and `reason` is undefined. The request runs
in the browser after mount and again when the options change. Markup you
render from it is yours, and so is its layout: give it a fixed space, or
render it where text appearing later cannot move the page. For text in the
page flow, use `<Fact>`.

| Option | |
|---|---|
| `campaignId` | The campaign whose products and legal lines to read. |
| `surfaceId` | The surface whose current campaign to read. |
| `products` | Product ids or handles, at most 20. Without them, the campaign's or surface's own products. |

It returns `{ facts, ok, reason, verify }`. `verify()` checks the signature
(see below).

Outside React, `fetchFacts` reads the same document:

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

const result = await fetchFacts({
  apiBase: "https://p.qrtree.ai",
  organizationId: ORG,
  publishableKey: KEY,
  campaignId: CAMPAIGN,          // or surfaceId, or products
  products: ["stoneware-mug"],
});

if (result.ok) {
  const mug = result.facts!.products[0];
}
```

`createClient({ publishableKey }).facts({ products })` does the same with
the client's API base, workspace and key. Both take `signal` and
`timeoutMs`: the call stops after 10 seconds without a complete answer
unless you pass another value.

`result` is `{ ok, facts, reason?, status?, url? }`. `facts` is the document
exactly as the edge sent it, unknown members kept, so it still verifies.
`reason` is one of:

| `reason` | |
|---|---|
| `insecure_api_base` | `apiBase` is not https (http is allowed for localhost only). No request was made. |
| `untrusted_api_base` | `apiBase` came from a publishable key and is not a SparkleTree host. No request was made. |
| `missing_organization` | No `organizationId`. No request was made. |
| `network`, `aborted` | The request did not complete. |
| `timeout` | No complete answer within `timeoutMs` (default 10000 ms; `0` or `Infinity` turns it off). |
| `http_error` | The edge answered with another status; see `status`. |
| `malformed` | The edge answered 200 with something that is not a facts document. |

`factText(product, fact, language, labels)` and `findFactProduct(facts, product)`
read one fact out of a document the same way a declaration does. `labels`
is used only for `availability`; without it, `factText` returns undefined
for that fact.

## What the document contains

```json
{
  "facts": 1,
  "organization": { "id": "…", "name": "Kiln & Co", "url": "https://kiln.example" },
  "campaign": {
    "id": "…",
    "name": "Autumn firing",
    "url": "https://p.qrtree.ai/c/…/autumn-firing",
    "legalLines": ["Prices include VAT."]
  },
  "products": [
    {
      "id": "…",
      "handle": "stoneware-mug",
      "name": "Stoneware mug",
      "price": "249.00",
      "currency": "SEK",
      "availability": "in_stock",
      "sku": "MUG-01",
      "url": "https://kiln.example/mug"
    }
  ],
  "ask": { "url": "https://p.qrtree.ai/ask", "campaign": "…" },
  "source": "stated",
  "asOf": "2026-11-19T10:00:00Z",
  "signature": { "alg": "ed25519", "keyId": "a1b2c3d4", "value": "…" }
}
```

- Values the workspace has not stated are left out, never sent as empty
  strings.
- The products are the ones you named, or the campaign's own when you named
  none. They come from campaigns the edge serves.
- `campaign` is `null` when no campaign resolved. Its `legalLines` follow
  the viewer's market (the request's `Accept-Language` and country), verbatim.
- `organization.url` is the website on record, or on a brand host that host.
  It is left out when there is neither.

Some members are sent only for campaigns that are public on the edge:

- `campaign.url`, the campaign's public page.
- `ask`, where to send questions about the campaign. It is also `null`
  when the workspace has switched its assistant off.
- A product's `url`, its page on your site.
- A product's `handle`, unless your request named the product by that
  handle.

The answer is cached for 60 seconds per viewer (`Cache-Control: private,
max-age=60`).

## Check the signature

When the edge has a signing key, the document carries an Ed25519 signature
over the canonical JSON of the whole document without its `signature`
member. Anyone can check it against the public keys at
`/.well-known/sparkletree-keys.json` on the edge:

```ts
import { fetchFacts, verifyFacts } from "@sparkletree/core";

const { facts } = await fetchFacts({ apiBase, organizationId, publishableKey, products: ["stoneware-mug"] });
const check = await verifyFacts(facts, { apiBase });
// { valid: true, keyId: "a1b2c3d4" }, or { valid: false, keyId?, reason }
```

`verifyFacts` fetches the keys document from `apiBase`, which must be a
SparkleTree host over https: keys from any other host prove nothing about
who signed. Pass `keys` instead to verify against keys you already have, and
nothing is fetched. It uses WebCrypto, so it works in browsers and in Node
where `crypto.subtle` supports Ed25519. It never rejects.

| `reason` | |
|---|---|
| `unsigned` | The document has no signature: the edge has no signing key. |
| `malformed` | Not a facts document, or a malformed signature. |
| `unsupported_alg` | The signature names an algorithm other than `ed25519`. |
| `unsupported` | Ed25519 is not available in this runtime. |
| `no_keys` | No `keys` and no `apiBase`. |
| `untrusted_key_source` | `apiBase` is not a SparkleTree host, or not https. |
| `keys_unavailable` | The keys document could not be read. |
| `unknown_key` | No key has the signature's `keyId`. |
| `bad_signature` | The signature does not match the document. |

The keys document is a list of JWKs:

```json
{ "keys": [{ "kty": "OKP", "crv": "Ed25519", "kid": "a1b2c3d4", "x": "…", "use": "sig", "alg": "EdDSA" }] }
```

`signature.keyId` names the key's `kid`; `x` is the raw 32-byte public key,
base64url. The list is empty when no key is configured.

To check a signature without the SDK, remove `signature`, write the rest as
canonical JSON, and verify `signature.value` (base64url, no padding) over its
UTF-8 bytes. Canonical JSON is RFC 8785 for the values a facts document
holds: object members sorted by the UTF-16 code units of their names, no
whitespace, and strings that escape only `"`, `\` and U+0000 to U+001F
(`\b \f \n \r \t` where they exist, lower-case `\u00xx` otherwise).
`canonicalJson(value)` from `@sparkletree/core` writes exactly this.

## From a server

`fetchFacts` and `verifyFacts` run on a server as they do in a browser. A
server sends no `Origin`, so the edge reads facts for a server caller only
with a valid publishable key: pass `publishableKey`.

```ts
// A server component, an API route or a build step.
import { fetchFacts } from "@sparkletree/core";

const result = await fetchFacts({
  apiBase: "https://p.qrtree.ai",
  organizationId: process.env.SPARKLETREE_ORG!,
  publishableKey: process.env.SPARKLETREE_KEY!,
  products: ["stoneware-mug"],
});
```

On a server, a fact field in `fetchFragments` formats `price` with the
`language` you pass. Pass the same value the browser will use, and both
write the same string.

To put the facts in your page's head for visiting agents and search
engines, use `getAgentSurface` or `<AgentSurface>`; see
[Be readable by visiting agents](https://docs.sparkletree.io/developers/sdk/agents.md).
