# JavaScript and TypeScript

Documentation version: 0.3.1.

> [!NOTE]
> SDKs are read-only. The CLI creates vaults and sets secret values;
> applications do not need a CLI process running alongside them.

## Project setup options

1. **Option 1: Set up with the CLI.** Follow the [CLI installation guide](https://sourceorrery.ai/getting-started/#install),
   then create the vault and set its secret values in your own terminal.
2. **Option 2: Set up with an AI coding agent.** Run
   `sourceorrery init --integration all`, then ask your agent to set up
   SourceOrrery for the project without showing values. You keep vault
   keys and new values private. [The agent setup guide](https://sourceorrery.ai/guides/ai-agents/)
   works with an existing CLI installation.

## Install




### From npm

```bash
npm install @sourceorreryai/sdk@0.3.1
```

[`@sourceorreryai/sdk` on npm](https://www.npmjs.com/package/@sourceorreryai/sdk)
is a napi-rs native addon for Node.js 20+ with TypeScript types included.
The main package pulls in the matching one of six platform packages
(`@sourceorreryai/sdk-<platform>` for Windows x64 and arm64, macOS x64 and
arm64, Linux glibc x64 and arm64) as an optional dependency, so nothing is
compiled on install. The addon is loaded only from this install: the
platform package beside `@sourceorreryai/sdk` (or inside it), never a
module of that name found in a parent directory's `node_modules`, so an
install without it (`--omit=optional`, 32-bit Node) fails with an error
naming the package rather than loading what another account put there.
Every package is published by trusted publishing with provenance, which
`npm audit signatures` checks ([Supply chain](https://sourceorrery.ai/security/supply-chain/#npm)).

### From the GitHub release

The [v0.3.1 release](https://github.com/Netizine/sourceorrery/releases/tag/v0.3.1)
carries the same packages as tarballs: `sourceorreryai-sdk-0.3.1.tgz` is
the main package, and `sourceorreryai-sdk-<platform>-0.3.1.tgz` (one each
for `win32-x64-msvc`, `win32-arm64-msvc`, `darwin-x64`, `darwin-arm64`,
`linux-x64-gnu` and `linux-arm64-gnu`) carries the native addon for that
platform. Install the main tarball and your platform's together:



#### Windows

```powershell
npm install https://github.com/Netizine/sourceorrery/releases/download/v0.3.1/sourceorreryai-sdk-0.3.1.tgz https://github.com/Netizine/sourceorrery/releases/download/v0.3.1/sourceorreryai-sdk-win32-x64-msvc-0.3.1.tgz   # win32-arm64-msvc on Arm
```

#### macOS

```bash
npm install https://github.com/Netizine/sourceorrery/releases/download/v0.3.1/sourceorreryai-sdk-0.3.1.tgz https://github.com/Netizine/sourceorrery/releases/download/v0.3.1/sourceorreryai-sdk-darwin-arm64-0.3.1.tgz   # darwin-x64 on Intel
```

#### Linux

```bash
npm install https://github.com/Netizine/sourceorrery/releases/download/v0.3.1/sourceorreryai-sdk-0.3.1.tgz https://github.com/Netizine/sourceorrery/releases/download/v0.3.1/sourceorreryai-sdk-linux-x64-gnu-0.3.1.tgz   # linux-arm64-gnu on arm64
```



### From source

See [Building from source](https://sourceorrery.ai/sdks/javascript/#building-from-source) below.

## Get a secret

```ts
import { SecretReader } from '@sourceorreryai/sdk';

using reader = new SecretReader('development');
using secret = reader.get('database-password');
connect({ password: secret.value.exposeText() });
// `using` closes the reader and zeroises the value at the end of the block
```

`using` needs Node 24+ or TypeScript 5.2+ with a target that supports
explicit resource management; otherwise call `close()` in a `finally`:

```js
const { SecretReader } = require('@sourceorreryai/sdk');

const reader = new SecretReader('development');
try {
  const secret = reader.get('database-password');
  try {
    connect({ password: secret.value.exposeText() });
  } finally {
    secret.close();
  }
} finally {
  reader.close();
}
```

`new SecretReader(vault, { home, recoveryKey, recoveryKeyFile, environment })`
opens the vault. With the default options, `SOURCEORRERY_HOME` locates the
vault; this machine's key in the OS credential store opens it, else the
recovery key: `recoveryKey`, `SOURCEORRERY_RECOVERY_KEY`, then
`recoveryKeyFile` or `SOURCEORRERY_RECOVERY_KEY_FILE`. `environment: false`
ignores the two variables. The SDK never prompts and never asks the
vault's view check.

A secret the vault keeps at a provider
([HashiCorp Vault](https://sourceorrery.ai/providers/hashicorp-vault/),
[AWS Secrets Manager](https://sourceorrery.ai/providers/aws-secrets-manager/),
[Azure Key Vault](https://sourceorrery.ai/providers/azure-key-vault/)) is read there through
the vault's connection, with the same calls: the connection signs in with
the credentials it stores, or with the provider's own sign-in on the
machine. No provider is contacted until a secret it keeps is read.

| Call | Returns |
|------|---------|
| `reader.get(name)` | `Secret` for the newest accessible version |
| `reader.get(name, version)` | `Secret` for exactly that version |
| `reader.properties(name, version?)` | `SecretProperties` (policy not applied) |
| `reader.resolve('sourceorrery://development/database-password')` | `Secret` |
| `reader.descriptor()` | the vault descriptor (no values) |
| `reader.close()` | releases the vault; also `Symbol.dispose` |

`secret.properties` is a frozen object (`vault`, `name`, `version`,
`enabled`, `contentType`, `tags`, `notBefore`, `expiresOn`, `createdOn`,
`updatedOn` as `Date`, `recoveryLevel`, `reference`). `secret.value` is a
`SecretValue`:

```js
value.expose();       // Buffer (a copy)
value.exposeText();   // string
value.length;
value.close();        // zeroise; expose() throws afterwards
String(value);        // '[REDACTED]'
JSON.stringify({ value });   // '{"value":"[REDACTED]"}'
util.inspect(value);  // 'SecretValue([REDACTED])'
```

## Errors

Every failure is a `SourceOrreryError` subclass with `code`, `detail`,
`hint` and `message` (`detail` plus `hint`):

```ts
import { SecretReader, SecretNotFoundError, VaultLockedError, SourceOrreryError } from '@sourceorreryai/sdk';

try {
  using reader = new SecretReader('development');
  using secret = reader.get('database-password');
} catch (err) {
  if (err instanceof VaultLockedError) console.error(err.hint);
  else if (err instanceof SecretNotFoundError) console.error(err.hint);
  else if (err instanceof SourceOrreryError) console.error(err.code, err.message);
  else throw err;
}
```

Classes: `VaultNotFoundError`, `VaultLockedError`,
`MigrationRequiredError`, `VaultMismatchError`, `SecretNotFoundError`,
`VersionNotFoundError`, `SecretDeletedError`, `PolicyError` with
`SecretDisabledError`, `SecretNotYetValidError` (`transient` is true),
`SecretExpiredError`, `IntegrityError`, `UnsupportedError`,
`InvalidArgumentError`, `InvalidNameError`, `ManifestError`,
`PermissionDeniedError`, `StorageError`, and for secrets kept at a provider
`UnauthenticatedError` (the provider has no credentials for this process)
and `ProviderUnavailableError` (it could not be reached; `transient` is
true). See [the SDK overview](https://sourceorrery.ai/sdks/#errors).

## Load a project

```ts
import { Project } from '@sourceorreryai/sdk';

using project = Project.load('sourceorrery.toml');   // or Project.load() to discover it
for (const secret of project) process.env[secret.env] = secret.value.exposeText();
```

`Project.load` resolves every `[secrets.*]` entry the way `sourceorrery run`
does and throws the first required secret's error if one cannot be read.

## Building from source

You need Git, Rust 1.91.1 or newer installed with rustup, and a C compiler
(on Linux also `pkg-config` and `libdbus-1-dev`);
[Building from source](https://sourceorrery.ai/guides/building-from-source/#what-you-need) has the commands for
each platform. For this SDK, also Node.js 20 or newer with npm.

Get the code and build the addon for this machine:

```bash
git clone https://github.com/Netizine/sourceorrery
cd sourceorrery
git checkout v0.3.1              # or stay on main for the newest changes
cd bindings/node
npm ci                           # the napi-rs CLI and TypeScript
npm run build                    # napi build --platform --release
```

`npm run build` compiles the addon as `sourceorrery.<platform>.node` (for
example `sourceorrery.linux-x64-gnu.node`) and generates the loader
`index.js` and the types `index.d.ts` next to it; the first build takes a
few minutes. To use it from your own project on the same machine, install
the directory:

```bash
cd /path/to/your-project
npm install /path/to/sourceorrery/bindings/node
```

npm links the directory rather than copying it, so a rebuild is picked up
without installing again. The version is the one committed in the
repository, not the release's.

To run the tests, the example and the conformance harness, build the CLI,
which creates the test vault, and run the rest in Bash (Git Bash on
Windows) from the repository root:

```bash
cargo build --release -p sourceorrery-cli
eval "$(bash scripts/ci/fixture-vault.sh)"       # a throwaway vault and the variables the tests read
cd bindings/node
npm test
npm run typecheck
node examples/get-secret.mjs "$SOURCEORRERY_TEST_VAULT" database-password
cd ../..
python tests/conformance/sdk/harness.py --runner node
```

What the fixture script creates: [The SDK test vault](https://sourceorrery.ai/guides/building-from-source/#the-sdk-test-vault).
Source: [`bindings/node`](https://github.com/Netizine/sourceorrery/blob/main/bindings/node/README.md).
