@alienplatform/platform-api
v1.14.1
Published
Developer-friendly & type-safe Typescript SDK specifically catered to leverage _openapi_ API.
Readme
openapi
Developer-friendly & type-safe Typescript SDK specifically catered to leverage openapi API.
[!IMPORTANT] This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your workspace. Delete this section before > publishing to a package manager.
Summary
Table of Contents
SDK Installation
[!TIP] To finish publishing your SDK to npm and others you must run your first generation action.
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add <UNSET>PNPM
pnpm add <UNSET>Bun
bun add <UNSET>Yarn
yarn add <UNSET>[!NOTE] This package is published as an ES Module (ESM) only. For applications using CommonJS, use
await import()to import and use this package.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { Alien } from "@alienplatform/platform-api";
const alien = new Alien({
apiKey: process.env["ALIEN_API_KEY"] ?? "",
});
async function run() {
const result = await alien.user.listMemberships();
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
| -------- | ---- | ----------- | -------------------- |
| apiKey | http | HTTP Bearer | ALIEN_API_KEY |
To authenticate with the API the apiKey parameter must be set when initializing the SDK client instance. For example:
import { Alien } from "@alienplatform/platform-api";
const alien = new Alien({
apiKey: process.env["ALIEN_API_KEY"] ?? "",
});
async function run() {
const result = await alien.user.listMemberships();
console.log(result);
}
run();
Available Resources and Operations
ApiKeys
- list - Retrieve all API keys for the current workspace.
- create - Create a new API key.
- get - Retrieve a specific API key.
- revoke - Revoke (soft delete) an API key.
- update - Update an API key (enable/disable, change description).
- deleteMultiple - Permanently delete multiple API keys.
Auth
- whoami - Get the current authenticated principal (user or service account). Works with both session cookies and API keys.
Billing
- listAuditLog - List billing activity entries for the current workspace.
- getEntitlements - Get the workspace billing entitlements used for product feature gates. Autumn is the source of truth; the response is served through the workspace billing read model with stale-cache fallback.
CloudRegions
- get - Get cloud regions supported by this Alien environment.
Commands
- list - Retrieve commands. Use for dashboard analytics and command history.
- create - Create command metadata. Called by manager when processing commands. Returns project info for routing decisions.
- listNames - List distinct command names. Use for filter dropdowns in the dashboard.
- listDeployments - List distinct deployments that have commands, including deployment group info. Use for filter dropdowns in the dashboard.
- get - Retrieve a command by ID.
- update - Update command state. Called by manager when command is dispatched or completes.
DebugSessions
- list - Retrieve debug sessions for dashboard audit. Filters: project, deployment, state, mode.
- create - Create a debug-session audit row. Called by the manager when a pull or push debug tunnel is opened. Workspace + project derived from deployment.
- get - Retrieve a debug session by ID.
- update - Update debug-session state. Called by manager on tunnel attach, close, or deadline expiry.
Deployment
- getInfo - Get deployment information for the deployment portal. Accepts both deployment-scoped and deployment-group-scoped API keys. Returns project information, package status/outputs, and either deployment or deployment group details depending on the token type. Poll this endpoint to check if packages are ready.
- planCompute - Plan deployment compute for the active release before stack preparation. The response contains recommended machine and scale choices for cloud compute pools.
- prepareStack - Prepare the active release stack for a deployment portal setup session. The response contains the generated stack shape plus setup compatibility metadata.
DeploymentGroups
- listDeploymentGroups - List deployment groups
- createDeploymentGroup - Create a new deployment group
- ensureDeploymentGroupByName - Get or create a deployment group by project and name
- getDeploymentGroup - Get deployment group details
- deleteDeploymentGroup - Delete deployment group
- updateDeploymentGroup - Update deployment group
- createDeploymentGroupToken - Create deployment group token
- createFirstPartyDeploymentSession - Create first-party deployment session
Deployments
- list - Retrieve all deployments.
- create - Create a new deployment. Deployment group tokens automatically use their group. Workspace/project tokens must provide deploymentGroupId.
- getStats - Get aggregated deployment statistics. Returns total count and breakdown by status.
- listFilterEnvironments - List distinct effective environments used by deployments. Used for filter dropdowns.
- listFilterDeploymentGroups - List deployment groups with deployment counts. Used for filter dropdowns.
- get - Retrieve a deployment by ID.
- getInfo - Get deployment connection information including command endpoint and resource URLs.
- import - Import a deployment from resolved setup infrastructure such as CloudFormation, Terraform, or Helm.
- setFirstPartyDeploymentInputs - Store operator-provided input values on a first-party deployment session token so CLI/local deploys apply them.
- createSetupRegistrationOperation - Start a durable setup registration operation for CloudFormation, Terraform, or Helm.
- getSetupRegistrationOperation - Get setup registration operation status.
- delete - Delete, detach, or forget a deployment by ID.
- redeploy - Redeploy a running deployment with the same release and fresh environment variables. Sets status to update-pending.
- pinRelease - Pin or unpin deployment to a specific release. Only works for running deployments. Controller will automatically trigger update to target release.
- retry - Retry a failed deployment operation. Uses alien-infra's retry mechanisms to resume from exact failure point.
- updateEnvironmentVariables - Update a deployment's environment variables. If the deployment is running and not locked, the status will be changed to update-pending to trigger a deployment.
- createToken - Create a deployment token (deployment-scoped API key). The deployment must exist before creating a token.
Domains
- list - List system domains and workspace domains.
- create - Create a workspace domain and optional initial endpoints.
- createEndpoint - Create an endpoint under a workspace domain.
- get - Get domain by ID.
- delete - Delete a workspace domain.
- refresh - Refresh workspace domain verification.
Events
Machines
- listJoinTokens
- createJoinToken
- rotateJoinToken
- revokeJoinToken
- listInventory
- drainMachine
- cancelMachineDrain
- removeMachine
Managers
- list - Retrieve all managers.
- create - Create a new manager.
- retrySetup - Revoke previous private-manager setup tokens and issue a fresh setup token/config.
- retry - Retry private-manager setup. Returns a fresh setup action before the internal deployment exists, or requests retry for the internal deployment after it exists.
- cancelSetup - Cancel pending private-manager setup, revoke setup/runtime tokens, and remove the undeployed manager record.
- get - Retrieve a manager by ID.
- delete - Delete a manager by ID.
- getDomainBinding - Get the custom domain binding for a private manager.
- updateDomainBinding - Create, update, or remove the custom domain binding for a private manager.
- getManagementConfig - Get the management configuration for a manager.
- provision - Enqueue provisioning for a manager by ID.
- update - Update a manager to a specific release ID or active release.
- listEvents - Retrieve all events of a manager.
- generateManagerToken - Generate a short-lived JWT for direct browser → manager communication. Used for fetching command payloads and querying logs without routing sensitive data through the platform API.
- resolveGcpOAuthProvider - Resolve decrypted project-level Google Cloud OAuth provider settings for a manager-side deployment bootstrap.
- reportHeartbeat - Report Manager health status and metrics.
- getDeployment - Get deployment details for a private manager (internal deployment platform, status, resources).
OperatorManifests
- prepareOperatorManifestPackage - Prepare the white-labeled Operator image for an Operate install
- renderOperatorManifest - Render a Kubernetes Operator manifest
Packages
- list - List packages with optional filters. Returns packages ordered by creation date (newest first).
- get - Get details of a specific package.
- rebuild - Rebuild packages for a project. This will cancel any pending packages and create new ones with auto-incremented versions.
- cancel - Cancel a pending or building package.
Projects
- list - Retrieve all projects.
- create - Create a new project.
- get - Retrieve a project by ID or name.
- delete - Delete a project. The project must have no deployments.
- update - Update a project.
- getGcpOAuthProvider - Retrieve redacted project-level Google Cloud OAuth provider settings.
- updateGcpOAuthProvider - Update project-level Google Cloud OAuth provider settings.
- getDeploymentPortalDomain - Get the deployment portal domain binding for a project.
- createFromTemplate - Create a project by forking alienplatform/alien into your namespace, then configuring GitHub Actions.
- getTemplateUrls - Get template URLs for deploying setup stacks in this project.
- getDeploymentLinkSetup - Get the active release stack and portal-visible setup availability for deployment-link configuration.
- getActiveRelease - Get the active release for this project. Returns the latest release, or the pinned release if deploymentId is provided and that deployment has a pinned release.
Releases
- list - Retrieve all releases.
- create - Create a new release.
- listBranches - List distinct git branches across releases. Used for filter dropdowns.
- listAuthors - List distinct commit authors across releases. Used for filter dropdowns.
- get - Retrieve a release by ID.
Resolve
- resolve - Resolve manager for a project and platform
Resources
Sync
- list - List full deployment records for manager operational loops. This endpoint is intentionally separate from the public deployments list, which returns lightweight UI rows.
- acquire - Acquire a batch of deployments for processing. Used by Manager to atomically lock deployments matching filters. Each deployment in the batch must be released after processing.
- reconcile - Reconcile deployment state. Push model requests that include a session verify lock ownership. Pull model state reports are accepted as authz-gated agent progress even when they carry an agent-sync session. Accepts full DeploymentState after step() execution.
- release - Release a deployment lock. Must be called after processing an acquired deployment, even if processing failed. This is critical to avoid deadlocks.
User
- listMemberships - List all workspaces the current user has access to.
- getProfile - Get the current user's profile and user-scoped onboarding state.
- updateProfile - Update the current user's profile (display name).
- completeProfileSetup - Complete the required beta intake and profile setup dialog.
- createWorkspace - Create a new workspace. The current user will be automatically added as an admin.
- listGitNamespaces - List all git namespaces (GitHub installations) the current user has access to.
- syncGitNamespaces - Sync git namespaces from the provider. For GitHub, this fetches all app installations accessible to the user.
- listGitNamespaceRepositories - List repositories accessible through a git namespace (GitHub installation).
Workspaces
- list - Retrieve all workspaces.
- get - Retrieve a workspace by ID.
- delete - Delete a workspace. The workspace must have no projects.
- update - Update a workspace.
- listMembers - List all members of a workspace.
- addMember - Add a member to a workspace by email. The user must already have an account.
- removeMember - Remove a member from a workspace.
- updateMember - Update a workspace member's role.
- dismissOnboarding - Mark the Getting Started walkthrough as dismissed for a workspace. The dashboard stops auto-promoting onboarding once this is set; users can still re-enter the walkthrough via the help menu.
Standalone functions
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
apiKeysCreate- Create a new API key.apiKeysDeleteMultiple- Permanently delete multiple API keys.apiKeysGet- Retrieve a specific API key.apiKeysList- Retrieve all API keys for the current workspace.apiKeysRevoke- Revoke (soft delete) an API key.apiKeysUpdate- Update an API key (enable/disable, change description).authWhoami- Get the current authenticated principal (user or service account). Works with both session cookies and API keys.billingGetEntitlements- Get the workspace billing entitlements used for product feature gates. Autumn is the source of truth; the response is served through the workspace billing read model with stale-cache fallback.billingListAuditLog- List billing activity entries for the current workspace.cloudRegionsGet- Get cloud regions supported by this Alien environment.commandsCreate- Create command metadata. Called by manager when processing commands. Returns project info for routing decisions.commandsGet- Retrieve a command by ID.commandsList- Retrieve commands. Use for dashboard analytics and command history.commandsListDeployments- List distinct deployments that have commands, including deployment group info. Use for filter dropdowns in the dashboard.commandsListNames- List distinct command names. Use for filter dropdowns in the dashboard.commandsUpdate- Update command state. Called by manager when command is dispatched or completes.debugSessionsCreate- Create a debug-session audit row. Called by the manager when a pull or push debug tunnel is opened. Workspace + project derived from deployment.debugSessionsGet- Retrieve a debug session by ID.debugSessionsList- Retrieve debug sessions for dashboard audit. Filters: project, deployment, state, mode.debugSessionsUpdate- Update debug-session state. Called by manager on tunnel attach, close, or deadline expiry.deploymentGetInfo- Get deployment information for the deployment portal. Accepts both deployment-scoped and deployment-group-scoped API keys. Returns project information, package status/outputs, and either deployment or deployment group details depending on the token type. Poll this endpoint to check if packages are ready.deploymentGroupsCreateDeploymentGroup- Create a new deployment groupdeploymentGroupsCreateDeploymentGroupToken- Create deployment group tokendeploymentGroupsCreateFirstPartyDeploymentSession- Create first-party deployment sessiondeploymentGroupsDeleteDeploymentGroup- Delete deployment groupdeploymentGroupsEnsureDeploymentGroupByName- Get or create a deployment group by project and namedeploymentGroupsGetDeploymentGroup- Get deployment group detailsdeploymentGroupsListDeploymentGroups- List deployment groupsdeploymentGroupsUpdateDeploymentGroup- Update deployment groupdeploymentPlanCompute- Plan deployment compute for the active release before stack preparation. The response contains recommended machine and scale choices for cloud compute pools.deploymentPrepareStack- Prepare the active release stack for a deployment portal setup session. The response contains the generated stack shape plus setup compatibility metadata.deploymentsCreate- Create a new deployment. Deployment group tokens automatically use their group. Workspace/project tokens must provide deploymentGroupId.deploymentsCreateSetupRegistrationOperation- Start a durable setup registration operation for CloudFormation, Terraform, or Helm.deploymentsCreateToken- Create a deployment token (deployment-scoped API key). The deployment must exist before creating a token.deploymentsDelete- Delete, detach, or forget a deployment by ID.deploymentsGet- Retrieve a deployment by ID.deploymentsGetInfo- Get deployment connection information including command endpoint and resource URLs.deploymentsGetSetupRegistrationOperation- Get setup registration operation status.deploymentsGetStats- Get aggregated deployment statistics. Returns total count and breakdown by status.deploymentsImport- Import a deployment from resolved setup infrastructure such as CloudFormation, Terraform, or Helm.deploymentsList- Retrieve all deployments.deploymentsListFilterDeploymentGroups- List deployment groups with deployment counts. Used for filter dropdowns.deploymentsListFilterEnvironments- List distinct effective environments used by deployments. Used for filter dropdowns.deploymentsPinRelease- Pin or unpin deployment to a specific release. Only works for running deployments. Controller will automatically trigger update to target release.deploymentsRedeploy- Redeploy a running deployment with the same release and fresh environment variables. Sets status to update-pending.deploymentsRetry- Retry a failed deployment operation. Uses alien-infra's retry mechanisms to resume from exact failure point.deploymentsSetFirstPartyDeploymentInputs- Store operator-provided input values on a first-party deployment session token so CLI/local deploys apply them.deploymentsUpdateEnvironmentVariables- Update a deployment's environment variables. If the deployment is running and not locked, the status will be changed to update-pending to trigger a deployment.domainsCreate- Create a workspace domain and optional initial endpoints.domainsCreateEndpoint- Create an endpoint under a workspace domain.domainsDelete- Delete a workspace domain.domainsGet- Get domain by ID.domainsList- List system domains and workspace domains.domainsRefresh- Refresh workspace domain verification.eventsGet- Retrieve an event by ID.eventsList- Retrieve all events.machinesCancelMachineDrainmachinesCreateJoinTokenmachinesDrainMachinemachinesListInventorymachinesListJoinTokensmachinesRemoveMachinemachinesRevokeJoinTokenmachinesRotateJoinTokenmanagersCancelSetup- Cancel pending private-manager setup, revoke setup/runtime tokens, and remove the undeployed manager record.managersCreate- Create a new manager.managersDelete- Delete a manager by ID.managersGenerateManagerToken- Generate a short-lived JWT for direct browser → manager communication. Used for fetching command payloads and querying logs without routing sensitive data through the platform API.managersGet- Retrieve a manager by ID.managersGetDeployment- Get deployment details for a private manager (internal deployment platform, status, resources).managersGetDomainBinding- Get the custom domain binding for a private manager.managersGetManagementConfig- Get the management configuration for a manager.managersList- Retrieve all managers.managersListEvents- Retrieve all events of a manager.managersProvision- Enqueue provisioning for a manager by ID.managersReportHeartbeat- Report Manager health status and metrics.managersResolveGcpOAuthProvider- Resolve decrypted project-level Google Cloud OAuth provider settings for a manager-side deployment bootstrap.managersRetry- Retry private-manager setup. Returns a fresh setup action before the internal deployment exists, or requests retry for the internal deployment after it exists.managersRetrySetup- Revoke previous private-manager setup tokens and issue a fresh setup token/config.managersUpdate- Update a manager to a specific release ID or active release.managersUpdateDomainBinding- Create, update, or remove the custom domain binding for a private manager.operatorManifestsPrepareOperatorManifestPackage- Prepare the white-labeled Operator image for an Operate installoperatorManifestsRenderOperatorManifest- Render a Kubernetes Operator manifestpackagesCancel- Cancel a pending or building package.packagesGet- Get details of a specific package.packagesList- List packages with optional filters. Returns packages ordered by creation date (newest first).packagesRebuild- Rebuild packages for a project. This will cancel any pending packages and create new ones with auto-incremented versions.projectsCreate- Create a new project.projectsCreateFromTemplate- Create a project by forking alienplatform/alien into your namespace, then configuring GitHub Actions.projectsDelete- Delete a project. The project must have no deployments.projectsGet- Retrieve a project by ID or name.projectsGetActiveRelease- Get the active release for this project. Returns the latest release, or the pinned release if deploymentId is provided and that deployment has a pinned release.projectsGetDeploymentLinkSetup- Get the active release stack and portal-visible setup availability for deployment-link configuration.projectsGetDeploymentPortalDomain- Get the deployment portal domain binding for a project.projectsGetGcpOAuthProvider- Retrieve redacted project-level Google Cloud OAuth provider settings.projectsGetTemplateUrls- Get template URLs for deploying setup stacks in this project.projectsList- Retrieve all projects.projectsUpdate- Update a project.projectsUpdateGcpOAuthProvider- Update project-level Google Cloud OAuth provider settings.releasesCreate- Create a new release.releasesGet- Retrieve a release by ID.releasesList- Retrieve all releases.releasesListAuthors- List distinct commit authors across releases. Used for filter dropdowns.releasesListBranches- List distinct git branches across releases. Used for filter dropdowns.resolveResolve- Resolve manager for a project and platformresourcesGetDeploymentDetailresourcesListDeploymentsresourcesListInventoryresourcesListOverviewsyncAcquire- Acquire a batch of deployments for processing. Used by Manager to atomically lock deployments matching filters. Each deployment in the batch must be released after processing.syncList- List full deployment records for manager operational loops. This endpoint is intentionally separate from the public deployments list, which returns lightweight UI rows.syncReconcile- Reconcile deployment state. Push model requests that include a session verify lock ownership. Pull model state reports are accepted as authz-gated agent progress even when they carry an agent-sync session. Accepts full DeploymentState after step() execution.syncRelease- Release a deployment lock. Must be called after processing an acquired deployment, even if processing failed. This is critical to avoid deadlocks.userCompleteProfileSetup- Complete the required beta intake and profile setup dialog.userCreateWorkspace- Create a new workspace. The current user will be automatically added as an admin.userGetProfile- Get the current user's profile and user-scoped onboarding state.userListGitNamespaceRepositories- List repositories accessible through a git namespace (GitHub installation).userListGitNamespaces- List all git namespaces (GitHub installations) the current user has access to.userListMemberships- List all workspaces the current user has access to.userSyncGitNamespaces- Sync git namespaces from the provider. For GitHub, this fetches all app installations accessible to the user.userUpdateProfile- Update the current user's profile (display name).workspacesAddMember- Add a member to a workspace by email. The user must already have an account.workspacesDelete- Delete a workspace. The workspace must have no projects.workspacesDismissOnboarding- Mark the Getting Started walkthrough as dismissed for a workspace. The dashboard stops auto-promoting onboarding once this is set; users can still re-enter the walkthrough via the help menu.workspacesGet- Retrieve a workspace by ID.workspacesList- Retrieve all workspaces.workspacesListMembers- List all members of a workspace.workspacesRemoveMember- Remove a member from a workspace.workspacesUpdate- Update a workspace.workspacesUpdateMember- Update a workspace member's role.
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { Alien } from "@alienplatform/platform-api";
const alien = new Alien({
apiKey: process.env["ALIEN_API_KEY"] ?? "",
});
async function run() {
const result = await alien.user.listMemberships({
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { Alien } from "@alienplatform/platform-api";
const alien = new Alien({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
apiKey: process.env["ALIEN_API_KEY"] ?? "",
});
async function run() {
const result = await alien.user.listMemberships();
console.log(result);
}
run();
Error Handling
AlienError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
| ------------------- | ---------- | --------------------------------------------------------------------------------------- |
| error.message | string | Error message |
| error.statusCode | number | HTTP response status code eg 404 |
| error.headers | Headers | HTTP response headers |
| error.body | string | HTTP body. Can be empty string if no body is returned. |
| error.rawResponse | Response | Raw HTTP response |
| error.data$ | | Optional. Some errors may contain structured data. See Error Classes. |
Example
import { Alien } from "@alienplatform/platform-api";
import * as errors from "@alienplatform/platform-api/models/errors";
const alien = new Alien({
apiKey: process.env["ALIEN_API_KEY"] ?? "",
});
async function run() {
try {
const result = await alien.user.listMemberships();
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.AlienError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.APIError) {
console.log(error.data$.code); // string
console.log(error.data$.message); // string
console.log(error.data$.source); // any
console.log(error.data$.retryable); // boolean
console.log(error.data$.context); // any
}
}
}
}
run();
Error Classes
Primary errors:
AlienError: The base class for HTTP error responses.APIError: *
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from AlienError:
ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
* Check the method documentation to see if the error is applicable.
Server Selection
Override Server URL Per-Client
The default server can be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { Alien } from "@alienplatform/platform-api";
const alien = new Alien({
serverURL: "https://api.alien.dev",
apiKey: process.env["ALIEN_API_KEY"] ?? "",
});
async function run() {
const result = await alien.user.listMemberships();
console.log(result);
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to use the "beforeRequest" hook to to add a
custom header and a timeout to requests and how to use the "requestError" hook
to log errors:
import { Alien } from "@alienplatform/platform-api";
import { HTTPClient } from "@alienplatform/platform-api/lib/http";
const httpClient = new HTTPClient({
// fetcher takes a function that has the same signature as native `fetch`.
fetcher: (request) => {
return fetch(request);
}
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new Alien({ httpClient: httpClient });Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { Alien } from "@alienplatform/platform-api";
const sdk = new Alien({ debugLogger: console });You can also enable a default debug logger by setting an environment variable ALIEN_DEBUG to true.
Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
