Dashboard SDK

Dashboard SDK

The Dashboard SDK is a monorepo of separate npm packages that work together to build Huitzo Dashboards that run inside Hub. The core is framework-agnostic; React bindings are layered on top.

Packages

Package npm Name Provides
Core @huitzo/dashboard-sdk Auth client, API client, types, error classes. Framework-agnostic. No DOM, no framework imports.
React @huitzo/dashboard-sdk-react Hooks (useCommand, useHuitzo, useRealtime, useHubNavigation, etc.) and components (HuitzoProvider). Depends on core as peer.

Installation

# Core SDK (framework-agnostic)
npm install @huitzo/dashboard-sdk

# React hooks and components
npm install @huitzo/dashboard-sdk @huitzo/dashboard-sdk-react

Quick Start

Core Client (Framework-Agnostic)

The core package works in any JavaScript/TypeScript environment—Node, Deno, or browser—without React or any framework:

import { HuitzoClient } from '@huitzo/dashboard-sdk';

const huitzo = new HuitzoClient({
  apiUrl: 'https://huitzo.ai',  // Optional, defaults to current origin
});

// Execute a command
const result = await huitzo.commands.execute('@acme/claims/process-claim', {
  claimId: 'CLM-12345'
});

console.log(result);

For React dashboards running inside Hub, pass the context object from mount() to HuitzoProvider:

# pseudocode — conceptual React usage
import type { HuitzoMountContext } from '@huitzo/dashboard-sdk-react';
import { HuitzoProvider, useCommand } from '@huitzo/dashboard-sdk-react';

// 1. Dashboard entry point receives context from Hub's mount()
export function mount(container: HTMLElement, context: HuitzoMountContext) {
  const root = createRoot(container);
  root.render(
    <HuitzoProvider context={context}>
      <ClaimsList />
    </HuitzoProvider>
  );
}

// 2. Use hooks in your components
function ClaimsList() {
  const { execute, data, loading, error } = useCommand('@acme/claims/list-claims');

  useEffect(() => { execute({ status: 'pending' }) }, []);

  if (loading) return <Spinner />;
  if (error) return <Error message={error.message} />;

  return <ul>{data?.claims.map(claim => <li key={claim.id}>{claim.title}</li>)}</ul>;
}

Core Client

The HuitzoClient is the foundation of the SDK. It handles authentication and API calls. The core package uses openapi-fetch for typed HTTP requests against the Huitzo REST API.

Initialization

# pseudocode
import { HuitzoClient } from '@huitzo/dashboard-sdk';

// Basic initialization (uses current origin)
const huitzo = new HuitzoClient();

// With options
const huitzo = new HuitzoClient({
  apiUrl: 'https://huitzo.ai',
  timeout: 60000,
  onAuthError: (error) => { /* redirect to login */ },
});

Configuration Options

Option Type Default Description
apiUrl string Current origin Huitzo API base URL
timeout number 60000 Request timeout (ms)
onAuthError function - Called when auth fails (receives Error)
getToken function - Per-request token accessor (@huitzo/dashboard-sdk ≥ 0.7.0); called synchronously on every request; takes precedence over setToken(); empty/undefined → no Authorization header; a throwing accessor is treated as no token

Sub-Objects

Sub-object Class Description
huitzo.auth AuthApi Login, register, refresh, logout, API key
huitzo.commands CommandsApi Execute and list Intelligence Pack commands
huitzo.packs PacksApi List and manage packs
huitzo.account AccountApi Account mode checks, developer mode
huitzo.organizations OrganizationsApi Organization and member management
huitzo.health HealthApi Liveness, readiness, and integration probes

Authentication

The SDK handles authentication via email/password login, token refresh, or API key. When running inside Hub, the HuitzoProvider syncs the JWT from the mount context automatically.

# pseudocode
// Email/password login
await huitzo.auth.login('[email protected]', 'password');

// Register a new account
await huitzo.auth.register('[email protected]', 'password', 'acme', 'coupon_code');

// API key (for development)
huitzo.auth.setApiKey('sk_...');

// Check auth status
const isAuthenticated = huitzo.auth.isAuthenticated();
const user = await huitzo.auth.getUser();

// Logout
await huitzo.auth.logout();

Accessor mode

Availability. The getToken accessor ships in @huitzo/dashboard-sdk ≥ 0.7.0 and @huitzo/dashboard-sdk-react ≥ 6.0.0 (frontend-sdk PR #111; the react package takes a major because its peer dependency on the 0.x core crossed a minor). Bundles built against earlier releases snapshot the token at mount and rely on the Hub's bundle auth backstop instead. The monorepo's tools/frontend-sdk pointer is bumped in a separate PR.

From @huitzo/dashboard-sdk-react 6.0.0, HuitzoProvider constructs the client with getToken: () => context.getToken(). Every request then reads the Hub's current access token at call time, so a bundle keeps working across the Hub's silent token rotations without re-mounting. Bundles on earlier releases (including the Hub's own pinned SDK until the tools/frontend-sdk pointer bump) snapshot the token at mount and are covered by the backstop instead.

Accessor mode changes two behaviours:

  • auth.refresh() rejects with a HuitzoError. The bundle holds no refresh cookie and must never rotate the session — the Hub owns that exclusively.
  • auth.isAuthenticated() reflects the accessor, returning true only while getToken() yields a non-empty token. It no longer reports a token the client stored itself.

setToken() still exists for standalone (non-Hub) use, but getToken wins when both are present. See Token lifetime contract for the full division of responsibility.


Commands API

Execute Intelligence Pack commands from your dashboard.

Execute Command

// Basic execution
const result = await huitzo.commands.execute('@acme/claims/process-claim', {
  claimId: 'CLM-12345',
  priority: 'high'
});

// With options
const result = await huitzo.commands.execute(
  '@acme/claims/process-claim',
  { claimId: 'CLM-12345' },
  {
    timeout: 60000,      // Override timeout
    signal: controller.signal,  // AbortController signal
  }
);

Command Response

# pseudocode
interface CommandResult<T> {
  result: T;                    // The command's return value
  execution: {
    duration_ms: number;        // Server-side execution time
    status: string;             // e.g. "success"
  };
}

// Type-safe usage
interface ClaimResult {
  id: string;
  status: string;
  processedAt: string;
}

const result = await huitzo.commands.execute<ClaimResult>(
  '@acme/claims/process-claim',
  { claimId: 'CLM-12345' }
);

console.log(result.result.status);       // "pending" | "approved" | ...
console.log(result.execution.duration_ms);

CommandResult<T> is the unwrapped payload. The HTTP envelope fields (success, correlationId, timestamps) are consumed by the client and surfaced on errors via HuitzoError.correlationId, not on successful responses.

List Available Commands

# pseudocode
// List all commands accessible to the current tenant
const all = await huitzo.commands.list();

// Filter by pack namespace (client-side filter over the full list)
const claims = await huitzo.commands.list({ pack: 'claims' });

// Get details for one command
const command = await huitzo.commands.get('@acme/claims/process-claim');
console.log(command.description);
console.log(command.input_schema);

CommandInfo.namespace is the pack namespace (e.g. "claims"), and CommandInfo.name is the command name within that pack. The pack filter matches commands whose namespace is exactly equal to the value passed.

Check Pack Availability

Pack-availability checks are cached in React via the usePacks hook, which exposes an isInstalled(packId) helper backed by the provider's cached list:

# pseudocode
import { usePacks } from '@huitzo/dashboard-sdk-react';

function ClaimsFeature() {
  const { isInstalled, loading } = usePacks();
  if (loading) return null;
  if (!isInstalled('@acme/claims-processor')) return <UpsellBanner />;
  return <ClaimsPanel />;
}

In framework-agnostic code, query the list directly:

# pseudocode
const packs = await huitzo.packs.list();
const isInstalled = packs.some(p => p.id === '@acme/claims-processor');

Real-Time API

Status: Planned (not yet implemented). The huitzo.realtime sub-object — a WebSocket to pack backends — does not exist in the current SDK, and useConnectionStatus is a stub that throws HuitzoError on invocation. useRealtime is implemented (from @huitzo/dashboard-sdk-react 4.1.0), but it carries only the events the Hub sends over the per-mount event bus, not pack-backend events; see useRealtime. This section describes the planned WebSocket API.

Subscribe to real-time events via WebSocket.

Subscribe to Events (Planned)

# pseudocode — planned API
const unsubscribe = huitzo.realtime.subscribe('claims:updated', {
  onMessage: (event) => { console.log('Claim updated:', event.data) },
  onError: (error) => { console.error('Subscription error:', error) },
});

unsubscribe();

Event Types (Planned)

Event Description Payload
{pack}:created Item created { id, type, data }
{pack}:updated Item updated { id, type, changes }
{pack}:deleted Item deleted { id, type }
command:started Command execution started { correlationId, command }
command:completed Command execution completed { correlationId, result }
command:failed Command execution failed { correlationId, error }

Connection Management (Planned)

# pseudocode — planned API
const status = huitzo.realtime.getStatus();  // 'connected' | 'connecting' | 'disconnected'
await huitzo.realtime.connect();
huitzo.realtime.disconnect();
huitzo.realtime.on('connected', () => {});
huitzo.realtime.on('disconnected', () => {});

React Integration

The React integration provides hooks and components for building dashboards with React.

HuitzoProvider

Wrap your application with HuitzoProvider to enable hooks. When running inside Hub, pass the context object received from mount():

// Dashboard entry point (src/main.tsx)
import { createRoot } from 'react-dom/client';
import type { HuitzoContext } from '@huitzo/dashboard-sdk';
import { HuitzoProvider } from '@huitzo/dashboard-sdk-react';

export function mount(container: HTMLElement, context: HuitzoContext) {
  const root = createRoot(container);
  root.render(
    <HuitzoProvider context={context}>
      <Dashboard />
    </HuitzoProvider>
  );
}

Context Integration

When a context object is provided (passed from Hub's mount() call), the provider: - Uses Hub's shared JWT session via context.getToken(), read live on every request from @huitzo/dashboard-sdk-react 6.0.0 (see Token lifetime contract) - Enables Hub navigation hooks via context.navigate - Provides user info and dashboard metadata - Enables the Hub event bus for cross-boundary communication

See Dashboard Loading Architecture — HuitzoContext for the full context shape.

useHuitzo

Access the Huitzo client, auth state, mount context, and provider-level init state.

Returns: { client, user, isAuthenticated, initError, packs, mountContext, isPackInstalled }

Field Type Description
client HuitzoClient The client instance created by the provider.
user UserInfo \| null The currently authenticated user, or null.
isAuthenticated boolean Whether the client holds valid auth tokens.
initError Error \| null Error from the provider's initial data fetch (user or packs). 401s do not appear here — they trigger onAuthError instead.
packs PackInfo[] Cached list of installed packs from the provider's initial fetch.
mountContext HuitzoMountContext The vanilla JS context object Hub passed to mount(). Used by Hub-specific hooks.
isPackInstalled (packId: string) => boolean Membership check against the cached packs list.
# pseudocode
import { useHuitzo } from '@huitzo/dashboard-sdk-react';

function UserInfo() {
  const { client, user, isAuthenticated, initError, isPackInstalled } = useHuitzo();

  if (initError) return <ErrorBanner error={initError} />;
  if (!isAuthenticated) return <LoginButton />;

  return (
    <div>
      <p>Welcome, {user.email}</p>
      {isPackInstalled('@huitzo/analytics') && <AnalyticsWidget />}
    </div>
  );
}

useCommand

Execute commands with automatic state management:

import { useCommand } from '@huitzo/dashboard-sdk-react';

interface Claim {
  id: string;
  title: string;
  status: string;
}

interface ListClaimsResult {
  claims: Claim[];
  total: number;
}

function ClaimsList() {
  const {
    execute,
    data,
    loading,
    error,
    reset
  } = useCommand<ListClaimsResult>('@acme/claims/list-claims');

  // Execute on mount
  useEffect(() => {
    execute({ status: 'pending', limit: 20 });
  }, []);

  // Execute with different params
  const handleFilter = (status: string) => {
    execute({ status, limit: 20 });
  };

  if (loading) return <Skeleton count={5} />;
  if (error) return <ErrorMessage error={error} onRetry={() => execute()} />;

  return (
    <div>
      <FilterBar onFilter={handleFilter} />
      <ul>
        {data?.claims.map(claim => (
          <ClaimItem key={claim.id} claim={claim} />
        ))}
      </ul>
      <p>Total: {data?.total}</p>
    </div>
  );
}

useCommand Options

Returns: { execute, data, loading, error, reset, status, isIdle, isSuccess, isError }

# pseudocode
const {
  execute,
  data,
  loading,
  error,
  reset,
  status,     // 'idle' | 'loading' | 'success' | 'error'
  isIdle,
  isSuccess,
  isError
} = useCommand('@acme/claims/process', {
  // Execute immediately with these args
  initialArgs: { claimId: 'CLM-123' },

  // Callbacks
  onSuccess: (data) => { toast.success('Claim processed!') },
  onError: (error) => { toast.error(error.message) },

  // Cache result for 5 seconds (keyed by args)
  cacheTime: 5000,
});

refetchInterval

# pseudocode
refetchInterval?: number | ((data: TOutput | null) => number)

Periodically re-executes the command with the most recent args (those last passed to execute, or initialArgs). Accepts a number of milliseconds, or a function deriving the next interval from the last result.

Behaviour Detail
Cancellable A non-positive value (or a function returning one) disables the loop; toggling between a positive value and 0/undefined is the reliable pause/resume
Visibility-aware Pauses while document.visibilityState === 'hidden'; on re-show it fires one catch-up execution, and only when a refetch is actually due, so rapid tab-toggling cannot flood the backend
Start condition Does not start until one successful execution has produced args to repeat
Cleanup Cleared on unmount
Failure A failed refetch surfaces through error/onError without stopping the loop
Composition with cacheTime Effective cadence is max(refetchInterval, cacheTime) for unchanged args

From @huitzo/dashboard-sdk-react 6.0.0, every tick reads the token through the accessor rather than a value captured when the loop was armed, so a polling dashboard keeps authenticating correctly across Hub token rotations — the case that most reliably outlives a snapshotted token. On earlier releases the Hub's bundle auth backstop repairs the stale token for each tick instead. See Token lifetime contract.

useRealtime

Status: Implemented in @huitzo/dashboard-sdk-react 4.1.0, and answered by the Hub. It subscribes through the per-mount event bus (context.on) and unsubscribes on unmount. It receives the events the Hub emits — theme-change, navigation and viewport-resize, which is also sent once for the first size observed after mount() (see Events the Hub emits). useRealtime carries Hub events only: there is no WebSocket behind it, so pack-backend events do not arrive here, and useConnectionStatus is the sole stub.

Subscribe to one event name or several; the callback does not need to be memoized:

# pseudocode
useRealtime('theme-change', ({ theme }) => { /* restyle */ });
useRealtime(['navigation', 'viewport-resize'], (event) => { /* handle */ });

useConnectionStatus

Status: Stub — throws HuitzoError on invocation. It would report the state of a WebSocket connection to pack backends, and that connection does not exist yet. Hub events do not need it: use useRealtime.

Planned return: { status, isConnected, reconnect }

usePacks

Query installed packs.

Returns: { packs, loading, error, isInstalled, refetch }

# pseudocode
import { usePacks } from '@huitzo/dashboard-sdk-react';

function PackList() {
  const { packs, loading, error, isInstalled, refetch } = usePacks();

  if (loading) return <p>Loading packs...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <ul>
      {packs.map(pack => (
        <li key={pack.name}>{pack.name} - {pack.version}</li>
      ))}
    </ul>
  );
}

Hub Integration

These hooks work when the dashboard runs inside Hub with a HuitzoContext provided via mount(). The Hub's side of their event contract — what it emits, what it accepts, and the limits it applies — is specified in Hub-side hosts.

Hub release. The Hub answers useHubActions and useHubBreadcrumbs from the first Hub release built after this change (#1243). An older self-hosted Hub drops hub-action:* and hub-breadcrumbs:* silently: no toast or trail appears, and a confirm resolves false when the SDK's timeoutMs runs out (4.2.0 or later; with 4.1.x the promise stays pending).

useHubNavigation

Navigate between Hub views.

Returns: { navigateToHub, navigateToDashboard, navigateToExplore, navigateToSettings, currentDashboard }

# pseudocode
import { useHubNavigation } from '@huitzo/dashboard-sdk-react';

function DashboardHeader() {
  const {
    navigateToHub,        // Go to Hub home
    navigateToDashboard,  // Go to specific dashboard
    navigateToExplore,    // Go to marketplace
    navigateToSettings,   // Go to settings
    currentDashboard,     // Current dashboard slug
  } = useHubNavigation();

  return (
    <header>
      <button onClick={navigateToHub}>← Hub</button>
      <h1>Claims Dashboard</h1>
      <button onClick={() => navigateToDashboard('analytics')}>Open Analytics</button>
    </header>
  );
}

useHubContext

Access Hub environment context.

Returns: { apiUrl, dashboardSlug, user, theme, locale, currency }

  • theme is reactive: it starts from context.theme, which the Hub supplies, and follows the Hub's theme-change events (Events the Hub emits). Verified against @huitzo/dashboard-sdk-react 7.0.0.
  • locale and currency would start from context.locale / context.currency and follow locale-change. The Hub supplies neither and never emits locale-change yet, so locale stays at the SDK default (en-US) and currency is undefined.
  • dashboardSlug is context.slug, the scope-qualified "<scope>/<slug>".
# pseudocode
import { useHubContext } from '@huitzo/dashboard-sdk-react';

function MyComponent() {
  const {
    apiUrl,         // Huitzo API base URL
    dashboardSlug,  // Current dashboard, "<scope>/<slug>"
    user,           // Current user from Hub session
    theme,          // Hub's current theme ('light' | 'dark')
    locale,         // BCP-47 tag; 'en-US' until the Hub supplies one
  } = useHubContext();

  return (
    <div className={theme}>
      <span>Dashboard: {dashboardSlug}</span>
      <span>User: {user?.email}</span>
    </div>
  );
}

useHubBreadcrumbs

Status: Implemented in @huitzo/dashboard-sdk-react 4.1.0, and rendered by the Hub.

Sets the breadcrumb trail in the Hub header, which shows it only while your dashboard route is showing. The hook emits hub-breadcrumbs:set whenever the items' content changes (an inline array literal is fine) and hub-breadcrumbs:clear on unmount. The Hub also clears the trail itself when the dashboard unmounts.

# pseudocode
useHubBreadcrumbs([
  { label: 'Claims', href: '/d/acme/claims-dashboard' },
  { label: 'Claim #123' },
]);

Two filters apply to href. The SDK drops any href that is neither https:// nor a root-relative path. The Hub then links only same-origin paths, using their normalized form: an https:// href renders as plain text, and so does the last entry, which marks the current page. The Hub router matches your dashboard only at /d/{scope}/{slug}, so a deeper path such as /d/acme/claims/claim/123 redirects to Hub home and unmounts it. Put a place inside your dashboard in the query string or hash (/d/acme/claims?claim=123) and follow it with the navigation event (useRealtime). The Hub shows at most five entries, with labels up to 80 UTF-16 code units that ellipsize when space is short; below 1024 px wide the trail is hidden. See Breadcrumbs.

useHubActions

Status: Implemented in @huitzo/dashboard-sdk-react 4.1.0, and answered by the Hub.

Triggers Hub-level UI. Returns { showNotification, showConfirmDialog, openSettings }; the functions keep their identity across renders.

Function Emits Hub behavior
showNotification({ message, variant, duration? }) hub-action:toast Shows a toast. Omit duration for a sticky toast; a positive duration auto-dismisses after 2–60 s and pauses while the toast is hovered or focused. Sticky or not, the Hub removes your toasts when the dashboard unmounts. See Toast host
showConfirmDialog({ title, body, confirmText?, cancelText?, variant?, signal?, timeoutMs? }) hub-action:confirm, then waits for hub-action:confirm-result Opens a modal dialog. Resolves true only when the user confirms; cancel, Escape, a newer dialog, the Hub's 30 s timeout, or your whole dashboard unmounting resolve false. The calling component unmounting settles it false too, but leaves the Hub dialog open (see Timeouts below). An empty title or a non-string body resolves false at once. See Confirm dialog host
openSettings() hub-action:open-settings Navigates the Hub to its Settings page, which unmounts your dashboard

What the Hub adds around your content:

  • Attribution. Above the title you supplied, the dialog shows a Hub-written eyebrow line with the Hub's info glyph, Request from {name} · {scope}/{slug}, set off from your content by a rule; each toast shows From {name} · {scope}/{slug}. You cannot change or hide them, and only your body scrolls, so the attribution stays in view.
  • Rate limits. Per scope, shared by every dashboard of your scope and kept across re-mounts: 10 toasts per 10 s (the excess is dropped), 5 dialogs per 30 s that end without the user confirming, and 20 dialogs opened per 60 s, confirmed or not. Over either dialog limit, requests resolve false at once until the window passes, and the Hub shows its own toast saying the request was declined, at most once every 30 s per scope.
  • Stacking. Toasts sit bottom-right, just above the Monitor, Terminal or Feedback panel while one is docked, and below every Hub modal; the confirm dialog is a Hub modal. Your own overlays stay inside your dashboard's stacking context (DOM Containment).
  • Text. Bidi embedding and isolate controls and invisible zero-width characters are removed (ZWJ, ZWNJ and the directional marks are kept), lengths count UTF-16 code units, and a dialog body keeps at most 10 lines with at most one blank line in a row; see Limits at a glance.

Timeouts. The signal and timeoutMs options arrived in 4.2.0: the SDK resolves false after timeoutMs (default 30 s; 0 disables) or rejects when signal aborts. The SDK does not send either to the Hub yet, so the Hub applies its own timeout: it closes an unanswered dialog after 30 s and answers false, the same as the SDK default. Keep the default. With a shorter timeoutMs, or an aborted signal, your promise settles while the Hub dialog stays open until it is answered or 30 s pass, and that answer reaches nobody. With a longer timeoutMs, or 0, the Hub still closes the dialog at 30 s and your promise resolves false. The same split happens when the component that called showConfirmDialog unmounts while the rest of your dashboard stays mounted: the SDK settles the promise false at once, but the Hub dialog stays open until it is answered or the Hub's 30 s timeout closes it.

# pseudocode
const { showNotification, showConfirmDialog, openSettings } = useHubActions();

showNotification({ message: 'Claim saved', variant: 'success', duration: 4000 });

const confirmed = await showConfirmDialog({
  title: 'Delete claim?',
  body: 'This cannot be undone.',
  confirmText: 'Delete',
  variant: 'destructive',
});

Components

The React package ships a small set of presentational components that match the Huitzo Hub design system. They are framework-agnostic in intent — they take typed props, accept either onClick or href for navigation, and apply design tokens from @huitzo/dashboard-sdk-react/styles/tokens.css.

Component Source Purpose
DashboardTile packages/dashboard-sdk-react/src/components/DashboardTile.tsx Clickable tile with icon, name, description, optional pinned indicator, and a custom accent color. Pass either onClick or href (mutually exclusive).
DashboardInfoBlock packages/dashboard-sdk-react/src/components/DashboardInfoBlock.tsx Card-like block displaying a title, description, optional icon, and optional metadata key-value pairs. Variant: default / elevated / outlined.
TileGlyphIcon packages/dashboard-sdk-react/src/components/TileGlyphIcon.tsx Renders one of the 10 geometric fallback glyphs used by the tile-identity system, in the same 24x24 stroke="currentColor" language as the rest of the icon set.

DashboardTile

# pseudocode — conceptual usage
import { DashboardTile } from '@huitzo/dashboard-sdk-react';

<DashboardTile
  name="Claims"
  description="Process and review insurance claims"
  icon="📋"
  isPinned
  color="var(--color-accent)"
  href="/d/acme/claims"
/>

The href form is preferred over onClick when navigating within Hub, so the SDK can apply same-origin / https:// allowlisting (cross-origin and http:// URLs are blocked by default; see allowInsecureHttp for local dev).

DashboardInfoBlock

# pseudocode — conceptual usage
import { DashboardInfoBlock } from '@huitzo/dashboard-sdk-react';

<DashboardInfoBlock
  title="Claims Dashboard"
  description="Manage and process insurance claims"
  icon="📋"
  variant="elevated"
  metadata={[
    { label: 'Version', value: '1.2.0' },
    { label: 'Last updated', value: '2 hours ago' },
  ]}
/>

Tile Identity (deterministic fallback)

A dashboard tile needs an icon and an accent color. This section documents the deterministic fallback ("Layer 1") the SDK always provides. A future author-declared icon/color read from a pack manifest ("Layer 2") is deferred — the bundle channel that would carry it isn't written by anything yet. Until Layer 2 ships, the SDK derives both deterministically from the dashboard's scope/slug pair — the same pair ix_dashboard_scope_slug guarantees is unique per dashboard — so a given dashboard always renders the same icon/accent without any stored state, and different dashboards spread visibly across the palette instead of collapsing onto one default look.

# pseudocode — conceptual usage
import { resolveTileIdentity, TileGlyphIcon, TILE_ACCENT_TOKENS } from '@huitzo/dashboard-sdk-react';

const { accentToken, glyphId } = resolveTileIdentity(scope, slug);

<div style={{ '--tile-color': accentToken }}>
  <TileGlyphIcon glyphId={glyphId} />
</div>

resolveTileIdentity(scope, slug) hashes `${scope}/${slug}` (32-bit FNV-1a) and derives two independent indices from disjoint bit ranges of the hash — one picks the accent, the other the glyph — so the two never move in lockstep. That decorrelation is the reason a grid of tiles reads as varied rather than as ~8 repeating accent/glyph pairs.

  • TILE_ACCENT_TOKENS — 8 var(--color-tile-1) … var(--color-tile-8) references. The underlying custom properties are defined in packages/brand-tokens/tokens.css (dark and light), mirrored exactly in the SDK's own styles/tokens.css so a hosted dashboard and the Hub agree even if only one of the two stylesheets is loaded.
  • TILE_GLYPH_IDS — 10 ordered glyph ids (square, circle, triangle, diamond, hexagon, plus, chevron, asterisk, zigzag, pentagon). Order is load-bearing — resolveTileIdentity() indexes into this array, so golden-vector tests break if it's ever reordered; new glyphs append.
  • TILE_IDENTITY_GOLDEN_VECTORS — frozen { scope, slug, hash, accentIndex, glyphIndex, glyphId } fixtures, published so a consumer's tests (e.g. the Hub's) can assert against the exact same expected output as the SDK's own tests, instead of each side re-deriving its own "correct" answer.

The Huitzo Hub's home-grid tile (apps/dashboard/src/components/home/DashboardTile.tsx — not the SDK's own DashboardTile component above) consumes this same resolver — see Hub Components.

Theming

Both components consume CSS custom properties from @huitzo/dashboard-sdk-react/styles/tokens.css. Import that file once at the top of the dashboard entry point. Dark mode is the default; switch to light by setting data-theme="light" on a parent element.

Token inheritance

The SDK's design-token defaults live in a @layer huitzo-tokens cascade layer. When a dashboard renders inside the Hub at /d/{scope}/{slug}, it shares the Hub's DOM, and the Hub defines the same --color-* / --font-* tokens unlayered (from @huitzo/brand-tokens). CSS gives unlayered declarations higher priority than any named layer regardless of stylesheet order, so the Hub's tokens always win: a hosted dashboard inherits the Hub's brand — including a white-labeled brand applied from the deployment's branding manifest (Project 4 / ADR-015) — with no SDK change. A dashboard running standalone (no Hub host) falls back to the SDK's own defaults, which the layer preserves in full (dark and light).

The contract for dashboard authors: consume tokens via var(--color-*) (directly or through the hz-* primitives) and never hardcode hex colors — one Hub-level override then restyles the entire dashboard. The overridable token surface (the brand-color allowlist and the font families) is defined by ADR-015; structural tokens (spacing, radius, type scale) are not brand-tunable.


Primitives

In addition to the React components above, the SDK ships a small set of theme-aware utility CSS classes for building dashboards that match the Hub visual language. They are delivered alongside the design tokens and are picked up automatically when the dashboard imports @huitzo/dashboard-sdk-react/styles.

Class names follow hz-{block}__{element}--{modifier} (BEM-ish). All colors resolve through Hub --color-* tokens, so the primitives flip between light and dark themes without any additional work. The terminal chrome uses fixed dark hex values intentionally — a terminal should look like a terminal regardless of the surrounding theme.

Family Purpose
.hz-card, .hz-card--lg, .hz-card--md Elevated card with shadow + border
.hz-card--accent, .hz-card--success, .hz-card--warning Card variants with accent border / top-border
.hz-stat__number, .hz-stat__number--success, .hz-stat__number--warning Iconic numeric display, clamp(3.75rem, 8vw, 6rem)
.hz-rail, .hz-step, .hz-step__badge Numbered onboarding rail with vertical gradient line
.hz-terminal, .hz-terminal__header, .hz-terminal__dots, .hz-terminal__dot, .hz-terminal__label Terminal block chrome (traffic-light dots + label)
.hz-terminal__body Terminal command line (light text on dark bg, monospace)
.hz-terminal__prompt Green $ prompt prefix; pair with .hz-terminal__body
.hz-terminal__output Expected output below a dashed divider
.hz-terminal__copy, .hz-terminal__copy--ok Copy button with success state
.hz-btn, .hz-btn--primary, .hz-btn--secondary, .hz-btn--ghost Standardized buttons
.hz-eyebrow, .hz-eyebrow--accent Uppercase section labels
.hz-kbd Inline keyboard chip
.hz-code Inline code

Example: numbered onboarding step + terminal block

# pseudocode — conceptual usage
<div className="hz-rail">
  <section className="hz-step hz-card hz-card--lg">
    <span className="hz-step__badge" aria-hidden>1</span>
    <h3>Run a pack</h3>
    <div className="hz-terminal">
      <div className="hz-terminal__header">
        <span className="hz-terminal__dots">
          <span className="hz-terminal__dot" />
          <span className="hz-terminal__dot" />
          <span className="hz-terminal__dot" />
        </span>
        <span className="hz-terminal__label">Terminal</span>
        <button className="hz-terminal__copy">Copy</button>
      </div>
      <pre className="hz-terminal__body">
        <span className="hz-terminal__prompt">$</span>
        huitzo run @yc/yc-weather-demo/current-weather --city san-francisco
      </pre>
      <pre className="hz-terminal__output">
        → {`{"city": "san-francisco", "temp_c": 14.2}`}
      </pre>
    </div>
  </section>
</div>

When to use what

  • Use a DashboardTile / DashboardInfoBlock component when the unit is a discrete reusable thing (a tile in a grid, an info card with metadata).
  • Use hz-* primitives when you are composing a page-level layout (hero + onboarding rail + terminal block + CTA). They are layout-free by design — bring your own grid / flex.

The primitives intentionally do not impose display: flex or grid layouts — combine them with whatever layout system your dashboard uses (CSS grid, Tailwind utilities, flexbox).


Error Handling

Error Hierarchy

All SDK errors extend HuitzoError and carry structured metadata:

Class HTTP Status Error Code Description
AuthenticationError 401 AUTHENTICATION_FAILED Missing or invalid credentials
AuthorizationError 403 PERMISSION_DENIED Insufficient permissions
NotFoundError 404 NOT_FOUND Resource does not exist
ValidationError 400/422 VALIDATION_FAILED Input validation failure
TimeoutError 408 TIMEOUT Request timed out
RateLimitError 429 RATE_LIMITED Rate limit exceeded (retryAfter field)
CommandError varies COMMAND_ERROR Command execution failure
NetworkError - NETWORK_ERROR DNS failure, offline, CORS
InternalError 500 INTERNAL_ERROR Unexpected server error
IntegrationError 502 INTEGRATION_ERROR External integration failure
ServiceUnavailableError 503 SERVICE_UNAVAILABLE Temporary unavailability

Error Properties

Every HuitzoError instance carries:

Property Type Description
code ErrorCode Machine-readable error code
statusCode number \| undefined HTTP status (undefined for network errors)
details unknown Structured context (field errors, etc.)
correlationId string \| undefined Request ID for debugging
timestamp string \| undefined Server ISO 8601 timestamp
# pseudocode
import {
  HuitzoError,
  AuthenticationError,
  ValidationError,
  RateLimitError,
  NetworkError
} from '@huitzo/dashboard-sdk';

try {
  await huitzo.commands.execute('@acme/claims/process', args);
} catch (error) {
  if (error instanceof AuthenticationError) {
    // 401 — redirect to login
  } else if (error instanceof ValidationError) {
    // 400/422 — field errors in error.details
  } else if (error instanceof RateLimitError) {
    // 429 — retry after error.retryAfter seconds
  } else if (error instanceof NetworkError) {
    // DNS failure, offline, etc.
  } else if (error instanceof HuitzoError) {
    // Catch-all for any SDK error
    console.error(error.code, error.message);
  }
}

React Error Handling

# pseudocode
function ClaimProcessor() {
  const { execute, error, isError } = useCommand('@acme/claims/process');

  if (isError) {
    if (error instanceof ValidationError) {
      return <ValidationErrors errors={error.details} />;
    }
    if (error instanceof AuthorizationError) {
      return <PermissionDenied />;
    }
    return <GenericError error={error} />;
  }
}

Packaging

The published @huitzo/dashboard-* packages contain dist/, package.json and the README and LICENSE files npm adds automatically. They do not ship source maps (including inline sourceMappingURL or sourcesContent), declaration maps or tests. @huitzo/dashboard-primitives additionally ships its registry/** copy-in source (without tests), because consumers copy those files into their own project.

scripts/check-pack-contents.mjs in the frontend-sdk repo enforces this: it inspects every package tarball and fails on maps, tests, fixtures, src/, env files, build config, non-allowlisted dist/ file types or publish lifecycle scripts. It runs as a blocking step in the frontend-sdk CI and before every publish.


TypeScript Support

The SDK is written in TypeScript and provides full type definitions.

Command Types

// Define your command types
interface ProcessClaimArgs {
  claimId: string;
  priority?: 'low' | 'medium' | 'high';
}

interface ProcessClaimResult {
  id: string;
  status: 'approved' | 'denied' | 'pending';
  processedAt: string;
  reviewer?: string;
}

// Use with execute
const result = await huitzo.commands.execute<ProcessClaimResult>(
  '@acme/claims/process',
  { claimId: 'CLM-123', priority: 'high' } satisfies ProcessClaimArgs
);

// result.result is typed as ProcessClaimResult

React Hook Types

# pseudocode
// useCommand is generic
const { data } = useCommand<ListClaimsResult>('@acme/claims/list');
// data is ListClaimsResult | null

Best Practices

1. Handle Loading States

function ClaimDetails({ id }: { id: string }) {
  const { execute, data, loading, error } = useCommand('@acme/claims/get');

  useEffect(() => {
    execute({ claimId: id });
  }, [id]);

  // Always handle all states
  if (loading) return <Skeleton />;
  if (error) return <ErrorDisplay error={error} />;
  if (!data) return null;

  return <ClaimCard claim={data} />;
}

2. Optimistic Updates

function ClaimActions({ claim }: { claim: Claim }) {
  const [optimisticStatus, setOptimisticStatus] = useState(claim.status);
  const { execute } = useCommand('@acme/claims/update-status');

  const handleApprove = async () => {
    setOptimisticStatus('approved');  // Optimistic update

    try {
      await execute({ claimId: claim.id, status: 'approved' });
    } catch (error) {
      setOptimisticStatus(claim.status);  // Revert on error
      toast.error('Failed to approve claim');
    }
  };

  return (
    <StatusBadge status={optimisticStatus} />
  );
}
function ClaimSearch() {
  const [query, setQuery] = useState('');
  const { execute, data, loading } = useCommand('@acme/claims/search');

  // Debounce search
  useEffect(() => {
    const timer = setTimeout(() => {
      if (query.length >= 2) {
        execute({ query });
      }
    }, 300);

    return () => clearTimeout(timer);
  }, [query]);

  return (
    <div>
      <input value={query} onChange={e => setQuery(e.target.value)} />
      {loading ? <Spinner /> : <Results data={data} />}
    </div>
  );
}

4. Clean Up Subscriptions

Prefer useRealtime to calling context.on directly: it unsubscribes on unmount, so a listener never outlives its component:

# pseudocode
useRealtime('viewport-resize', ({ width }) => {
  setCompact(width < 640);
});

Testing

The SDK packages in tools/frontend-sdk test themselves with vitest. Their test helpers are part of that contract. Both fetch mocks share one rule: every mocked call gets a new Response, because a body can be read only once and a shared instance breaks the second call of any test that fetches twice (a retry, a poll, a refetch).

Package Test layout Fetch mock
@huitzo/dashboard-sdk Two vitest projects: unit (tests/**/*.test.ts, fetch mocked) and integration (tests/integration/**) installMockFetch() replaces globalThis.fetch for one test and restores it after the test. Responses can be set as a default or queued and served in order; a custom content-type header overrides the JSON default
@huitzo/dashboard-sdk-react One jsdom project that also type-checks tests/**/*.test-d.ts; a global setup file unmounts every rendered tree after each test installMockFetch(body) answers every call with the same JSON body, records each request's URL and Authorization header, and is removed by an explicit restore(), so a test can install it inside its own body

React hook tests render inside a real HuitzoProvider through a helper that supplies a test HuitzoContext, the same contract a Hub dashboard receives (see HuitzoProvider).