This is the TypeScript SDK for AltScore. It provides a simple interface to the AltScore API with full TypeScript support and modern JavaScript patterns.
- π Multiple authentication methods: user credentials, client credentials, token, form token
- π Automatic token renewal with configurable callbacks
- π Environment-specific configurations
- π Rich API for working with Borrower Central
- π Fully typed with TypeScript for better IDE integration
- π Modern async/await API design
- π Detailed error handling with specific error types
- 𧩠Modular architecture for easy extension
npm install altscore
Or if you prefer pnpm:
pnpm add altscore
You can initialize the SDK in two ways:
import { AltScore } from 'altscore';
// Use the fluent builder pattern
const altScore = AltScore.configure()
.withEnvironment('production')
.withClientCredentials('your-client-id', 'your-client-secret')
.withTokenRefreshCallback(token => {
console.log('Token refreshed:', token);
})
.build();
import { AltScore } from 'altscore';
// Initialize with options object
const altScore = new AltScore({
environment: 'production',
auth: {
type: 'client_credentials',
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
},
onTokenRefresh: token => {
console.log('Token refreshed:', token);
},
});
import { AltScore } from 'altscore';
// Create from token directly
const altScore = AltScore.fromToken('your-jwt-token', {
environment: 'production',
});
// Create a borrower
const borrowerId = await altScore.borrowerCentral.borrowers.create({
persona: 'INDIVIDUAL',
externalId: 'ext-123',
label: 'John Doe',
});
// Retrieve a borrower
const borrower = await altScore.borrowerCentral.borrowers.retrieve(borrowerId);
// Update a borrower
if (borrower) {
// Update label
const updatedBorrower = await borrower.setLabel('Jane Doe');
// Add tags
await borrower.addTags(['vip', 'priority']);
// Set risk rating
await borrower.setRiskRating('A');
}
// Query borrowers with pagination
const response = await altScore.borrowerCentral.borrowers.queryPaginated({
perPage: 10,
page: 1,
sortBy: 'createdAt',
sortDirection: 'desc',
});
console.log(`Page ${response.meta.currentPage} of ${response.meta.totalPages}`);
console.log(`Total: ${response.meta.totalItems} borrowers`);
// Find by identity
const borrowerByEmail = await altScore.borrowerCentral.borrowers.findByIdentity(
'email',
'john@example.com'
);
The tenant ID is automatically read from the authentication token:
// Get the tenant from the token
const tenantId = client.getTenantFromToken();
console.log(`Current tenant: ${tenantId}`);
import { AltScore, HTTPError, TokenRenewalError, ResourceNotFoundError } from 'altscore';
try {
const borrower = await altScore.borrowerCentral.borrowers.retrieve('nonexistent-id');
// borrower will be null if not found
} catch (error) {
if (error instanceof HTTPError) {
console.log(`HTTP Error ${error.status}: ${error.message}`);
} else if (error instanceof TokenRenewalError) {
console.log('Token renewal failed:', error.message);
} else if (error instanceof ResourceNotFoundError) {
console.log(`${error.resourceType} with ID ${error.resourceId} not found`);
}
}
// In an API route
import { AltScore } from 'altscore';
export default async function handler(req, res) {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}
try {
// Create client from token
const client = AltScore.fromToken(token, {
environment: process.env.ALTSCORE_ENVIRONMENT,
});
// Tenant is automatically read from the token
const tenant = client.getTenantFromToken();
console.log(`Request for tenant: ${tenant}`);
// Handle request
if (req.method === 'GET') {
const borrowers = await client.borrowerCentral.borrowers.query(req.query);
return res.status(200).json(borrowers);
}
} catch (error) {
if (error.status) {
return res.status(error.status).json({
error: error.message,
details: error.response,
});
}
return res.status(500).json({ error: error.message });
}
}
The SDK supports the following environment variables:
ALTSCORE_EMAIL
- Email for user authenticationALTSCORE_PASSWORD
- Password for user authenticationALTSCORE_CLIENT_ID
- Client ID for API token authenticationALTSCORE_CLIENT_SECRET
- Client secret for API token authenticationALTSCORE_TOKEN
- Direct JWT token for authenticationALTSCORE_FORM_TOKEN
- Form token for public formsALTSCORE_TENANT
- Tenant name for authentication (only needed when not using tokens)ALTSCORE_ENVIRONMENT
- Environment (default: 'production')ALTSCORE_LOCAL_BC_URL
- Custom URL for local borrower central environmentALTSCORE_LOCAL_AUTH_URL
- Custom URL for local authentication environment
src/
βββ core/ # Core functionality
β βββ auth/ # Authentication
β βββ http/ # HTTP handling
β βββ config/ # Configuration
βββ modules/ # API modules
β βββ borrower-central/
β βββ models/ # Data models
β βββ services/ # API services
β βββ index.ts
βββ models/ # Shared models
βββ errors/ # Error types
βββ utils/ # Utilities
# Clone the repository
git clone https://github.com/altscore/altscore-typescript.git
cd altscore-typescript
# Install dependencies
npm install
# Build the SDK
npm run build
# Run in development mode with watch
npm run dev
# Configure your environment variables
cp .env.example .env
# Edit .env with your credentials
# Run examples:
# Test connection
npm run test:connection
# Test with token
npm run test:token
# Test builder pattern
npm run test:builder
MIT