@tiun/sdk
Version:
tiun SDK for payments and subscriptions
439 lines (371 loc) • 11.6 kB
TypeScript
/**
* tiun SDK Type Definitions
*
* Install: npm install @tiun/types --save-dev
*
* These types are for the global `tiun` object exposed by the tiun script.
* Load the script, then use tiun.* with full TypeScript support.
*
* @generated from packages/types/src/index.ts - Do not edit directly.
* Run `npm run generate:types` to regenerate.
*/
// =============================================================================
// Core Types
// =============================================================================
export type ContentType = 'active' | 'inactive' | 'paused';
export type MediaType = 'text' | 'audio' | 'video';
export type SupportedLanguage = 'en' | 'de' | 'fr';
/** 'auto' follows the visitor's OS setting (prefers-color-scheme). */
export type Appearance = 'light' | 'dark' | 'auto';
export type TiunEventType =
| 'ready'
| 'paywallShow'
| 'paywallHide'
| 'error'
| 'userChange'
| 'login'
| 'logout';
// =============================================================================
// Configuration
// =============================================================================
export interface TiunConfig {
/**
* Your unique tiun snippet ID.
* Required when using the NPM package (SDK loads the snippet from backend).
* For legacy script tag usage, this is provided via the backend.
*/
snippetId?: string;
/**
* Language for the snippet UI. Case-insensitive ('en', 'EN', 'De' all work).
* Falls back to 'en' if an unsupported value is provided.
* @default 'en'
*/
language?: SupportedLanguage;
/**
* UI tone/style.
* - 'formal': More professional tone
* - 'informal': More casual/friendly tone
* @default 'informal'
*/
tone?: 'formal' | 'informal';
/**
* Color theme for the snippet UI. Case-insensitive. 'auto' follows the
* visitor's OS setting and re-themes live when it changes.
* Change it later with `tiun.setAppearance()`.
* @default 'light'
*/
appearance?: Appearance;
/**
* Enable debug logging to console.
* @default false
*/
debug?: boolean;
/**
* Use sandbox base URL instead of production.
* @default false
*/
sandbox?: boolean;
/**
* Called when the snippet has finished initializing and is ready
*/
onReady?: () => void;
/**
* Called when paywall should be shown to the user
*/
onPaywallShow?: (data: PaywallShowEvent) => void;
/**
* Called when paywall should be hidden (user has access)
*/
onPaywallHide?: (data: PaywallHideEvent) => void;
/**
* Called on user state changes (init + every subsequent change)
*/
onUserChange?: (data: UserChangeEvent) => void;
/**
* Called when user logs in
*/
onLogin?: (data: LoginEvent) => void;
/**
* Called when user logs out
*/
onLogout?: () => void;
/**
* Called on any error
*/
onError?: (error: TiunError) => void;
}
// =============================================================================
// Event Payloads
// =============================================================================
export interface PaywallShowEvent {
/**
* Whether user has connected a payment method
*/
isConnected: boolean;
}
export interface PaywallHideEvent {
/**
* Active session ID
*/
sessionId: string;
/**
* Whether user is connected
*/
isConnected: boolean;
}
export interface TiunError {
code: string;
message: string;
details?: unknown;
}
export interface UserInfo {
userId: string;
email: string;
/** Whether the user has opted in to the newsletter. */
hasNewsletterOptIn: boolean;
/**
* IDs of the products the user has access to. Product IDs only, so it can't
* tell which references of a repeatable product were bought — use
* `checkProductAccess(productId, { referenceId })` for those.
*/
productAccess: string[];
}
export interface UserChangeEvent {
/**
* What changed:
* - 'init': first state after the snippet loads
* - 'login' / 'logout': the user signed in or out
* - 'checkout': the user's access changed — gained or lost, for any product
* type, including a repeatable product bought with a new reference
* (which doesn't change `productAccess`). Not only after a checkout.
* - 'update': profile details changed (email, newsletter opt-in)
*/
event: 'init' | 'login' | 'checkout' | 'logout' | 'update';
isAuthenticated: boolean;
user: UserInfo | null;
}
export interface LoginEvent {
user: UserInfo;
}
export interface GetUserResponse {
isAuthenticated: boolean;
user: UserInfo | null;
}
// =============================================================================
// Checkout Options
// =============================================================================
export interface CheckoutOptions {
/**
* The product to check out, from your tiun dashboard.
*/
productId?: string;
/**
* Your own identifier for this purchase (e.g. an order or booking ID).
* Required for repeatable products, which can be bought more than once —
* each purchase is tied to its reference ID.
*/
referenceId?: string;
}
// =============================================================================
// Products
// =============================================================================
export type ProductType = 'Subscription' | 'OneTime';
export interface Product {
productId: string;
name: string;
type: ProductType;
}
export interface ProductDetail extends Product {
/** Localized price summary, e.g. "€9.90 / month". */
pricingLine: string;
/** Optional localized explanation shown under the price. */
explanationLine?: string | null;
}
export interface ProductAccess {
productId: string;
/** Purchase reference for repeatable products; null for ordinary access. */
referenceId?: string | null;
type: ProductType;
/** ISO 8601 date-time. */
activatedAt: string;
/**
* When the access ends (ISO 8601 date-time). null while a subscription is
* active and renewing; set to the end of the paid period once it's cancelled.
*/
expiresAt?: string | null;
}
export interface ProductAccessCheck {
hasAccess: boolean;
/** Access details when `hasAccess` is true; null otherwise. */
access?: ProductAccess | null;
}
export interface ProductAccessOptions {
/**
* Purchase reference for repeatable products (the `referenceId` passed to
* `checkout()`). Omit for ordinary product access.
*/
referenceId?: string;
}
// =============================================================================
// Content Options
// =============================================================================
export interface ContentOptions {
/**
* Type of content (affects session state)
*/
type: ContentType;
/**
* Unique identifier for this content/route
*/
contentId?: string;
/**
* Media type being consumed
* @default 'text'
*/
mediaType?: MediaType;
}
// =============================================================================
// SDK Interface (for global tiun object)
// =============================================================================
export interface TiunSDK {
/**
* Initialize the SDK. Call once at app startup.
*
* ```typescript
* tiun.init({ snippetId: 'your-snippet-id' });
* ```
*/
init(config?: TiunConfig): TiunSDK;
/**
* Open the time-based connect flow (no specific product).
*/
start(): Promise<void>;
/**
* Open the checkout flow for a specific product.
*/
checkout(options?: CheckoutOptions): Promise<void>;
/**
* Update the current content context.
*/
setContent(options: ContentOptions): Promise<void>;
/**
* Switch the snippet's color theme at runtime, e.g. when your site's theme
* toggle flips. Safe to call before the snippet is ready.
*/
setAppearance(appearance: Appearance): void;
/**
* Open the OTP login modal for returning subscribers.
*/
login(): Promise<void>;
/**
* Clear session and fire logout + userChange events.
*/
logout(): void;
/**
* Returns the cached user state. Does not call the backend —
* the snippet keeps user info in sync automatically.
*/
getUser(): GetUserResponse;
/**
* Returns a signed JWT for server-to-server user verification.
* Valid for 5 minutes. Returns null if the user is not authenticated.
*/
getUserVerificationToken(): Promise<string | null>;
/**
* List the products available on this snippet.
*/
listProducts(): Promise<Product[]>;
/**
* Get a product's details and localized pricing.
* Rejects with a TiunError if the product doesn't exist.
*/
getProduct(productId: string): Promise<ProductDetail>;
/**
* List the current user's active product access, fetched from the backend.
* Resolves to [] when the user is not authenticated.
*/
listProductAccess(): Promise<ProductAccess[]>;
/**
* Check whether the current user has access to a product.
* Resolves to { hasAccess: false, access: null } when the user is not authenticated.
*/
checkProductAccess(
productId: string,
options?: ProductAccessOptions
): Promise<ProductAccessCheck>;
/**
* Subscribe to an event. Returns unsubscribe function.
*/
on(event: 'ready', callback: () => void): () => void;
on(
event: 'paywallShow',
callback: (data: PaywallShowEvent) => void
): () => void;
on(
event: 'paywallHide',
callback: (data: PaywallHideEvent) => void
): () => void;
on(event: 'error', callback: (error: TiunError) => void): () => void;
on(
event: 'userChange',
callback: (data: UserChangeEvent) => void
): () => void;
on(event: 'login', callback: (data: LoginEvent) => void): () => void;
on(event: 'logout', callback: () => void): () => void;
/**
* Subscribe to an event once (auto-unsubscribes after first fire).
*/
once(event: 'ready', callback: () => void): () => void;
once(
event: 'paywallShow',
callback: (data: PaywallShowEvent) => void
): () => void;
once(
event: 'paywallHide',
callback: (data: PaywallHideEvent) => void
): () => void;
once(event: 'error', callback: (error: TiunError) => void): () => void;
once(
event: 'userChange',
callback: (data: UserChangeEvent) => void
): () => void;
once(event: 'login', callback: (data: LoginEvent) => void): () => void;
once(event: 'logout', callback: () => void): () => void;
/**
* Remove the SDK's listeners and reset its state. The snippet stays on the
* page; calling init() again works, but `user` stays empty until the next
* login, logout or checkout.
*/
destroy(): void;
/**
* Wait for the SDK to be ready.
*/
waitForReady(): Promise<void>;
/** SDK version */
readonly version: string;
/** Whether init() has been called */
readonly isInitialized: boolean;
/** Whether the snippet is ready */
readonly isReady: boolean;
/** Whether the user is identified (has valid session) */
readonly isAuthenticated: boolean;
/** Current user info or null */
readonly user: UserInfo | null;
}
/** NPM: use import { tiun } from '@tiun/sdk' or import tiun from '@tiun/sdk' */
export const tiun: TiunSDK;
export default tiun;
// =============================================================================
// Global Declaration
// =============================================================================
declare global {
/**
* Global tiun SDK instance.
* Available after loading the tiun script.
*/
const tiun: TiunSDK;
interface Window {
tiun: TiunSDK;
}
}
export {};