API Reference

Complete API documentation for the Asterisms JS SDK Backend.

Main SDK Interface

AsterismsBackendSDK

The main SDK interface providing access to all services.

interface AsterismsBackendSDK {
  authorization(): AuthorizationService;
  storage(): StorageService;
  notifications(): NotificationSendingService;
  registration(): RegistrationService;
  discovery(): DiscoveryService;
  information(): InformationService;
  logging(): AsterismsLogger;
  boot(): Promise<void>;
  isBooted(): boolean;
}

Methods

boot(): Promise<void>

Initializes the SDK and establishes connections to core services.

await sdk.boot();

Throws:

  • AsterismsSDKError - When initialization fails
  • AuthorizationError - When product authorization key is invalid
isBooted(): boolean

Returns whether the SDK has been successfully booted.

if (sdk.isBooted()) {
  // SDK is ready to use
}

Factory Functions

getAsterismsBackendSDK(props: AsterismsBackendSDKInitProps): AsterismsBackendSDK

Creates or returns the singleton SDK instance.

import { getAsterismsBackendSDK } from '@asterisms/sdk-backend';
import { createFetchAdapter } from '@asterisms/sdk';

const sdk = getAsterismsBackendSDK({
  bundleId: 'com.example.app',
  domain: 'asterisms.example.com',
  subdomain: 'app',
  httpFactory: createFetchAdapter(fetch),
  signingJwk: 'your-signing-jwk',
  proxyTerminatedSSL: false,
  authorities: ['https://auth.asterisms.example.com'],
  // Plus other required RegistrationData properties
  capabilities: ['FRONTEND_WEBSITE'],
  description: 'My Application',
  name: 'My App',
  title: 'My App'
});

createSvelteKitBackendSDK(props: SvelteKitBackendSDKProps): AsterismsSDKProvider

Creates a SvelteKit-optimized SDK provider.

import { createSvelteKitBackendSDK } from '@asterisms/sdk-backend';
import { createFetchAdapter } from '@asterisms/sdk';

const provider = createSvelteKitBackendSDK({
  env: process.env,
  building: false,
  httpFactory: createFetchAdapter(fetch),
  registrationData: {
    bundleId: 'com.example.app',
    capabilities: ['FRONTEND_WEBSITE'],
    description: 'My Application',
    name: 'My App',
    subdomain: 'app',
    title: 'My App'
  }
});

Configuration Types

AsterismsBackendSDKInitProps

Configuration for initializing the SDK.

type AsterismsBackendSDKInitProps = RegistrationData & {
  domain: string;
  signingJwk: string;
  proxyTerminatedSSL: boolean;
  authorities: string[];
  httpFactory: HttpServiceAdapterFactory;
  productAuthorizationKey?: ProductAuthorizationKey;
};

SvelteKitBackendSDKProps

Configuration for SvelteKit SDK integration.

interface SvelteKitBackendSDKProps {
  env: Record<string, string | undefined>;
  building: boolean;
  httpFactory: HttpServiceAdapterFactory;
  registrationData: Partial<RegistrationData>;
  authorities?: string[];
  includeBackendCoreRoutes?: boolean;
  productAuthorizationKey?: ProductAuthorizationKey;
}

RegistrationData

Application registration information.

interface RegistrationData {
  bundleId: string;
  capabilities: string[];
  description: string;
  name: string;
  subdomain: string;
  title: string;
  icon?: string;
  group?: string;
}

Services

Authorization Service

Handles user authentication and authorization.

interface AuthorizationService {
  getCurrentUser(): Promise<User>;
  hasPermission(permission: string): Promise<boolean>;
  // Additional methods available - check source code for complete API
}

Methods

getCurrentUser(): Promise<User>

Gets the current authenticated user.

const auth = sdk.authorization();
const user = await auth.getCurrentUser();
hasPermission(permission: string): Promise<boolean>

Checks if the current user has a specific permission.

const canRead = await auth.hasPermission('resource.read');

Storage Service

Provides secure data storage and retrieval.

interface StorageService {
  // File operations
  getFile(externalId: string, config: { fileName?: string; etag?: string }): Promise<Response>;
  download(externalId: string, config: { fileName?: string; etag?: string }): Promise<Response>;
  getData(externalId: string): Promise<StorageFileData>;
  upload(file: WrappedBuffer | File, meta?: StorageUploadMetadata): Promise<StorageFileData>;
  replace(
    externalId: string,
    file: WrappedBuffer | File,
    meta?: StorageUploadMetadata
  ): Promise<StorageFileData>;
  delete(externalId: string): Promise<StorageFileData>;
  move(
    externalId: string,
    config: { fileName?: string },
    payload: StorageFileMoveRequest
  ): Promise<StorageFileData>;
  list(params?: { path?: string; bucketId?: string }): Promise<StorageFileData[]>;

  // Workspace scoping
  forWorkspace(bearerToken: string): Omit<StorageService, 'forWorkspace'>;

  // Ephemeral links
  ephemeral(): EphemeralLinksService;
}

Storage Service Methods

upload(file: WrappedBuffer | File, meta?: StorageUploadMetadata): Promise<StorageFileData>

Uploads a file to storage.

const storage = sdk.storage();
const file = new File(['content'], 'example.txt', { type: 'text/plain' });
const uploadedFile = await storage.upload(file, {
  prefix: 'documents/',
  bucketId: 'my-bucket'
});
getData(externalId: string): Promise<StorageFileData>

Retrieves file metadata.

const fileData = await storage.getData('file-external-id');
console.log(fileData.fileName, fileData.size);
delete(externalId: string): Promise<StorageFileData>

Deletes a file from storage.

const deletedFile = await storage.delete('file-external-id');

Notification Service

Sends notifications to accounts and workspaces.

interface NotificationSendingService {
  sendToAccount(accountId: string, notification: Notification): Promise<GenericSuccessResponse>;
  sendToWorkspace(workspaceId: string, notification: Notification): Promise<GenericSuccessResponse>;
}

Methods

sendToAccount(accountId: string, notification: Notification): Promise<GenericSuccessResponse>

Sends a notification to a specific account.

import { createNotification } from '@asterisms/sdk-backend';

const notifications = sdk.notifications();
const notification = createNotification({
  sender: 'your-app',
  subject: 'Welcome!',
  text: 'Thanks for joining our service',
  urgency: 'NONE'
});

await notifications.sendToAccount(accountId, notification);
sendToWorkspace(workspaceId: string, notification: Notification): Promise<GenericSuccessResponse>

Sends a notification to all members of a workspace.

const notification = createNotification({
  sender: 'your-app',
  subject: 'New Update Available',
  text: 'Version 2.0 has been released',
  urgency: 'IMPORTANT'
});

await notifications.sendToWorkspace(workspaceId, notification);

Registration Service

Manages app registration and metadata.

interface RegistrationService {
  getAppInfo(): Promise<AppInfo>;
  updateCapabilities(capabilities: string[]): Promise<void>;
  // Additional methods available - check source code for complete API
}

Methods

getAppInfo(): Promise<AppInfo>

Gets information about the current application.

const registration = sdk.registration();
const appInfo = await registration.getAppInfo();
updateCapabilities(capabilities: string[]): Promise<void>

Updates the application's capabilities.

await registration.updateCapabilities(['BACKEND_SERVICE', 'WEBHOOKS']);

Discovery Service

Discovers other services in the ecosystem.

interface DiscoveryService {
  findServices(capability: string): Promise<ServiceInfo[]>;
  // Additional methods available - check source code for complete API
}

Methods

findServices(capability: string): Promise<ServiceInfo[]>

Finds services with a specific capability.

const discovery = sdk.discovery();
const services = await discovery.findServices('BACKEND_SERVICE');

Information Service

Provides system and application information.

interface InformationService {
  getSystemInfo(): Promise<SystemInfo>;
  getAppInfo(): Promise<AppInfo>;
  // Additional methods available - check source code for complete API
}

Methods

getSystemInfo(): Promise<SystemInfo>

Gets system information.

const info = sdk.information();
const systemInfo = await info.getSystemInfo();
getAppInfo(): Promise<AppInfo>

Gets application information.

const appInfo = await info.getAppInfo();

Middleware

createAuthorizerMiddleware(authService: AuthorizationService): RequestHandler

Creates Express middleware for authorization.

import { createAuthorizerMiddleware } from '@asterisms/sdk-backend';

const authMiddleware = createAuthorizerMiddleware(sdk.authorization());
app.use(authMiddleware);

Controllers

StatusController

Pre-built controller for status endpoints.

import { StatusController } from '@asterisms/sdk-backend';

const statusController = new StatusController();
app.use('/status', statusController.getRouter());

ProductController

Pre-built controller for product endpoints.

import { ProductController } from '@asterisms/sdk-backend';

const productController = new ProductController(sdk);
app.use('/product', productController.getRouter());

WellKnownController

Pre-built controller for well-known endpoints.

import { WellKnownController } from '@asterisms/sdk-backend';

const wellKnownController = new WellKnownController();
app.use('/.well-known', wellKnownController.getRouter());

Error Types

AsterismsSDKError

Base error class for SDK-related errors.

import { AsterismsSDKError } from '@asterisms/sdk-backend';

try {
  await sdk.boot();
} catch (error) {
  if (error instanceof AsterismsSDKError) {
    console.error('SDK Error:', error.message);
  }
}

AsterismsMiddlewareError

Error class for middleware-related errors.

import { AsterismsMiddlewareError } from '@asterisms/sdk-backend';

// Thrown by middleware when authorization fails

Logging

The SDK provides structured logging through the common core:

const logger = sdk.logging();

logger.info('Operation completed', { userId: '123' });
logger.warn('Rate limit approaching', { limit: 100 });
logger.error('Operation failed', { error: error.message });

Types

Common Types

// From @asterisms/common-core
interface HttpServiceAdapterFactory {
  // Factory for creating HTTP adapters
}

interface ProductAuthorizationKey {
  // Product authorization key structure
}

interface User {
  id: string;
  email: string;
  name: string;
  // Additional user properties
}

interface NotificationData {
  title: string;
  message: string;
  // Additional notification properties
}

Version Information

Access version information:

import { versionInfo } from '@asterisms/sdk-backend';

console.log('SDK Version:', versionInfo.version);
console.log('Build Date:', versionInfo.buildDate);

Best Practices

Error Handling

Always wrap SDK calls in try-catch blocks:

try {
  const user = await sdk.authorization().getCurrentUser();
} catch (error) {
  if (error instanceof AsterismsSDKError) {
    // Handle SDK-specific errors
  } else {
    // Handle other errors
  }
}

Service Reuse

Cache service instances for better performance:

class MyService {
  private auth = this.sdk.authorization();
  private storage = this.sdk.storage();

  constructor(private sdk: AsterismsBackendSDK) {}
}

Type Safety

Use TypeScript for better type safety:

interface UserPreferences {
  theme: 'light' | 'dark';
  language: string;
}

const preferences = await storage.get<UserPreferences>('user-preferences');

Migration Notes

When upgrading SDK versions:

  1. Check the changelog for breaking changes
  2. Update import statements if needed
  3. Test all SDK integrations
  4. Update error handling if error types changed

For detailed migration information, see the Migration Guide.

Complete API Coverage

Note: This API reference covers the most commonly used methods. For complete API coverage, refer to:

  1. TypeScript Definitions: Check the TypeScript definitions in your IDE
  2. Source Code: Review the source code in /packages/sdk-backend/src/
  3. Tests: Examine test files for usage examples

The SDK is actively developed, and new methods may be added in future versions. Always refer to the latest TypeScript definitions for the most up-to-date API.