Skip to content

Repository files navigation

sanka-sdk

Official Node.js and TypeScript SDK for Sanka's hosted API and local migration lifecycle.

Built by Speakeasy License: Apache-2.0

Summary

The official Node.js and TypeScript SDK for Sanka's hosted API and local migration lifecycle.

Table of Contents

SDK Installation

The SDK can be installed with either npm, pnpm, bun or yarn package managers.

NPM

npm add sanka-sdk

PNPM

pnpm add sanka-sdk

Bun

bun add sanka-sdk

Yarn

yarn add sanka-sdk

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 Sanka from "sanka-sdk";

const sanka = new Sanka({
  apiKey: process.env["SANKA_API_KEY"] ?? "",
});

async function run() {
  const result = await sanka.ai.enrich({
    objectType: "<value>",
  });

  console.log(result);
}

run();

Local migration

The hosted API client and local migration runtime are separate:

Import What runs Authentication
import Sanka from "sanka-sdk" Sanka's hosted HTTP API API token
import { SankaMigrate } from "sanka-sdk/migrate" A local sanka subprocess None

Install sanka separately. The Node adapter does not bundle the runtime or call the hosted API.

uv tool install sanka-cli

Use a runtime release that includes the extension marketplace commands and the published default DRF extension dependency.

import { SankaMigrate } from "sanka-sdk/migrate";

const migrate = new SankaMigrate({
  cwd: "./django-app",
  env: { DJANGO_SECRET_KEY: process.env["DJANGO_SECRET_KEY"] },
});

await migrate.extensions.marketplaces.add(
  "git@github.com:sankaHQ/extensions.git",
  { name: "sanka" },
);
const extensions = await migrate.extensions.list();
console.log(extensions.data);
await migrate.extensions.add("sanka/drf-to-fastapi", {
  marketplace: "sanka",
});

const scan = await migrate.scan();
for (const recommendation of scan.data.recommendations ?? []) {
  console.log(
    recommendation.id,
    recommendation.targets,
    recommendation.status,
    recommendation.add_command,
  );
}

const plan = await migrate.plan({
  to: "fastapi",
  generation: "full",
  strategy: "native",
  packageManager: "uv",
  extensionConfig: { output: "target" },
  extensionEnvironment: ["DJANGO_SECRET_KEY"],
});
const applied = await migrate.apply({ planHash: plan.data.plan_hash });
const tested = await migrate.test();
const verified = await migrate.verify();

scan.data.recommendations contains typed extension IDs, versions, marketplace names, targets, static evidence, status, and the exact add command. plan({ to }) selects one enabled extension that advertises that target. SDK calls are non-interactive, so pass to. A missing, incompatible, or ambiguous extension fails instead of choosing one silently. For SANKA_EXTENSION_REQUIRED, read the same recommendation data from error.parsedError?.details?.["recommendations"].

extensionConfig and extensionEnvironment are available on scan, plan, apply, test, and verify. Configuration must be a plain JSON object. The adapter snapshots and serializes it before spawning. extensionEnvironment accepts names such as DJANGO_SECRET_KEY, not secret values. Values come from process.env plus the constructor's env overrides and are forwarded only when named.

Manage extensions and marketplaces

await migrate.extensions.marketplaces.add("./marketplace", {
  name: "third-party",
  trust: true,
});
await migrate.extensions.marketplaces.list();
await migrate.extensions.marketplaces.upgrade("third-party");
await migrate.extensions.marketplaces.upgrade(); // Upgrade every marketplace.

await migrate.extensions.add("example/demo", {
  marketplace: "third-party",
});
await migrate.extensions.list();
await migrate.extensions.remove("example/demo");

await migrate.extensions.marketplaces.remove("third-party");

The Node adapter does not make trust or snapshot decisions. sanka owns marketplace trust checks, immutable snapshots, artifact validation, installed caches, and project extension locks. Adding an untrusted marketplace requires trust: true. Upgrading reads a new immutable snapshot. Removing a marketplace fails while a project extension still depends on it.

Command and result contract

Node.js method Runtime command Purpose
scan() sanka scan ... --json Inspect the source and write the scan artifact
plan() sanka plan ... --json Create a reviewable plan and plan hash
apply() sanka apply ... --json Generate only from the supplied reviewed plan hash
test() sanka test ... --json Prepare the generated target environment and run its tests
verify() sanka verify ... --json Verify integrity and configured behavior
extensions.add/list/remove sanka extension ... --json Manage project extension pins
extensions.marketplaces.add/list/upgrade/remove sanka extension marketplace ... --json Manage immutable marketplace snapshots

Every subprocess receives an argument array with shell: false and --json. Invalid extension configuration or environment names throw before the process starts. String arguments are never interpreted as shell commands.

Successful calls return a typed SankaMigrateResult only after the adapter validates one complete sanka-cli/v1 document. It requires the matching command, a success outcome with exit 0, object data, string-array artifacts, limitations, and next_actions, and a string migration_state.

Failures reject with SankaMigrateError. A valid CLI failure has an error outcome with exit 1 for a migration or verification failure, or exit 2 for invalid usage. parsedError contains its stable code, message, and optional details. result keeps the complete validated envelope. Missing executables, signals, malformed JSON, unsupported schemas, command mismatches, malformed error data, and inconsistent outcome/exit pairs fail closed without a result.

import { SankaMigrateError } from "sanka-sdk/migrate";

try {
  await migrate.plan({ to: "fastapi" });
} catch (error) {
  if (error instanceof SankaMigrateError) {
    console.error(error.parsedError?.code, error.parsedError?.details);
    console.error(error.exitCode, error.stderr);
  }
}

See the CLI execution model and Sanka developer documentation.

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme Environment Variable
bearerAuth http HTTP Bearer SANKA_BEARER_AUTH

To authenticate with the API the apiKey parameter must be set when initializing the SDK client instance. For example:

import Sanka from "sanka-sdk";

const sanka = new Sanka({
  apiKey: process.env["SANKA_API_KEY"] ?? "",
});

async function run() {
  const result = await sanka.ai.enrich({
    objectType: "<value>",
  });

  console.log(result);
}

run();

Available Resources and Operations

Available methods
  • list - List Public Contacts
  • create - Create Public Contact
  • get - Get Public Contact
  • update - Update Public Contact
  • delete - Delete Public Contact
  • list - List Public Expenses
  • create - Create Public Expense
  • uploadFile - Upload Public Expense File
  • get - Get Public Expense
  • update - Update Public Expense
  • delete - Delete Public Expense
  • list - List Public Inventories
  • create - Create Public Inventory
  • get - Get Public Inventory
  • update - Update Public Inventory
  • delete - Delete Public Inventory
  • list - List Public Inventory Transactions
  • create - Create Public Inventory Transaction
  • get - Get Public Inventory Transaction
  • update - Update Public Inventory Transaction
  • delete - Delete Public Inventory Transaction
  • list - List Public Items
  • create - Create Public Item
  • get - Get Public Item
  • update - Update Public Item
  • delete - Delete Public Item
  • list - List Public Locations
  • create - Create Public Location
  • get - Get Public Location
  • update - Update Public Location
  • delete - Delete Public Location
  • list - List Public Meters
  • create - Create Public Meter
  • get - Get Public Meter
  • update - Update Public Meter
  • delete - Delete Public Meter
  • list - List Public Projects
  • create - Create Public Project
  • get - Get Public Project
  • update - Update Public Project
  • delete - Delete Public Project
  • list - List Public Developer Properties
  • create - Create Public Developer Property
  • get - Retrieve Public Developer Property
  • update - Update Public Developer Property
  • delete - Delete Public Developer Property
  • list - List Public Reports
  • create - Create Public Report
  • get - Get Public Report
  • update - Update Public Report
  • delete - Delete Public Report

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.

Available standalone functions

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 { Sanka } from "sanka-sdk";

const sanka = new Sanka({
  bearerAuth: process.env["SANKA_BEARER_AUTH"] ?? "",
});

async function run() {
  const result = await sanka.absences.listPublicAbsencesApiV2PublicAbsencesGet(
    {},
    {
      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 { Sanka } from "sanka-sdk";

const sanka = new Sanka({
  retryConfig: {
    strategy: "backoff",
    backoff: {
      initialInterval: 1,
      maxInterval: 50,
      exponent: 1.1,
      maxElapsedTime: 100,
    },
    retryConnectionErrors: false,
  },
  bearerAuth: process.env["SANKA_BEARER_AUTH"] ?? "",
});

async function run() {
  const result = await sanka.absences.listPublicAbsencesApiV2PublicAbsencesGet(
    {},
  );

  console.log(result);
}

run();

Error Handling

SankaError 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 { Sanka } from "sanka-sdk";
import * as errors from "sanka-sdk/models/errors";

const sanka = new Sanka({
  bearerAuth: process.env["SANKA_BEARER_AUTH"] ?? "",
});

async function run() {
  try {
    const result = await sanka.absences
      .listPublicAbsencesApiV2PublicAbsencesGet({});

    console.log(result);
  } catch (error) {
    // The base class for HTTP error responses
    if (error instanceof errors.SankaError) {
      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.ErrorEnvelope) {
        console.log(error.data$.success); // boolean
        console.log(error.data$.error); // models.ErrorBody
        console.log(error.data$.meta); // models.EnvelopeMeta
      }
    }
  }
}

run();

Error Classes

Primary errors:

Less common errors (6)

Network errors:

Inherit from SankaError:

  • ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. See error.rawValue for the raw value and error.pretty() for a nicely formatted multi-line string.

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 { Sanka } from "sanka-sdk";

const sanka = new Sanka({
  serverURL: "https://api.sanka.com",
  bearerAuth: process.env["SANKA_BEARER_AUTH"] ?? "",
});

async function run() {
  const result = await sanka.absences.listPublicAbsencesApiV2PublicAbsencesGet(
    {},
  );

  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:

  • route requests through a proxy server using undici's ProxyAgent
  • use the "beforeRequest" hook to add a custom header and a timeout to requests
  • use the "requestError" hook to log errors
import { Sanka } from "sanka-sdk";
import { ProxyAgent } from "undici";
import { HTTPClient } from "sanka-sdk/lib/http";

const dispatcher = new ProxyAgent("http://proxy.example.com:8080");

const httpClient = new HTTPClient({
  // 'fetcher' takes a function that has the same signature as native 'fetch'.
  fetcher: (input, init) =>
    // 'dispatcher' is specific to undici and not part of the standard Fetch API.
    fetch(input, { ...init, dispatcher } as RequestInit),
});

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 Sanka({ 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 { Sanka } from "sanka-sdk";

const sdk = new Sanka({ debugLogger: console });

You can also enable a default debug logger by setting an environment variable SANKA_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.

SDK Created by Speakeasy

Developer Cloud release candidate: bounded execution, Repair, certificates and Fleet.

About

Official TypeScript library for the Sanka API

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages