Skip to Content
SPAPS is proprietary hosted SaaS. Paid access required; pre-1.0 contracts may change. Terms and access
PackagesTypeScript SDK

SPAPS SDK (TypeScript)

spaps-sdk is the typed TypeScript client for SPAPS-compatible APIs. It wraps common API surfaces in namespaces (auth, payments, issueReporting, entitlements, and others), re-exports many spaps-types contracts, and ships helper utilities for permission checks, feature gates, WebSocket auth, and webhook verification.

Verified source surface: spaps-sdk 1.14.1 at Sweet Potato 5b09d3df1194577c5313c865fef1db98f694cdea, with Node.js 14 or newer. The symbols below come from packages/sdk/src; check the installed version because a published package can lag the checkout.

Install

npm install spaps-sdk npm ls spaps-sdk

Alternative package managers:

pnpm add spaps-sdk yarn add spaps-sdk

Client Setup And Key Modes

The SDK supports:

  • publishableKey for browser-safe usage.
  • secretKey for server-side privileged usage.
  • legacy apiKey for compatibility.

Constructor values override environment variables.

import { SPAPSClient, createBrowserClient, createServerClient } from 'spaps-sdk' // Generic constructor const spaps = new SPAPSClient({ apiUrl: 'https://api.example.test', publishableKey: 'spaps_pub_example' }) // Browser helper const browserClient = createBrowserClient('spaps_pub_example', { apiUrl: 'https://api.example.test' }) // Server helper const serverClient = createServerClient('spaps_sec_example', { apiUrl: 'https://api.example.test' })

Relevant env vars:

  • SPAPS_API_URL
  • NEXT_PUBLIC_SPAPS_API_URL
  • SPAPS_API_KEY
  • NEXT_PUBLIC_SPAPS_API_KEY

Namespace Surface

NamespacePurpose
authPassword, wallet, magic-link, refresh, logout, and password management flows
paymentsCheckout, products, prices, subscriptions, and crypto helpers
sessionsSession lookup and lifecycle helpers
secureMessagesSecure message create/list helpers
issueReportingStatus, list/get/create/update/reply, and voice-token helpers
emailTemplate lookup, preview, and send helpers
entitlementsUser and resource entitlement queries
dayrateAvailability and booking helpers
adminProduct/pricing admin helper methods
cfoCFO-facing reporting helper methods

Permission And Role Helpers

The SDK exports permission helpers from packages/sdk/src/permissions.ts, including:

  • isAdminAccount
  • getUserRole
  • hasPermission
  • canAccessAdmin
  • PermissionChecker
  • createPermissionChecker
import { createPermissionChecker, canAccessAdmin, isAdminAccount } from 'spaps-sdk' const checker = createPermissionChecker(['admin@example.com']) const role = checker.getRole('staff@example.com') const access = canAccessAdmin({ id: 'u1', email: 'admin@example.com' }) const isAdmin = isAdminAccount('admin@example.com') console.log(role, access.allowed, isAdmin)

RoleHierarchy And FeatureEvaluator

RoleHierarchy gives deterministic role comparisons. FeatureEvaluator applies three layers in order:

  1. System kill switch entitlement key
  2. Resource-scoped block entitlement key
  3. Minimum role check
import { FeatureEvaluator, RoleHierarchy } from 'spaps-sdk' const hierarchy = new RoleHierarchy({ guest: 0, user: 10, accountant: 20, admin: 30 }) const evaluator = new FeatureEvaluator(hierarchy) evaluator.registerFeature('billing_export', { killSwitchKey: 'kill:billing_export', resourceBlockKey: 'block:billing_export', resourceBlockType: 'company', minimumRole: 'accountant' })

WebSocketAuthHelper

WebSocketAuthHelper manages authenticated WebSocket connections with token refresh and reconnect handling.

Notable behaviors from packages/sdk/src/websocket-auth-helper.ts:

  • Prefers a short-lived, single-use connect ticket in ?ticket=...; never puts the long-lived access token in the URL. Without a ticket, the bearer token travels in the Sec-WebSocket-Protocol handshake header.
  • Refreshes tokens before expiry (buffer-based).
  • Reconnects on auth close codes 4001 and 4003.
  • Uses exponential backoff for network retries.
  • Optional ping interval for stale connection detection.
import { WebSocketAuthHelper } from 'spaps-sdk' const ws = new WebSocketAuthHelper({ url: 'wss://api.example.test/ws', getAccessToken: () => localStorage.getItem('access_token') || undefined, refreshAccessToken: async () => { // Call your refresh flow and return a fresh access token return 'new_access_token' }, getConnectTicket: async () => { const response = await fetch('https://api.example.test/api/realtime/ws-ticket', { method: 'POST', headers: { 'X-API-Key': 'spaps_pub_example', Authorization: `Bearer ${localStorage.getItem('access_token')}` } }) if (!response.ok) throw new Error(`WebSocket ticket failed: ${response.status}`) return (await response.json()).data.ticket }, onMessage: data => console.log(data) }) await ws.connect()

Issue Reporting Helpers

The issueReporting namespace exposes:

  • getStatus
  • list
  • get
  • create
  • update
  • reply
  • createVoiceToken

scope is currently restricted to "mine" in the stock SPAPS API path; wider scopes are rejected by the SDK guard.

Entitlements Helpers

The entitlements namespace includes:

  • list(params?)
  • check(key, userId?)
  • listByResource(resourceType, resourceId?)

Scope behavior:

  • Publishable-key contexts require user JWT and are user-scoped.
  • Secret-key contexts can query broader resource scopes.
  • Non-user resource scopes in publishable contexts are blocked server-side.

Webhook Verification Helper

Use verifyCryptoWebhookSignature for crypto webhook signature validation.

import { verifyCryptoWebhookSignature } from 'spaps-sdk' verifyCryptoWebhookSignature({ body: requestBody, signature: request.headers['x-spaps-signature'] as string, // Resolve the provider-specific signing secret from your server-side secret store. // SPAPS does not define one universal webhook-secret environment variable. secret: await loadWebhookSecret('crypto-provider') })

Never expose this secret through a browser bundle or a NEXT_PUBLIC_*/VITE_* variable. The hosted server’s provider map is CRYPTO_WEBHOOK_SECRETS; downstream consumers may use a different secret-store key.

Test Coverage And Validation

From packages/sdk:

npm ci npm run build npm run typecheck:readme npm run test:readme npm run test

Key behavior is covered by tests such as:

  • test/entitlements.test.ts
  • test/issue-reporting.test.ts
  • test/feature-evaluator.test.ts
  • test/role-hierarchy.test.ts
  • test/websocket-auth-helper.test.ts

For endpoint semantics and backend rules, pair this page with Endpoint reference, Billing and entitlements, and Issue reporting and support.