Skip to the page
Docs menu

Docs Tools and reference

TypeScript SDK

Reference for the TypeScript SDK your backend uses in all three steps - installing it, the client, its resources, paging, errors, webhook verification and test mode - and the volume-rule library.

Reference for all three steps. Your backend uses it to create groups (Create), mint capture tokens for phones (Scan) and handle events and reads (Sync).

@timbereye/sdk is the server-side SDK: one method per API operation, typed from the OpenAPI document. It is Apache-2.0, version 0.2.0, built and tested (against a fake fetch, and end to end against the real server in the backend tests), and on npm. The scanner SDKs for iOS and Android are covered in Scan in your app.

Install#

Shell
npm install @timbereye/sdk

It runs on Node 18 or later, current browsers, and edge runtimes that provide fetch and Web Crypto. It ships ES module and CommonJS builds with bundled types and has no runtime dependencies.

Build it from source#

To work on the SDK itself, from a checkout of the repository:

Shell
npm install                       # once, at the repository root: the build tools
cd sdk/typescript && npm run build

Then point your project at the folder, for example with npm install /path/to/repo/sdk/typescript or npm link.

The client#

TypeScript
import Timbereye from "@timbereye/sdk" // or: const { Timbereye } = require("@timbereye/sdk")

const timbereye = new Timbereye() // reads TIMBEREYE_SECRET_KEY, and TIMBEREYE_API_URL when set

With no key argument the client reads TIMBEREYE_SECRET_KEY from the environment and throws api_key_missing when it is not set. TIMBEREYE_API_URL, when set, points it at another Timbereye API (a local one); unset, it uses https://api.timbereye.com/v1. Both are read only where the runtime has process.env; in a browser or an edge runtime without one, pass them as options. An option wins over the environment: new Timbereye("te_test_sk_…", options) or new Timbereye({ apiKey, webhookSecret, baseUrl, ...options }).

OptionDefaultMeaning
baseUrlTIMBEREYE_API_URL, else https://api.timbereye.com/v1API base URL
fetchglobal fetchYour own fetch
webhookSecretTIMBEREYE_WEBHOOK_SECRETThe secret webhooks.verify(req) uses
maxRetries2Retries after the first attempt
timeoutMs60000Timeout per attempt
modelive or test. For dashboard session tokens only
dangerouslyAllowBrowserfalseAllow a secret or restricted key in a browser. Do not

The client refuses to start with a secret or restricted key in a browser. A phone uses a publishable key or a capture token instead; see Keys.

Resources#

ResourceMethodsStep
timbereye.groupscreate, open, lookup, retrieve, update, list, delete, setWeight, volume, origin, listImagesCreate
timbereye.groups.itemsadd, remove, bulkUpdate, listRead
timbereye.itemslist, retrieve, update, remove, listMeasurements, createMeasurement, volume, listGroups, listImagesRead
timbereye.captureTokenscreateScan
timbereye.scanscreate, list, retrieve, addItems, addObservations, submit, uploadImageScan
timbereye.imagescreateUploadSession, createSession, retrieve, completeScan
timbereye.webhookEndpointscreate, list, retrieve, update, delete, test, rollSecretSync
timbereye.eventslist, retrieveSync
timbereye.webhooksverifySync
timbereye.placescreate, list, retrieve, update, validate
timbereye.specieslist, create, update
timbereye.volumeRuleslist
timbereye.usageretrieve, listRecords
timbereye.accountretrieve
timbereye.modelsretrieveDetector
timbereye.testModesimulateScan, runRefinements (test keys only)

timbereye.groups.open({ kind, externalRef, name?, defaults?, applyToExisting?, existing?, startedAt? }) continues or creates a group for a reference, and timbereye.groups.lookup({ kind, externalRef }) shows the group a reference has and the suggested choice (Create groups). With a publishable key, open, retrieve and update return a CaptureGroup (id, kind, externalRef, name, defaults, version); the method types describe the full Group.

timbereye.apiKeys (list, create, update, roll, revoke, voidRecords), timbereye.team, timbereye.auditLog and timbereye.console exist for the developer console and work only with a dashboard session; an API key is refused. With a console session, timbereye.apiKeys.create({ kind: "publishable", groupAccess, spec, allowedAppIds, limits }) creates a publishable key and timbereye.apiKeys.voidRecords(id, { createdAfter, createdBefore }) removes what it captured. The scanner calls timbereye.scans and timbereye.images for you; you rarely call them from a server. Field detail for each is in the API reference.

The routes behind them: timbereye.models.retrieveDetector({ platform }) returns log detector 1.0.0 where the environment holds it, else 503 model_unavailable. Uploads through timbereye.scans.uploadImage and timbereye.images need image storage configured for the environment, else 503 service_unavailable. Everything else is implemented.

Naming#

The REST API is snake_case; the SDK takes and returns camelCase (externalRef, originPlaceId). Only keys are converted: metadata is yours and passes through unchanged, and error param values and event type strings stay wire names.

Idempotency#

Each state-changing POST gets a generated Idempotency-Key, reused by every retry of that call. Pass your own to make a step of your workflow safe to repeat, and to set one on PATCH, PUT and DELETE:

TypeScript
const group = await timbereye.groups.create(
    { kind: "container", externalRef: "ctr_4821", name: "MSKU1234567" },
    { idempotencyKey: "ctr_4821-group" }, // a retry, even from another process, returns the same group
)

Every method takes these per-call options: idempotencyKey, timeoutMs, maxRetries, signal, and onResponse (the status and headers of each response: request id, Idempotent-Replayed, rate limit).

Paging#

A list method returns one page that is also an async iterator over every page.

TypeScript
const page = await timbereye.groups.list({ kind: "container", limit: 50 }) // page.data, page.hasMore, page.nextCursor

for await (const group of timbereye.groups.list({ kind: "container" })) {
    await db.containers.update(group.externalRef, { pieces: group.summary.items })
}

const first200 = await timbereye.groups.list().autoPagingToArray({ limit: 200 })

Errors#

Failures throw subclasses of TimbereyeError, chosen by the error type:

ClassWhen
InvalidRequestError400, 404, 409, 412, 413, 422
AuthenticationError401
PermissionError403
RateLimitError429. Carries retryAfterSeconds
ApiError5xx
ConnectionErrorNetwork failure
TimeoutErrorA timeout elapsed
AbortErrorYou aborted the call

Each API error carries code, param, requestId, status, type and docUrl. Switch on code:

TypeScript
import { InvalidRequestError } from "@timbereye/sdk"

const group = await timbereye.groups.retrieve("grp_7QxV3m")
try {
    await timbereye.groups.update(group.id, { name: "MSKU1234567" }, { ifMatch: group.version })
} catch (e) {
    if (!(e instanceof InvalidRequestError && e.code === "version_mismatch")) throw e
    // someone changed the group since you read it: read it again and retry
}

The client retries network errors, timeouts, 409 idempotency_request_in_progress, 429 and 5xx, with exponential backoff from 500 ms doubling to 8 s, with jitter, waiting for Retry-After up to 60 s. It never retries another 4xx. In an app where a person waits for the answer, set maxRetryWaitMs (for example 5_000): a limit that asks for a longer wait is then reported at once, with retryAfterSeconds, instead of being waited out. Every code is in Errors, idempotency and pagination.

Webhook verification#

TypeScript
const onEvent = timbereye.webhooks.handler(async (event) => {
    if (event.type === "group.measured") {
        const { externalRef, pieces, volume } = event.data.object
        await db.containers.update(externalRef, { pieces, volumeM3: volume?.m3 })
    }
})
app.post("/webhooks/timbereye", express.raw({ type: "application/json" }), onEvent)

In a Fetch route handler (Next.js, Hono, Workers): export const POST = timbereye.webhooks.handler(onEvent).

handler(onEvent) verifies each delivery, calls onEvent(event), and answers 200; a request Timbereye did not sign gets 400 without calling it; a setup mistake or an error from onEvent goes to next (Express) or is thrown, so the delivery is retried. To answer yourself, use verify:

TypeScript
const event = await timbereye.webhooks.verify(req) // a Fetch Request, or Express behind express.raw(...)

verify(req) takes a Fetch Request (Next.js route handlers, Hono, Workers, Deno, Bun) or a Node request that still has its raw body: in Express, put express.raw({ type: "application/json" }) on the route, before any express.json(). A body already parsed into an object is refused with raw_body_required. The secret is the webhookSecret option, else TIMBEREYE_WEBHOOK_SECRET (read when verify is called; neither set is webhook_secret_missing).

timbereye.webhooks.verify(rawBody, headers, secret) does the same from the parts. Both check the Standard Webhooks signature and timestamp (5 minutes by default; { toleranceSeconds } changes it) and return the event in camelCase, typed as a union on type. secret may be an array during a roll. A failure throws WebhookSignatureError with a code such as signature_mismatch or timestamp_out_of_tolerance; answer it with 400. verifyWebhook is also exported on its own. The full handler is in Stay in sync.

A lumber or panel bundle's group.measured has volume: null: its figures are in totals. So tally.totals?.m3 ?? tally.volume?.m3 reads the cubic metres of either product.

Testing a handler#

timbereye.webhooks.generateTestHeaders({ payload, secret?, id?, timestamp? }) returns the headers Timbereye would send with payload (the raw body as a string), signed with secret, or the client's webhook secret when you leave it out. verify and handler accept them. webhook-id is the event's id unless you pass one; timestamp is Unix seconds, now unless you pass one, so an old one tests your tolerance. generateTestWebhookHeaders is the same without a client. It only signs: never use it to accept a request.

TypeScript
import { readFileSync } from "node:fs"

const onEvent = timbereye.webhooks.handler(async (event) => {
    // your handler
})
const body = readFileSync("test/group-measured.json", "utf8") // a delivery's body, as in Stay in sync
const headers = await timbereye.webhooks.generateTestHeaders({ payload: body })
const res = await onEvent(
    new Request("http://localhost/webhooks/timbereye", { method: "POST", body, headers }),
)
// res.status is 200; signed with another secret, or with an old timestamp, it is 400

To receive real events on your machine, timbereye webhooks listen --forward-to posts them to your local route with no tunnel (CLI).

Test mode#

With a te_test_ key, timbereye.testMode stands in for the phone. A live key is refused with 403 test_mode_only.

TypeScript
await timbereye.testMode.simulateScan({ groupId: "grp_7QxV3m", logs: 35, seed: 7 })
await timbereye.testMode.runRefinements() // refined: group.measured is sent to your endpoint

simulateScan needs the group's id, and takes logs (1 to 100), species and length (default: the group's spec), seed, spread and tagPrefix. It returns the scan at estimated, and runRefinements() refines every pending log at once ({ claimed, refined, failed }), after which the group's tally settles and group.measured is sent. refine: true does the same in one call: the scan comes back refined. The numbers are synthetic and marked provenance.simulated: true. The whole loop is in the Quickstart.

Display units#

formatLength, formatDiameter, formatWeight and formatVolume show SI values in metric or imperial. They never change a request.

TypeScript
import { formatLength, formatWeight } from "@timbereye/sdk"

formatLength(11.8, "imperial") // "38.71 ft"
formatWeight(21400, "metric") // "21.4 t"

Types are generated from the OpenAPI document. The API ignores unknown fields and enum values within v1; do the same in your code.

Volume-rule library#

@timbereye/volume-rules computes one log's volume from its diameters and length under a named rule. It is TypeScript, has no runtime dependencies, needs no account, and is not on npm (build it from sdk/volume-rules).

TypeScript
import {
    volume,
    volumeImperial,
    jas,
    normalizeJasInput,
    scalingDiameterIn,
    rules,
} from "@timbereye/volume-rules"

jas({ short_diameter_cm: 26, long_diameter_cm: 28, length_m: 5.8 }) // 0.392

const clean = normalizeJasInput({ short_diameter_cm: 27.234, long_diameter_cm: 23.957, length_m: 5 })
volume("jas", clean) // 0.288

// Board-foot rules: small-end diameter inside bark and length, in inches and feet.
volumeImperial("scribner_decimal_c", { small_end_diameter_in: 12, length_ft: 16 }) // 80
volumeImperial("international_quarter", { small_end_diameter_in: 12, length_ft: 16 }) // 95
volumeImperial("doyle", { small_end_diameter_in: 12, length_ft: 16 }) // 64

// The table rules take whole inches and feet. Round a measured diameter first.
scalingDiameterIn(11.6) // 12

rules.scribner_decimal_c.status // "verified"

Every rule carries a status. Read it before you rely on a rule.

RuleUnitStatusVerified against
jasm3verifiedTimbereye's production implementation. Not the published JAS text
smalianm3verifiedHand-computed vectors. Pure geometry
huberm3verifiedHand-computed vectors. Pure geometry
newtonm3verifiedHand-computed vectors. Pure geometry
doyleboard feetverifiedTwo published Doyle tables (USDA Forest Service NA-FR-15; Purdue FNR-191)
international_quarterboard feetverifiedUSDA Forest Service FSH 2409.11 Appendix 8, 6-40 in x 4-20 ft
scribner_decimal_cboard feetverifiedUSDA Forest Service FSH 2409.11 Appendix 2, 6-40 in x 4-20 ft
scribner_formulaboard feetunverifiedAn approximation, not a table: differs from Scribner Decimal C in 558 of 595 cells
scribnerboard feetunverifiedDeprecated id for scribner_formula, kept so existing code keeps working

"Verified" for JAS means the library behaves identically to the implementation Timbereye runs, not that it conforms to the JAS notice. If you need that claim, check the class and length rules against the current JAS text.

"Verified" for a board-foot rule means the library reproduces the named table cell for cell. It is not a statement that a figure is accepted for settlement or tax anywhere: that depends on your contract and local law.

international_quarter and scribner_decimal_c return the published table value and take only whole inches (6-40) and whole feet (4-20); anything else is an error (not_normalized or out_of_range), never a guess. doyle is a formula, rounded to the nearest whole board foot with halves up. Pass { rounding: "none" } to volume or volumeImperial for the unrounded formula of doyle, international_quarter or scribner_formula. For Scribner, use scribner_decimal_c: it is the Forest Service table that western US logs trade on. The formula rule is a smooth approximation that is off by up to 70% on small logs.

The library refuses a field a rule does not use, never clamps or defaults, uses exact arithmetic and rounds once at the end. It models single logs only: no taper estimation, bark deduction, defect or grade. The server computes only jas (GET /volume_rules). The test vectors are language-neutral JSON, so a Swift or Kotlin port can run the same cases.

Open source#

The SDKs, the volume-rule library and the OpenAPI document are Apache-2.0. Detector and segmentation weights are not released. Only the hosted pipeline issues a Timbereye measurement for settlement.