@timbereye/sdk 0.0.0-stage → 0.1.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 +68 -0
- package/LICENSE +202 -0
- package/README.md +330 -2
- package/dist/cjs/case.d.ts +23 -0
- package/dist/cjs/case.js +46 -0
- package/dist/cjs/client.d.ts +89 -0
- package/dist/cjs/client.js +122 -0
- package/dist/cjs/errors.d.ts +63 -0
- package/dist/cjs/errors.js +107 -0
- package/dist/cjs/generated/schema.d.ts +13436 -0
- package/dist/cjs/generated/schema.js +6 -0
- package/dist/cjs/http.d.ts +92 -0
- package/dist/cjs/http.js +238 -0
- package/dist/cjs/index.d.ts +14 -0
- package/dist/cjs/index.js +28 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +31 -0
- package/dist/cjs/pagination.js +52 -0
- package/dist/cjs/resources.d.ts +7879 -0
- package/dist/cjs/resources.js +456 -0
- package/dist/cjs/runtime.d.ts +20 -0
- package/dist/cjs/runtime.js +74 -0
- package/dist/cjs/types.d.ts +525 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/units.d.ts +26 -0
- package/dist/cjs/units.js +45 -0
- package/dist/cjs/webhooks.d.ts +44 -0
- package/dist/cjs/webhooks.js +149 -0
- package/dist/esm/case.d.ts +23 -0
- package/dist/esm/case.js +39 -0
- package/dist/esm/client.d.ts +89 -0
- package/dist/esm/client.js +118 -0
- package/dist/esm/errors.d.ts +63 -0
- package/dist/esm/errors.js +93 -0
- package/dist/esm/generated/schema.d.ts +13436 -0
- package/dist/esm/generated/schema.js +5 -0
- package/dist/esm/http.d.ts +92 -0
- package/dist/esm/http.js +232 -0
- package/dist/esm/index.d.ts +14 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/pagination.d.ts +31 -0
- package/dist/esm/pagination.js +49 -0
- package/dist/esm/resources.d.ts +7879 -0
- package/dist/esm/resources.js +453 -0
- package/dist/esm/runtime.d.ts +20 -0
- package/dist/esm/runtime.js +46 -0
- package/dist/esm/types.d.ts +525 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/units.d.ts +26 -0
- package/dist/esm/units.js +38 -0
- package/dist/esm/webhooks.d.ts +44 -0
- package/dist/esm/webhooks.js +145 -0
- package/package.json +51 -5
package/dist/cjs/case.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Case mapping between the API (snake_case JSON) and the SDK (camelCase).
|
|
4
|
+
*
|
|
5
|
+
* The mapping is purely mechanical: it is applied to object keys only, never to values, and the
|
|
6
|
+
* contents of free-form maps are left exactly as the caller or server wrote them. Opaque keys are
|
|
7
|
+
* listed once here; a test derives the same list from the OpenAPI document so they cannot drift.
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.OPAQUE_KEYS = void 0;
|
|
11
|
+
exports.snakeToCamel = snakeToCamel;
|
|
12
|
+
exports.camelToSnake = camelToSnake;
|
|
13
|
+
exports.toSnake = toSnake;
|
|
14
|
+
exports.toCamel = toCamel;
|
|
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"];
|
|
17
|
+
const OPAQUE_SNAKE = new Set(exports.OPAQUE_KEYS);
|
|
18
|
+
const OPAQUE_CAMEL = new Set(exports.OPAQUE_KEYS.map(snakeToCamel));
|
|
19
|
+
function snakeToCamel(key) {
|
|
20
|
+
return key.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
21
|
+
}
|
|
22
|
+
function camelToSnake(key) {
|
|
23
|
+
return key.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase());
|
|
24
|
+
}
|
|
25
|
+
function isPlainObject(v) {
|
|
26
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
27
|
+
}
|
|
28
|
+
function convert(value, mapKey, opaque) {
|
|
29
|
+
if (Array.isArray(value))
|
|
30
|
+
return value.map((v) => convert(v, mapKey, opaque));
|
|
31
|
+
if (!isPlainObject(value))
|
|
32
|
+
return value;
|
|
33
|
+
const out = {};
|
|
34
|
+
for (const [k, v] of Object.entries(value)) {
|
|
35
|
+
out[mapKey(k)] = opaque.has(k) ? v : convert(v, mapKey, opaque);
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
/** Convert a request value from the SDK's camelCase to the API's snake_case. */
|
|
40
|
+
function toSnake(value) {
|
|
41
|
+
return convert(value, camelToSnake, OPAQUE_CAMEL);
|
|
42
|
+
}
|
|
43
|
+
/** Convert a response value from the API's snake_case to the SDK's camelCase. */
|
|
44
|
+
function toCamel(value) {
|
|
45
|
+
return convert(value, snakeToCamel, OPAQUE_SNAKE);
|
|
46
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { type ClientOptions } from "./http.js";
|
|
2
|
+
import { createResources } from "./resources.js";
|
|
3
|
+
import { type HeadersInput, type VerifyOptions, type WebhookRequest } from "./webhooks.js";
|
|
4
|
+
import type { WebhookEvent } from "./types.js";
|
|
5
|
+
/** The client's options: the transport's, plus the webhook signing secret. */
|
|
6
|
+
export interface TimbereyeOptions extends ClientOptions {
|
|
7
|
+
/** The API key; default `TIMBEREYE_SECRET_KEY` from the environment. */
|
|
8
|
+
apiKey?: string;
|
|
9
|
+
/**
|
|
10
|
+
* The webhook endpoint's signing secret (`whsec_…`) that `webhooks.verify(req)` uses; default
|
|
11
|
+
* `TIMBEREYE_WEBHOOK_SECRET` from the environment, read when `verify` is called.
|
|
12
|
+
*/
|
|
13
|
+
webhookSecret?: string | string[];
|
|
14
|
+
}
|
|
15
|
+
/** The webhook helpers on a client. */
|
|
16
|
+
export interface WebhookHelpers {
|
|
17
|
+
/**
|
|
18
|
+
* Verifies a delivery from the request it arrived on, with the client's webhook secret
|
|
19
|
+
* (`webhookSecret`, else `TIMBEREYE_WEBHOOK_SECRET`). The request must still carry the raw body: a
|
|
20
|
+
* Fetch `Request`, or a Node request behind `express.raw({ type: "application/json" })` (or one no
|
|
21
|
+
* middleware has read). A body that was already parsed is refused with `raw_body_required`.
|
|
22
|
+
*/
|
|
23
|
+
verify(req: WebhookRequest, options?: VerifyOptions): Promise<WebhookEvent>;
|
|
24
|
+
/** Verifies a delivery from its raw body, headers and the secret (or secrets, while rolling one). */
|
|
25
|
+
verify(rawBody: string | Uint8Array | ArrayBuffer, headers: HeadersInput, secret: string | string[], options?: VerifyOptions): Promise<WebhookEvent>;
|
|
26
|
+
/**
|
|
27
|
+
* A route handler that verifies each delivery, calls `onEvent` with the event, and answers `200`. A
|
|
28
|
+
* request Timbereye did not sign (bad or missing signature, stale timestamp, not JSON) is answered `400`
|
|
29
|
+
* and `onEvent` is not called. A mistake in your setup (no secret, a body already parsed) and an error
|
|
30
|
+
* thrown by `onEvent` are not hidden: they go to `next` in Express (or are thrown), so Timbereye retries
|
|
31
|
+
* the delivery once you fix it.
|
|
32
|
+
*
|
|
33
|
+
* Express: `app.post("/webhooks/timbereye", express.raw({ type: "application/json" }), te.webhooks.handler(fn))`.
|
|
34
|
+
* Fetch (Next.js, Hono, Workers): `export const POST = te.webhooks.handler(fn)`.
|
|
35
|
+
*/
|
|
36
|
+
handler(onEvent: (event: WebhookEvent) => unknown, options?: VerifyOptions): WebhookRouteHandler;
|
|
37
|
+
}
|
|
38
|
+
/** What `webhooks.handler` returns: a Fetch handler, or a Node/Express one. */
|
|
39
|
+
export interface WebhookRouteHandler {
|
|
40
|
+
(req: Request): Promise<Response>;
|
|
41
|
+
(req: WebhookRequest, res: WebhookResponse, next?: (error?: unknown) => void): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
/** The part of a Node `ServerResponse` the handler uses. */
|
|
44
|
+
export interface WebhookResponse {
|
|
45
|
+
statusCode: number;
|
|
46
|
+
headersSent?: boolean;
|
|
47
|
+
setHeader(name: string, value: string): unknown;
|
|
48
|
+
end(body?: string): unknown;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* ```ts
|
|
52
|
+
* const te = new Timbereye() // reads TIMBEREYE_SECRET_KEY (and TIMBEREYE_WEBHOOK_SECRET for webhooks.verify)
|
|
53
|
+
* const group = await te.groups.create({ kind: "container", externalRef: "MSKU1234567" })
|
|
54
|
+
* ```
|
|
55
|
+
*
|
|
56
|
+
* `new Timbereye(apiKey, options)` and `new Timbereye({ apiKey, webhookSecret, ... })` also work; an explicit
|
|
57
|
+
* key or secret wins over the environment.
|
|
58
|
+
*/
|
|
59
|
+
export declare class Timbereye {
|
|
60
|
+
/** Test mode only: a simulated scan and refinement, so the loop can run with no device and no model. */
|
|
61
|
+
readonly testMode: ReturnType<typeof createResources>["testMode"];
|
|
62
|
+
readonly groups: ReturnType<typeof createResources>["groups"];
|
|
63
|
+
readonly items: ReturnType<typeof createResources>["items"];
|
|
64
|
+
readonly scans: ReturnType<typeof createResources>["scans"];
|
|
65
|
+
readonly images: ReturnType<typeof createResources>["images"];
|
|
66
|
+
readonly places: ReturnType<typeof createResources>["places"];
|
|
67
|
+
/** Tag printing: label designs for the 62 mm QR tags. */
|
|
68
|
+
readonly labelTemplates: ReturnType<typeof createResources>["labelTemplates"];
|
|
69
|
+
/** Tag printing: batches of tags and their ZPL or PDF print files. */
|
|
70
|
+
readonly tagBatches: ReturnType<typeof createResources>["tagBatches"];
|
|
71
|
+
readonly species: ReturnType<typeof createResources>["species"];
|
|
72
|
+
readonly volumeRules: ReturnType<typeof createResources>["volumeRules"];
|
|
73
|
+
readonly events: ReturnType<typeof createResources>["events"];
|
|
74
|
+
readonly webhookEndpoints: ReturnType<typeof createResources>["webhookEndpoints"];
|
|
75
|
+
readonly captureTokens: ReturnType<typeof createResources>["captureTokens"];
|
|
76
|
+
/** Key management: dashboard sessions only (an API key is refused with 403 `session_required`). */
|
|
77
|
+
readonly apiKeys: ReturnType<typeof createResources>["apiKeys"];
|
|
78
|
+
readonly team: ReturnType<typeof createResources>["team"];
|
|
79
|
+
readonly auditLog: ReturnType<typeof createResources>["auditLog"];
|
|
80
|
+
readonly usage: ReturnType<typeof createResources>["usage"];
|
|
81
|
+
/** The organisation's billing (dashboard sessions only). */
|
|
82
|
+
readonly billing: ReturnType<typeof createResources>["billing"];
|
|
83
|
+
readonly models: ReturnType<typeof createResources>["models"];
|
|
84
|
+
readonly account: ReturnType<typeof createResources>["account"];
|
|
85
|
+
/** The developer console's bootstrap and onboarding: dashboard sessions only. */
|
|
86
|
+
readonly console: ReturnType<typeof createResources>["console"];
|
|
87
|
+
readonly webhooks: WebhookHelpers;
|
|
88
|
+
constructor(apiKeyOrOptions?: string | TimbereyeOptions, options?: TimbereyeOptions);
|
|
89
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Timbereye = void 0;
|
|
4
|
+
const errors_js_1 = require("./errors.js");
|
|
5
|
+
const http_js_1 = require("./http.js");
|
|
6
|
+
const resources_js_1 = require("./resources.js");
|
|
7
|
+
const runtime_js_1 = require("./runtime.js");
|
|
8
|
+
const webhooks_js_1 = require("./webhooks.js");
|
|
9
|
+
/** Verification failures that mean "not from Timbereye": answered 400. Everything else is a setup mistake. */
|
|
10
|
+
const FORGED_CODES = new Set([
|
|
11
|
+
"missing_headers",
|
|
12
|
+
"invalid_timestamp",
|
|
13
|
+
"timestamp_out_of_tolerance",
|
|
14
|
+
"signature_mismatch",
|
|
15
|
+
"invalid_payload",
|
|
16
|
+
]);
|
|
17
|
+
/**
|
|
18
|
+
* ```ts
|
|
19
|
+
* const te = new Timbereye() // reads TIMBEREYE_SECRET_KEY (and TIMBEREYE_WEBHOOK_SECRET for webhooks.verify)
|
|
20
|
+
* const group = await te.groups.create({ kind: "container", externalRef: "MSKU1234567" })
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* `new Timbereye(apiKey, options)` and `new Timbereye({ apiKey, webhookSecret, ... })` also work; an explicit
|
|
24
|
+
* key or secret wins over the environment.
|
|
25
|
+
*/
|
|
26
|
+
class Timbereye {
|
|
27
|
+
constructor(apiKeyOrOptions, options = {}) {
|
|
28
|
+
const merged = typeof apiKeyOrOptions === "object" && apiKeyOrOptions !== null
|
|
29
|
+
? apiKeyOrOptions
|
|
30
|
+
: { ...options, apiKey: apiKeyOrOptions ?? options.apiKey };
|
|
31
|
+
const { apiKey: explicitKey, webhookSecret, ...transportOptions } = merged;
|
|
32
|
+
const apiKey = explicitKey ?? (0, runtime_js_1.readEnv)("TIMBEREYE_SECRET_KEY");
|
|
33
|
+
if (apiKey === undefined) {
|
|
34
|
+
throw new errors_js_1.TimbereyeError({
|
|
35
|
+
message: "No Timbereye API key: set TIMBEREYE_SECRET_KEY in the environment, or pass the key: " +
|
|
36
|
+
'new Timbereye("te_test_sk_…").',
|
|
37
|
+
type: "client_error",
|
|
38
|
+
code: "api_key_missing",
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
this.webhooks = {
|
|
42
|
+
verify: ((first, ...rest) => {
|
|
43
|
+
if (typeof first === "string" ||
|
|
44
|
+
first instanceof Uint8Array ||
|
|
45
|
+
first instanceof ArrayBuffer) {
|
|
46
|
+
const [headers, secret, verifyOptions] = rest;
|
|
47
|
+
return (0, webhooks_js_1.verifyWebhook)(first, headers, secret, verifyOptions);
|
|
48
|
+
}
|
|
49
|
+
return verifyRequest(first, webhookSecret, rest[0]);
|
|
50
|
+
}),
|
|
51
|
+
handler: (onEvent, verifyOptions) => webhookHandler(webhookSecret, onEvent, verifyOptions),
|
|
52
|
+
};
|
|
53
|
+
const r = (0, resources_js_1.createResources)(new http_js_1.Transport(apiKey, transportOptions));
|
|
54
|
+
this.testMode = r.testMode;
|
|
55
|
+
this.groups = r.groups;
|
|
56
|
+
this.items = r.items;
|
|
57
|
+
this.scans = r.scans;
|
|
58
|
+
this.images = r.images;
|
|
59
|
+
this.places = r.places;
|
|
60
|
+
this.labelTemplates = r.labelTemplates;
|
|
61
|
+
this.tagBatches = r.tagBatches;
|
|
62
|
+
this.species = r.species;
|
|
63
|
+
this.volumeRules = r.volumeRules;
|
|
64
|
+
this.events = r.events;
|
|
65
|
+
this.webhookEndpoints = r.webhookEndpoints;
|
|
66
|
+
this.captureTokens = r.captureTokens;
|
|
67
|
+
this.apiKeys = r.apiKeys;
|
|
68
|
+
this.team = r.team;
|
|
69
|
+
this.auditLog = r.auditLog;
|
|
70
|
+
this.usage = r.usage;
|
|
71
|
+
this.billing = r.billing;
|
|
72
|
+
this.models = r.models;
|
|
73
|
+
this.account = r.account;
|
|
74
|
+
this.console = r.console;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
exports.Timbereye = Timbereye;
|
|
78
|
+
async function verifyRequest(req, configured, options) {
|
|
79
|
+
const secret = configured ?? (0, runtime_js_1.readEnv)("TIMBEREYE_WEBHOOK_SECRET");
|
|
80
|
+
if (secret === undefined || (Array.isArray(secret) && secret.length === 0)) {
|
|
81
|
+
throw new errors_js_1.WebhookSignatureError("webhook_secret_missing", "No webhook secret: set TIMBEREYE_WEBHOOK_SECRET (the endpoint's whsec_… secret) in the environment, " +
|
|
82
|
+
"or pass it: new Timbereye({ webhookSecret }).");
|
|
83
|
+
}
|
|
84
|
+
const { body, headers } = await (0, webhooks_js_1.readWebhookRequest)(req);
|
|
85
|
+
return (0, webhooks_js_1.verifyWebhook)(body, headers, secret, options);
|
|
86
|
+
}
|
|
87
|
+
function webhookHandler(configured, onEvent, options) {
|
|
88
|
+
return (async (req, res, next) => {
|
|
89
|
+
const answer = (status, body) => {
|
|
90
|
+
if (res === undefined)
|
|
91
|
+
return new Response(body, { status, headers: { "content-type": "application/json" } });
|
|
92
|
+
if (res.headersSent !== true) {
|
|
93
|
+
res.statusCode = status;
|
|
94
|
+
res.setHeader("content-type", "application/json");
|
|
95
|
+
res.end(body);
|
|
96
|
+
}
|
|
97
|
+
return undefined;
|
|
98
|
+
};
|
|
99
|
+
try {
|
|
100
|
+
let event;
|
|
101
|
+
try {
|
|
102
|
+
event = await verifyRequest(req, configured, options);
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (error instanceof errors_js_1.WebhookSignatureError &&
|
|
106
|
+
error.code !== null &&
|
|
107
|
+
FORGED_CODES.has(error.code))
|
|
108
|
+
return answer(400, JSON.stringify({ error: { code: error.code, message: error.message } }));
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
await onEvent(event);
|
|
112
|
+
return answer(200, "{}");
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
if (res === undefined)
|
|
116
|
+
throw error;
|
|
117
|
+
if (next !== undefined)
|
|
118
|
+
return next(error);
|
|
119
|
+
answer(500, JSON.stringify({ error: { code: "handler_error" } }));
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
export type ErrorType = "invalid_request_error" | "authentication_error" | "permission_error" | "rate_limit_error" | "api_error";
|
|
2
|
+
export interface ErrorInit {
|
|
3
|
+
message: string;
|
|
4
|
+
type?: string;
|
|
5
|
+
code?: string | null;
|
|
6
|
+
param?: string | null;
|
|
7
|
+
requestId?: string | null;
|
|
8
|
+
status?: number;
|
|
9
|
+
docUrl?: string | null;
|
|
10
|
+
existingId?: string | null;
|
|
11
|
+
}
|
|
12
|
+
/** Base class of everything the SDK throws on purpose. */
|
|
13
|
+
export declare class TimbereyeError extends Error {
|
|
14
|
+
/** The API's error `type`, or a client-side marker for errors raised in the SDK. */
|
|
15
|
+
readonly type: string;
|
|
16
|
+
/** Stable machine-readable code. Unknown codes may appear within v1: treat them as the generic case. */
|
|
17
|
+
readonly code: string | null;
|
|
18
|
+
/** The request field at fault, with dots for nesting (`defaults.length_m`). Wire names, not camelCase. */
|
|
19
|
+
readonly param: string | null;
|
|
20
|
+
/** The `Request-Id` of the failed request. Quote it to support. */
|
|
21
|
+
readonly requestId: string | null;
|
|
22
|
+
/** HTTP status, or undefined when no response was received. */
|
|
23
|
+
readonly status: number | undefined;
|
|
24
|
+
readonly docUrl: string | null;
|
|
25
|
+
/** For `external_ref_in_use`: the open group that already has the reference (`grp_…`). */
|
|
26
|
+
readonly existingId: string | null;
|
|
27
|
+
constructor(init: ErrorInit);
|
|
28
|
+
}
|
|
29
|
+
/** 400, 404, 409, 412, 413, 422. */
|
|
30
|
+
export declare class InvalidRequestError extends TimbereyeError {
|
|
31
|
+
}
|
|
32
|
+
/** 401. */
|
|
33
|
+
export declare class AuthenticationError extends TimbereyeError {
|
|
34
|
+
}
|
|
35
|
+
/** 403. */
|
|
36
|
+
export declare class PermissionError extends TimbereyeError {
|
|
37
|
+
}
|
|
38
|
+
/** 429. `retryAfterSeconds` is the server's `Retry-After`, when sent. */
|
|
39
|
+
export declare class RateLimitError extends TimbereyeError {
|
|
40
|
+
retryAfterSeconds: number | null;
|
|
41
|
+
}
|
|
42
|
+
/** 5xx. */
|
|
43
|
+
export declare class ApiError extends TimbereyeError {
|
|
44
|
+
}
|
|
45
|
+
/** No usable response: DNS, connection reset, TLS, or the body could not be read. */
|
|
46
|
+
export declare class ConnectionError extends TimbereyeError {
|
|
47
|
+
readonly cause: unknown;
|
|
48
|
+
constructor(message: string, cause?: unknown, type?: string);
|
|
49
|
+
}
|
|
50
|
+
/** The per-attempt `timeoutMs` elapsed. */
|
|
51
|
+
export declare class TimeoutError extends ConnectionError {
|
|
52
|
+
constructor(timeoutMs: number);
|
|
53
|
+
}
|
|
54
|
+
/** The caller's `AbortSignal` fired. Never retried. */
|
|
55
|
+
export declare class AbortError extends TimbereyeError {
|
|
56
|
+
constructor();
|
|
57
|
+
}
|
|
58
|
+
/** A webhook failed verification. `code` says why. */
|
|
59
|
+
export declare class WebhookSignatureError extends TimbereyeError {
|
|
60
|
+
constructor(code: string, message: string);
|
|
61
|
+
}
|
|
62
|
+
/** Build the error for a non-2xx response. `body` is the parsed JSON, if the body was JSON. */
|
|
63
|
+
export declare function errorFromResponse(status: number, body: unknown, requestIdHeader: string | null): TimbereyeError;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WebhookSignatureError = exports.AbortError = exports.TimeoutError = exports.ConnectionError = exports.ApiError = exports.RateLimitError = exports.PermissionError = exports.AuthenticationError = exports.InvalidRequestError = exports.TimbereyeError = void 0;
|
|
4
|
+
exports.errorFromResponse = errorFromResponse;
|
|
5
|
+
/** Base class of everything the SDK throws on purpose. */
|
|
6
|
+
class TimbereyeError extends Error {
|
|
7
|
+
constructor(init) {
|
|
8
|
+
super(init.message);
|
|
9
|
+
this.name = new.target.name;
|
|
10
|
+
this.type = init.type ?? "client_error";
|
|
11
|
+
this.code = init.code ?? null;
|
|
12
|
+
this.param = init.param ?? null;
|
|
13
|
+
this.requestId = init.requestId ?? null;
|
|
14
|
+
this.status = init.status;
|
|
15
|
+
this.docUrl = init.docUrl ?? null;
|
|
16
|
+
this.existingId = init.existingId ?? null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
exports.TimbereyeError = TimbereyeError;
|
|
20
|
+
/** 400, 404, 409, 412, 413, 422. */
|
|
21
|
+
class InvalidRequestError extends TimbereyeError {
|
|
22
|
+
}
|
|
23
|
+
exports.InvalidRequestError = InvalidRequestError;
|
|
24
|
+
/** 401. */
|
|
25
|
+
class AuthenticationError extends TimbereyeError {
|
|
26
|
+
}
|
|
27
|
+
exports.AuthenticationError = AuthenticationError;
|
|
28
|
+
/** 403. */
|
|
29
|
+
class PermissionError extends TimbereyeError {
|
|
30
|
+
}
|
|
31
|
+
exports.PermissionError = PermissionError;
|
|
32
|
+
/** 429. `retryAfterSeconds` is the server's `Retry-After`, when sent. */
|
|
33
|
+
class RateLimitError extends TimbereyeError {
|
|
34
|
+
constructor() {
|
|
35
|
+
super(...arguments);
|
|
36
|
+
this.retryAfterSeconds = null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
exports.RateLimitError = RateLimitError;
|
|
40
|
+
/** 5xx. */
|
|
41
|
+
class ApiError extends TimbereyeError {
|
|
42
|
+
}
|
|
43
|
+
exports.ApiError = ApiError;
|
|
44
|
+
/** No usable response: DNS, connection reset, TLS, or the body could not be read. */
|
|
45
|
+
class ConnectionError extends TimbereyeError {
|
|
46
|
+
constructor(message, cause, type = "connection_error") {
|
|
47
|
+
super({ message, type });
|
|
48
|
+
this.cause = cause;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
exports.ConnectionError = ConnectionError;
|
|
52
|
+
/** The per-attempt `timeoutMs` elapsed. */
|
|
53
|
+
class TimeoutError extends ConnectionError {
|
|
54
|
+
constructor(timeoutMs) {
|
|
55
|
+
super(`Request timed out after ${timeoutMs} ms`, undefined, "timeout_error");
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
exports.TimeoutError = TimeoutError;
|
|
59
|
+
/** The caller's `AbortSignal` fired. Never retried. */
|
|
60
|
+
class AbortError extends TimbereyeError {
|
|
61
|
+
constructor() {
|
|
62
|
+
super({ message: "Request aborted", type: "abort_error" });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
exports.AbortError = AbortError;
|
|
66
|
+
/** A webhook failed verification. `code` says why. */
|
|
67
|
+
class WebhookSignatureError extends TimbereyeError {
|
|
68
|
+
constructor(code, message) {
|
|
69
|
+
super({ message, type: "webhook_signature_error", code });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
exports.WebhookSignatureError = WebhookSignatureError;
|
|
73
|
+
const BY_TYPE = {
|
|
74
|
+
invalid_request_error: InvalidRequestError,
|
|
75
|
+
authentication_error: AuthenticationError,
|
|
76
|
+
permission_error: PermissionError,
|
|
77
|
+
rate_limit_error: RateLimitError,
|
|
78
|
+
api_error: ApiError,
|
|
79
|
+
};
|
|
80
|
+
function typeFromStatus(status) {
|
|
81
|
+
if (status === 401)
|
|
82
|
+
return "authentication_error";
|
|
83
|
+
if (status === 403)
|
|
84
|
+
return "permission_error";
|
|
85
|
+
if (status === 429)
|
|
86
|
+
return "rate_limit_error";
|
|
87
|
+
if (status >= 500)
|
|
88
|
+
return "api_error";
|
|
89
|
+
return "invalid_request_error";
|
|
90
|
+
}
|
|
91
|
+
/** Build the error for a non-2xx response. `body` is the parsed JSON, if the body was JSON. */
|
|
92
|
+
function errorFromResponse(status, body, requestIdHeader) {
|
|
93
|
+
const e = body?.error;
|
|
94
|
+
const err = e && typeof e === "object" ? e : {};
|
|
95
|
+
const type = typeof err.type === "string" && err.type in BY_TYPE ? err.type : typeFromStatus(status);
|
|
96
|
+
const Cls = BY_TYPE[type] ?? TimbereyeError;
|
|
97
|
+
return new Cls({
|
|
98
|
+
message: typeof err.message === "string" ? err.message : `Request failed with status ${status}`,
|
|
99
|
+
type,
|
|
100
|
+
code: typeof err.code === "string" ? err.code : null,
|
|
101
|
+
param: typeof err.param === "string" ? err.param : null,
|
|
102
|
+
requestId: typeof err.request_id === "string" ? err.request_id : requestIdHeader,
|
|
103
|
+
docUrl: typeof err.doc_url === "string" ? err.doc_url : null,
|
|
104
|
+
existingId: typeof err.existing_id === "string" ? err.existing_id : null,
|
|
105
|
+
status,
|
|
106
|
+
});
|
|
107
|
+
}
|