@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.
@@ -1,7 +1,7 @@
1
1
  import { makeList } from "./pagination.js";
2
2
  import { toSnake } from "./case.js";
3
3
  const id = (v) => encodeURIComponent(v);
4
- /** Builds the resource tree. One method per operation in `Timbereye/OpenApi/timbereye.v1.yaml`. */
4
+ /** Builds the resource tree. One method per operation in the OpenAPI document (https://www.timbereye.com/docs/openapi.yaml). */
5
5
  export function createResources(t) {
6
6
  const get = (path, query, o) => t.request({ method: "GET", path, query: query }, o);
7
7
  const post = (path, body, o, extra) => t.request({ method: "POST", path, body, ...extra }, o);
@@ -40,20 +40,32 @@ export function createResources(t) {
40
40
  /** The group's photos, oldest first, with kind, caption, who took them and a 15-minute `downloadUrl`. */
41
41
  listImages: (groupId, params, o) => list(`/groups/${id(groupId)}/images`, params, o),
42
42
  /**
43
- * Lumber and panels (in development): up to 500 groups in one call and one transaction, optionally under a
44
- * parent created in the same call (a packing list and its bundles) or an existing `parentId`.
43
+ * Lumber and panels: up to 500 groups in one call and one transaction, optionally under a
44
+ * parent created in the same call (a container and its bundles) or an existing `parentId`.
45
45
  */
46
46
  createBatch: (params, o) => post("/groups/batch", params, o),
47
47
  /** A bundle's tally sheet: the tally with its lines and a `document` block, or with `format: "html"` a printable page. */
48
48
  tallySheet: (groupId, params, o) => get(`/groups/${id(groupId)}/tally_sheet`, params, o),
49
49
  /**
50
- * The packing list of a group whose children are bundles or units: one row per bundle, width classes, the
51
- * thickness × length pivot, `totals` under the list's convention and `totalsAlternative` under the other.
50
+ * The packing list of any group that holds bundles or units (a container, truck load, stack): one row per
51
+ * bundle or unit, width classes, the thickness × length pivot, `totals` under the list's convention and
52
+ * `totalsAlternative` under the other. A shipment whose containers sit inside it reads as one list: each
53
+ * row's `inGroup` names its container and `groups` gives each container's totals; `logs` lists its logs.
54
+ *
55
+ * With `format: "pdf"` it resolves to the document itself (`{ data, contentType, fileName }`), made from the
56
+ * group's data on every call: `paper` is `"a4"` or `"letter"`, `detail: "tally"` adds each bundle's tally lines.
52
57
  */
53
- packingList: (groupId, params, o) => get(`/groups/${id(groupId)}/packing_list`, params, o),
58
+ packingList: (groupId, params, o) => (params?.format === "pdf"
59
+ ? t.request({
60
+ method: "GET",
61
+ path: `/groups/${id(groupId)}/packing_list`,
62
+ query: params,
63
+ binary: true,
64
+ }, o)
65
+ : get(`/groups/${id(groupId)}/packing_list`, params, o)),
54
66
  /** Where a group has been: its parents over time, oldest first, the current one last. */
55
67
  listParents: (groupId, o) => list(`/groups/${id(groupId)}/parents`, undefined, o),
56
- /** A lumber bundle's or panel unit's tally (in development). */
68
+ /** A lumber bundle's or panel unit's tally. */
57
69
  tally: {
58
70
  /** The tally: lines, what the rule tallied, totals by length and width, the label beside the count. */
59
71
  retrieve: (groupId, params, o) => get(`/groups/${id(groupId)}/tally`, params, o),
@@ -178,6 +190,8 @@ export function createResources(t) {
178
190
  list: (params, o) => list("/label_templates", params, o),
179
191
  retrieve: (templateId, o) => get(`/label_templates/${id(templateId)}`, undefined, o),
180
192
  update: (templateId, params, o) => send("PATCH", `/label_templates/${id(templateId)}`, params, o),
193
+ /** Deletes a template; one a batch was made with is kept (409 `label_template_in_use`). */
194
+ delete: (templateId, o) => send("DELETE", `/label_templates/${id(templateId)}`, undefined, o),
181
195
  /** One test label (short id TEST0) after a 62 mm ruler label: print it and measure with a ruler. */
182
196
  testLabel: (templateId, params, o) => get(`/label_templates/${id(templateId)}/test_label`, params, o),
183
197
  };
@@ -264,6 +278,23 @@ export function createResources(t) {
264
278
  * live mode, because test-mode requests need the test account to exist already.
265
279
  */
266
280
  createTestAccount: (o) => post("/account/test_mode", undefined, o),
281
+ /**
282
+ * Changes the organisation's lumber settings in this mode (`account.lumber`): whether phones may open lumber
283
+ * groups, the default board-foot method (`perBoard` or `bundleTotal`), whether new bundles need photos.
284
+ */
285
+ updateLumber: (params, o) => send("PATCH", "/account/lumber", params, o),
286
+ /**
287
+ * The organisation's logo, printed top left on its documents (the packing list PDF), in both modes. Without
288
+ * one, documents set the organisation's name. PNG or JPEG, at most 256 KB, each side 16 to 4,000 pixels.
289
+ */
290
+ logo: {
291
+ /** The logo and its image (`data`, base64). 404 when there is none. */
292
+ retrieve: (o) => get("/account/logo", undefined, o),
293
+ /** Sets the logo, replacing any. `data` is the PNG or JPEG image, base64-encoded. */
294
+ set: (params, o) => send("PUT", "/account/logo", params, o),
295
+ /** Removes the logo; documents set the organisation's name again. */
296
+ delete: (o) => send("DELETE", "/account/logo", undefined, o),
297
+ },
267
298
  };
268
299
  /**
269
300
  * The organisation's members, roles and invitations. **Dashboard sessions only** (403 `session_required`
@@ -284,11 +315,13 @@ export function createResources(t) {
284
315
  invitations: {
285
316
  /** Open invitations, newest first; `includeClosed` adds accepted, revoked and expired ones. */
286
317
  list: (params, o) => list("/team/invitations", params, o),
287
- /** `token` in the result is shown once; build the accept link from it. */
318
+ /** Emails the invitation; `emailed` says whether it went out, and `token` (once) builds the link to copy. */
288
319
  create: (params, o) => post("/team/invitations", params, o),
289
320
  revoke: (invitationId, o) => send("DELETE", `/team/invitations/${id(invitationId)}`, undefined, o),
290
- /** Issues a new `token` (shown once) and restarts the 7 days; the old link stops working. */
321
+ /** Emails a new link and restarts the 7 days; the old link stops working. `token` is in the result once. */
291
322
  resend: (invitationId, o) => post(`/team/invitations/${id(invitationId)}/resend`, undefined, o),
323
+ /** A pending invitation with its current `token`, to send the link yourself. Nothing is emailed. */
324
+ retrieveLink: (invitationId, o) => get(`/team/invitations/${id(invitationId)}/link`, undefined, o),
292
325
  /** Accepts as the signed-in user, whose verified email must be the invited address. Single-use. */
293
326
  accept: (params, o) => post("/invitations/accept", params, o, { noIdempotency: true }),
294
327
  },
@@ -365,6 +398,15 @@ export function createResources(t) {
365
398
  list: (o) => get("/console/data_requests", undefined, o),
366
399
  create: (params, o) => post("/console/data_requests", params, o),
367
400
  },
401
+ /**
402
+ * The console's Contact us form: a message to Timbereye support with the context the console attaches (the
403
+ * page, the session's failed request ids and codes, the browser). Every member may, viewers included; support
404
+ * replies by email. Limited per organisation (429). `list` is the signed-in person's own requests.
405
+ */
406
+ supportRequests: {
407
+ list: (o) => get("/console/support_requests", undefined, o),
408
+ create: (params, o) => post("/console/support_requests", params, o),
409
+ },
368
410
  /**
369
411
  * Records, once, the Terms of Service and Privacy Policy versions in force when this person first opens the console
370
412
  * after signing up. Nothing is recorded for a person created before `termsEffective`.
@@ -409,8 +451,16 @@ export function createResources(t) {
409
451
  },
410
452
  };
411
453
  const models = {
412
- /** The detector for a platform: `download_url` serves a Core ML ZIP for `ios` and a `.tflite` for `android`. */
454
+ /**
455
+ * The detector for a platform: `download_url` serves a Core ML ZIP for `ios` and a `.tflite` for `android`.
456
+ * `variant: "640"` asks for the smaller fallback. 503 `model_unavailable`: this environment has no model file yet.
457
+ */
413
458
  retrieveDetector: (params, o) => get("/models/detector", params, o),
459
+ /**
460
+ * The lumber board-end counter (a preview) for a platform: the detector's fields plus the counting recipe
461
+ * (`tiling`, `count`). `variant: "s"` asks for the smaller model. 503 `model_unavailable`: none in this environment.
462
+ */
463
+ retrieveBoardEndCounter: (params, o) => get("/models/board-end-counter", params, o),
414
464
  };
415
465
  /**
416
466
  * Test mode only (a `te_test_` key; a live key is refused with 403 `test_mode_only`). Exercises the whole loop
@@ -6,8 +6,9 @@ export type Schemas = {
6
6
  [K in keyof S]: Camel<S[K]>;
7
7
  };
8
8
  /**
9
- * A group. Lumber and panel groups (in development) also carry `spec`, `bundle`, `rule`, `expected`,
10
- * `totalsConvention`, `photos` and `images`, and `summary.pieces` and `summary.tally`.
9
+ * A group. Lumber and panel groups also carry `spec`, `bundle`, `rule`, `expected`,
10
+ * `totalsConvention`, `photos` and `images`, and `summary.pieces` and `summary.tally`. Every group's
11
+ * `summary.products` says what it holds, product by product (a group may hold logs, bundles and units).
11
12
  */
12
13
  export type Group = Omit<Schemas["Group"], "spec" | "bundle" | "rule" | "expected" | "summary" | "parent"> & {
13
14
  summary: Omit<Schemas["Group"]["summary"], "tally"> & {
@@ -33,6 +34,8 @@ export type Place = Schemas["Place"];
33
34
  export type PlaceValidation = Schemas["PlaceValidation"];
34
35
  export type Species = Schemas["Species"];
35
36
  export type Volume = Schemas["Volume"];
37
+ /** One log's volume on an item (`item.volume`): rule, ruleVersion and m3, null while unmeasured. */
38
+ export type ItemVolume = Schemas["ItemVolume"];
36
39
  export type VolumeRule = Schemas["VolumeRule"];
37
40
  export type Origin = Schemas["Origin"];
38
41
  export type Event = Schemas["Event"];
@@ -41,10 +44,11 @@ export type WebhookEndpoint = Schemas["WebhookEndpoint"];
41
44
  export type WebhookEndpointDeleted = Schemas["WebhookEndpointDeleted"];
42
45
  export type GroupDeleted = Schemas["GroupDeleted"];
43
46
  export type PlaceDeleted = Schemas["PlaceDeleted"];
47
+ export type LabelTemplateDeleted = Schemas["LabelTemplateDeleted"];
44
48
  export type CaptureToken = Schemas["CaptureToken"];
45
49
  export type ApiKey = Schemas["ApiKey"];
46
50
  /**
47
- * Metered usage. Lumber and panels (in development): `lumber` and `panels` hold the period's figures; only `m3` is
51
+ * Metered usage. Lumber and panels: `lumber` and `panels` hold the period's figures; only `m3` is
48
52
  * billed (at the one price per m³), the rest are counts for display.
49
53
  */
50
54
  export type Usage = Omit<Schemas["Usage"], "lumber" | "panels"> & {
@@ -63,6 +67,7 @@ export type Usage = Omit<Schemas["Usage"], "lumber" | "panels"> & {
63
67
  };
64
68
  export type UsageRecord = Schemas["UsageRecord"];
65
69
  export type DetectorModel = Schemas["DetectorModel"];
70
+ export type BoardEndCounterModel = Schemas["BoardEndCounterModel"];
66
71
  export type BulkUpdateResult = Schemas["BulkUpdateResult"];
67
72
  export type GroupMembership = Schemas["GroupMembership"];
68
73
  export type TeamMember = Schemas["TeamMember"];
@@ -81,6 +86,14 @@ export type WebhookEvent = Event;
81
86
  export type ItemLengthInput = Schemas["ItemLengthInput"];
82
87
  export type LengthInput = Schemas["LengthInput"];
83
88
  export type GroupWeightInput = Schemas["GroupWeightInput"];
89
+ /**
90
+ * A group's shipping details, as stored (`group.shipping`): the parties, references, voyage, ports and seal the packing
91
+ * list PDF prints. Display only: Timbereye prints them as given and does not issue, validate or file shipping documents.
92
+ */
93
+ export type GroupShipping = Schemas["GroupShipping"];
94
+ /** `shipping` on create, open and update: each field optional; on update a field you send replaces it, null removes it. */
95
+ export type GroupShippingInput = Schemas["GroupShippingInput"];
96
+ export type ShippingParty = Schemas["ShippingParty"];
84
97
  export type ItemRefSelector = Schemas["ItemRefSelector"];
85
98
  export type ItemPatch = Schemas["ItemPatch"];
86
99
  export type ScanItemInput = Schemas["ScanItemInput"];
@@ -103,12 +116,22 @@ export type OnboardingOrganisation = Schemas["OnboardingOrganisation"];
103
116
  export type OnboardingMeasures = Schemas["OnboardingMeasures"];
104
117
  export type ConsoleOrganisation = Schemas["ConsoleOrganisation"];
105
118
  export type AccountDataUse = Schemas["AccountDataUse"];
119
+ export type AccountLumberSettings = Schemas["AccountLumberSettings"];
120
+ export type AccountLumberSettingsObject = Schemas["AccountLumberSettingsObject"];
121
+ export type AccountLogo = Camel<Schemas["AccountLogo"]>;
122
+ export type AccountLogoSetParams = Schemas["AccountLogoSet"];
123
+ export type AccountLogoDeleted = Schemas["AccountLogoDeleted"];
124
+ export type AccountLumberSettingsUpdateParams = Schemas["AccountLumberSettingsUpdate"];
106
125
  export type AccountDataRequest = Schemas["AccountDataRequest"];
107
126
  export type AccountDataRequestList = Schemas["AccountDataRequestList"];
127
+ export type SupportRequest = Schemas["SupportRequest"];
128
+ export type SupportRequestList = Schemas["SupportRequestList"];
129
+ export type SupportRequestCategory = Schemas["SupportRequestCategory"];
130
+ export type SupportRequestContext = Schemas["SupportRequestContext"];
108
131
  export type LegalAgreement = Schemas["LegalAgreement"];
109
132
  export type ConsoleAgreement = Schemas["ConsoleAgreement"];
110
133
  export type LiveAccess = Schemas["LiveAccess"];
111
- /** Billing. `currentPeriod` gains `lumberM3` and `panelM3` (in development) where the server reports them. */
134
+ /** Billing. `currentPeriod` gains `lumberM3` and `panelM3` where the server reports them. */
112
135
  export type Billing = Omit<Schemas["Billing"], "currentPeriod"> & {
113
136
  currentPeriod: Schemas["Billing"]["currentPeriod"] & {
114
137
  lumberM3?: number;
@@ -165,6 +188,7 @@ export type ConsoleOnboardingUpdateParams = Schemas["ConsoleOnboardingUpdate"];
165
188
  export type ConsoleOrganisationCreateParams = Schemas["ConsoleOrganisationCreate"];
166
189
  export type ConsoleDataUseUpdateParams = Schemas["ConsoleDataUseUpdate"];
167
190
  export type AccountDataRequestCreateParams = Schemas["AccountDataRequestCreate"];
191
+ export type SupportRequestCreateParams = Schemas["SupportRequestCreate"];
168
192
  export type ConsoleAgreementCreateParams = Schemas["ConsoleAgreementCreate"];
169
193
  export type LiveAccessUpdateParams = Schemas["LiveAccessUpdate"];
170
194
  export type BillingUpdateParams = Schemas["BillingUpdate"];
@@ -228,7 +252,7 @@ export type LumberGroupFields = {
228
252
  /** One group of a batch: the fields of `groups.create`, including the lumber and panel fields. */
229
253
  export type LumberGroupCreateParams = Omit<Schemas["LumberGroupCreate"], keyof LumberGroupFields> & LumberGroupFields;
230
254
  export type GroupBatchCreateParams = {
231
- /** A parent created in the same call (a packing list). */
255
+ /** A parent created in the same call (a container, truck load or stack). */
232
256
  parent?: LumberGroupCreateParams;
233
257
  /** Or an existing parent. */
234
258
  parentId?: string;
@@ -274,6 +298,21 @@ export type GroupTallySubmitParams = {
274
298
  lines: TallyLineInput[];
275
299
  /** The submission this one replaces; 409 `tally_replaced` when it is not the current one. */
276
300
  replaces?: string;
301
+ /**
302
+ * The bundle's revision the sender last saw (0: no final tally yet); any other current revision is 409
303
+ * `tally_replaced`, so a re-tally never silently replaces a correction made meanwhile.
304
+ */
305
+ replacesRevision?: number;
306
+ /** Pieces counted on a photo or read off the label, beside the tally's pieces. */
307
+ visionCount?: {
308
+ countedPieces: number;
309
+ imageId?: string;
310
+ regions?: unknown[];
311
+ model?: string;
312
+ confirmed?: boolean;
313
+ /** Who counted: a counting `model`, the operator tapping board ends (`operator_taps`), or the label (`operator_label`). */
314
+ method?: "model" | "operator_taps" | "operator_label";
315
+ };
277
316
  /** Photos of the bundle already uploaded with `images.createUploadSession` (subject group). */
278
317
  imageIds?: string[];
279
318
  device?: Record<string, unknown>;
@@ -308,8 +347,14 @@ export type TallySheetParams = {
308
347
  export type PackingListParams = {
309
348
  totals?: "exact" | "reported";
310
349
  include?: "tally_sheets";
311
- format?: "json" | "html";
312
- };
350
+ /** `pdf`: the document itself (a `BinaryResponse`). */
351
+ format?: "json" | "html" | "pdf";
352
+ /** With `format: "pdf"`: by default Letter for lumber in inches and feet, else A4. */
353
+ paper?: "a4" | "letter";
354
+ /** With `format: "pdf"`: `tally` adds each bundle's tally lines. */
355
+ detail?: "tally";
356
+ };
357
+ export type { BinaryResponse } from "./http.js";
313
358
  export type TallyRevisionListParams = {
314
359
  itemId?: string;
315
360
  limit?: number;
@@ -335,6 +380,7 @@ export type PhotosStatus = {
335
380
  noPhoto: boolean;
336
381
  missing: string[];
337
382
  count: number;
383
+ /** The count per image kind, keyed by the kind as the API writes it (`bundle_end`), not camelCased. */
338
384
  byKind: Record<string, number>;
339
385
  ids: string[];
340
386
  };
@@ -373,6 +419,8 @@ export type GroupTally = Omit<Schemas["LumberGroupTally"], "totals" | "lines"> &
373
419
  revision: number;
374
420
  /** Pieces counted on a photo (a vision count sent with the tally), beside the tally's `pieces`. */
375
421
  countedPieces: number | null;
422
+ /** Who counted (`visionCount.method`), or null when nothing was counted. */
423
+ countMethod: "model" | "operator_taps" | "operator_label" | null;
376
424
  countMatches: boolean | null;
377
425
  countDifference: number | null;
378
426
  rule: TallyRuleApplied | null;
@@ -410,6 +458,7 @@ export type GroupTally = Omit<Schemas["LumberGroupTally"], "totals" | "lines"> &
410
458
  regions: unknown[] | null;
411
459
  model: string | null;
412
460
  confirmed: boolean;
461
+ method?: "model" | "operator_taps" | "operator_label";
413
462
  } | null;
414
463
  pieces: number;
415
464
  createdAt: string;
@@ -424,6 +473,9 @@ export type GroupTally = Omit<Schemas["LumberGroupTally"], "totals" | "lines"> &
424
473
  /** One row of a packing list: a bundle with its pieces, figures and (for width-class tallies) its histogram. */
425
474
  export type PackingListRow = {
426
475
  groupId: string;
476
+ /** A group may hold bundles and units together: `lumber` or `panel`. */
477
+ product: LumberProduct;
478
+ kind: string | null;
427
479
  externalRef: string | null;
428
480
  number: string | null;
429
481
  qualityCode: string | null;
@@ -432,13 +484,57 @@ export type PackingListRow = {
432
484
  final: boolean;
433
485
  rule: string | null;
434
486
  pieces: number;
487
+ /** The lengths its tally has, shortest first (empty before a tally). */
488
+ lengths?: {
489
+ value: number;
490
+ unit: string;
491
+ }[];
435
492
  histogram: Record<string, number> | null;
493
+ /**
494
+ * The group inside the list's group that this row sits in (a shipment's container), or null for a bundle or unit
495
+ * directly in the list's group.
496
+ */
497
+ inGroup: {
498
+ groupId: string;
499
+ kind: string | null;
500
+ name: string | null;
501
+ externalRef: string | null;
502
+ } | null;
436
503
  [field: string]: unknown;
437
504
  };
438
505
  export type PackingListTotals = LumberTotals & {
439
506
  convention: "exact" | "reported";
440
507
  bundles: number;
441
508
  };
509
+ /** One log of a packing list, as stored: tag, species, grade, length, small-end diameters and JAS volume. */
510
+ export type PackingListLog = {
511
+ itemId: string;
512
+ product: "sawlog";
513
+ /** The tag's payload; null for an untagged log. */
514
+ tag: string | null;
515
+ species: string;
516
+ grade: string | null;
517
+ lengthM: number;
518
+ diameterShortM: number;
519
+ diameterLongM: number;
520
+ /** JAS volume as recorded for the log. */
521
+ m3: number;
522
+ inGroup: PackingListRow["inGroup"];
523
+ };
524
+ /** A group's weighbridge net weight on a packing list. */
525
+ export type PackingListWeight = {
526
+ netKg: number;
527
+ ticketRef: string | null;
528
+ };
529
+ /** A packing list's logs, per group or in all: how many and their JAS volume. */
530
+ export type PackingListSawlogTotals = {
531
+ count: number;
532
+ totals: {
533
+ rule: "jas";
534
+ logs: number;
535
+ m3: number;
536
+ };
537
+ };
442
538
  export type PackingList = {
443
539
  object: "packing_list";
444
540
  livemode: boolean;
@@ -457,10 +553,39 @@ export type PackingList = {
457
553
  unit: string;
458
554
  }[];
459
555
  pivot: Record<string, unknown>[];
460
- /** Under the list's convention. */
461
- totals: PackingListTotals;
556
+ /**
557
+ * Under the list's convention: the list's own product's, or, for a group without a product, the one product it
558
+ * holds. Null while a group without a product holds bundles and units (see `totalsByProduct`).
559
+ */
560
+ totals: PackingListTotals | null;
462
561
  /** Under the other convention. */
463
- totalsAlternative: PackingListTotals;
562
+ totalsAlternative: PackingListTotals | null;
563
+ /** Per product, never added together: how many bundles or units, and their totals under both conventions. */
564
+ totalsByProduct: Partial<Record<LumberProduct, {
565
+ count: number;
566
+ totals: PackingListTotals;
567
+ totalsAlternative: PackingListTotals;
568
+ }>> & {
569
+ sawlog?: PackingListSawlogTotals;
570
+ };
571
+ /** The logs in the group and in the groups inside it, oldest first within each group. */
572
+ logs: PackingListLog[];
573
+ /** More logs than a packing list lists (5,000). */
574
+ logsHasMore: boolean;
575
+ /** The group's weighbridge net weight, when it has one. */
576
+ weight: PackingListWeight | null;
577
+ /**
578
+ * The groups inside this one that hold rows (a shipment's containers), in row order, each with its own totals
579
+ * per product. Empty for a group whose bundles and units sit directly in it.
580
+ */
581
+ groups: {
582
+ groupId: string;
583
+ kind: string | null;
584
+ name: string | null;
585
+ externalRef: string | null;
586
+ totalsByProduct: PackingList["totalsByProduct"];
587
+ weight: PackingListWeight | null;
588
+ }[];
464
589
  tallySheets?: GroupTally[];
465
590
  document?: DocumentBlock;
466
591
  [field: string]: unknown;
@@ -522,4 +647,3 @@ export type ScanImageParams = {
522
647
  file: Blob | Uint8Array | ArrayBuffer;
523
648
  filename?: string;
524
649
  };
525
- export {};
@@ -42,3 +42,26 @@ export declare function readWebhookRequest(req: WebhookRequest): Promise<{
42
42
  * It is async because Web Crypto is: `await te.webhooks.verify(...)`.
43
43
  */
44
44
  export declare function verifyWebhook(rawBody: string | Uint8Array | ArrayBuffer, headers: HeadersInput, secret: string | string[], options?: VerifyOptions): Promise<WebhookEvent>;
45
+ /** What {@link generateTestWebhookHeaders} signs. */
46
+ export interface TestWebhookParams {
47
+ /** The raw body to sign, exactly as your handler will receive it (a string or bytes, not an object). */
48
+ payload: string | Uint8Array | ArrayBuffer;
49
+ /** The `whsec_…` secret your handler verifies with. */
50
+ secret: string;
51
+ /** `webhook-id`. Default: the payload's `id` when it is an event (as in a real delivery), else `msg_` and random hex. */
52
+ id?: string;
53
+ /** `webhook-timestamp`, in Unix seconds. Default: now. Pass an old one to test your handler's tolerance. */
54
+ timestamp?: number;
55
+ }
56
+ /**
57
+ * The headers Timbereye would send with `payload`, signed with `secret` (Standard Webhooks: `webhook-id`,
58
+ * `webhook-timestamp`, `webhook-signature`), for testing your webhook handler without the network. `verifyWebhook`
59
+ * accepts them. Never use it to accept a request: it signs, it does not check.
60
+ *
61
+ * ```ts
62
+ * const body = JSON.stringify(event)
63
+ * const headers = await generateTestWebhookHeaders({ payload: body, secret: "whsec_…" })
64
+ * await handler(new Request("http://localhost/webhooks", { method: "POST", body, headers }))
65
+ * ```
66
+ */
67
+ export declare function generateTestWebhookHeaders(params: TestWebhookParams): Promise<Record<string, string>>;
@@ -1,6 +1,6 @@
1
1
  import { toCamel } from "./case.js";
2
2
  import { WebhookSignatureError } from "./errors.js";
3
- import { getWebCrypto } from "./runtime.js";
3
+ import { getWebCrypto, randomUUID } from "./runtime.js";
4
4
  function header(headers, name) {
5
5
  if (typeof headers.get === "function") {
6
6
  return headers.get(name) ?? undefined;
@@ -143,3 +143,66 @@ export async function verifyWebhook(rawBody, headers, secret, options = {}) {
143
143
  throw new WebhookSignatureError("invalid_payload", "Webhook body is not valid JSON");
144
144
  }
145
145
  }
146
+ function bytesOf(payload) {
147
+ return typeof payload === "string"
148
+ ? new TextEncoder().encode(payload)
149
+ : payload instanceof Uint8Array
150
+ ? payload
151
+ : new Uint8Array(payload);
152
+ }
153
+ function b64encode(bytes) {
154
+ let bin = "";
155
+ for (let i = 0; i < bytes.length; i++)
156
+ bin += String.fromCharCode(bytes[i]);
157
+ return btoa(bin);
158
+ }
159
+ function defaultMessageId(body) {
160
+ try {
161
+ const parsed = JSON.parse(new TextDecoder().decode(body));
162
+ if (typeof parsed?.id === "string" && parsed.id !== "")
163
+ return parsed.id;
164
+ }
165
+ catch {
166
+ // not JSON: a random id
167
+ }
168
+ return `msg_${randomUUID().replace(/-/g, "").slice(0, 24)}`;
169
+ }
170
+ /**
171
+ * The headers Timbereye would send with `payload`, signed with `secret` (Standard Webhooks: `webhook-id`,
172
+ * `webhook-timestamp`, `webhook-signature`), for testing your webhook handler without the network. `verifyWebhook`
173
+ * accepts them. Never use it to accept a request: it signs, it does not check.
174
+ *
175
+ * ```ts
176
+ * const body = JSON.stringify(event)
177
+ * const headers = await generateTestWebhookHeaders({ payload: body, secret: "whsec_…" })
178
+ * await handler(new Request("http://localhost/webhooks", { method: "POST", body, headers }))
179
+ * ```
180
+ */
181
+ export async function generateTestWebhookHeaders(params) {
182
+ const { secret } = params;
183
+ if (typeof secret !== "string" || secret === "")
184
+ throw new WebhookSignatureError("invalid_secret", "generateTestWebhookHeaders needs the whsec_… secret");
185
+ const body = bytesOf(params.payload);
186
+ const id = params.id ?? defaultMessageId(body);
187
+ const timestamp = String(Math.floor(params.timestamp ?? Date.now() / 1000));
188
+ let keyBytes;
189
+ try {
190
+ keyBytes = b64decode(secret.startsWith("whsec_") ? secret.slice(6) : secret);
191
+ }
192
+ catch {
193
+ throw new WebhookSignatureError("invalid_secret", "Webhook secret is not whsec_<base64>");
194
+ }
195
+ const prefix = new TextEncoder().encode(`${id}.${timestamp}.`);
196
+ const signed = new Uint8Array(prefix.length + body.length);
197
+ signed.set(prefix);
198
+ signed.set(body, prefix.length);
199
+ const crypto = await getWebCrypto();
200
+ const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
201
+ const signature = new Uint8Array(await crypto.subtle.sign("HMAC", key, signed));
202
+ return {
203
+ "content-type": "application/json",
204
+ "webhook-id": id,
205
+ "webhook-timestamp": timestamp,
206
+ "webhook-signature": `v1,${b64encode(signature)}`,
207
+ };
208
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timbereye/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "TypeScript SDK for the Timbereye API: measurements of logs and loads, groups, scans, places and webhooks.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -37,10 +37,10 @@
37
37
  "sdk"
38
38
  ],
39
39
  "scripts": {
40
- "generate": "../../node_modules/.bin/openapi-typescript ../../Timbereye/OpenApi/timbereye.v1.yaml --default-non-nullable false -o src/generated/schema.ts",
41
- "build": "rm -rf dist && ../../node_modules/.bin/tsc -p tsconfig.build.json && ../../node_modules/.bin/tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json','{\\\"type\\\":\\\"commonjs\\\"}\\n')\"",
42
- "typecheck": "../../node_modules/.bin/tsc -p tsconfig.json --noEmit",
43
- "test": "../../node_modules/.bin/mocha",
40
+ "generate": "node scripts/generate.mjs",
41
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json','{\\\"type\\\":\\\"commonjs\\\"}\\n')\"",
42
+ "typecheck": "tsc -p tsconfig.json --noEmit",
43
+ "test": "mocha",
44
44
  "prepack": "npm run build"
45
45
  },
46
46
  "module": "./dist/esm/index.js",