@tracken/cli 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.
- package/CHANGELOG.md +404 -0
- package/LICENSE +21 -0
- package/README.md +310 -2
- package/dist/bin/tracken.d.ts +2 -0
- package/dist/bin/tracken.js +5 -0
- package/dist/cli/args.d.ts +17 -0
- package/dist/cli/args.js +114 -0
- package/dist/cli/commands/api.d.ts +2 -0
- package/dist/cli/commands/api.js +73 -0
- package/dist/cli/commands/auth.d.ts +8 -0
- package/dist/cli/commands/auth.js +141 -0
- package/dist/cli/commands/mcp.d.ts +19 -0
- package/dist/cli/commands/mcp.js +89 -0
- package/dist/cli/commands/org.d.ts +24 -0
- package/dist/cli/commands/org.js +123 -0
- package/dist/cli/context.d.ts +54 -0
- package/dist/cli/context.js +135 -0
- package/dist/cli/execute.d.ts +16 -0
- package/dist/cli/execute.js +112 -0
- package/dist/cli/help.d.ts +8 -0
- package/dist/cli/help.js +153 -0
- package/dist/cli/main.d.ts +2 -0
- package/dist/cli/main.js +114 -0
- package/dist/cli/operation-args.d.ts +25 -0
- package/dist/cli/operation-args.js +245 -0
- package/dist/core/auth/oauth.d.ts +39 -0
- package/dist/core/auth/oauth.js +102 -0
- package/dist/core/auth/scopes.d.ts +19 -0
- package/dist/core/auth/scopes.js +49 -0
- package/dist/core/auth/secret-store.d.ts +60 -0
- package/dist/core/auth/secret-store.js +141 -0
- package/dist/core/auth/session.d.ts +75 -0
- package/dist/core/auth/session.js +200 -0
- package/dist/core/catalog.d.ts +12 -0
- package/dist/core/catalog.js +33 -0
- package/dist/core/client.d.ts +22 -0
- package/dist/core/client.js +45 -0
- package/dist/core/config.d.ts +27 -0
- package/dist/core/config.js +109 -0
- package/dist/core/environments.d.ts +21 -0
- package/dist/core/environments.js +53 -0
- package/dist/core/errors.d.ts +96 -0
- package/dist/core/errors.js +248 -0
- package/dist/core/index.d.ts +21 -0
- package/dist/core/index.js +22 -0
- package/dist/core/jobs.d.ts +15 -0
- package/dist/core/jobs.js +19 -0
- package/dist/core/operations.d.ts +108 -0
- package/dist/core/operations.js +7 -0
- package/dist/core/output/format.d.ts +19 -0
- package/dist/core/output/format.js +62 -0
- package/dist/core/output/render.d.ts +53 -0
- package/dist/core/output/render.js +229 -0
- package/dist/core/pagination.d.ts +2 -0
- package/dist/core/pagination.js +3 -0
- package/dist/core/request.d.ts +29 -0
- package/dist/core/request.js +109 -0
- package/dist/core/version.d.ts +10 -0
- package/dist/core/version.js +13 -0
- package/dist/generated/mcp-tools.d.ts +2 -0
- package/dist/generated/mcp-tools.js +5937 -0
- package/dist/generated/operations.d.ts +4 -0
- package/dist/generated/operations.js +17701 -0
- package/dist/mcp/errors.d.ts +34 -0
- package/dist/mcp/errors.js +100 -0
- package/dist/mcp/live.d.ts +3 -0
- package/dist/mcp/live.js +5 -0
- package/dist/mcp/prompts.d.ts +23 -0
- package/dist/mcp/prompts.js +101 -0
- package/dist/mcp/resources.d.ts +25 -0
- package/dist/mcp/resources.js +125 -0
- package/dist/mcp/server.d.ts +20 -0
- package/dist/mcp/server.js +59 -0
- package/dist/mcp/session.d.ts +60 -0
- package/dist/mcp/session.js +105 -0
- package/dist/mcp/tools.d.ts +17 -0
- package/dist/mcp/tools.js +181 -0
- package/dist/mcp/types.d.ts +25 -0
- package/dist/mcp/types.js +2 -0
- package/node_modules/@tracken/sdk/LICENSE +21 -0
- package/node_modules/@tracken/sdk/README.md +76 -0
- package/node_modules/@tracken/sdk/SOURCE.json +10 -0
- package/node_modules/@tracken/sdk/dist/client.d.ts +94 -0
- package/node_modules/@tracken/sdk/dist/client.js +258 -0
- package/node_modules/@tracken/sdk/dist/credentials.d.ts +60 -0
- package/node_modules/@tracken/sdk/dist/credentials.js +122 -0
- package/node_modules/@tracken/sdk/dist/decimal.d.ts +20 -0
- package/node_modules/@tracken/sdk/dist/decimal.js +67 -0
- package/node_modules/@tracken/sdk/dist/environments.d.ts +14 -0
- package/node_modules/@tracken/sdk/dist/environments.js +16 -0
- package/node_modules/@tracken/sdk/dist/errors.d.ts +150 -0
- package/node_modules/@tracken/sdk/dist/errors.js +190 -0
- package/node_modules/@tracken/sdk/dist/generated/operations.d.ts +1955 -0
- package/node_modules/@tracken/sdk/dist/generated/operations.js +2746 -0
- package/node_modules/@tracken/sdk/dist/generated/schema.d.ts +17988 -0
- package/node_modules/@tracken/sdk/dist/generated/schema.js +5 -0
- package/node_modules/@tracken/sdk/dist/index.d.ts +27 -0
- package/node_modules/@tracken/sdk/dist/index.js +24 -0
- package/node_modules/@tracken/sdk/dist/jobs.d.ts +23 -0
- package/node_modules/@tracken/sdk/dist/jobs.js +80 -0
- package/node_modules/@tracken/sdk/dist/operations.d.ts +23 -0
- package/node_modules/@tracken/sdk/dist/operations.js +2 -0
- package/node_modules/@tracken/sdk/dist/pagination.d.ts +19 -0
- package/node_modules/@tracken/sdk/dist/pagination.js +49 -0
- package/node_modules/@tracken/sdk/dist/request.d.ts +27 -0
- package/node_modules/@tracken/sdk/dist/request.js +10 -0
- package/node_modules/@tracken/sdk/dist/runtime.d.ts +22 -0
- package/node_modules/@tracken/sdk/dist/runtime.js +33 -0
- package/node_modules/@tracken/sdk/dist/tracken.d.ts +74 -0
- package/node_modules/@tracken/sdk/dist/tracken.js +203 -0
- package/node_modules/@tracken/sdk/dist/types.d.ts +130 -0
- package/node_modules/@tracken/sdk/dist/types.js +1 -0
- package/node_modules/@tracken/sdk/dist/version.d.ts +2 -0
- package/node_modules/@tracken/sdk/dist/version.js +2 -0
- package/node_modules/@tracken/sdk/package.json +42 -0
- package/node_modules/openapi-fetch/CHANGELOG.md +565 -0
- package/node_modules/openapi-fetch/CONTRIBUTING.md +102 -0
- package/node_modules/openapi-fetch/LICENSE +21 -0
- package/node_modules/openapi-fetch/README.md +122 -0
- package/node_modules/openapi-fetch/dist/index.cjs +547 -0
- package/node_modules/openapi-fetch/dist/index.cjs.map +1 -0
- package/node_modules/openapi-fetch/dist/index.d.cts +337 -0
- package/node_modules/openapi-fetch/dist/index.d.mts +335 -0
- package/node_modules/openapi-fetch/dist/index.d.ts +337 -0
- package/node_modules/openapi-fetch/dist/index.mjs +531 -0
- package/node_modules/openapi-fetch/dist/index.mjs.map +1 -0
- package/node_modules/openapi-fetch/package.json +77 -0
- package/node_modules/openapi-fetch/src/index.d.ts +345 -0
- package/node_modules/openapi-fetch/src/index.js +689 -0
- package/node_modules/openapi-typescript-helpers/CHANGELOG.md +98 -0
- package/node_modules/openapi-typescript-helpers/LICENSE +21 -0
- package/node_modules/openapi-typescript-helpers/README.md +5 -0
- package/node_modules/openapi-typescript-helpers/dist/index.cjs +3 -0
- package/node_modules/openapi-typescript-helpers/dist/index.cjs.map +1 -0
- package/node_modules/openapi-typescript-helpers/dist/index.d.cts +167 -0
- package/node_modules/openapi-typescript-helpers/dist/index.d.mts +167 -0
- package/node_modules/openapi-typescript-helpers/dist/index.d.ts +167 -0
- package/node_modules/openapi-typescript-helpers/dist/index.mjs +2 -0
- package/node_modules/openapi-typescript-helpers/dist/index.mjs.map +1 -0
- package/node_modules/openapi-typescript-helpers/package.json +39 -0
- package/openapi/SOURCE.json +10 -0
- package/openapi/openapi.yaml +30514 -0
- package/package.json +63 -4
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@tracken/sdk`: a typed client for Tracken Accounts' public API, generated from its public document.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { Tracken, isApiError } from "@tracken/sdk";
|
|
6
|
+
*
|
|
7
|
+
* const tracken = new Tracken({ environment: "dev", auth: { clientId, clientSecret } });
|
|
8
|
+
* for await (const invoice of tracken.paginate("listSalesInvoices", { query: { status: ["draft"] } })) {
|
|
9
|
+
* await tracken.salesInvoices.issue({ path: { id: invoice.id } });
|
|
10
|
+
* }
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export { Tracken, requestFor, type AccessTokenAuth, type ClientCredentialsAuth, type TrackenOptions } from "./tracken.js";
|
|
14
|
+
export type { ItemOf, OperationId, OperationInput, OperationMethod, PaginatedOperationId, RequestBody, RequestOptions, ResourceName, Resources, ResponseBody, TrackenResponse, } from "./types.js";
|
|
15
|
+
export { ORGANIZATION_HEADER, TrackenClient, newIdempotencyKey, type ApiResponse, type ClientOptions } from "./client.js";
|
|
16
|
+
export { ClientCredentials, EXPIRY_SKEW_MS, jwtClaims, jwtExpiry, staticToken, tokenExpiry, type ClientCredentialsOptions, type Credentials, type TokenResponse, } from "./credentials.js";
|
|
17
|
+
export { assertDecimalStrings, fromMinorUnits, isDecimal, toMinorUnits, type DecimalFormat } from "./decimal.js";
|
|
18
|
+
export { ENVIRONMENTS, type ApiEnvironment, type EnvironmentName } from "./environments.js";
|
|
19
|
+
export { TrackenApiError, TrackenAuthError, TrackenConflictError, TrackenError, TrackenForbiddenError, TrackenJobFailedError, TrackenJobTimeoutError, TrackenNetworkError, TrackenNotFoundError, TrackenPaymentRequiredError, TrackenPreconditionFailedError, TrackenRateLimitedError, TrackenServerError, TrackenTrialLimitError, TrackenUnauthenticatedError, TrackenUsageError, TrackenValidationError, apiError, isApiError, type ErrorCode, type ErrorDetail, type KnownErrorCode, type SubscriptionInactiveReason, type TrialLimit, } from "./errors.js";
|
|
20
|
+
export { DECIMAL_PATTERNS, DOCUMENT, KNOWN_ERROR_CODES, OPERATIONS } from "./generated/operations.js";
|
|
21
|
+
export type { components, operations, paths } from "./generated/schema.js";
|
|
22
|
+
export { pollPath, waitForJob, type WaitOptions } from "./jobs.js";
|
|
23
|
+
export type { HttpMethod, OperationDescriptor } from "./operations.js";
|
|
24
|
+
export { collectAll, nextCursor, nextSince, pageItems, pages } from "./pagination.js";
|
|
25
|
+
export { serializeQuery, withQuery, type ApiRequest, type OperationRef } from "./request.js";
|
|
26
|
+
export { AGENT_HEADER, agentLabel, systemClock, userAgent, type Clock, type Fetch } from "./runtime.js";
|
|
27
|
+
export { SDK_VERSION } from "./version.js";
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@tracken/sdk`: a typed client for Tracken Accounts' public API, generated from its public document.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { Tracken, isApiError } from "@tracken/sdk";
|
|
6
|
+
*
|
|
7
|
+
* const tracken = new Tracken({ environment: "dev", auth: { clientId, clientSecret } });
|
|
8
|
+
* for await (const invoice of tracken.paginate("listSalesInvoices", { query: { status: ["draft"] } })) {
|
|
9
|
+
* await tracken.salesInvoices.issue({ path: { id: invoice.id } });
|
|
10
|
+
* }
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export { Tracken, requestFor } from "./tracken.js";
|
|
14
|
+
export { ORGANIZATION_HEADER, TrackenClient, newIdempotencyKey } from "./client.js";
|
|
15
|
+
export { ClientCredentials, EXPIRY_SKEW_MS, jwtClaims, jwtExpiry, staticToken, tokenExpiry, } from "./credentials.js";
|
|
16
|
+
export { assertDecimalStrings, fromMinorUnits, isDecimal, toMinorUnits } from "./decimal.js";
|
|
17
|
+
export { ENVIRONMENTS } from "./environments.js";
|
|
18
|
+
export { TrackenApiError, TrackenAuthError, TrackenConflictError, TrackenError, TrackenForbiddenError, TrackenJobFailedError, TrackenJobTimeoutError, TrackenNetworkError, TrackenNotFoundError, TrackenPaymentRequiredError, TrackenPreconditionFailedError, TrackenRateLimitedError, TrackenServerError, TrackenTrialLimitError, TrackenUnauthenticatedError, TrackenUsageError, TrackenValidationError, apiError, isApiError, } from "./errors.js";
|
|
19
|
+
export { DECIMAL_PATTERNS, DOCUMENT, KNOWN_ERROR_CODES, OPERATIONS } from "./generated/operations.js";
|
|
20
|
+
export { pollPath, waitForJob } from "./jobs.js";
|
|
21
|
+
export { collectAll, nextCursor, nextSince, pageItems, pages } from "./pagination.js";
|
|
22
|
+
export { serializeQuery, withQuery } from "./request.js";
|
|
23
|
+
export { AGENT_HEADER, agentLabel, systemClock, userAgent } from "./runtime.js";
|
|
24
|
+
export { SDK_VERSION } from "./version.js";
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An asynchronous operation answers 202 with a job (a `Job`, or a record that is its own job, like a
|
|
3
|
+
* billing run) and usually a `Location`. `waitForJob` polls it with backoff until it leaves
|
|
4
|
+
* `queued`/`running`.
|
|
5
|
+
*/
|
|
6
|
+
import type { ApiResponse, TrackenClient } from "./client.js";
|
|
7
|
+
import type { ApiRequest } from "./request.js";
|
|
8
|
+
export interface WaitOptions {
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
now?(): number;
|
|
11
|
+
sleep?(ms: number): Promise<void>;
|
|
12
|
+
onProgress?: (status: string, progress: number | undefined) => void;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Where to poll: the `Location` header when present (absolute, or a path under the API base),
|
|
16
|
+
* else `/jobs/{id}` for a `Job`, else the created record (`POST /billing-runs` → `/billing-runs/{id}`).
|
|
17
|
+
*/
|
|
18
|
+
export declare function pollPath(response: ApiResponse, request: ApiRequest, baseUrl: string): string;
|
|
19
|
+
/**
|
|
20
|
+
* Polls until the job is done and answers the final response; throws `TrackenJobFailedError` when it
|
|
21
|
+
* failed and `TrackenJobTimeoutError` when it outlasts `timeoutMs`.
|
|
22
|
+
*/
|
|
23
|
+
export declare function waitForJob(client: TrackenClient, accepted: ApiResponse, request: ApiRequest, options?: WaitOptions): Promise<ApiResponse>;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { TrackenError, TrackenJobFailedError, TrackenJobTimeoutError } from "./errors.js";
|
|
2
|
+
import { systemClock } from "./runtime.js";
|
|
3
|
+
const PENDING = new Set(["queued", "running"]);
|
|
4
|
+
const FAILED = new Set(["failed"]);
|
|
5
|
+
const FIRST_DELAY_MS = 1000;
|
|
6
|
+
const MAX_DELAY_MS = 10_000;
|
|
7
|
+
/** Ten minutes, the CLI's `--wait-timeout` default. */
|
|
8
|
+
const DEFAULT_TIMEOUT_MS = 10 * 60_000;
|
|
9
|
+
const jobOf = (body) => {
|
|
10
|
+
const data = body?.data;
|
|
11
|
+
return typeof data === "object" && data !== null ? data : undefined;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Where to poll: the `Location` header when present (absolute, or a path under the API base),
|
|
15
|
+
* else `/jobs/{id}` for a `Job`, else the created record (`POST /billing-runs` → `/billing-runs/{id}`).
|
|
16
|
+
*/
|
|
17
|
+
export function pollPath(response, request, baseUrl) {
|
|
18
|
+
const location = response.headers.get("location");
|
|
19
|
+
if (location) {
|
|
20
|
+
const base = new URL(baseUrl);
|
|
21
|
+
const url = new URL(location, `${base.origin}${base.pathname.replace(/\/?$/, "/")}`);
|
|
22
|
+
if (url.origin !== base.origin)
|
|
23
|
+
throw new TrackenError(`The job's Location ${location} is not on ${base.origin}; refusing to follow it.`);
|
|
24
|
+
const prefix = base.pathname.replace(/\/$/, "");
|
|
25
|
+
return url.pathname.startsWith(`${prefix}/`) ? url.pathname.slice(prefix.length) + url.search : url.pathname + url.search;
|
|
26
|
+
}
|
|
27
|
+
const job = jobOf(response.body);
|
|
28
|
+
if (typeof job?.id !== "string")
|
|
29
|
+
throw new TrackenError("The answer names no job to wait for.");
|
|
30
|
+
if (typeof job.type === "string" && typeof job.status === "string" && !request.path.startsWith("/jobs"))
|
|
31
|
+
return `/jobs/${job.id}`;
|
|
32
|
+
const collection = request.path.replace(/:[^/]*$/, "").replace(/\/\{[^}]+\}$/, "");
|
|
33
|
+
return `${collection}/${job.id}`;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Polls until the job is done and answers the final response; throws `TrackenJobFailedError` when it
|
|
37
|
+
* failed and `TrackenJobTimeoutError` when it outlasts `timeoutMs`.
|
|
38
|
+
*/
|
|
39
|
+
export async function waitForJob(client, accepted, request, options = {}) {
|
|
40
|
+
// Called through `options` so a clock object's methods keep their `this`.
|
|
41
|
+
const now = () => (options.now ? options.now() : systemClock.now());
|
|
42
|
+
const sleep = (ms) => (options.sleep ? options.sleep(ms) : systemClock.sleep(ms));
|
|
43
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
44
|
+
const path = pollPath(accepted, request, client.baseUrl);
|
|
45
|
+
const [pathname, search = ""] = path.split("?");
|
|
46
|
+
const poll = {
|
|
47
|
+
method: "get",
|
|
48
|
+
path: pathname,
|
|
49
|
+
pathParams: {},
|
|
50
|
+
query: [...new URLSearchParams(search)].map(([key, value]) => [key, value]),
|
|
51
|
+
headers: {},
|
|
52
|
+
};
|
|
53
|
+
if (request.organization !== undefined)
|
|
54
|
+
poll.organization = request.organization;
|
|
55
|
+
if (request.signal)
|
|
56
|
+
poll.signal = request.signal;
|
|
57
|
+
const deadline = now() + timeoutMs;
|
|
58
|
+
let delay = FIRST_DELAY_MS;
|
|
59
|
+
let current = accepted;
|
|
60
|
+
for (;;) {
|
|
61
|
+
const job = jobOf(current.body);
|
|
62
|
+
const status = typeof job?.status === "string" ? job.status : undefined;
|
|
63
|
+
if (status && !PENDING.has(status)) {
|
|
64
|
+
if (FAILED.has(status)) {
|
|
65
|
+
const reason = job?.error && typeof job.error.message === "string" ? `: ${job.error.message}` : "";
|
|
66
|
+
const code = job?.error && typeof job.error.code === "string" ? ` (${job.error.code})` : "";
|
|
67
|
+
throw new TrackenJobFailedError(`The job ${String(job?.id ?? "")} failed${reason}${code}.`, current.body);
|
|
68
|
+
}
|
|
69
|
+
return current;
|
|
70
|
+
}
|
|
71
|
+
if (now() + delay > deadline)
|
|
72
|
+
throw new TrackenJobTimeoutError(path, status, timeoutMs);
|
|
73
|
+
await sleep(delay);
|
|
74
|
+
delay = Math.min(MAX_DELAY_MS, Math.round(delay * 1.5));
|
|
75
|
+
current = await client.send(poll);
|
|
76
|
+
const next = jobOf(current.body);
|
|
77
|
+
if (typeof next?.status === "string")
|
|
78
|
+
options.onProgress?.(next.status, typeof next.progress === "number" ? next.progress : undefined);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** The shape of one entry in the generated operation table (`generated/operations.ts`). */
|
|
2
|
+
export type HttpMethod = "get" | "post" | "put" | "patch" | "delete";
|
|
3
|
+
export interface OperationDescriptor {
|
|
4
|
+
readonly method: HttpMethod;
|
|
5
|
+
/** The path template relative to the API base (`/sales-invoices/{id}:issue`). */
|
|
6
|
+
readonly path: string;
|
|
7
|
+
/** The namespace on `Tracken` (`salesInvoices`) and the method in it (`issue`, `listValues`). */
|
|
8
|
+
readonly resource: string;
|
|
9
|
+
readonly name: string;
|
|
10
|
+
/** Whether a person's token must name the organization (`X-Organization-ID`). */
|
|
11
|
+
readonly organization: boolean;
|
|
12
|
+
/** A cursor-paginated list: `meta.pagination.next_cursor` leads to the next page. */
|
|
13
|
+
readonly paginated: boolean;
|
|
14
|
+
/** Answers `202 Accepted` with a job to wait for. */
|
|
15
|
+
readonly async: boolean;
|
|
16
|
+
readonly body?: "json" | "multipart";
|
|
17
|
+
/** The header parameters it takes (`Idempotency-Key`, `If-Match`), by wire name. */
|
|
18
|
+
readonly headers: readonly string[];
|
|
19
|
+
/** Array query parameters sent as one comma-joined value (`explode: false`), not repeated. */
|
|
20
|
+
readonly csvQuery?: readonly string[];
|
|
21
|
+
/** JSON Pointers (`*` for any index or key) to the decimal strings in the request body. */
|
|
22
|
+
readonly decimals?: readonly string[];
|
|
23
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cursor pagination: follow `meta.pagination.next_cursor` until it is null. Lists carry their
|
|
3
|
+
* records in `data`; a paginated report (the general ledger) carries them in `data.rows`.
|
|
4
|
+
*/
|
|
5
|
+
import type { ApiResponse, TrackenClient } from "./client.js";
|
|
6
|
+
import { type ApiRequest } from "./request.js";
|
|
7
|
+
/**
|
|
8
|
+
* Where the next incremental pass starts (`meta.sync.next_since`, to send as `updated_since`): the
|
|
9
|
+
* same on every page of a pass, 16 minutes before its first page was read. Never "now": a writer
|
|
10
|
+
* still committing would be missed.
|
|
11
|
+
*/
|
|
12
|
+
export declare function nextSince(body: unknown): string | undefined;
|
|
13
|
+
export declare function nextCursor(body: unknown): string | undefined;
|
|
14
|
+
/** The records of one page: `data` when it is a list, else a report's `data.rows`. */
|
|
15
|
+
export declare function pageItems(body: unknown): unknown[];
|
|
16
|
+
/** Every page, in order, starting from the request's own cursor (if any). */
|
|
17
|
+
export declare function pages(client: TrackenClient, request: ApiRequest): AsyncGenerator<ApiResponse>;
|
|
18
|
+
/** Every record of every page. For large sets prefer `pages`, which holds one page at a time. */
|
|
19
|
+
export declare function collectAll(client: TrackenClient, request: ApiRequest): Promise<unknown[]>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { TrackenError } from "./errors.js";
|
|
2
|
+
import { withQuery } from "./request.js";
|
|
3
|
+
/**
|
|
4
|
+
* Where the next incremental pass starts (`meta.sync.next_since`, to send as `updated_since`): the
|
|
5
|
+
* same on every page of a pass, 16 minutes before its first page was read. Never "now": a writer
|
|
6
|
+
* still committing would be missed.
|
|
7
|
+
*/
|
|
8
|
+
export function nextSince(body) {
|
|
9
|
+
const value = body?.meta?.sync?.next_since;
|
|
10
|
+
return typeof value === "string" && value ? value : undefined;
|
|
11
|
+
}
|
|
12
|
+
export function nextCursor(body) {
|
|
13
|
+
const pagination = body?.meta?.pagination;
|
|
14
|
+
if (!pagination || pagination.has_more === false)
|
|
15
|
+
return undefined;
|
|
16
|
+
return typeof pagination.next_cursor === "string" && pagination.next_cursor ? pagination.next_cursor : undefined;
|
|
17
|
+
}
|
|
18
|
+
/** The records of one page: `data` when it is a list, else a report's `data.rows`. */
|
|
19
|
+
export function pageItems(body) {
|
|
20
|
+
const data = body?.data;
|
|
21
|
+
if (Array.isArray(data))
|
|
22
|
+
return data;
|
|
23
|
+
const rows = data?.rows;
|
|
24
|
+
return Array.isArray(rows) ? rows : [];
|
|
25
|
+
}
|
|
26
|
+
/** Every page, in order, starting from the request's own cursor (if any). */
|
|
27
|
+
export async function* pages(client, request) {
|
|
28
|
+
let current = request;
|
|
29
|
+
const seen = new Set();
|
|
30
|
+
for (;;) {
|
|
31
|
+
const response = await client.send(current);
|
|
32
|
+
yield response;
|
|
33
|
+
const cursor = nextCursor(response.body);
|
|
34
|
+
if (!cursor)
|
|
35
|
+
return;
|
|
36
|
+
// A cursor that repeats would loop forever; the API never sends one, so stop loudly.
|
|
37
|
+
if (seen.has(cursor))
|
|
38
|
+
throw new TrackenError(`The API returned the cursor ${cursor} twice; stopping.`);
|
|
39
|
+
seen.add(cursor);
|
|
40
|
+
current = withQuery(current, "cursor", cursor);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Every record of every page. For large sets prefer `pages`, which holds one page at a time. */
|
|
44
|
+
export async function collectAll(client, request) {
|
|
45
|
+
const items = [];
|
|
46
|
+
for await (const page of pages(client, request))
|
|
47
|
+
items.push(...pageItems(page.body));
|
|
48
|
+
return items;
|
|
49
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** A request as the client sends it: an operation's path template, its parameters and its body. */
|
|
2
|
+
import type { HttpMethod } from "./operations.js";
|
|
3
|
+
/** What the client needs to know about the operation a request belongs to. */
|
|
4
|
+
export interface OperationRef {
|
|
5
|
+
operationId: string;
|
|
6
|
+
/** Whether a person's token must name the organization (`X-Organization-ID`). */
|
|
7
|
+
organization: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface ApiRequest {
|
|
10
|
+
method: HttpMethod;
|
|
11
|
+
/** Path template relative to the API base (`/sales-invoices/{id}:issue`), or a literal path. */
|
|
12
|
+
path: string;
|
|
13
|
+
pathParams: Record<string, string>;
|
|
14
|
+
/** Query pairs in order, already serialized per each parameter's style. */
|
|
15
|
+
query: Array<[string, string]>;
|
|
16
|
+
headers: Record<string, string>;
|
|
17
|
+
/** A JSON value, or `FormData` for multipart. */
|
|
18
|
+
body?: unknown;
|
|
19
|
+
operation?: OperationRef;
|
|
20
|
+
/** Overrides the client's organization for this request; `null` sends none (listing a person's organizations). */
|
|
21
|
+
organization?: string | null;
|
|
22
|
+
/** Cancels the request (and the client's retries of it). */
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
}
|
|
25
|
+
export declare function serializeQuery(pairs: ReadonlyArray<readonly [string, string]>): string;
|
|
26
|
+
/** Replaces `key` in the query pairs (the cursor on each page). */
|
|
27
|
+
export declare function withQuery<R extends ApiRequest>(request: R, key: string, value: string | undefined): R;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export function serializeQuery(pairs) {
|
|
2
|
+
return pairs.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
|
|
3
|
+
}
|
|
4
|
+
/** Replaces `key` in the query pairs (the cursor on each page). */
|
|
5
|
+
export function withQuery(request, key, value) {
|
|
6
|
+
const query = request.query.filter(([name]) => name !== key);
|
|
7
|
+
if (value !== undefined)
|
|
8
|
+
query.push([key, value]);
|
|
9
|
+
return { ...request, query };
|
|
10
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export type Fetch = typeof fetch;
|
|
2
|
+
export interface Clock {
|
|
3
|
+
now(): number;
|
|
4
|
+
sleep(ms: number): Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
export declare const systemClock: Clock;
|
|
7
|
+
/**
|
|
8
|
+
* `product/version (node 22.x; darwin-arm64)`, sent on every request: Tracken's edge refuses requests
|
|
9
|
+
* without a User-Agent, and support can tell one client's traffic from another's. Outside Node the
|
|
10
|
+
* runtime part is left out (a browser sends its own User-Agent).
|
|
11
|
+
*/
|
|
12
|
+
export declare function userAgent(product?: string, version?: string): string;
|
|
13
|
+
/**
|
|
14
|
+
* `Tracken-Agent`: the program acting with a token, which Accounts records in the audit log beside
|
|
15
|
+
* the token's client. A label only; it changes no right.
|
|
16
|
+
*/
|
|
17
|
+
export declare const AGENT_HEADER = "Tracken-Agent";
|
|
18
|
+
/**
|
|
19
|
+
* `<name>/<version>`, made acceptable to the server: unprintable characters and spaces dropped,
|
|
20
|
+
* the name shortened so the whole fits. `undefined` when nothing printable is left of the name.
|
|
21
|
+
*/
|
|
22
|
+
export declare function agentLabel(name: string, version: string): string | undefined;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** What the client needs from its host: `fetch`, a clock to wait with, and how to name itself. */
|
|
2
|
+
import { SDK_VERSION } from "./version.js";
|
|
3
|
+
export const systemClock = {
|
|
4
|
+
now: () => Date.now(),
|
|
5
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* `product/version (node 22.x; darwin-arm64)`, sent on every request: Tracken's edge refuses requests
|
|
9
|
+
* without a User-Agent, and support can tell one client's traffic from another's. Outside Node the
|
|
10
|
+
* runtime part is left out (a browser sends its own User-Agent).
|
|
11
|
+
*/
|
|
12
|
+
export function userAgent(product = "tracken-sdk", version = SDK_VERSION) {
|
|
13
|
+
const host = globalThis.process;
|
|
14
|
+
const node = host?.versions?.node;
|
|
15
|
+
return node ? `${product}/${version} (node ${node}; ${host.platform}-${host.arch})` : `${product}/${version}`;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* `Tracken-Agent`: the program acting with a token, which Accounts records in the audit log beside
|
|
19
|
+
* the token's client. A label only; it changes no right.
|
|
20
|
+
*/
|
|
21
|
+
export const AGENT_HEADER = "Tracken-Agent";
|
|
22
|
+
/** The server ignores a value longer than this or with anything but printable ASCII. */
|
|
23
|
+
const AGENT_MAX = 100;
|
|
24
|
+
/**
|
|
25
|
+
* `<name>/<version>`, made acceptable to the server: unprintable characters and spaces dropped,
|
|
26
|
+
* the name shortened so the whole fits. `undefined` when nothing printable is left of the name.
|
|
27
|
+
*/
|
|
28
|
+
export function agentLabel(name, version) {
|
|
29
|
+
const clean = (text) => text.replace(/[^\x21-\x7e]/g, "");
|
|
30
|
+
const tail = clean(version) ? `/${clean(version).slice(0, 40)}` : "";
|
|
31
|
+
const head = clean(name).slice(0, AGENT_MAX - tail.length);
|
|
32
|
+
return head ? `${head}${tail}` : undefined;
|
|
33
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Tracken`: the typed client. Every v1 operation is a method on its resource
|
|
3
|
+
* (`tracken.salesInvoices.list`, `tracken.salesInvoices.issue`, `tracken.dimensions.listValues`),
|
|
4
|
+
* named the way the CLI names its commands, and `call` reaches any of them by operation id. Inputs
|
|
5
|
+
* and answers are typed from the public document; requests go through the shared transport, so every
|
|
6
|
+
* call gets the token, retries, the automatic Idempotency-Key and the 303 download.
|
|
7
|
+
*/
|
|
8
|
+
import { TrackenClient } from "./client.js";
|
|
9
|
+
import { type Credentials } from "./credentials.js";
|
|
10
|
+
import { type EnvironmentName } from "./environments.js";
|
|
11
|
+
import { type WaitOptions } from "./jobs.js";
|
|
12
|
+
import type { ApiRequest } from "./request.js";
|
|
13
|
+
import type { Clock, Fetch } from "./runtime.js";
|
|
14
|
+
import type { CallArgs, ItemOf, OperationId, OperationInput, PaginatedOperationId, RequestOptions, Resources, ResponseBody, TrackenResponse } from "./types.js";
|
|
15
|
+
/** A machine credential: an API key from Accounts → Settings → API access. */
|
|
16
|
+
export interface ClientCredentialsAuth {
|
|
17
|
+
clientId: string;
|
|
18
|
+
clientSecret: string;
|
|
19
|
+
/** Space-separated scopes; absent asks for everything the credential holds. */
|
|
20
|
+
scope?: string;
|
|
21
|
+
}
|
|
22
|
+
/** A token you obtained yourself; give `organizationId` too when it is a person's. */
|
|
23
|
+
export interface AccessTokenAuth {
|
|
24
|
+
accessToken: string | (() => string | Promise<string>);
|
|
25
|
+
}
|
|
26
|
+
export interface TrackenOptions {
|
|
27
|
+
/** `prod` (default) or `dev`: where the API and Tracken ID are. */
|
|
28
|
+
environment?: EnvironmentName;
|
|
29
|
+
/** Overrides the environment's API base (`http://localhost:8000/v1`). */
|
|
30
|
+
baseUrl?: string;
|
|
31
|
+
/** Overrides the environment's Tracken ID, for a machine credential. */
|
|
32
|
+
issuer?: string;
|
|
33
|
+
auth: ClientCredentialsAuth | AccessTokenAuth | Credentials;
|
|
34
|
+
/** The organization a person's token acts in (`X-Organization-ID`). A machine credential names its own. */
|
|
35
|
+
organizationId?: string;
|
|
36
|
+
/** `et` or `en`: the language of error messages. */
|
|
37
|
+
language?: string;
|
|
38
|
+
/** Retries after 429, gateway errors and network failures (default 3). */
|
|
39
|
+
maxRetries?: number;
|
|
40
|
+
fetch?: Fetch;
|
|
41
|
+
clock?: Clock;
|
|
42
|
+
/** Sent as `User-Agent`; name your integration (`acme-sync/2.1`). */
|
|
43
|
+
userAgent?: string;
|
|
44
|
+
/** Sent as `Tracken-Agent` and recorded in the audit log (default `tracken-sdk/<version>`); see `agentLabel`. */
|
|
45
|
+
agent?: string;
|
|
46
|
+
debug?: (line: string) => void;
|
|
47
|
+
}
|
|
48
|
+
/** The request one typed call makes. Exported for tests and for callers that send through `client`. */
|
|
49
|
+
export declare function requestFor<Id extends OperationId>(operationId: Id, input: OperationInput<Id> | undefined, options?: RequestOptions): ApiRequest;
|
|
50
|
+
export interface Tracken extends Resources {
|
|
51
|
+
}
|
|
52
|
+
export declare class Tracken {
|
|
53
|
+
/** The transport, for raw requests (`client.send`) and the typed openapi-fetch client (`client.http`). */
|
|
54
|
+
readonly client: TrackenClient;
|
|
55
|
+
/** The request and raw answer behind each typed response, so `waitForJob` can follow it. */
|
|
56
|
+
private readonly sent;
|
|
57
|
+
constructor(options: TrackenOptions);
|
|
58
|
+
/** The typed openapi-fetch client: token and headers added, no retries. */
|
|
59
|
+
get http(): TrackenClient["http"];
|
|
60
|
+
/** Calls any operation by its id: `tracken.call("issueSalesInvoice", { path: { id } })`. */
|
|
61
|
+
call<Id extends OperationId>(operationId: Id, ...[input, options]: CallArgs<Id>): Promise<TrackenResponse<ResponseBody<Id>>>;
|
|
62
|
+
/** Every page of a list, one at a time, following `meta.pagination.next_cursor`. */
|
|
63
|
+
pages<Id extends PaginatedOperationId>(operationId: Id, ...[input, options]: CallArgs<Id>): AsyncGenerator<TrackenResponse<ResponseBody<Id>>>;
|
|
64
|
+
/**
|
|
65
|
+
* Every record of a list across all its pages, fetched a page at a time as you iterate:
|
|
66
|
+
* `for await (const invoice of tracken.paginate("listSalesInvoices", { query: { status: ["issued"] } }))`.
|
|
67
|
+
*/
|
|
68
|
+
paginate<Id extends PaginatedOperationId>(operationId: Id, ...args: CallArgs<Id>): AsyncGenerator<ItemOf<ResponseBody<Id>>>;
|
|
69
|
+
/**
|
|
70
|
+
* Waits for the job a `202 Accepted` answer started (a billing run, a bank statement import) and
|
|
71
|
+
* answers its final state; throws `TrackenJobFailedError` if it failed.
|
|
72
|
+
*/
|
|
73
|
+
waitForJob(accepted: TrackenResponse, options?: WaitOptions): Promise<TrackenResponse>;
|
|
74
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Tracken`: the typed client. Every v1 operation is a method on its resource
|
|
3
|
+
* (`tracken.salesInvoices.list`, `tracken.salesInvoices.issue`, `tracken.dimensions.listValues`),
|
|
4
|
+
* named the way the CLI names its commands, and `call` reaches any of them by operation id. Inputs
|
|
5
|
+
* and answers are typed from the public document; requests go through the shared transport, so every
|
|
6
|
+
* call gets the token, retries, the automatic Idempotency-Key and the 303 download.
|
|
7
|
+
*/
|
|
8
|
+
import { TrackenClient } from "./client.js";
|
|
9
|
+
import { ClientCredentials, staticToken } from "./credentials.js";
|
|
10
|
+
import { assertDecimalStrings } from "./decimal.js";
|
|
11
|
+
import { ENVIRONMENTS } from "./environments.js";
|
|
12
|
+
import { TrackenUsageError } from "./errors.js";
|
|
13
|
+
import { OPERATIONS } from "./generated/operations.js";
|
|
14
|
+
import { waitForJob as waitFor } from "./jobs.js";
|
|
15
|
+
import { nextSince, pageItems, pages as rawPages } from "./pagination.js";
|
|
16
|
+
const table = OPERATIONS;
|
|
17
|
+
const isCredentials = (auth) => typeof auth.accessToken === "function" && "renew" in auth;
|
|
18
|
+
function credentialsOf(options) {
|
|
19
|
+
const { auth } = options;
|
|
20
|
+
if (isCredentials(auth))
|
|
21
|
+
return auth;
|
|
22
|
+
if ("clientId" in auth) {
|
|
23
|
+
const environment = ENVIRONMENTS[options.environment ?? "prod"];
|
|
24
|
+
const credentials = {
|
|
25
|
+
issuer: options.issuer ?? environment.issuer,
|
|
26
|
+
audience: environment.integrationAudience,
|
|
27
|
+
clientId: auth.clientId,
|
|
28
|
+
clientSecret: auth.clientSecret,
|
|
29
|
+
scope: auth.scope,
|
|
30
|
+
};
|
|
31
|
+
if (options.fetch)
|
|
32
|
+
credentials.fetch = options.fetch;
|
|
33
|
+
if (options.clock)
|
|
34
|
+
credentials.clock = options.clock;
|
|
35
|
+
if (options.userAgent)
|
|
36
|
+
credentials.userAgent = options.userAgent;
|
|
37
|
+
return new ClientCredentials(credentials);
|
|
38
|
+
}
|
|
39
|
+
return staticToken(auth.accessToken, options.organizationId ? "user" : "machine");
|
|
40
|
+
}
|
|
41
|
+
function headerName(operation, operationId, wanted, option) {
|
|
42
|
+
const name = operation.headers.find((header) => header.toLowerCase() === wanted.toLowerCase());
|
|
43
|
+
if (!name)
|
|
44
|
+
throw new TrackenUsageError(`${operationId} takes no ${wanted} header, so ${option} does not apply.`);
|
|
45
|
+
return name;
|
|
46
|
+
}
|
|
47
|
+
function formOf(fields) {
|
|
48
|
+
const form = new FormData();
|
|
49
|
+
for (const [name, value] of Object.entries(fields)) {
|
|
50
|
+
if (value === undefined)
|
|
51
|
+
continue;
|
|
52
|
+
if (value instanceof Blob)
|
|
53
|
+
form.append(name, value, value instanceof File ? value.name : name);
|
|
54
|
+
else
|
|
55
|
+
form.append(name, String(value));
|
|
56
|
+
}
|
|
57
|
+
return form;
|
|
58
|
+
}
|
|
59
|
+
/** The request one typed call makes. Exported for tests and for callers that send through `client`. */
|
|
60
|
+
export function requestFor(operationId, input, options = {}) {
|
|
61
|
+
const operation = table[operationId];
|
|
62
|
+
if (!operation)
|
|
63
|
+
throw new TrackenUsageError(`No operation ${String(operationId)} in this SDK's document.`);
|
|
64
|
+
const given = (input ?? {});
|
|
65
|
+
const pathParams = {};
|
|
66
|
+
const names = [...operation.path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
67
|
+
for (const name of names) {
|
|
68
|
+
const value = given.path?.[name];
|
|
69
|
+
if (value === undefined || value === null || value === "")
|
|
70
|
+
throw new TrackenUsageError(`${operationId} needs the path parameter ${name}.`);
|
|
71
|
+
pathParams[name] = String(value);
|
|
72
|
+
}
|
|
73
|
+
for (const name of Object.keys(given.path ?? {})) {
|
|
74
|
+
if (!names.includes(name))
|
|
75
|
+
throw new TrackenUsageError(`${operationId} has no path parameter ${name}.`);
|
|
76
|
+
}
|
|
77
|
+
const query = [];
|
|
78
|
+
const text = (value) => (typeof value === "boolean" ? (value ? "true" : "false") : String(value));
|
|
79
|
+
for (const [name, value] of Object.entries(given.query ?? {})) {
|
|
80
|
+
if (value === undefined || value === null)
|
|
81
|
+
continue;
|
|
82
|
+
if (!Array.isArray(value))
|
|
83
|
+
query.push([name, text(value)]);
|
|
84
|
+
else if (operation.csvQuery?.includes(name)) {
|
|
85
|
+
if (value.length > 0)
|
|
86
|
+
query.push([name, value.map(text).join(",")]);
|
|
87
|
+
}
|
|
88
|
+
else
|
|
89
|
+
for (const entry of value)
|
|
90
|
+
query.push([name, text(entry)]);
|
|
91
|
+
}
|
|
92
|
+
const headers = {};
|
|
93
|
+
if (options.idempotencyKey !== undefined)
|
|
94
|
+
headers[headerName(operation, operationId, "Idempotency-Key", "idempotencyKey")] = options.idempotencyKey;
|
|
95
|
+
if (options.ifMatch !== undefined) {
|
|
96
|
+
const etag = typeof options.ifMatch === "string" ? options.ifMatch : options.ifMatch.etag;
|
|
97
|
+
if (!etag)
|
|
98
|
+
throw new TrackenUsageError(`ifMatch for ${operationId} names no ETag: the read it came from answered none.`);
|
|
99
|
+
headers[headerName(operation, operationId, "If-Match", "ifMatch")] = etag;
|
|
100
|
+
}
|
|
101
|
+
if (options.onBehalfOf !== undefined)
|
|
102
|
+
headers[headerName(operation, operationId, "Tracken-On-Behalf-Of", "onBehalfOf")] = options.onBehalfOf;
|
|
103
|
+
const request = { method: operation.method, path: operation.path, pathParams, query, headers, operation: { operationId, organization: operation.organization } };
|
|
104
|
+
if (options.organizationId !== undefined)
|
|
105
|
+
request.organization = options.organizationId;
|
|
106
|
+
if (options.signal)
|
|
107
|
+
request.signal = options.signal;
|
|
108
|
+
if (given.body !== undefined) {
|
|
109
|
+
if (!operation.body)
|
|
110
|
+
throw new TrackenUsageError(`${operationId} takes no request body.`);
|
|
111
|
+
if (operation.body === "multipart") {
|
|
112
|
+
if (given.body instanceof FormData)
|
|
113
|
+
request.body = given.body;
|
|
114
|
+
else if (typeof given.body === "object" && given.body !== null)
|
|
115
|
+
request.body = formOf(given.body);
|
|
116
|
+
else
|
|
117
|
+
throw new TrackenUsageError(`${operationId} uploads a form: pass FormData or an object of its fields.`);
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
if (operation.decimals)
|
|
121
|
+
assertDecimalStrings(given.body, operation.decimals, operationId);
|
|
122
|
+
request.body = given.body;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return request;
|
|
126
|
+
}
|
|
127
|
+
function typed(response) {
|
|
128
|
+
return {
|
|
129
|
+
body: response.body,
|
|
130
|
+
status: response.status,
|
|
131
|
+
headers: response.headers,
|
|
132
|
+
contentType: response.contentType,
|
|
133
|
+
requestId: response.requestId,
|
|
134
|
+
etag: response.headers.get("etag") ?? undefined,
|
|
135
|
+
location: response.headers.get("location") ?? undefined,
|
|
136
|
+
dryRun: response.dryRun,
|
|
137
|
+
nextSince: nextSince(response.body),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
|
141
|
+
export class Tracken {
|
|
142
|
+
/** The transport, for raw requests (`client.send`) and the typed openapi-fetch client (`client.http`). */
|
|
143
|
+
client;
|
|
144
|
+
/** The request and raw answer behind each typed response, so `waitForJob` can follow it. */
|
|
145
|
+
sent = new WeakMap();
|
|
146
|
+
constructor(options) {
|
|
147
|
+
const environment = ENVIRONMENTS[options.environment ?? "prod"];
|
|
148
|
+
if (!environment)
|
|
149
|
+
throw new TrackenUsageError(`Unknown environment "${String(options.environment)}"; use prod or dev.`);
|
|
150
|
+
this.client = new TrackenClient({
|
|
151
|
+
baseUrl: (options.baseUrl ?? environment.apiBaseUrl).replace(/\/+$/, ""),
|
|
152
|
+
credentials: credentialsOf(options),
|
|
153
|
+
organizationId: options.organizationId,
|
|
154
|
+
language: options.language,
|
|
155
|
+
...(options.fetch && { fetch: options.fetch }),
|
|
156
|
+
...(options.clock && { clock: options.clock }),
|
|
157
|
+
...(options.maxRetries !== undefined && { maxRetries: options.maxRetries }),
|
|
158
|
+
...(options.userAgent && { userAgent: options.userAgent }),
|
|
159
|
+
...(options.agent && { agent: options.agent }),
|
|
160
|
+
debug: options.debug,
|
|
161
|
+
});
|
|
162
|
+
const namespaces = {};
|
|
163
|
+
for (const [operationId, operation] of Object.entries(table)) {
|
|
164
|
+
(namespaces[operation.resource] ??= {})[operation.name] = (input, callOptions) => this.call(operationId, ...[input, callOptions]);
|
|
165
|
+
}
|
|
166
|
+
Object.assign(this, namespaces);
|
|
167
|
+
}
|
|
168
|
+
/** The typed openapi-fetch client: token and headers added, no retries. */
|
|
169
|
+
get http() {
|
|
170
|
+
return this.client.http;
|
|
171
|
+
}
|
|
172
|
+
/** Calls any operation by its id: `tracken.call("issueSalesInvoice", { path: { id } })`. */
|
|
173
|
+
async call(operationId, ...[input, options]) {
|
|
174
|
+
const request = requestFor(operationId, input, options);
|
|
175
|
+
const response = await this.client.send(request);
|
|
176
|
+
const result = typed(response);
|
|
177
|
+
this.sent.set(result, { request, response });
|
|
178
|
+
return result;
|
|
179
|
+
}
|
|
180
|
+
/** Every page of a list, one at a time, following `meta.pagination.next_cursor`. */
|
|
181
|
+
async *pages(operationId, ...[input, options]) {
|
|
182
|
+
for await (const page of rawPages(this.client, requestFor(operationId, input, options)))
|
|
183
|
+
yield typed(page);
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Every record of a list across all its pages, fetched a page at a time as you iterate:
|
|
187
|
+
* `for await (const invoice of tracken.paginate("listSalesInvoices", { query: { status: ["issued"] } }))`.
|
|
188
|
+
*/
|
|
189
|
+
async *paginate(operationId, ...args) {
|
|
190
|
+
for await (const page of this.pages(operationId, ...args))
|
|
191
|
+
yield* pageItems(page.body);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Waits for the job a `202 Accepted` answer started (a billing run, a bank statement import) and
|
|
195
|
+
* answers its final state; throws `TrackenJobFailedError` if it failed.
|
|
196
|
+
*/
|
|
197
|
+
async waitForJob(accepted, options = {}) {
|
|
198
|
+
const sent = this.sent.get(accepted);
|
|
199
|
+
if (!sent)
|
|
200
|
+
throw new TrackenUsageError("waitForJob takes a response this client answered.");
|
|
201
|
+
return typed(await waitFor(this.client, sent.response, sent.request, options));
|
|
202
|
+
}
|
|
203
|
+
}
|