Docs / AR Experiences

The @maravilla/ar SDK

Studio is the backend: it stores the experience, compiles the targets and publishes. You build the frontend. @maravilla/ar is the small SDK that turns the published content into something a phone camera can use. It has two halves.

HalfRunsDoes
@maravilla/ar/server — loadExperience()Your serverReads the published experience and returns a JSON manifest: the compiled bundle URL, the targets, the scenes and their blocks.
@maravilla/ar — mountArViewer()The browserStarts the camera, tracks the printed target, draws the blocks and emits events.

It does not own routing, page design, the camera-permission screen, analytics, consent or the “unsupported browser” screen. Those are yours.

Experimental. Pin the version, and expect to adjust on upgrades.

Install

@maravilla/* packages come from the Maravilla registry, not public npm. Add an .npmrc next to your package.json:

@maravilla:registry=https://solutas.registry.maravilla.cloud/-/npm
npm i @maravilla/ar

1. A server route that returns the manifest

The browser cannot hold an API key, and signed asset URLs are minted on the server. So your server owns one small route. It talks to RaisinDB over plain HTTP with a Bearer key — no client library and no tenant id. Read the three settings from the runtime environment, so a secret set only in production is not baked into the build empty. (vite dev does not load .env into process.env by itself — start it with node --env-file-if-exists=.env ./node_modules/vite/bin/vite.js dev, or use your framework’s own env access.)

# .env  (never commit it, never send it to the browser)
RAISINDB_URL=https://your-studio.example.com
RAISINDB_API_KEY=...
RAISINDB_REPO=studio
// src/routes/api/ar/[name]/+server.ts
import { json, error } from '@sveltejs/kit';
import { loadExperience } from '@maravilla/ar/server';

export async function GET({ params }) {
  try {
    const manifest = await loadExperience({
      path: `/${params.name}`,                       // path inside the Assets workspace
      repository: process.env.RAISINDB_REPO ?? 'studio',
      baseUrl: process.env.RAISINDB_URL!,
      apiKey: process.env.RAISINDB_API_KEY,
      signAsset: async (_ws, p) => `/media${p}`,     // serve media from YOUR origin
    });
    return json(manifest);
  } catch (e: any) {
    if (e.code === 'AR_NOT_FOUND' || e.code === 'AR_NOT_COMPILED') throw error(404, e.message);
    throw error(502, 'The content server could not be reached');
  }
}
// app/routes/api.ar.$name.ts   (register: route('api/ar/:name', 'routes/api.ar.$name.ts'))
import { loadExperience } from '@maravilla/ar/server';

export async function loader({ params }: { params: { name: string } }) {
  try {
    const manifest = await loadExperience({
      path: `/${params.name}`,
      repository: process.env.RAISINDB_REPO ?? 'studio',
      baseUrl: process.env.RAISINDB_URL!,
      apiKey: process.env.RAISINDB_API_KEY,
      signAsset: async (_ws, p) => `/media${p}`,
    });
    return Response.json(manifest);
  } catch (e: any) {
    const missing = e.code === 'AR_NOT_FOUND' || e.code === 'AR_NOT_COMPILED';
    return Response.json({ error: e.message }, { status: missing ? 404 : 502 });
  }
}

Things worth knowing:

  • path is relative to the Assets workspace: an experience you see at /assets/birthday-invitation in the Studio address bar is /birthday-invitation here.
  • repository is required. It is the RaisinDB repository the content lives in (studio unless you named it otherwise).
  • baseUrl + apiKey are the normal way in: plain HTTP, no client library. If your app already holds a RaisinClient, pass it as client instead.
  • It reads the published branch. If the route says No AR experience at …, the experience is not published yet — or the key cannot read the repository (an unauthorised read looks empty, not forbidden).
  • It throws if the experience is not compiled. Serving a missing bundle would open the camera and silently never match, which looks exactly like a bug.
  • Errors you can branch on carry a code: AR_NOT_FOUND (no such experience on the published branch) and AR_NOT_COMPILED. Any error without a code is a transport or database failure — answer 502, not 404.

The manifest is plain JSON:

{
  "version": 1,
  "experience": { "path": "/birthday-invitation", "title": "Birthday invitation" },
  "bundleUrl": "/media/.ar-bundles/birthday-invitation/<hash>.mind",
  "targets": [{
    "index": 0,
    "name": "Invitation front",
    "physicalWidthMm": 90,
    "scenes": [{ "id": "/birthday-invitation/invitation-front/main", "blocks": [ /* ar:* blocks */ ] }]
  }]
}

2. Mount the viewer

The viewer needs a browser (a camera, WebGL), so import it only on the client — inside onMount in Svelte, inside an effect in React — never at the top of a module that also renders on the server.

<!-- src/routes/ar/[name]/+page.svelte -->
<script lang="ts">
  import { onMount } from 'svelte';
  import { page } from '$app/state';

  let host: HTMLElement;
  let viewer: any;
  let state = $state<'idle' | 'loading' | 'running' | 'unsupported' | 'error'>('idle');
  let found = $state(false);
  let message = $state('');

  async function start() {
    state = 'loading';
    try {
      const { mountArViewer, detectArSupport } = await import('@maravilla/ar');
      const support = detectArSupport();
      if (!support.supported) { message = support.reason ?? ''; state = 'unsupported'; return; }

      const res = await fetch(`/api/ar/${page.params.name}`);
      if (!res.ok) throw new Error((await res.json()).message ?? 'Could not load the experience');
      viewer = await mountArViewer(host, await res.json());
      viewer.on('targetFound', () => (found = true));
      viewer.on('targetLost', () => (found = false));
      await viewer.start();                       // we are inside a tap handler
      state = 'running';
    } catch (e) {
      message = e instanceof Error ? e.message : String(e);
      state = 'error';
    }
  }

  onMount(() => () => viewer?.destroy());
</script>

<div bind:this={host} class="ar-host"></div>

{#if state === 'idle' || state === 'loading'}
  <button onclick={start} disabled={state === 'loading'}>Start AR</button>
{:else if state === 'running' && !found}
  <p>Point your camera at the card</p>
{:else if state === 'unsupported'}
  <p>Open this page in Safari or Chrome. {message}</p>
{:else if state === 'error'}
  <p>{message}</p><button onclick={start}>Try again</button>
{/if}
// app/routes/ar.$name.tsx   (register: route('ar/:name', 'routes/ar.$name.tsx'))
import { useRef, useState, useEffect } from 'react';
import { useParams } from 'react-router';

export default function Ar() {
  const { name } = useParams();
  const host = useRef<HTMLDivElement>(null);
  const viewer = useRef<any>(null);
  const [state, setState] = useState<'idle' | 'loading' | 'running' | 'unsupported' | 'error'>('idle');
  const [found, setFound] = useState(false);
  const [message, setMessage] = useState('');

  useEffect(() => () => viewer.current?.destroy(), []);

  async function start() {
    setState('loading');
    try {
      const { mountArViewer, detectArSupport } = await import('@maravilla/ar');
      const support = detectArSupport();
      if (!support.supported) { setMessage(support.reason ?? ''); setState('unsupported'); return; }

      const res = await fetch(`/api/ar/${name}`);
      if (!res.ok) throw new Error((await res.json()).error ?? 'Could not load the experience');
      viewer.current = await mountArViewer(host.current!, await res.json());
      viewer.current.on('targetFound', () => setFound(true));
      viewer.current.on('targetLost', () => setFound(false));
      await viewer.current.start();               // we are inside a tap handler
      setState('running');
    } catch (e) {
      setMessage(e instanceof Error ? e.message : String(e));
      setState('error');
    }
  }

  return (
    <>
      <div ref={host} className="ar-host" />
      {(state === 'idle' || state === 'loading') && (
        <button onClick={start} disabled={state === 'loading'}>Start AR</button>
      )}
      {state === 'running' && !found && <p>Point your camera at the card</p>}
      {state === 'unsupported' && <p>Open this page in Safari or Chrome. {message}</p>}
      {state === 'error' && (<><p>{message}</p><button onClick={start}>Try again</button></>)}
    </>
  );
}

Give .ar-host the full viewport (position: fixed; inset: 0) — the camera and the 3D scene are drawn into it.

The viewer object has start(), stop(), destroy(), on(), scene and overlayButtons.

Actions and buttons

blockAction hands you an action that is already normalised — WhatsApp, phone and mail buttons arrive as a url action with a https://wa.me/…, tel: or mailto: address:

action.kindFieldsWhat to do
urlurlOpen it (window.open, or set location for tel: and mailto:).
sharetextnavigator.share({ text }) when available, otherwise copy.
scenesceneSwitch to another scene of the same target.
eventnameYour own hook — whatever the author typed into Event name.

viewer.overlayButtons is a list of { id, block, fire, visible }: block.label is the text to show, fire() runs the button’s action. It is filled while the scene is built, so read it right after mountArViewer() resolves.

Draw only the buttons whose visible is true, and keep them in step with the buttonVisible event. An author can say “show this button 42 seconds into the video” or “hide it when the card is lost”; the SDK evaluates that rule and tells you the result — it does not draw the button for you:

let buttons = viewer.overlayButtons.map((b) => ({ ...b }));   // { id, block, fire, visible }
render(buttons.filter((b) => b.visible));

viewer.on('buttonVisible', ({ blockId, visible }) => {
  buttons = buttons.map((b) => (b.id === blockId ? { ...b, visible } : b));
  render(buttons.filter((b) => b.visible));
});

Events

EventWhen
readyThe camera is running and tracking has started.
targetFound / targetLostA target entered or left the camera view.
buttonVisibleAn AR Button’s reveal rule showed or hid it: { blockId, visible }.
blockActionAn AR Button was activated; action.kind says which.
videoPlayThe visitor tapped a video’s poster and playback started.

Steadier overlays

MindAR’s own defaults barely smooth the tracked pose, so text over a card can shiver. The viewer applies a smoother profile by default, taken from the target’s Tracking tab in Studio when you set values there, and from the options you pass:

mountArViewer(host, manifest, {
  tracking: { filterMinCF: 0.05, filterBeta: 5 },   // calmer, a little more lag
  // tracking: { smooth: false },                  // MindAR's raw defaults
});

Lower filterBeta and filterMinCF make the overlay steadier but slightly laggier; higher values follow the card faster but shake more. missTolerance is how many frames the overlay survives a lost detection before it hides.

Media: your own origin is optional

By default loadExperience() signs every file with RaisinDB’s asset endpoint and the viewer loads it from there. That works as it is. Newer RaisinDB servers answer Range requests (so video seeks) and CORS for configured origins themselves, so a media proxy is optional — check before building one.

Test the endpoint with a signed video URL:

# must answer 206 with a Content-Range header
curl -s -o /dev/null -D- -H 'Range: bytes=0-1' "<signed video url>"
# must include Access-Control-Allow-Origin for your site's origin
curl -s -o /dev/null -D- -H 'Origin: https://your-site.example' "<signed video url>"

If both pass, leave signAsset out. Add a same-origin proxy when:

  • the endpoint does not honour Range (older servers — video cannot seek);
  • your origin is not on the CORS allow-list and you do not want to configure it;
  • you want your own cache headers — the endpoint’s default is a short private cache, so a large bundle or video is re-fetched often, while the compiled bundle’s file name contains a content hash and can be cached for a year;
  • you do not want signed URLs, which expire, reaching the browser.

The proxy is one route: point signAsset at /media/... on your server, fetch the file from RaisinDB there, answer Range with a 206, and set long cache headers for the bundle.

// src/routes/media/[...path]/+server.ts
import { signAssetUrl } from '@maravilla/ar/server';

export async function GET({ params, request }) {
  const path = '/' + params.path;
  const url = await signAssetUrl({
    baseUrl: process.env.RAISINDB_URL!,
    apiKey: process.env.RAISINDB_API_KEY,
    repository: process.env.RAISINDB_REPO ?? 'studio',
    path,
  }).catch(() => undefined);          // a path with `..` or `?` is refused, not signed
  if (!url) return new Response('Not found', { status: 404 });
  const upstream = await fetch(url);
  if (!upstream.ok) return new Response('Not found', { status: 404 });
  const bytes = new Uint8Array(await upstream.arrayBuffer());
  const type = upstream.headers.get('content-type') ?? 'application/octet-stream';
  const cache = path.startsWith('/.ar-bundles/') ? 'public, max-age=31536000, immutable' : 'public, max-age=3600';

  const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.get('range') ?? '');
  if (range) {
    const start = range[1] ? Number(range[1]) : 0;
    const end = Math.min(range[2] ? Number(range[2]) : bytes.length - 1, bytes.length - 1);
    return new Response(bytes.slice(start, end + 1), {
      status: 206,
      headers: {
        'content-type': type, 'accept-ranges': 'bytes', 'cache-control': cache,
        'content-range': `bytes ${start}-${end}/${bytes.length}`,
      },
    });
  }
  return new Response(bytes, {
    headers: { 'content-type': type, 'accept-ranges': 'bytes', 'cache-control': cache },
  });
}
// app/routes/media.$.ts   (register: route('media/*', 'routes/media.$.ts'))
import { signAssetUrl } from '@maravilla/ar/server';

export async function loader({ params, request }: { params: { '*': string }; request: Request }) {
  const path = '/' + params['*'];
  const url = await signAssetUrl({
    baseUrl: process.env.RAISINDB_URL!,
    apiKey: process.env.RAISINDB_API_KEY,
    repository: process.env.RAISINDB_REPO ?? 'studio',
    path,
  }).catch(() => undefined);          // a path with `..` or `?` is refused, not signed
  if (!url) return new Response('Not found', { status: 404 });
  const upstream = await fetch(url);
  if (!upstream.ok) return new Response('Not found', { status: 404 });
  const bytes = new Uint8Array(await upstream.arrayBuffer());
  const type = upstream.headers.get('content-type') ?? 'application/octet-stream';
  const cache = path.startsWith('/.ar-bundles/') ? 'public, max-age=31536000, immutable' : 'public, max-age=3600';

  const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.get('range') ?? '');
  if (range) {
    const start = range[1] ? Number(range[1]) : 0;
    const end = Math.min(range[2] ? Number(range[2]) : bytes.length - 1, bytes.length - 1);
    return new Response(bytes.slice(start, end + 1), {
      status: 206,
      headers: {
        'content-type': type, 'accept-ranges': 'bytes', 'cache-control': cache,
        'content-range': `bytes ${start}-${end}/${bytes.length}`,
      },
    });
  }
  return new Response(bytes, {
    headers: { 'content-type': type, 'accept-ranges': 'bytes', 'cache-control': cache },
  });
}

signAssetUrl reads the published branch only and refuses paths that could leave the asset address. For a preview route an author looks at, pass allowDraft: true.

This buffers each file in memory, which is right for a card’s bundle and a short video; put a CDN or object store in front of anything bigger.

Buttons: use real HTML

An AR Button always emits blockAction. Draw your own HTML buttons from viewer.overlayButtons over the camera instead of relying on buttons inside the 3D scene: they have proper hit targets and accessibility, and on iOS a link opened from a 3D click is often swallowed as “not a user gesture”.

Images, video and sound

loadExperience() signs every image, poster, video, model and audio file a scene references and puts the address on the block, so the viewer can load it. Those addresses go through your signAsset function — which is how you point them at your own media route if you add one.

Video

Browsers autoplay only muted video. A message with sound must start from a tap, so poster + tap-to-play is the default and autoplay is honoured only when the block is also muted.

In-app browsers

A QR code scanned inside WhatsApp or Instagram opens an in-app browser where the camera is often blocked. detectArSupport() tells you; show an “Open in Safari or Chrome” screen. Treat it as a required feature.

Custom blocks and self-hosting

Add your own block type to the registry:

import { arRegistry } from '@maravilla/ar/registry';

arRegistry['acme:Confetti'] = (block, ctx) => {
  const el = document.createElement('a-entity');
  ctx.registerReveal(el, block.reveal);   // take part in the reveal timeline
  return el;
};

By default the viewer loads A-Frame and MindAR from a CDN. For production, host both yourself and pass them in, so you depend on no third party and a strict CSP names one origin:

mountArViewer(host, manifest, {
  runtimeUrls: { aframeUrl: '/vendor/aframe.min.js', mindarUrl: '/vendor/mindar-image-aframe.js' },
});

Troubleshooting

SymptomCause
Repository 'assets' not foundrepository was left out of loadExperience() — pass the repository name, not the workspace.
No AR experience at …Wrong path (it is workspace-relative), not published, or the key cannot read the repository.
… is not compiledThe experience’s bundle state is not compiled. Compile it in Studio and publish again.
Camera runs, nothing is detectedThe target is a photo of the object, the artwork was uploaded without the QR printed on the card, or the card is mostly QR or repeating pattern. See choosing the artwork.
Video will not seekThe media endpoint does not answer Range with 206 — check it with the curl above, and put the media behind your own proxy if it does not.
Nothing shows after a content editThe experience was edited but not published again.

Pilot documentation. Studio is in a partner pilot. Screens and YAML shown here are current as of the version noted on each page; tell your Maravilla contact when something does not match what you see.