@tracken/sdk 0.0.0-stage → 0.2.1

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.
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Money, prices and quantities travel as decimal strings (`"1234.50"`), never as JSON numbers, so no
3
+ * client rounds them through a binary float. The types already say `string`; these helpers check a
4
+ * value against the document's patterns, convert to and from integer minor units with `bigint`, and
5
+ * refuse a JavaScript number where the document expects a decimal string before anything is sent.
6
+ */
7
+ import { TrackenUsageError } from "./errors.js";
8
+ import { DECIMAL_PATTERNS } from "./generated/operations.js";
9
+ const PATTERNS = Object.fromEntries(Object.entries(DECIMAL_PATTERNS).map(([name, pattern]) => [name, new RegExp(pattern)]));
10
+ /** Whether `value` is a decimal string the API accepts as `format` (default `MoneyAmount`). */
11
+ export function isDecimal(value, format = "MoneyAmount") {
12
+ return typeof value === "string" && PATTERNS[format].test(value);
13
+ }
14
+ const MINOR_PATTERN = /^(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?$/;
15
+ /**
16
+ * Integer minor units of a decimal string: `toMinorUnits("1234.50")` is `123450n`. Refuses a value
17
+ * with more fraction digits than `scale` rather than rounding it.
18
+ */
19
+ export function toMinorUnits(value, scale = 2) {
20
+ const match = MINOR_PATTERN.exec(value);
21
+ if (!match)
22
+ throw new TrackenUsageError(`"${value}" is not a decimal string such as "1234.50".`);
23
+ const [, sign, whole, fraction = ""] = match;
24
+ if (fraction.length > scale)
25
+ throw new TrackenUsageError(`"${value}" has more than ${scale} fraction digits.`);
26
+ const minor = BigInt(whole + fraction.padEnd(scale, "0"));
27
+ return sign ? -minor : minor;
28
+ }
29
+ /** The decimal string of integer minor units: `fromMinorUnits(123450n)` is `"1234.50"`. */
30
+ export function fromMinorUnits(minor, scale = 2) {
31
+ if (typeof minor === "number" && !Number.isSafeInteger(minor))
32
+ throw new TrackenUsageError(`${minor} is not a whole number of minor units.`);
33
+ const value = BigInt(minor);
34
+ const digits = (value < 0n ? -value : value).toString().padStart(scale + 1, "0");
35
+ const whole = digits.slice(0, digits.length - scale);
36
+ const fraction = scale > 0 ? `.${digits.slice(digits.length - scale)}` : "";
37
+ return `${value < 0n ? "-" : ""}${whole}${fraction}`;
38
+ }
39
+ const unescapeToken = (token) => token.replace(/~1/g, "/").replace(/~0/g, "~");
40
+ function visit(node, tokens, index, at, operationId) {
41
+ if (index === tokens.length) {
42
+ if (typeof node === "number" || typeof node === "bigint") {
43
+ throw new TrackenUsageError(`${operationId}: ${at} is a decimal string such as "1234.50", never a number; got ${String(node)}.`);
44
+ }
45
+ return;
46
+ }
47
+ if (typeof node !== "object" || node === null)
48
+ return;
49
+ const token = tokens[index];
50
+ if (token === "*") {
51
+ const entries = Array.isArray(node) ? node.entries() : Object.entries(node);
52
+ for (const [key, child] of entries)
53
+ visit(child, tokens, index + 1, `${at}/${key}`, operationId);
54
+ return;
55
+ }
56
+ const name = unescapeToken(token);
57
+ if (Object.hasOwn(node, name))
58
+ visit(node[name], tokens, index + 1, `${at}/${token}`, operationId);
59
+ }
60
+ /**
61
+ * Throws `TrackenUsageError` when the body holds a number at any of the operation's decimal
62
+ * pointers (such as `/data/lines/<any index>/unit_price`).
63
+ */
64
+ export function assertDecimalStrings(body, pointers, operationId) {
65
+ for (const pointer of pointers)
66
+ visit(body, pointer.split("/").slice(1), 0, "", operationId);
67
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Where each Tracken environment's API and Tracken ID live. Values follow tracken-id's registry (the
3
+ * issuer and the integration resource) and the public document's `servers`.
4
+ */
5
+ export type EnvironmentName = "prod" | "dev";
6
+ export interface ApiEnvironment {
7
+ /** Tracken ID: where a machine credential is exchanged for a token. */
8
+ issuer: string;
9
+ /** The public API base, including the major version. */
10
+ apiBaseUrl: string;
11
+ /** The resource a machine credential's token is issued for. */
12
+ integrationAudience: string;
13
+ }
14
+ export declare const ENVIRONMENTS: Readonly<Record<EnvironmentName, Readonly<ApiEnvironment>>>;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Where each Tracken environment's API and Tracken ID live. Values follow tracken-id's registry (the
3
+ * issuer and the integration resource) and the public document's `servers`.
4
+ */
5
+ export const ENVIRONMENTS = {
6
+ prod: {
7
+ issuer: "https://id.tracken.ee",
8
+ apiBaseUrl: "https://accounts-api.tracken.ee/v1",
9
+ integrationAudience: "https://accounts-api.tracken.ee/integration",
10
+ },
11
+ dev: {
12
+ issuer: "https://id.dev.tracken.ee",
13
+ apiBaseUrl: "https://accounts-api.dev.tracken.ee/v1",
14
+ integrationAudience: "https://accounts-api.dev.tracken.ee/integration",
15
+ },
16
+ };
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Every failure the SDK raises is a `TrackenError`. An answer from the API that is not a success is a
3
+ * `TrackenApiError`, of the subclass its status names, so a caller can tell "sign in again" from "you
4
+ * may not" from "it changed under you" with `instanceof`, and a specific case by its stable `code`.
5
+ */
6
+ import type { KNOWN_ERROR_CODES } from "./generated/operations.js";
7
+ /** A code the public document names. The API may add codes, so any string can arrive. */
8
+ export type KnownErrorCode = (typeof KNOWN_ERROR_CODES)[number];
9
+ export type ErrorCode = KnownErrorCode | (string & {});
10
+ export declare class TrackenError extends Error {
11
+ constructor(message: string, options?: {
12
+ cause?: unknown;
13
+ });
14
+ }
15
+ /** The request was refused before it was sent: a missing path parameter, a number where money goes. */
16
+ export declare class TrackenUsageError extends TrackenError {
17
+ }
18
+ /** The API (or Tracken ID) could not be reached, after the client's own retries. */
19
+ export declare class TrackenNetworkError extends TrackenError {
20
+ readonly cause?: unknown | undefined;
21
+ constructor(message: string, cause?: unknown | undefined);
22
+ }
23
+ /** Tracken ID refused a credential (RFC 6749 §5.2): `error` is its OAuth code, such as `invalid_client`. */
24
+ export declare class TrackenAuthError extends TrackenError {
25
+ readonly error: string;
26
+ readonly description: string | undefined;
27
+ readonly status: number;
28
+ constructor(error: string, description: string | undefined, status: number);
29
+ }
30
+ /** An asynchronous job finished as `failed`; `job` is the API's last answer about it. */
31
+ export declare class TrackenJobFailedError extends TrackenError {
32
+ readonly job: unknown;
33
+ constructor(message: string, job: unknown);
34
+ }
35
+ /** `waitForJob` gave up before the job finished; poll `path` later to see how it ended. */
36
+ export declare class TrackenJobTimeoutError extends TrackenError {
37
+ readonly path: string;
38
+ readonly jobStatus: string | undefined;
39
+ readonly timeoutMs: number;
40
+ constructor(path: string, jobStatus: string | undefined, timeoutMs: number);
41
+ }
42
+ export interface ErrorDetail {
43
+ code?: string;
44
+ message?: string;
45
+ /** JSON Pointer to the offending request field, or `?name` for a query parameter. */
46
+ pointer?: string;
47
+ }
48
+ /** A non-2xx answer from the API, read from its `{error}` envelope. */
49
+ export declare class TrackenApiError extends TrackenError {
50
+ readonly status: number;
51
+ /** The answer as it came: the parsed `{error}` envelope, or text. */
52
+ readonly body: unknown;
53
+ readonly code: ErrorCode;
54
+ readonly details: ErrorDetail[];
55
+ /** Machine-readable figures of the error, keyed by `code`, for a caller's own localized message. */
56
+ readonly context: Record<string, unknown> | undefined;
57
+ readonly requestId: string | undefined;
58
+ readonly docUrl: string | undefined;
59
+ /** On a conflict with an existing record (a taken `external_ref`): that record's id. */
60
+ readonly existingId: string | undefined;
61
+ /** For 403: the `scope` of `WWW-Authenticate`, as sent: the scopes any one of which would admit the call. */
62
+ readonly missingScope: string | undefined;
63
+ /** `missingScope` as a list. */
64
+ readonly admittingScopes: string[];
65
+ /**
66
+ * For a 401: why the client's one renewal failed (Tracken ID refused the refresh or the
67
+ * credential). Absent when the renewed token was refused too.
68
+ */
69
+ renewalError: unknown;
70
+ /** What to do about it, when the caller knows better than the API's message (set by a wrapping client). */
71
+ hint: string | undefined;
72
+ /** For 429: seconds the API asked to wait. */
73
+ readonly retryAfter: number | undefined;
74
+ constructor(status: number,
75
+ /** The answer as it came: the parsed `{error}` envelope, or text. */
76
+ body: unknown, headers: Headers);
77
+ }
78
+ /** 400 or 422: the request is invalid; `details` point at every field at fault. */
79
+ export declare class TrackenValidationError extends TrackenApiError {
80
+ }
81
+ /** 401: no token, an expired one, or one for another audience. */
82
+ export declare class TrackenUnauthenticatedError extends TrackenApiError {
83
+ }
84
+ /**
85
+ * Why an organization's subscription is not active (`context.reason` of `SUBSCRIPTION_INACTIVE`). The
86
+ * document names these four in prose and keeps the list open: accept a value you do not know.
87
+ */
88
+ export type SubscriptionInactiveReason = "trial_ended" | "not_paid" | "cancelled" | "payer_stopped" | (string & {});
89
+ /**
90
+ * 402 (`SUBSCRIPTION_INACTIVE`): the organization's subscription is not active, so every operation but
91
+ * reading the current user and the organization (and the data export) is refused, reads included. Not
92
+ * retried: the same request fails the same way until an owner reopens the subscription in the app.
93
+ */
94
+ export declare class TrackenPaymentRequiredError extends TrackenApiError {
95
+ /** `context.reason`, as sent. */
96
+ readonly reason: SubscriptionInactiveReason | undefined;
97
+ /** `context.export_until`: the last day (ISO date) the organization's data can still be exported. */
98
+ readonly exportUntil: string | undefined;
99
+ constructor(status: number, body: unknown, headers: Headers);
100
+ }
101
+ /** 403: a scope or the role does not allow it; `missingScope` names the scope when that is why. */
102
+ export declare class TrackenForbiddenError extends TrackenApiError {
103
+ }
104
+ export declare class TrackenNotFoundError extends TrackenApiError {
105
+ }
106
+ /** 409: the record's state does not allow it, or it exists already (`existingId`). */
107
+ export declare class TrackenConflictError extends TrackenApiError {
108
+ }
109
+ /**
110
+ * Which trial allowance a `TRIAL_LIMIT_REACHED` names (`context.limit`). Public operations answer
111
+ * `emails_per_day` (sending a sales invoice or a quote) and `ocr_per_month` (digitizing a document);
112
+ * the app's own operations also `companies`, `firm_companies` and `ai_per_month`. The list is open:
113
+ * accept a value you do not know.
114
+ */
115
+ export type TrialLimit = "emails_per_day" | "ocr_per_month" | "companies" | "firm_companies" | "ai_per_month" | (string & {});
116
+ /**
117
+ * 409 `TRIAL_LIMIT_REACHED`: a company on a free trial has used one of the trial's allowances, and
118
+ * nothing was sent or started. Not retried: do not retry before `resetsOn`; an owner choosing a plan in
119
+ * the app lifts every allowance at once.
120
+ */
121
+ export declare class TrackenTrialLimitError extends TrackenConflictError {
122
+ /** `context.limit`, as sent. */
123
+ readonly limit: TrialLimit | undefined;
124
+ /** `context.max`: how many the allowance holds. */
125
+ readonly max: number | undefined;
126
+ /**
127
+ * `context.resets_on`: the ISO date the count starts again (days and months counted in
128
+ * Europe/Tallinn). Absent for an allowance only a plan lifts.
129
+ */
130
+ readonly resetsOn: string | undefined;
131
+ constructor(status: number, body: unknown, headers: Headers);
132
+ }
133
+ /** 412: `If-Match` did not match; the record changed since it was read. */
134
+ export declare class TrackenPreconditionFailedError extends TrackenApiError {
135
+ }
136
+ /** 429 after the client's own retries; `retryAfter` says how long to wait. */
137
+ export declare class TrackenRateLimitedError extends TrackenApiError {
138
+ }
139
+ /** 5xx after the client's own retries. */
140
+ export declare class TrackenServerError extends TrackenApiError {
141
+ }
142
+ /** The `TrackenApiError` subclass for a status (and, for a 409, the trial's limit by its code). */
143
+ export declare function apiError(status: number, body: unknown, headers: Headers): TrackenApiError;
144
+ /**
145
+ * Whether `error` is an API error, and when `code` is given, one with that code:
146
+ * `if (isApiError(error, "INVOICE_NOT_DRAFT")) …`.
147
+ */
148
+ export declare function isApiError<C extends ErrorCode>(error: unknown, code?: C): error is TrackenApiError & {
149
+ code: C;
150
+ };
package/dist/errors.js ADDED
@@ -0,0 +1,190 @@
1
+ export class TrackenError extends Error {
2
+ constructor(message, options) {
3
+ super(message, options);
4
+ this.name = new.target.name;
5
+ }
6
+ }
7
+ /** The request was refused before it was sent: a missing path parameter, a number where money goes. */
8
+ export class TrackenUsageError extends TrackenError {
9
+ }
10
+ /** The API (or Tracken ID) could not be reached, after the client's own retries. */
11
+ export class TrackenNetworkError extends TrackenError {
12
+ cause;
13
+ constructor(message, cause) {
14
+ super(message, { cause });
15
+ this.cause = cause;
16
+ }
17
+ }
18
+ /** Tracken ID refused a credential (RFC 6749 §5.2): `error` is its OAuth code, such as `invalid_client`. */
19
+ export class TrackenAuthError extends TrackenError {
20
+ error;
21
+ description;
22
+ status;
23
+ constructor(error, description, status) {
24
+ super(description ? `${error}: ${description}` : error);
25
+ this.error = error;
26
+ this.description = description;
27
+ this.status = status;
28
+ }
29
+ }
30
+ /** An asynchronous job finished as `failed`; `job` is the API's last answer about it. */
31
+ export class TrackenJobFailedError extends TrackenError {
32
+ job;
33
+ constructor(message, job) {
34
+ super(message);
35
+ this.job = job;
36
+ }
37
+ }
38
+ /** `waitForJob` gave up before the job finished; poll `path` later to see how it ended. */
39
+ export class TrackenJobTimeoutError extends TrackenError {
40
+ path;
41
+ jobStatus;
42
+ timeoutMs;
43
+ constructor(path, jobStatus, timeoutMs) {
44
+ super(`Gave up waiting after ${Math.round(timeoutMs / 1000)} s; the job is still ${jobStatus ?? "pending"}. Poll GET ${path} to follow it.`);
45
+ this.path = path;
46
+ this.jobStatus = jobStatus;
47
+ this.timeoutMs = timeoutMs;
48
+ }
49
+ }
50
+ const text = (value) => (typeof value === "string" && value ? value : undefined);
51
+ /** A non-2xx answer from the API, read from its `{error}` envelope. */
52
+ export class TrackenApiError extends TrackenError {
53
+ status;
54
+ body;
55
+ code;
56
+ details;
57
+ /** Machine-readable figures of the error, keyed by `code`, for a caller's own localized message. */
58
+ context;
59
+ requestId;
60
+ docUrl;
61
+ /** On a conflict with an existing record (a taken `external_ref`): that record's id. */
62
+ existingId;
63
+ /** For 403: the `scope` of `WWW-Authenticate`, as sent: the scopes any one of which would admit the call. */
64
+ missingScope;
65
+ /** `missingScope` as a list. */
66
+ admittingScopes;
67
+ /**
68
+ * For a 401: why the client's one renewal failed (Tracken ID refused the refresh or the
69
+ * credential). Absent when the renewed token was refused too.
70
+ */
71
+ renewalError;
72
+ /** What to do about it, when the caller knows better than the API's message (set by a wrapping client). */
73
+ hint;
74
+ /** For 429: seconds the API asked to wait. */
75
+ retryAfter;
76
+ constructor(status,
77
+ /** The answer as it came: the parsed `{error}` envelope, or text. */
78
+ body, headers) {
79
+ const envelope = typeof body === "object" && body !== null ? body.error : undefined;
80
+ super(text(envelope?.message) ?? (typeof body === "string" && body.trim() ? body.trim().slice(0, 500) : `HTTP ${status}`));
81
+ this.status = status;
82
+ this.body = body;
83
+ this.code = text(envelope?.code) ?? `HTTP_${status}`;
84
+ this.details = Array.isArray(envelope?.details) ? envelope.details : [];
85
+ const context = envelope?.context;
86
+ this.context = typeof context === "object" && context !== null && !Array.isArray(context) ? context : undefined;
87
+ this.requestId = text(envelope?.request_id) ?? headers.get("x-request-id") ?? undefined;
88
+ this.docUrl = text(envelope?.doc_url);
89
+ this.existingId = text(envelope?.existing_id);
90
+ this.missingScope = headers.get("www-authenticate")?.match(/scope="([^"]+)"/)?.[1];
91
+ this.admittingScopes = (this.missingScope ?? "").split(/\s+/).filter(Boolean);
92
+ this.renewalError = undefined;
93
+ this.hint = undefined;
94
+ const retry = Number(headers.get("retry-after") ?? Number.NaN);
95
+ this.retryAfter = Number.isFinite(retry) && retry >= 0 ? retry : undefined;
96
+ }
97
+ }
98
+ /** 400 or 422: the request is invalid; `details` point at every field at fault. */
99
+ export class TrackenValidationError extends TrackenApiError {
100
+ }
101
+ /** 401: no token, an expired one, or one for another audience. */
102
+ export class TrackenUnauthenticatedError extends TrackenApiError {
103
+ }
104
+ /**
105
+ * 402 (`SUBSCRIPTION_INACTIVE`): the organization's subscription is not active, so every operation but
106
+ * reading the current user and the organization (and the data export) is refused, reads included. Not
107
+ * retried: the same request fails the same way until an owner reopens the subscription in the app.
108
+ */
109
+ export class TrackenPaymentRequiredError extends TrackenApiError {
110
+ /** `context.reason`, as sent. */
111
+ reason;
112
+ /** `context.export_until`: the last day (ISO date) the organization's data can still be exported. */
113
+ exportUntil;
114
+ constructor(status, body, headers) {
115
+ super(status, body, headers);
116
+ this.reason = text(this.context?.reason);
117
+ this.exportUntil = text(this.context?.export_until);
118
+ }
119
+ }
120
+ /** 403: a scope or the role does not allow it; `missingScope` names the scope when that is why. */
121
+ export class TrackenForbiddenError extends TrackenApiError {
122
+ }
123
+ export class TrackenNotFoundError extends TrackenApiError {
124
+ }
125
+ /** 409: the record's state does not allow it, or it exists already (`existingId`). */
126
+ export class TrackenConflictError extends TrackenApiError {
127
+ }
128
+ /**
129
+ * 409 `TRIAL_LIMIT_REACHED`: a company on a free trial has used one of the trial's allowances, and
130
+ * nothing was sent or started. Not retried: do not retry before `resetsOn`; an owner choosing a plan in
131
+ * the app lifts every allowance at once.
132
+ */
133
+ export class TrackenTrialLimitError extends TrackenConflictError {
134
+ /** `context.limit`, as sent. */
135
+ limit;
136
+ /** `context.max`: how many the allowance holds. */
137
+ max;
138
+ /**
139
+ * `context.resets_on`: the ISO date the count starts again (days and months counted in
140
+ * Europe/Tallinn). Absent for an allowance only a plan lifts.
141
+ */
142
+ resetsOn;
143
+ constructor(status, body, headers) {
144
+ super(status, body, headers);
145
+ this.limit = text(this.context?.limit);
146
+ const max = this.context?.max;
147
+ this.max = typeof max === "number" && Number.isFinite(max) ? max : undefined;
148
+ this.resetsOn = text(this.context?.resets_on);
149
+ }
150
+ }
151
+ /** 412: `If-Match` did not match; the record changed since it was read. */
152
+ export class TrackenPreconditionFailedError extends TrackenApiError {
153
+ }
154
+ /** 429 after the client's own retries; `retryAfter` says how long to wait. */
155
+ export class TrackenRateLimitedError extends TrackenApiError {
156
+ }
157
+ /** 5xx after the client's own retries. */
158
+ export class TrackenServerError extends TrackenApiError {
159
+ }
160
+ const envelopeCode = (body) => typeof body === "object" && body !== null ? text(body.error?.code) : undefined;
161
+ /** The `TrackenApiError` subclass for a status (and, for a 409, the trial's limit by its code). */
162
+ export function apiError(status, body, headers) {
163
+ if (status === 400 || status === 422)
164
+ return new TrackenValidationError(status, body, headers);
165
+ if (status === 401)
166
+ return new TrackenUnauthenticatedError(status, body, headers);
167
+ if (status === 402)
168
+ return new TrackenPaymentRequiredError(status, body, headers);
169
+ if (status === 403)
170
+ return new TrackenForbiddenError(status, body, headers);
171
+ if (status === 404)
172
+ return new TrackenNotFoundError(status, body, headers);
173
+ if (status === 409) {
174
+ return envelopeCode(body) === "TRIAL_LIMIT_REACHED" ? new TrackenTrialLimitError(status, body, headers) : new TrackenConflictError(status, body, headers);
175
+ }
176
+ if (status === 412)
177
+ return new TrackenPreconditionFailedError(status, body, headers);
178
+ if (status === 429)
179
+ return new TrackenRateLimitedError(status, body, headers);
180
+ if (status >= 500)
181
+ return new TrackenServerError(status, body, headers);
182
+ return new TrackenApiError(status, body, headers);
183
+ }
184
+ /**
185
+ * Whether `error` is an API error, and when `code` is given, one with that code:
186
+ * `if (isApiError(error, "INVOICE_NOT_DRAFT")) …`.
187
+ */
188
+ export function isApiError(error, code) {
189
+ return error instanceof TrackenApiError && (code === undefined || error.code === code);
190
+ }