@timbereye/sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,8 +1,63 @@
1
1
  # Changelog
2
2
 
3
- ## 0.1.0 (unreleased)
3
+ ## 0.2.0
4
4
 
5
- Lumber and panels (in development): `groups.createBatch`, `groups.tally.retrieve`, `groups.tally.submit`,
5
+ The first release since 0.1.0 on npm. 0.1.1 was never published, so everything under 0.1.1 below arrives with this
6
+ version too (`TIMBEREYE_API_URL`, `generateTestHeaders`, nullable lumber `volume`, photo counts on the tally).
7
+ Nothing is removed or renamed.
8
+
9
+ - **Each log's volume on the item.** `Item` gains `volume` (`ItemVolume`: `rule`, `ruleVersion`, `m3`; `null` while
10
+ the log has no measurement), the same `m3` that `items.volume(id)` returns, on `items.list`, `items.retrieve`,
11
+ `groups.items.list` and item events. Reading a group's volumes no longer costs one call per log.
12
+ - **A time window on the event feed.** `events.list({ createdAfter, createdBefore })` (ISO 8601; `createdAfter` is
13
+ inclusive), to catch up after downtime from the `createdAt` of the newest event you processed.
14
+ - **Logs and photos on the sawlog tally.** `GroupTally` (`group.measured`'s `data.object`) has `logs` (each with
15
+ `itemId`, `clientId`, `tag`, `detectionConfidence`, `photoRef`), `logsHasMore`, `photos`, `outlines`, `products`,
16
+ `children` and typed `totals`.
17
+ - **Per-log photo reference and detector confidence.** `Item` and `ScanItemStatus` gain `photoRef`
18
+ (`{ imageId, region }`), `detectionConfidence` and `outline`; `Item` gains `origin` and `measured`; measurements
19
+ gain `provenance.diameterSource`.
20
+ - **Groups.** `Group` gains `holds`, `origin` and `shipping` (`groups.create`, `update` and `open` take `shipping`
21
+ and `holds`; `open` takes the lumber fields); `summary.products`; `groups.packingList` takes `detail` and `paper`;
22
+ `groups.images.list` takes `includeChildren`.
23
+ - **New methods.** `account.updateLumber`, `account.logo.retrieve` / `.set` / `.delete`,
24
+ `team.invitations.retrieveLink`, `labelTemplates.delete`, `models.retrieveBoardEndCounter`,
25
+ `console.supportRequests.list` / `.create` (dashboard sessions); `models.retrieveDetector` takes `variant`;
26
+ `places.list` takes `owner`; `Scan` gains `measuredPlaceId` and `placeMatch`; `Error` gains `details`.
27
+ - `photos.byKind`, `totals.msf`, `layout` and `error.details` keep their keys as the API writes them.
28
+
29
+ ## 0.1.1
30
+
31
+ Not published to npm; released as part of 0.2.0.
32
+
33
+ Fixes found by building a small integration against 0.1.0. Nothing is removed or renamed, and no runtime behaviour
34
+ of 0.1.0 changes except where noted.
35
+
36
+ - **`TIMBEREYE_API_URL`.** `new Timbereye()` takes its API address from the `baseUrl` option, else from
37
+ `TIMBEREYE_API_URL` in the environment, else `https://api.timbereye.com/v1`, as the CLI already did. Where the
38
+ runtime has no `process.env` (browsers, some edge runtimes) it is not read.
39
+ - **Signing a test delivery.** `te.webhooks.generateTestHeaders({ payload, secret?, id?, timestamp? })` and the
40
+ standalone `generateTestWebhookHeaders` return the `webhook-id`, `webhook-timestamp` and `webhook-signature` headers
41
+ Timbereye would send with a body, so a test can drive `verify` or `handler` without hand-rolled HMAC code.
42
+ - **`group.measured` for lumber and panels: `volume` is `null`.** It used to carry a sawlog volume block of zeros
43
+ beside the real figures in `totals`. The type of `GroupTally.volume` (the event's `data.object`) and of
44
+ `Group.summary.volume` is now nullable, so TypeScript flags a bare `tally.volume.m3`: write `tally.volume?.m3`, or
45
+ `tally.totals?.m3 ?? tally.volume?.m3` to read both products. A sawlog tally's fields are unchanged; a handler
46
+ that reads `totals` first was already correct for every product. `GroupTally` gains typed `totals`.
47
+ - **Photo count on every `group.measured`.** A sawlog tally gains `photos` (`count`, `by_kind`, `ids`), as lumber's
48
+ had: the group's uploaded photos when the revision settled, so a handler need not list the images.
49
+ - `photos.byKind` and `totals.msf` keep their keys as the API writes them (`load_face`, `3/4 in`): they are image
50
+ kinds and thickness bases, not field names. Before, a lumber event's `byKind` keys were camelCased (`bundleEnd`).
51
+ - The package's README links to the docs on timbereye.com, and its `package.json` scripts no longer name paths
52
+ outside the package.
53
+
54
+ ## 0.1.0
55
+
56
+ Team invitations are emailed: `Invitation` gains `emailed` (true when create or resend emailed it, `null`
57
+ elsewhere), and `team.invitations.retrieveLink(invitationId)` returns a pending invitation with its current `token`
58
+ without sending anything.
59
+
60
+ Lumber and panels: `groups.createBatch`, `groups.tally.retrieve`, `groups.tally.submit`,
6
61
  `groups.tally.correct`, `groups.tally.listRevisions`, `groups.tallySheet`, `groups.packingList`, `groups.listParents`
7
62
  and `testMode.simulatePackingList`, with the `GroupTally`, `PackingList`, `LumberHtmlDocument`, `TallyLineInput` and
8
63
  related types. `groups.create` accepts `product`, `spec`, `bundle`, `rule`, `expected`, `totals` and `photos`, and
@@ -32,13 +87,13 @@ Developer console: `console.bootstrap()` and `console.updateOnboarding({ organis
32
87
  dashboard sessions only (`x-session-only`), with the `ConsoleBootstrap`, `ConsoleOnboarding` and `OnboardingUseCase`
33
88
  types. They have no CLI command.
34
89
 
35
- Mobile contract (`docs/timbereye-sync-protocol.md`): `images.createSession`, `scans.list({ clientId })` for capture
90
+ Mobile contract (the offline queue in [Working offline](https://www.timbereye.com/docs/working-offline/)): `images.createSession`, `scans.list({ clientId })` for capture
36
91
  tokens, `scans.uploadImage` with `sha256`, `width`, `height`, `location`, `region`, `sourceImageId`, `itemClientId` and
37
92
  `detections`, `scans.submit(id, { endedAt })`, `scans.addItems` entries typed `ScanItemResult` (with `created`),
38
93
  `models.retrieveDetector({ platform })`, and the new request and response fields (`appVersion`, `tagCorners`,
39
94
  `diameterLines`, `measuredRect`, `uploadSession`, `sightings`).
40
95
 
41
- First version, written against `Timbereye/OpenApi/timbereye.v1.yaml` (one method per operation) and checked end to end against
96
+ First version, written against the OpenAPI document (one method per operation) and checked end to end against
42
97
  the real server by `SdkEndToEndTest`.
43
98
 
44
99
  - `Timbereye` client with resources for groups (and group items), items, scans, images, places,
package/README.md CHANGED
@@ -4,10 +4,10 @@ TypeScript SDK for the Timbereye API: counts, measurements and tallies of forest
4
4
  versioned data, grouped the way you group wood (containers, truck loads, stacks), bound to an origin place.
5
5
  Apache-2.0.
6
6
 
7
- Status: version 0.1.0, written from the OpenAPI document (https://www.timbereye.com/docs/openapi.yaml, one method
8
- per operation) and exercised end to end against the real server. The contract may still change. Only
9
- `models.retrieveDetector` answers `501 not_implemented` in the current build, and an environment that has no
10
- image storage configured answers uploads with `503 storage_unavailable`.
7
+ Status: version 0.2.0, written from the OpenAPI document (https://www.timbereye.com/docs/openapi.yaml, one method
8
+ per operation) and exercised end to end against the real server. The contract may still change. An environment
9
+ that has no image storage configured answers uploads with `503 storage_unavailable`, and one whose storage does not
10
+ hold the on-device detector yet answers `models.retrieveDetector` with `503 model_unavailable`.
11
11
 
12
12
  ## Install
13
13
 
@@ -33,8 +33,12 @@ secret where your server reads them:
33
33
  ```bash
34
34
  export TIMBEREYE_SECRET_KEY=te_test_sk_...
35
35
  export TIMBEREYE_WEBHOOK_SECRET=whsec_... # from creating the webhook endpoint
36
+ export TIMBEREYE_API_URL=http://localhost:8080/v1 # optional: another Timbereye API; unset means the hosted one
36
37
  ```
37
38
 
39
+ `new Timbereye()` reads all three where the runtime has an environment (`process.env`); in a browser or an edge
40
+ runtime without one, pass them as options. An option you pass (`apiKey`, `webhookSecret`, `baseUrl`) wins.
41
+
38
42
  ### 1. Create
39
43
 
40
44
  When your backend creates its record for a container, it creates the Timbereye group and keeps the group's id.
@@ -76,7 +80,7 @@ const onEvent = timbereye.webhooks.handler(async (event) => {
76
80
  const tally = event.data.object
77
81
  await db.containers.update(tally.externalRef, {
78
82
  pieces: tally.pieces,
79
- volumeM3: tally.volume.m3,
83
+ volumeM3: tally.volume?.m3,
80
84
  })
81
85
  }
82
86
  })
@@ -84,6 +88,9 @@ app.post("/webhooks/timbereye", express.raw({ type: "application/json" }), onEve
84
88
  app.listen(3000)
85
89
  ```
86
90
 
91
+ For a lumber or panel bundle the same event has no sawlog `volume` (it is `null`): its figures are in `totals`, so
92
+ `tally.totals?.m3 ?? tally.volume?.m3` reads both.
93
+
87
94
  `handler` verifies the signature with `TIMBEREYE_WEBHOOK_SECRET` and answers `200`; a request Timbereye did not
88
95
  sign gets `400`. Register the endpoint once with
89
96
  `timbereye.webhookEndpoints.create({ url, enabledEvents: ["group.measured"] })`; its `secret` is returned only
@@ -255,14 +262,14 @@ creates a scan of synthetic, tagged logs and completes it, and `te.testMode.runR
255
262
  refinements now. The numbers are simulated (`provenance.simulated` is `true`), never billed, and a live key is refused
256
263
  with `403 test_mode_only`.
257
264
 
258
- ## Lumber and panels (in development)
265
+ ## Lumber and panels
259
266
 
260
- No phone app tallies lumber yet; the API and the test-mode simulator do. `te.groups.createBatch({ parent, groups })`
267
+ `te.groups.createBatch({ parent, groups })`
261
268
  creates a packing list and its bundles in one call, `te.groups.tally.submit(id, { clientId, lines })` sends a
262
269
  bundle's tally (final when submitted), `te.groups.tally.correct` and `te.groups.tally.listRevisions` correct and audit it, and
263
270
  `te.groups.packingList(id)` and `te.groups.tallySheet(id)` return the documents as JSON (or, with `format: "html"`, a
264
271
  printable page). `te.groups.listParents(id)` is where a bundle has been. `te.testMode.simulatePackingList({ scenario })`
265
- builds a whole tallied list. See `developer-docs/lumber-and-panels.md`.
272
+ builds a whole tallied list. See [Lumber and panels](https://www.timbereye.com/docs/lumber-and-panels/).
266
273
 
267
274
  ## Webhooks
268
275
 
@@ -290,6 +297,24 @@ delivery to that endpoint only and returns a `WebhookTest` reference (it is not
290
297
  `retrieveDelivery(deliveryId)` gives every attempt as sent and as received, and `resendDelivery(deliveryId)` sends one
291
298
  again now. `verifyWebhook` is also exported on its own for code that has no client.
292
299
 
300
+ **Testing your handler.** `te.webhooks.generateTestHeaders({ payload, secret?, id?, timestamp? })` (or
301
+ `generateTestWebhookHeaders` without a client) returns the headers Timbereye would send with `payload`, the raw body
302
+ string, signed with `secret` (default: the client's webhook secret). `verify` and `handler` accept them; an old
303
+ `timestamp` (Unix seconds) or another secret is refused, as a forged delivery is. `webhook-id` defaults to the
304
+ event's `id`, as in a real delivery.
305
+
306
+ ```ts
307
+ const body = JSON.stringify(sampleEvent) // the delivery's raw body
308
+ const headers = await timbereye.webhooks.generateTestHeaders({ payload: body })
309
+ const res = await onEvent(
310
+ new Request("http://localhost/webhooks/timbereye", { method: "POST", body, headers }),
311
+ )
312
+ // res.status === 200
313
+ ```
314
+
315
+ To receive real events on your machine with no tunnel, `timbereye webhooks listen --forward-to
316
+ http://localhost:3000/webhooks/timbereye --secret-env TIMBEREYE_WEBHOOK_SECRET` ([CLI](https://www.timbereye.com/docs/cli/)).
317
+
293
318
  ## Key management (dashboard sessions only)
294
319
 
295
320
  `te.apiKeys.list/create/roll/revoke` and `te.account.createTestAccount()` are for the Timbereye dashboard: they
@@ -305,26 +330,17 @@ with code `last_owner`. `invitations.create` and `resend` return the accept `tok
305
330
 
306
331
  ## Types
307
332
 
308
- Types come from the OpenAPI document with `openapi-typescript` (`npm run generate`, output committed
309
- in `src/generated/schema.ts`); a test fails if the file no longer matches the document. The public types
333
+ Types are generated from the [OpenAPI document](https://www.timbereye.com/docs/openapi.yaml) with
334
+ `openapi-typescript`, and a test fails when they no longer match it. The public types
310
335
  (`Group`, `Item`, `Scan`, `Event`, and `Schemas["..."]` for the rest) are the same types with camelCase
311
336
  keys, derived by a type-level mapping. Two lists are single pages by contract (`volumeRules.list`, `scans.addItems`); they return a `Page` with `hasMore: false`. `scans.addItems` returns one entry per input item, in input order, each with the input's `clientId` and `created`. The API ignores unknown fields and enum values in v1, so do the same.
312
337
 
313
- ## Development
314
-
315
- ```
316
- npm test # mocha, fake fetch, no network
317
- npm run typecheck
318
- npm run build
319
- npm run generate # regenerate src/generated/schema.ts
320
- ```
321
-
322
338
  Licensed under the Apache License 2.0. Using the hosted Timbereye service through this package is governed by the [Terms of Service](https://www.timbereye.com/terms); what the service collects is in the [Privacy Policy](https://www.timbereye.com/privacy).
323
339
 
324
340
  ### Syncing a capture queue
325
341
 
326
- The offline-queue protocol that the mobile SDKs follow (order of steps, idempotency keys, retries) is
327
- `docs/timbereye-sync-protocol.md`. The calls it relies on are all here: `scans.list({ clientId })` finds a scan
342
+ The mobile SDKs' offline queue ([Working offline](https://www.timbereye.com/docs/working-offline/)) uses only calls
343
+ that are here, so a capture queue of your own can follow the same order: `scans.list({ clientId })` finds a scan
328
344
  again after a lost response (a capture token may call it, within its groups), `scans.create`, `scans.addItems`
329
345
  and `scans.addObservations` are idempotent by `clientId` and tag, `images.createSession` opens a new upload
330
346
  session, `scans.uploadImage` takes `sha256`, `width`, `height`, `location`, `region`, `sourceImageId`,
@@ -15,7 +15,7 @@ export declare function toSnake<T = unknown>(value: unknown): T;
15
15
  export declare function toCamel<T = unknown>(value: unknown): T;
16
16
  /** Type-level twin of `snakeToCamel`. */
17
17
  export type CamelKey<S extends string> = S extends `${infer H}_${infer R}` ? `${H}${Capitalize<CamelKey<R>>}` : S;
18
- type OpaqueKey = "headers" | "metadata" | "rejection_gates";
18
+ type OpaqueKey = "by_kind" | "headers" | "layout" | "metadata" | "msf" | "rejection_gates";
19
19
  /** Type-level twin of `toCamel`: every object key camelCased except the contents of opaque maps. */
20
20
  export type Camel<T> = T extends readonly (infer U)[] ? Camel<U>[] : T extends object ? {
21
21
  [K in keyof T as K extends string ? CamelKey<K> : K]: K extends OpaqueKey ? T[K] : Camel<T[K]>;
package/dist/cjs/case.js CHANGED
@@ -13,7 +13,15 @@ exports.camelToSnake = camelToSnake;
13
13
  exports.toSnake = toSnake;
14
14
  exports.toCamel = toCamel;
15
15
  /** Property names (snake_case, as on the wire) whose value is a free-form map that must not be converted. */
16
- exports.OPAQUE_KEYS = ["details", "headers", "metadata", "rejection_gates"];
16
+ exports.OPAQUE_KEYS = [
17
+ "by_kind",
18
+ "details",
19
+ "headers",
20
+ "layout",
21
+ "metadata",
22
+ "msf",
23
+ "rejection_gates",
24
+ ];
17
25
  const OPAQUE_SNAKE = new Set(exports.OPAQUE_KEYS);
18
26
  const OPAQUE_CAMEL = new Set(exports.OPAQUE_KEYS.map(snakeToCamel));
19
27
  function snakeToCamel(key) {
@@ -1,6 +1,6 @@
1
1
  import { type ClientOptions } from "./http.js";
2
2
  import { createResources } from "./resources.js";
3
- import { type HeadersInput, type VerifyOptions, type WebhookRequest } from "./webhooks.js";
3
+ import { type TestWebhookParams, type HeadersInput, type VerifyOptions, type WebhookRequest } from "./webhooks.js";
4
4
  import type { WebhookEvent } from "./types.js";
5
5
  /** The client's options: the transport's, plus the webhook signing secret. */
6
6
  export interface TimbereyeOptions extends ClientOptions {
@@ -34,6 +34,14 @@ export interface WebhookHelpers {
34
34
  * Fetch (Next.js, Hono, Workers): `export const POST = te.webhooks.handler(fn)`.
35
35
  */
36
36
  handler(onEvent: (event: WebhookEvent) => unknown, options?: VerifyOptions): WebhookRouteHandler;
37
+ /**
38
+ * For tests: the headers Timbereye would send with `payload`, signed with `secret` (default: the client's
39
+ * webhook secret, else `TIMBEREYE_WEBHOOK_SECRET`). `verify` and `handler` accept them. It signs; it never
40
+ * checks a request.
41
+ */
42
+ generateTestHeaders(params: Omit<TestWebhookParams, "secret"> & {
43
+ secret?: string;
44
+ }): Promise<Record<string, string>>;
37
45
  }
38
46
  /** What `webhooks.handler` returns: a Fetch handler, or a Node/Express one. */
39
47
  export interface WebhookRouteHandler {
@@ -53,8 +61,9 @@ export interface WebhookResponse {
53
61
  * const group = await te.groups.create({ kind: "container", externalRef: "MSKU1234567" })
54
62
  * ```
55
63
  *
56
- * `new Timbereye(apiKey, options)` and `new Timbereye({ apiKey, webhookSecret, ... })` also work; an explicit
57
- * key or secret wins over the environment.
64
+ * `new Timbereye(apiKey, options)` and `new Timbereye({ apiKey, webhookSecret, baseUrl, ... })` also work; an
65
+ * explicit key, secret or `baseUrl` wins over the environment (`TIMBEREYE_SECRET_KEY`, `TIMBEREYE_WEBHOOK_SECRET`,
66
+ * `TIMBEREYE_API_URL`).
58
67
  */
59
68
  export declare class Timbereye {
60
69
  /** Test mode only: a simulated scan and refinement, so the loop can run with no device and no model. */
@@ -20,8 +20,9 @@ const FORGED_CODES = new Set([
20
20
  * const group = await te.groups.create({ kind: "container", externalRef: "MSKU1234567" })
21
21
  * ```
22
22
  *
23
- * `new Timbereye(apiKey, options)` and `new Timbereye({ apiKey, webhookSecret, ... })` also work; an explicit
24
- * key or secret wins over the environment.
23
+ * `new Timbereye(apiKey, options)` and `new Timbereye({ apiKey, webhookSecret, baseUrl, ... })` also work; an
24
+ * explicit key, secret or `baseUrl` wins over the environment (`TIMBEREYE_SECRET_KEY`, `TIMBEREYE_WEBHOOK_SECRET`,
25
+ * `TIMBEREYE_API_URL`).
25
26
  */
26
27
  class Timbereye {
27
28
  constructor(apiKeyOrOptions, options = {}) {
@@ -49,8 +50,17 @@ class Timbereye {
49
50
  return verifyRequest(first, webhookSecret, rest[0]);
50
51
  }),
51
52
  handler: (onEvent, verifyOptions) => webhookHandler(webhookSecret, onEvent, verifyOptions),
53
+ generateTestHeaders: async (params) => {
54
+ const configured = Array.isArray(webhookSecret) ? webhookSecret[0] : webhookSecret;
55
+ const secret = params.secret ?? configured ?? (0, runtime_js_1.readEnv)("TIMBEREYE_WEBHOOK_SECRET");
56
+ if (secret === undefined)
57
+ throw new errors_js_1.WebhookSignatureError("webhook_secret_missing", "No webhook secret: pass { secret }, set TIMBEREYE_WEBHOOK_SECRET, or new Timbereye({ webhookSecret }).");
58
+ return (0, webhooks_js_1.generateTestWebhookHeaders)({ ...params, secret });
59
+ },
52
60
  };
53
- const r = (0, resources_js_1.createResources)(new http_js_1.Transport(apiKey, transportOptions));
61
+ // An explicit baseUrl, else TIMBEREYE_API_URL where the runtime has an environment, else production.
62
+ const baseUrl = transportOptions.baseUrl ?? (0, runtime_js_1.readEnv)("TIMBEREYE_API_URL");
63
+ const r = (0, resources_js_1.createResources)(new http_js_1.Transport(apiKey, baseUrl === undefined ? transportOptions : { ...transportOptions, baseUrl }));
54
64
  this.testMode = r.testMode;
55
65
  this.groups = r.groups;
56
66
  this.items = r.items;