@tracken/cli 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +376 -0
- package/LICENSE +21 -0
- package/README.md +307 -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 +87 -0
- package/dist/core/errors.js +226 -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 +91 -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 +72 -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 +126 -0
- package/node_modules/@tracken/sdk/dist/errors.js +165 -0
- package/node_modules/@tracken/sdk/dist/generated/operations.d.ts +1955 -0
- package/node_modules/@tracken/sdk/dist/generated/operations.js +2745 -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 +30513 -0
- package/package.json +63 -4
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The transport every Tracken client shares (the SDK's typed methods, the CLI and its MCP server):
|
|
3
|
+
* requests go through openapi-fetch with the credential's bearer token, the organization header for a
|
|
4
|
+
* person, a User-Agent and `Tracken-Agent`, an automatic Idempotency-Key on every POST (the same key
|
|
5
|
+
* on the client's own retries), `Retry-After` on 429 and backoff on a gateway error. A rendition's 303
|
|
6
|
+
* is followed to its pre-signed link without any of those credentials.
|
|
7
|
+
*
|
|
8
|
+
* A 401 is never masked: the client renews once (a person's refresh, or a fresh client-credentials
|
|
9
|
+
* token) and retries; a second 401, or a renewal Tracken ID refuses, is thrown as the API's own 401
|
|
10
|
+
* (`TrackenUnauthenticatedError`, with the refusal as `renewalError`). The credentials a client is
|
|
11
|
+
* built with are the only ones it ever uses.
|
|
12
|
+
*/
|
|
13
|
+
import createClient, {} from "openapi-fetch";
|
|
14
|
+
import { apiError, TrackenAuthError, TrackenError, TrackenNetworkError, TrackenUsageError } from "./errors.js";
|
|
15
|
+
import { serializeQuery } from "./request.js";
|
|
16
|
+
import { AGENT_HEADER, systemClock, userAgent } from "./runtime.js";
|
|
17
|
+
import { SDK_VERSION } from "./version.js";
|
|
18
|
+
/** A 429 asking for longer than this is reported rather than slept through. */
|
|
19
|
+
const MAX_RETRY_AFTER_S = 120;
|
|
20
|
+
const GATEWAY_ERRORS = new Set([502, 503, 504]);
|
|
21
|
+
/** The organization header is credentials, never a parameter: a person's token always names one. */
|
|
22
|
+
export const ORGANIZATION_HEADER = "X-Organization-ID";
|
|
23
|
+
function parseRetryAfter(value, now) {
|
|
24
|
+
if (!value)
|
|
25
|
+
return undefined;
|
|
26
|
+
const seconds = Number(value);
|
|
27
|
+
if (Number.isFinite(seconds))
|
|
28
|
+
return Math.max(0, seconds);
|
|
29
|
+
const date = Date.parse(value);
|
|
30
|
+
return Number.isNaN(date) ? undefined : Math.max(0, (date - now) / 1000);
|
|
31
|
+
}
|
|
32
|
+
const hasHeader = (headers, name) => Object.keys(headers).some((key) => key.toLowerCase() === name.toLowerCase());
|
|
33
|
+
/** A fresh `Idempotency-Key`: a random UUID, from the platform's Web Crypto. */
|
|
34
|
+
export function newIdempotencyKey() {
|
|
35
|
+
return globalThis.crypto.randomUUID();
|
|
36
|
+
}
|
|
37
|
+
export class TrackenClient {
|
|
38
|
+
options;
|
|
39
|
+
/**
|
|
40
|
+
* The typed openapi-fetch client, for callers that know their operation at compile time: it adds
|
|
41
|
+
* the token, User-Agent and organization header, but neither retries nor renews; `send` does both.
|
|
42
|
+
*/
|
|
43
|
+
http;
|
|
44
|
+
/** `send`'s own client: no middleware, since `send` sets every header itself per attempt. */
|
|
45
|
+
transport;
|
|
46
|
+
maxRetries;
|
|
47
|
+
clock;
|
|
48
|
+
userAgent;
|
|
49
|
+
agent;
|
|
50
|
+
constructor(options) {
|
|
51
|
+
this.options = options;
|
|
52
|
+
const fetchFn = (request) => (options.fetch ?? fetch)(request);
|
|
53
|
+
this.http = createClient({ baseUrl: options.baseUrl, fetch: fetchFn });
|
|
54
|
+
this.http.use(this.authMiddleware());
|
|
55
|
+
this.transport = createClient({ baseUrl: options.baseUrl, fetch: fetchFn });
|
|
56
|
+
this.maxRetries = options.maxRetries ?? 3;
|
|
57
|
+
this.clock = options.clock ?? systemClock;
|
|
58
|
+
this.userAgent = options.userAgent ?? userAgent();
|
|
59
|
+
this.agent = options.agent ?? `tracken-sdk/${SDK_VERSION}`;
|
|
60
|
+
}
|
|
61
|
+
get credentials() {
|
|
62
|
+
return this.options.credentials;
|
|
63
|
+
}
|
|
64
|
+
get baseUrl() {
|
|
65
|
+
return this.options.baseUrl;
|
|
66
|
+
}
|
|
67
|
+
/** For `http` users: the token, User-Agent and organization header on every request. */
|
|
68
|
+
authMiddleware() {
|
|
69
|
+
return {
|
|
70
|
+
onRequest: async ({ request }) => {
|
|
71
|
+
request.headers.set("Authorization", `Bearer ${await this.options.credentials.accessToken()}`);
|
|
72
|
+
request.headers.set("User-Agent", this.userAgent);
|
|
73
|
+
if (!request.headers.has(AGENT_HEADER))
|
|
74
|
+
request.headers.set(AGENT_HEADER, this.agent);
|
|
75
|
+
if (this.options.language && !request.headers.has("Accept-Language"))
|
|
76
|
+
request.headers.set("Accept-Language", this.options.language);
|
|
77
|
+
if (this.options.credentials.kind === "user" && this.options.organizationId && !request.headers.has(ORGANIZATION_HEADER)) {
|
|
78
|
+
request.headers.set(ORGANIZATION_HEADER, this.options.organizationId);
|
|
79
|
+
}
|
|
80
|
+
return request;
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
organizationFor(request) {
|
|
85
|
+
if (this.options.credentials.kind !== "user")
|
|
86
|
+
return undefined;
|
|
87
|
+
if (request.organization === null)
|
|
88
|
+
return undefined;
|
|
89
|
+
const organization = request.organization ?? this.options.organizationId;
|
|
90
|
+
if (!organization && request.operation?.organization) {
|
|
91
|
+
throw new TrackenUsageError(this.options.missingOrganizationMessage ??
|
|
92
|
+
`${request.operation.operationId} acts in one organization: set organizationId (sent as ${ORGANIZATION_HEADER}) for a person's token.`);
|
|
93
|
+
}
|
|
94
|
+
return organization;
|
|
95
|
+
}
|
|
96
|
+
retryable(method, headers) {
|
|
97
|
+
return method === "GET" || method === "PUT" || method === "DELETE" || hasHeader(headers, "Idempotency-Key");
|
|
98
|
+
}
|
|
99
|
+
backoff(attempt) {
|
|
100
|
+
return Math.min(8000, 500 * 2 ** (attempt - 1));
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Sends a request and answers its success, or throws a `TrackenApiError` for a non-2xx answer once
|
|
104
|
+
* retries are spent. `organization: null` leaves the organization header off.
|
|
105
|
+
*/
|
|
106
|
+
async send(request) {
|
|
107
|
+
const method = request.method.toUpperCase();
|
|
108
|
+
const headers = { ...request.headers };
|
|
109
|
+
if (method === "POST" && !hasHeader(headers, "Idempotency-Key"))
|
|
110
|
+
headers["Idempotency-Key"] = newIdempotencyKey();
|
|
111
|
+
const organization = this.organizationFor(request);
|
|
112
|
+
const call = this.transport.request;
|
|
113
|
+
const query = serializeQuery(request.query);
|
|
114
|
+
let renewed = false;
|
|
115
|
+
let attempt = 0;
|
|
116
|
+
for (;;) {
|
|
117
|
+
request.signal?.throwIfAborted();
|
|
118
|
+
const token = await this.options.credentials.accessToken();
|
|
119
|
+
const sent = { ...headers, Authorization: `Bearer ${token}`, "User-Agent": this.userAgent };
|
|
120
|
+
if (!hasHeader(sent, AGENT_HEADER))
|
|
121
|
+
sent[AGENT_HEADER] = this.agent;
|
|
122
|
+
if (organization)
|
|
123
|
+
sent[ORGANIZATION_HEADER] = organization;
|
|
124
|
+
if (this.options.language && !hasHeader(sent, "Accept-Language"))
|
|
125
|
+
sent["Accept-Language"] = this.options.language;
|
|
126
|
+
const started = this.clock.now();
|
|
127
|
+
this.options.debug?.(`→ ${method} ${this.options.baseUrl}${request.path}${query ? `?${query}` : ""}`);
|
|
128
|
+
let result;
|
|
129
|
+
try {
|
|
130
|
+
const init = {
|
|
131
|
+
params: { path: request.pathParams },
|
|
132
|
+
headers: sent,
|
|
133
|
+
body: request.body,
|
|
134
|
+
querySerializer: () => query,
|
|
135
|
+
bodySerializer: (body) => (body instanceof FormData ? body : JSON.stringify(body)),
|
|
136
|
+
parseAs: "arrayBuffer",
|
|
137
|
+
// A redirect is never followed with the token: see `download`.
|
|
138
|
+
redirect: "manual",
|
|
139
|
+
};
|
|
140
|
+
if (request.signal)
|
|
141
|
+
init.signal = request.signal;
|
|
142
|
+
result = await call(method, request.path, init);
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (error instanceof TrackenError)
|
|
146
|
+
throw error;
|
|
147
|
+
request.signal?.throwIfAborted();
|
|
148
|
+
if (attempt < this.maxRetries && this.retryable(method, headers)) {
|
|
149
|
+
attempt++;
|
|
150
|
+
await this.clock.sleep(this.backoff(attempt));
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
throw new TrackenNetworkError(`Could not reach ${new URL(this.options.baseUrl).origin}: ${error.message}`, error);
|
|
154
|
+
}
|
|
155
|
+
const { response } = result;
|
|
156
|
+
const requestId = response.headers.get("x-request-id") ?? undefined;
|
|
157
|
+
this.options.debug?.(`← ${response.status} in ${this.clock.now() - started} ms${requestId ? ` (${requestId})` : ""}`);
|
|
158
|
+
if (response.status === 401) {
|
|
159
|
+
const refused = apiError(401, result.error, response.headers);
|
|
160
|
+
if (renewed)
|
|
161
|
+
throw refused;
|
|
162
|
+
renewed = true;
|
|
163
|
+
this.options.debug?.(` 401: renewing the ${this.options.credentials.kind === "machine" ? "client-credentials token" : "session (refresh)"} once`);
|
|
164
|
+
try {
|
|
165
|
+
await this.options.credentials.renew(token);
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
// Tracken ID refused the renewal: the session ended or the credential is gone. Network
|
|
169
|
+
// failures and other errors keep their own type.
|
|
170
|
+
if (!(this.options.isRenewalRefusal ?? ((value) => value instanceof TrackenAuthError))(error))
|
|
171
|
+
throw error;
|
|
172
|
+
this.options.debug?.(` renewal refused: ${error.message}`);
|
|
173
|
+
refused.renewalError = error;
|
|
174
|
+
throw refused;
|
|
175
|
+
}
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (response.status === 429 && attempt < this.maxRetries) {
|
|
179
|
+
const wait = parseRetryAfter(response.headers.get("retry-after"), this.clock.now()) ?? this.backoff(attempt + 1) / 1000;
|
|
180
|
+
if (wait <= MAX_RETRY_AFTER_S) {
|
|
181
|
+
attempt++;
|
|
182
|
+
this.options.debug?.(` rate limited; retrying in ${wait} s`);
|
|
183
|
+
await this.clock.sleep(wait * 1000);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (GATEWAY_ERRORS.has(response.status) && attempt < this.maxRetries && this.retryable(method, headers)) {
|
|
188
|
+
attempt++;
|
|
189
|
+
await this.clock.sleep(this.backoff(attempt));
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
if (response.status === 303)
|
|
193
|
+
return await this.download(response, requestId, request.signal);
|
|
194
|
+
if (!response.ok)
|
|
195
|
+
throw apiError(response.status, result.error, response.headers);
|
|
196
|
+
return answer(response.status, response.headers, result.data instanceof ArrayBuffer ? new Uint8Array(result.data) : undefined, requestId);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* A rendition (`format=pdf`) answers 303 with a short-lived pre-signed link to the file. The link
|
|
201
|
+
* carries its own signature, so it is fetched with neither the token nor the organization header
|
|
202
|
+
* (a storage service refuses a second credential, and the token must not leave the API). The link
|
|
203
|
+
* is itself a credential while it lives: messages name its origin only.
|
|
204
|
+
*/
|
|
205
|
+
async download(redirect, requestId, signal) {
|
|
206
|
+
const location = redirect.headers.get("location");
|
|
207
|
+
let url;
|
|
208
|
+
try {
|
|
209
|
+
url = location ? new URL(location, redirect.url || this.options.baseUrl) : undefined;
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
url = undefined;
|
|
213
|
+
}
|
|
214
|
+
if (!url || (url.protocol !== "https:" && url.protocol !== "http:")) {
|
|
215
|
+
throw new TrackenError(`The API answered 303 without a usable Location${requestId ? ` (request id ${requestId})` : ""}.`);
|
|
216
|
+
}
|
|
217
|
+
this.options.debug?.(`→ GET ${url.origin}${url.pathname} (pre-signed link)`);
|
|
218
|
+
let file;
|
|
219
|
+
try {
|
|
220
|
+
const init = { headers: { "User-Agent": this.userAgent } };
|
|
221
|
+
if (signal)
|
|
222
|
+
init.signal = signal;
|
|
223
|
+
file = await (this.options.fetch ?? fetch)(url.href, init);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
signal?.throwIfAborted();
|
|
227
|
+
throw new TrackenNetworkError(`Could not download the file from ${url.origin}: ${error.message}`, error);
|
|
228
|
+
}
|
|
229
|
+
if (!file.ok) {
|
|
230
|
+
throw new TrackenError(`Downloading the file from ${url.origin} failed with ${file.status}; the link may have expired, so run the request again.`);
|
|
231
|
+
}
|
|
232
|
+
return answer(file.status, file.headers, new Uint8Array(await file.arrayBuffer()), requestId);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
/** A success: JSON parsed, other content (a PDF, a KMD file) kept as bytes. */
|
|
236
|
+
function answer(status, headers, bytes, requestId) {
|
|
237
|
+
const contentType = headers.get("content-type") ?? "";
|
|
238
|
+
const isJson = /\bjson\b/i.test(contentType);
|
|
239
|
+
let body = bytes;
|
|
240
|
+
if (bytes && (isJson || bytes.length === 0)) {
|
|
241
|
+
const text = new TextDecoder().decode(bytes);
|
|
242
|
+
try {
|
|
243
|
+
body = text ? JSON.parse(text) : undefined;
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
body = text;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return {
|
|
250
|
+
status,
|
|
251
|
+
headers,
|
|
252
|
+
body,
|
|
253
|
+
contentType,
|
|
254
|
+
binary: bytes !== undefined && !isJson && bytes.length > 0,
|
|
255
|
+
requestId,
|
|
256
|
+
dryRun: headers.get("tracken-dry-run")?.toLowerCase() === "true",
|
|
257
|
+
};
|
|
258
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { type Clock, type Fetch } from "./runtime.js";
|
|
2
|
+
export interface Credentials {
|
|
3
|
+
/** A person acts in the organization the client names; a machine token carries its own. */
|
|
4
|
+
readonly kind: "user" | "machine";
|
|
5
|
+
/** A token valid for at least the next minute. */
|
|
6
|
+
accessToken(): Promise<string>;
|
|
7
|
+
/** After the API answered 401 to `rejected`: obtain a new token, or throw. */
|
|
8
|
+
renew(rejected: string): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* A token the caller manages (a person's access token, or one minted elsewhere). It is never
|
|
12
|
+
* renewed, so a 401 surfaces as `TrackenUnauthenticatedError`. Pass a function to read the current
|
|
13
|
+
* token on every request.
|
|
14
|
+
*/
|
|
15
|
+
export declare function staticToken(token: string | (() => string | Promise<string>), kind?: Credentials["kind"]): Credentials;
|
|
16
|
+
export interface TokenResponse {
|
|
17
|
+
access_token: string;
|
|
18
|
+
token_type: string;
|
|
19
|
+
expires_in?: number;
|
|
20
|
+
refresh_token?: string;
|
|
21
|
+
scope?: string;
|
|
22
|
+
id_token?: string;
|
|
23
|
+
}
|
|
24
|
+
/** A JWT's claims, unverified: only to know when it lapses, never to trust. */
|
|
25
|
+
export declare function jwtClaims(token: string): Record<string, unknown>;
|
|
26
|
+
/** When a JWT access token lapses (epoch ms), from its `exp` claim. */
|
|
27
|
+
export declare function jwtExpiry(token: string): number | undefined;
|
|
28
|
+
/** Renew this long before the access token lapses, so a request never leaves with a dying token. */
|
|
29
|
+
export declare const EXPIRY_SKEW_MS = 60000;
|
|
30
|
+
/** When `tokens` lapse (epoch ms): the sooner of `expires_in` and the token's own `exp`. */
|
|
31
|
+
export declare function tokenExpiry(tokens: TokenResponse, now: number): number;
|
|
32
|
+
export interface ClientCredentialsOptions {
|
|
33
|
+
/** Tracken ID (`https://id.tracken.ee`). */
|
|
34
|
+
issuer: string;
|
|
35
|
+
/** The resource the token is for: the API's integration audience. */
|
|
36
|
+
audience: string;
|
|
37
|
+
clientId: string;
|
|
38
|
+
clientSecret: string;
|
|
39
|
+
/** Space-separated scopes; absent asks for everything the credential holds. */
|
|
40
|
+
scope?: string | undefined;
|
|
41
|
+
fetch?: Fetch;
|
|
42
|
+
clock?: Clock;
|
|
43
|
+
userAgent?: string;
|
|
44
|
+
}
|
|
45
|
+
/** A machine credential: client-credentials tokens from Tracken ID, in memory only. */
|
|
46
|
+
export declare class ClientCredentials implements Credentials {
|
|
47
|
+
private readonly options;
|
|
48
|
+
readonly kind = "machine";
|
|
49
|
+
private token;
|
|
50
|
+
private expires;
|
|
51
|
+
private pending;
|
|
52
|
+
constructor(options: ClientCredentialsOptions);
|
|
53
|
+
get clientId(): string;
|
|
54
|
+
private now;
|
|
55
|
+
/** One token request at a time: concurrent callers share it rather than each minting their own. */
|
|
56
|
+
private issue;
|
|
57
|
+
private request;
|
|
58
|
+
accessToken(): Promise<string>;
|
|
59
|
+
renew(rejected: string): Promise<void>;
|
|
60
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who a client acts as. A machine credential (an API key created in Accounts under Settings → API
|
|
3
|
+
* access) is exchanged at Tracken ID for a short-lived token (OAuth 2.0 client credentials), kept in
|
|
4
|
+
* memory and renewed as it nears expiry; a person's token is obtained elsewhere (Tracken ID sign-in,
|
|
5
|
+
* the CLI's device flow) and handed in as is.
|
|
6
|
+
*/
|
|
7
|
+
import { TrackenAuthError, TrackenNetworkError } from "./errors.js";
|
|
8
|
+
import { systemClock, userAgent } from "./runtime.js";
|
|
9
|
+
/**
|
|
10
|
+
* A token the caller manages (a person's access token, or one minted elsewhere). It is never
|
|
11
|
+
* renewed, so a 401 surfaces as `TrackenUnauthenticatedError`. Pass a function to read the current
|
|
12
|
+
* token on every request.
|
|
13
|
+
*/
|
|
14
|
+
export function staticToken(token, kind = "machine") {
|
|
15
|
+
return {
|
|
16
|
+
kind,
|
|
17
|
+
accessToken: async () => (typeof token === "function" ? await token() : token),
|
|
18
|
+
renew: async () => { },
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** A JWT's claims, unverified: only to know when it lapses, never to trust. */
|
|
22
|
+
export function jwtClaims(token) {
|
|
23
|
+
const payload = token.split(".")[1];
|
|
24
|
+
if (!payload)
|
|
25
|
+
return {};
|
|
26
|
+
try {
|
|
27
|
+
const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
|
|
28
|
+
const bytes = Uint8Array.from(atob(base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=")), (char) => char.charCodeAt(0));
|
|
29
|
+
const claims = JSON.parse(new TextDecoder().decode(bytes));
|
|
30
|
+
return typeof claims === "object" && claims !== null ? claims : {};
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return {};
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** When a JWT access token lapses (epoch ms), from its `exp` claim. */
|
|
37
|
+
export function jwtExpiry(token) {
|
|
38
|
+
const exp = jwtClaims(token).exp;
|
|
39
|
+
return typeof exp === "number" ? exp * 1000 : undefined;
|
|
40
|
+
}
|
|
41
|
+
/** Renew this long before the access token lapses, so a request never leaves with a dying token. */
|
|
42
|
+
export const EXPIRY_SKEW_MS = 60_000;
|
|
43
|
+
/** Tracken ID's access tokens for Accounts last 15 minutes; used when a response names no lifetime. */
|
|
44
|
+
const DEFAULT_LIFETIME_MS = 15 * 60_000;
|
|
45
|
+
/** When `tokens` lapse (epoch ms): the sooner of `expires_in` and the token's own `exp`. */
|
|
46
|
+
export function tokenExpiry(tokens, now) {
|
|
47
|
+
const fromResponse = typeof tokens.expires_in === "number" ? now + tokens.expires_in * 1000 : undefined;
|
|
48
|
+
const fromToken = jwtExpiry(tokens.access_token);
|
|
49
|
+
const known = [fromResponse, fromToken].filter((value) => value !== undefined);
|
|
50
|
+
return known.length > 0 ? Math.min(...known) : now + DEFAULT_LIFETIME_MS;
|
|
51
|
+
}
|
|
52
|
+
/** A machine credential: client-credentials tokens from Tracken ID, in memory only. */
|
|
53
|
+
export class ClientCredentials {
|
|
54
|
+
options;
|
|
55
|
+
kind = "machine";
|
|
56
|
+
token;
|
|
57
|
+
expires = 0;
|
|
58
|
+
pending;
|
|
59
|
+
constructor(options) {
|
|
60
|
+
this.options = options;
|
|
61
|
+
}
|
|
62
|
+
get clientId() {
|
|
63
|
+
return this.options.clientId;
|
|
64
|
+
}
|
|
65
|
+
now() {
|
|
66
|
+
return (this.options.clock ?? systemClock).now();
|
|
67
|
+
}
|
|
68
|
+
/** One token request at a time: concurrent callers share it rather than each minting their own. */
|
|
69
|
+
issue() {
|
|
70
|
+
this.pending ??= this.request().finally(() => {
|
|
71
|
+
this.pending = undefined;
|
|
72
|
+
});
|
|
73
|
+
return this.pending;
|
|
74
|
+
}
|
|
75
|
+
async request() {
|
|
76
|
+
const { issuer, audience, clientId, clientSecret, scope } = this.options;
|
|
77
|
+
const url = `${issuer.replace(/\/+$/, "")}/token`;
|
|
78
|
+
const form = { grant_type: "client_credentials", resource: audience };
|
|
79
|
+
if (scope)
|
|
80
|
+
form.scope = scope;
|
|
81
|
+
// RFC 6749 §2.3.1: the id and secret are form-encoded before the Basic encoding.
|
|
82
|
+
const pair = `${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`;
|
|
83
|
+
const headers = {
|
|
84
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
85
|
+
accept: "application/json",
|
|
86
|
+
"user-agent": this.options.userAgent ?? userAgent(),
|
|
87
|
+
authorization: `Basic ${btoa(pair)}`,
|
|
88
|
+
};
|
|
89
|
+
let response;
|
|
90
|
+
try {
|
|
91
|
+
response = await (this.options.fetch ?? fetch)(url, { method: "POST", headers, body: new URLSearchParams(form) });
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
throw new TrackenNetworkError(`Could not reach Tracken ID at ${new URL(url).origin}: ${error.message}`, error);
|
|
95
|
+
}
|
|
96
|
+
const text = await response.text();
|
|
97
|
+
let body;
|
|
98
|
+
try {
|
|
99
|
+
body = text ? JSON.parse(text) : {};
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
body = { error: "invalid_response", error_description: `HTTP ${response.status} from ${new URL(url).pathname}: ${text.slice(0, 200)}` };
|
|
103
|
+
}
|
|
104
|
+
if (response.status !== 200 || typeof body.access_token !== "string") {
|
|
105
|
+
const code = typeof body.error === "string" ? body.error : `http_${response.status}`;
|
|
106
|
+
throw new TrackenAuthError(code, typeof body.error_description === "string" ? body.error_description : undefined, response.status);
|
|
107
|
+
}
|
|
108
|
+
const tokens = body;
|
|
109
|
+
this.token = tokens.access_token;
|
|
110
|
+
this.expires = tokenExpiry(tokens, this.now());
|
|
111
|
+
return this.token;
|
|
112
|
+
}
|
|
113
|
+
async accessToken() {
|
|
114
|
+
if (this.token && this.now() < this.expires - EXPIRY_SKEW_MS)
|
|
115
|
+
return this.token;
|
|
116
|
+
return this.issue();
|
|
117
|
+
}
|
|
118
|
+
async renew(rejected) {
|
|
119
|
+
if (this.token === rejected || this.token === undefined)
|
|
120
|
+
await this.issue();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { DECIMAL_PATTERNS } from "./generated/operations.js";
|
|
2
|
+
/**
|
|
3
|
+
* The document's decimal schemas: `MoneyAmount` (2 places), `UnitPrice` and `Quantity` (4), a billing
|
|
4
|
+
* run's `VariableDecimal` (6), `LineDecimal` (10) and the positive `ExchangeRate` (10).
|
|
5
|
+
*/
|
|
6
|
+
export type DecimalFormat = keyof typeof DECIMAL_PATTERNS;
|
|
7
|
+
/** Whether `value` is a decimal string the API accepts as `format` (default `MoneyAmount`). */
|
|
8
|
+
export declare function isDecimal(value: unknown, format?: DecimalFormat): value is string;
|
|
9
|
+
/**
|
|
10
|
+
* Integer minor units of a decimal string: `toMinorUnits("1234.50")` is `123450n`. Refuses a value
|
|
11
|
+
* with more fraction digits than `scale` rather than rounding it.
|
|
12
|
+
*/
|
|
13
|
+
export declare function toMinorUnits(value: string, scale?: number): bigint;
|
|
14
|
+
/** The decimal string of integer minor units: `fromMinorUnits(123450n)` is `"1234.50"`. */
|
|
15
|
+
export declare function fromMinorUnits(minor: bigint | number, scale?: number): string;
|
|
16
|
+
/**
|
|
17
|
+
* Throws `TrackenUsageError` when the body holds a number at any of the operation's decimal
|
|
18
|
+
* pointers (such as `/data/lines/<any index>/unit_price`).
|
|
19
|
+
*/
|
|
20
|
+
export declare function assertDecimalStrings(body: unknown, pointers: readonly string[], operationId: string): void;
|
|
@@ -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
|
+
};
|