@uengage.io/platform-sdk
v0.9.1
Published
Client SDK for the uEngage platform API (audit, business, auth). Single createClient(...) factory; OAuth2 client_credentials, static Bearer, or legacy session-token auth modes.
Downloads
975
Maintainers
Readme
@uengage.io/platform-sdk
Client SDK for uEngage platform services. One factory (createClient) returns a PlatformClient exposing business, audit, and auth. No singletons, no module-level state — each consumer constructs its own client with explicit config.
CDK constructs live in a separate package: @uengage/platform-constructs.
Quick start
import { createClient } from '@uengage.io/platform-sdk';
// No args: read everything from UENGAGE_* env vars (baseUrl, service
// credentials or auth token, etc.). Convenient for Lambdas where the
// deploy stack already injects the right env.
const client = createClient();
// Or override per call:
const explicit = createClient({
baseUrl: 'https://api.platform.uengage.io',
serviceId: 'my-service',
serviceSecret: process.env.MY_SERVICE_SECRET!,
scope: 'business.profile:read business.menu:read',
actorVia: 'my-service', // stamped into audit events
});
const acme = await client.business.get(123, { groups: ['profile'] });
client.audit.record({
event_type: 'business.updated',
tenant: { id: 'biz_123', parent_id: null },
actor: { type: 'user', id: 'usr_42' },
resource: { type: 'business', id: 'biz_123' },
changes: { name: { before: 'Old', after: 'New' } },
});Auth modes
createClient takes exactly one of three auth modes (or none, for fully-public calls). Passing more than one throws ConfigError.
// Service-to-service (OAuth2 client_credentials)
createClient({ serviceId: 'svc', serviceSecret: 'sup', scope: '...' });
// Static Bearer (caller already minted the token, e.g. a BFF that has
// the end user's access_token from cookie / session)
createClient({ authToken: req.headers.authorization!.slice(7) });
// Customer surface: legacy session_token → JWT (transparent rotation)
createClient({ sessionToken: req.cookies.uengage_session });Each call returns a fresh, isolated client. Per-request scopes — say a BFF binding to the calling user's token — just call createClient again at the start of the handler.
Why no singleton?
Earlier versions of the SDK exported platform, audit, and business as module-level singletons that read configuration from process.env. That shape created problems in Node:
- Module-load side effects. Importing the SDK eagerly constructed clients even when the caller didn't use them.
- Cross-invocation state in Lambda. A singleton's token cache, JWKS cache, and fetch handle survived across invocations and could leak between tenants.
- No multi-tenant story. A single Node process couldn't act as multiple identities; only one set of
UENGAGE_*env vars was readable. - First-access config locking.
process.envmutated after the first call was a no-op. - Tests needed a
_resetPlatformSingleton()escape hatch.
Forcing every consumer to call createClient(...) removes all of that. Each instance is isolated, configuration is explicit, and the only state is what the caller chose to keep.
Configuration
| Field | Env override | Default |
| --------------------- | -------------------------------- | --------------------------------- |
| baseUrl | UENGAGE_BASE_URL | https://api.platform.uengage.io |
| authBaseUrl | UENGAGE_AUTH_BASE_URL | ${baseUrl}/auth/business |
| customerAuthBaseUrl | UENGAGE_CUSTOMER_AUTH_BASE_URL | ${baseUrl}/auth/customer |
| serviceId | UENGAGE_SERVICE_ID | none |
| serviceSecret | UENGAGE_SERVICE_SECRET | none |
| scope | UENGAGE_SCOPE | none |
| authToken | UENGAGE_AUTH_TOKEN | none |
| sessionToken | UENGAGE_SESSION_TOKEN | none |
| actorVia | UENGAGE_ACTOR_VIA | falls back to serviceId |
| expiryBufferMs | UENGAGE_EXPIRY_BUFFER_MS | 30000 |
| fetchFn | (no env override) | globalThis.fetch |
createClient() reads env defaults; explicit fields passed to createClient(input) override the matching env value for that one call. Passing any auth-mode field explicitly (authToken, sessionToken, or the serviceId/serviceSecret pair) suppresses every env-derived auth default — so callers never get a silent merge of two different auth modes.
Audit client
client.audit.record({
event_type: 'business.updated',
tenant: { id: 'biz_123', parent_id: null },
actor: { type: 'user', id: 'usr_42' },
resource: { type: 'business', id: 'biz_123' },
changes: { name: { before: 'Old', after: 'New' } },
});
await client.audit.flush(); // optional: drain on shutdownrecord()is fire-and-forget. It generatesevent_id(ULID) andoccurred_at, fillsactor.viawith the configuredactorVia(orserviceId), validates the event, and enqueues it. It never throws.- Events batch and flush every 5 s (configurable) or when the batch reaches 50.
- Failed batches retry up to 3 times with exponential backoff (500 ms / 2 s / 8 s); on final failure the full batch is logged.
- Queue overflow (default 1000) drops new events with a warning log.
flush()resolves when the queue is empty or retries are exhausted.- If
actorViais unset,record()logs an error and drops the event.
Business client
const biz = await client.business.get(123);
// { id: 123, parent_id: 42, profile: { name: 'Acme' } }
const detailed = await client.business.get(123, {
groups: ['profile', 'gst', 'payment_gateway'],
});
const many = await client.business.bulk([123, 124], { groups: ['profile'] });get()returns the record or throwsBusinessApiError(with.statusand.body).bulk()returns matched records in input order; missing ids are dropped silently.- The
profilegroup (justname) is public; other groups need matchingbusiness.<group>:readcapability for the calling service id.
Auth helpers
import { auth } from '@uengage.io/platform-sdk';
// or: client.auth.* — same namespace either way (stateless functions)
const pkce = auth.generatePKCE();
const url = auth.createAuthorizeUrl({
authBaseUrl: 'https://api.platform.uengage.io/auth/business',
clientId: 'my-app',
redirectUri: 'https://my-app.example/cb',
tenant: 'demo-tenant',
codeChallenge: pkce.code_challenge,
state: 'csrf-state',
});
// browser navigates to `url`; on callback, exchange the code:
const tokens = await auth.exchangeCode({
authBaseUrl: 'https://api.platform.uengage.io/auth/business',
code: 'returned-code',
codeVerifier: pkce.code_verifier,
clientId: 'my-app',
redirectUri: 'https://my-app.example/cb',
});auth exports stateless helpers; you can import the namespace directly or reach it via any client (client.auth). The same object is reused across clients because there's no state to isolate.
Build / test
pnpm --filter @uengage.io/platform-sdk build
pnpm --filter @uengage.io/platform-sdk testPublish
The package publishes on a platform-sdk-vX.Y.Z tag push. To cut a release:
- Bump
versioninpackage.json. - Open a PR; merge.
- Tag
platform-sdk-vX.Y.Zonmainand push — the publish workflow runspnpm publish --filter @uengage.io/platform-sdk --access public.
