@farthershore/sdk
v0.13.0
Published
Farther Shore API client: the authenticated HTTP transport, credential sources, and typed errors shared by the CLI and agent tooling
Readme
@farthershore/sdk
The Farther Shore API client that the farthershore CLI runs on: a
namespaced, typed operation surface (fs.secretKeys.revoke(…)) over an
authenticated fetch transport with exact retry and outcome semantics,
pluggable credential sources, and typed errors.
Status:
0.13.0. Pre-1.0: minor releases may include breaking changes. Every response is typed. Responses are generated from the platform's zod schemas (through the API's OpenAPI components), so a field exists in a type exactly when the server sends it.
npm install @farthershore/sdkWorks anywhere with a standard fetch (Node 22+, browsers, workers): the
package uses Web APIs only.
Writing an agent or script against the client? See
AGENTS.mdfor the working summary: setup, metadata checks and retry rules.
Quick start
import {
createFartherShore,
createTransport,
accessTokenCredentials,
} from "@farthershore/sdk";
const fs = createFartherShore({
transport: createTransport({
baseUrl: "https://api.example.com",
credentials: accessTokenCredentials(process.env.FARTHERSHORE_TOKEN!),
surface: "my-tool",
}),
});
const businesses = await fs.businesses.list();
const revoked = await fs.secretKeys.revoke({ businessId, tokenId });The namespaced API
Every operation is a method fs.<namespace>.<method>(input, options?):
- input is one object. Path parameters are named fields
(
{ businessId, tokenId }); typed body fields sit next to them; endpoints whose body is an open record take it asbody. - options are
{ signal?, dryRun?, retry? }.signalcancels the request and any retry wait.dryRun: trueasks for a preview and is accepted only wheremethod.meta.previewis true; anywhere else the method throwsDRY_RUN_NOT_SUPPORTEDbefore sending anything.retry: "none"makes a single attempt.
On preview-capable methods, literal { dryRun: true } resolves to
DryRunPreview<W> ({ dryRun: true, wouldHave: W }), while omitted options or
{ dryRun: false } resolve to the write result. A CallOptions variable
resolves to the union, so check "dryRun" in result before using the result.
W is the preview payload, which can differ from the write result.
The namespace path comes from the operation key (secret_key.revoke →
fs.secretKeys.revoke). The namespaces:
| Namespace | Covers |
| -------------------- | --------------------------------------------------------------------------------------- |
| fs.agents | Operating agents: list, status, runs, enable, disable |
| fs.analytics | Event analytics: timeseries, latency, top, log, query |
| fs.auditLogs | Organization and business audit logs, CSV export |
| fs.auth | context.read (who am I), context.issue, listOrganizations, selectedOrganization |
| fs.automationRules | Automation rules |
| fs.backends | Backends: read, create, bind, delete |
| fs.billing | stripe (status, disconnect) and taxSettings |
| fs.bulletin | Business bulletin: list, read, ack, resolve |
| fs.businesses | Businesses, publish/status, brand, docs, previewEnv, cors, rbac, … |
| fs.changeSets | Governed ChangeSet proposals and the apply timeline |
| fs.consumers | Subscribers: read, block, remove, migrate, roles, RBAC, API keys |
| fs.environments | Preview environments: read, create, delete |
| fs.frontend | Hosted frontend: status, rollback |
| fs.knowledge | Knowledge index (guide, business) |
| fs.makerTokens | Organization access tokens |
| fs.notifications | Notification preferences |
| fs.organizations | Organizations, roles, non-owner members, invitations, overview |
| fs.personas | Test personas and local-preview sign-in |
| fs.plans | Compiled plans (read) |
| fs.platform | Denial explanations, dependents, resource counts, workflow replay/rollback previews |
| fs.portal | Subscriber plane (consumer credentials): service accounts, usage limits |
| fs.promoCodes | Promo codes |
| fs.secretKeys | Secret keys: read, mint, rotate, revoke |
| fs.usage | Usage |
| fs.variables | Write-only business variables and their asynchronous operations |
| fs.webhooks | Webhook endpoints, test/trigger, secret rotation, event types, deliveries |
Each method carries static metadata as method.meta:
fs.secretKeys.revoke.meta;
// { path: "secretKeys.revoke", op: "secret_key.revoke",
// summary, description, sideEffect: "write", destructive: true,
// oneTimeSecret: false, preview: false,
// reconcile: { op: "secret_key.read" }, pagination: null,
// maxPageSize: null, permission: "secret_key:revoke" }Portal-plane methods have no opKey; they declare the same safety and paging
flags themselves (fs.portal.serviceAccounts.rotate.meta.oneTimeSecret is
true). paginate clamps a requested limit to meta.maxPageSize, so a
server-capped page is never mistaken for the last one.
fs.call(opKey, input, options) runs an operation by its key.
A write that may have run without an answer proving it (OUTCOME_UNKNOWN)
carries the read that reconciles it: error.details.reconcile = { op }
(merged into the server's object details; a non-object details is left
as the server sent it). Run
that read before deciding whether to send the write again.
The surface never exposes the transport, the credential source, or a token.
Helpers
import {
paginate,
poll,
resolveBusiness,
resolveEnvironment,
searchDocs,
waitForFrontendBuild,
} from "@farthershore/sdk";
// Every item of a paginated method (offset or cursor, from `meta.pagination`).
for await (const env of paginate(
fs.environments.read,
{ businessId },
{
maxItems: 500,
signal,
},
)) {
console.log(env.name);
}
// Resolve references (pure lookups; no working directory or env vars).
const businessId = await resolveBusiness(fs, "acme");
const preview = await resolveEnvironment(fs, businessId, "preview");
// Search the platform docs (public: no credential, no transport).
const answer = await searchDocs({
baseUrl: "https://core.farthershore.com",
query: "add a free trial",
});
if (answer.ok) for (const hit of answer.results) console.log(hit.page);
// Wait for a condition.
const { value, timedOut } = await poll({
check: (signal) => fs.businesses.status({ businessId }, { signal }),
until: (status) => status.live,
intervalMs: 2_000,
deadlineMs: 120_000,
});
// Wait for a git-triggered frontend build to be built and served.
const build = await waitForFrontendBuild(fs, {
businessId,
ref: commitSha,
timeoutMs: 600_000,
});The wait keeps the selected build's identity fixed. FAILED, CANCELLED, and
SUPERSEDED return immediately with timedOut: false; inspect status and
error before treating the result as success. A successful build is ready only
once that exact build is active.
paginate fails with PAGINATION_NOT_ADVANCING rather than looping when a
page does not advance. A starting offset or limit may be a number or a
numeric string ("50"); anything else fails with INVALID_PAGE_PARAMETER
before a page is fetched. collect(method, input, options) gathers the items
into an array.
createTransport
import { createTransport, accessTokenCredentials } from "@farthershore/sdk";
const transport = createTransport({
baseUrl: "https://api.example.com",
credentials: accessTokenCredentials(process.env.FARTHERSHORE_TOKEN!),
surface: "my-tool",
clientInfo: "my-tool/1.0.0",
});
const businesses = await transport.request("GET", "/businesses");Options: baseUrl, credentials, surface (sent as x-fs-surface), and
optionally fetch (defaults to globalThis.fetch), organizationId (id or
slug), requiredOrganizationId (refuses a credential acting in any other
organization), clientInfo (appended to the x-fs-client
header after @farthershore/sdk/<version>), and retry
({ attempts, sleep }; attempts must be a whole number).
| Method | What it does |
| -------------------------------------------------------- | ------------------------------------------------------------- |
| request(method, path, body?, options?) | JSON request; resolves the parsed body (undefined for 204). |
| requestRaw(method, path, bytes, contentType, options?) | Binary body, JSON answer. |
| requestText(method, path, options?) | Text answer (CSV exports). |
| raw(method, path, { query, body, headers, ... }) | Any path; resolves { status, headers, data }. |
| selectedOrganizationId() | The organization the credential acts in. |
| listOrganizations() | Organizations a sign-in can act in. |
raw never follows a redirect, so caller headers never reach another
location: a 3xx answer fails with REDIRECT_NOT_FOLLOWED (the 3xx status,
details.location; outcomeUnknown: true for a write, which may have run).
Per-request options: signal (an AbortSignal), headers, dryRun
(appends dry_run=true), and retry:
- omitted:
GET/HEADare reads, everything else is a write; "read": a read-onlyPOST(queries, previews);"write": force write handling;"none": one attempt, same classification.
One exception applies to every mode: a refreshable credential
(signInCredentials given a token provider) that the server rejects with 401 is
renewed and the request is resent once, even with "none" or attempts: 1. A 401 means the
request did not run, so that resend cannot apply a write twice.
Reads are retried on network errors, timeouts, 429 and 5xx. Writes are retried
only when the server proves nothing ran (429, or an error marked retryable
with retryDisposition: "safe_to_repeat"). A write that may have run fails with
outcomeUnknown: true: read current state before sending it again. Key on
outcomeUnknown, not on code: when the server answered with an error
envelope the error keeps the server's own code (a 5xx write can be
TEARDOWN_FAILED with outcomeUnknown: true); code: "OUTCOME_UNKNOWN" is
used only when no server code arrived. Each attempt has a 30-second deadline that also covers
reading the response body.
Credential sources
| Source | Use |
| --------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| accessTokenCredentials(token) | An access token (mk_…), sent as is. It acts only in its own organization. |
| signInCredentials(token, { organizationId? }) | A sign-in token, sent as is with the one organization the source acts in. |
| bearerCredentials(token) | A static bearer token, sent as is. |
| consumerCredentials({ token, environmentId, organizationId }) | A subscriber session acting in one environment and subscribing organization. |
signInCredentials takes the token itself, or a function asked for the current
token before every request (and once more, with rejected, when the server
refuses one). The organization is decided once per source and never changes
afterwards: options.organizationId if given, else the transport's
organizationId (an id or a slug, looked up once), else the person's default
organization (read once). Every request carries that organization id. Using
one source with a different selection fails with
CREDENTIAL_SOURCE_ORGANIZATION_CONFLICT: create a source per organization.
A CredentialSource is { kind, getAccessToken({ signal, forceRefresh, rejectedToken, context }) }.
The transport keeps the source private: no transport method returns a token.
Give each transport its own source.
Errors
Request failures are FartherShoreErrors with status (0 when no HTTP answer
arrived), code, message, details, param, retryable,
retryDisposition, outcomeUnknown and cause; an error from an HTTP answer
also carries that answer's headers (Retry-After, request ids). toJSON()
returns the plain data, without headers. Requests that got no answer throw FartherShoreTransportError
(NETWORK_ERROR, TIMEOUT, REQUEST_ABORTED or OUTCOME_UNKNOWN). A
custom fetch that resolves to something other than a response fails with
INVALID_RESPONSE (status 0; counted against the attempt limit for a read,
outcomeUnknown: true for a write). No outcome retries past retry.attempts.
Two deterministic failures stay native, because repeating them cannot help:
a successful read whose JSON body is malformed rejects with the parser's
SyntaxError (it is not retried), and a request body that JSON.stringify
cannot serialize (a BigInt, a cycle) throws its TypeError before anything
is sent.
Human-only actions have no client methods: business or organization deletion, ownership transfer, and Stripe disconnection. The API also refuses delegated credentials for owner removal or demotion. Use the dashboard after fresh sign-in and typed-name confirmation.
