@tribulnation/terminal 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +231 -2
- package/dist/answer.d.ts +3 -0
- package/dist/answer.js +1 -0
- package/dist/client.d.ts +73 -0
- package/dist/client.js +218 -0
- package/dist/errors.d.ts +76 -0
- package/dist/errors.js +143 -0
- package/dist/index.d.ts +51 -0
- package/dist/index.js +58 -0
- package/dist/live.d.ts +74 -0
- package/dist/live.js +60 -0
- package/dist/livestream.d.ts +99 -0
- package/dist/livestream.js +390 -0
- package/dist/me.d.ts +66 -0
- package/dist/me.js +34 -0
- package/dist/pages.d.ts +21 -0
- package/dist/pages.js +35 -0
- package/dist/types.gen.d.ts +5716 -0
- package/dist/types.gen.js +24 -0
- package/dist/v1.d.ts +154 -0
- package/dist/v1.js +113 -0
- package/dist/v2.d.ts +75 -0
- package/dist/v2.js +25 -0
- package/package.json +55 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tribulnation
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,232 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tribulnation/terminal
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Typed TypeScript client for the [Tribulnation Terminal API](https://api.tribulnation.com/docs):
|
|
4
|
+
your portfolio (`/me`), market data (`/v1`, `/v2`) and live order books and funding
|
|
5
|
+
(`/live`, including the WebSocket). Read-only. No runtime dependencies.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm i @tribulnation/terminal
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
You need an API key (`tn_key_…`). Create one on [/integrations](https://app.tribulnation.com/integrations).
|
|
12
|
+
`/me` works on every plan with the `me:read` scope. Market data (`/v1`, `/v2`, `/live`) needs
|
|
13
|
+
`market:read`, which comes with Ultra.
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { Terminal } from '@tribulnation/terminal'
|
|
19
|
+
|
|
20
|
+
const t = new Terminal() // reads TN_API_KEY (and TN_API_BASE, if set)
|
|
21
|
+
|
|
22
|
+
const prices = await t.v1.prices.latest({ assets: ['bitcoin', 'ethereum'] })
|
|
23
|
+
for (const p of prices.data) console.log(p.asset_id, p.price) // price: string | null
|
|
24
|
+
|
|
25
|
+
const me = await t.me.get()
|
|
26
|
+
const week = await t.me.portfolio.get({ start: new Date(Date.now() - 7 * 86_400_000) })
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Pass the key yourself when it does not come from the environment:
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
const t = new Terminal({ apiKey: process.env.MY_KEY })
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## What you get back
|
|
36
|
+
|
|
37
|
+
Each method returns the JSON the API sends, typed from the API's own OpenAPI document. The
|
|
38
|
+
client does not convert anything at runtime:
|
|
39
|
+
|
|
40
|
+
- **Money and other decimals are strings** (`type Decimal = string`), as the API sends them,
|
|
41
|
+
so no precision is lost to floats. Parse them with the decimal library you already use.
|
|
42
|
+
- **Times are what the API sends.** That is ISO-8601 strings on `/v1` and `/v2` and epoch
|
|
43
|
+
milliseconds on `/me`.
|
|
44
|
+
- **Field names are the wire names.** Some are `snake_case` (`asset_id`, `observed_at`) and
|
|
45
|
+
some are `camelCase` (`marketCap`, `price24hAgo`).
|
|
46
|
+
|
|
47
|
+
The Python client (`pip install tribulnation-terminal`) validates answers into `Decimal`
|
|
48
|
+
and `datetime`. This package does not, so that it can stay free of dependencies.
|
|
49
|
+
|
|
50
|
+
The generated types are exported too, so you can type your own code:
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import type { LatestPrice, PerpFundingSettlementsRecord, Operations } from '@tribulnation/terminal'
|
|
54
|
+
|
|
55
|
+
type Funding = Operations['get_market_perps_funding_latest']['response']
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Arguments
|
|
59
|
+
|
|
60
|
+
- **Lists** take a string or an array and are sent as a comma list: `assets: 'bitcoin'` or
|
|
61
|
+
`assets: ['bitcoin', 'ethereum']`.
|
|
62
|
+
- **Times** take a `Date`, epoch milliseconds or a string. A string is sent unchanged.
|
|
63
|
+
`start` and `end` become the `from` and `to` each endpoint reads: a day (`2026-10-01`) for
|
|
64
|
+
prices, candles and earn history, an instant for funding history and `/v2`, and epoch
|
|
65
|
+
milliseconds for `/me`.
|
|
66
|
+
- An endpoint without a method yet is still reachable: `t.get(path, params)` sends any read to
|
|
67
|
+
`/me`, `/v1/…`, `/v2/…` or `/live/…` and returns the JSON as it came.
|
|
68
|
+
|
|
69
|
+
## Endpoints
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
// /me: your own data (me:read)
|
|
73
|
+
t.me.get() · t.me.accounts() · t.me.profiles() · t.me.position('bitcoin')
|
|
74
|
+
t.me.portfolio.get({ start, end, profile }) · t.me.portfolio.asset('bitcoin', { start })
|
|
75
|
+
t.me.portfolio.fills({ start, end, segments, cursor }) · .funding(…) · .transfers(…)
|
|
76
|
+
t.me.charts.list() · t.me.charts.get(id)
|
|
77
|
+
|
|
78
|
+
// /v1: market data (market:read, Ultra)
|
|
79
|
+
t.v1.assets.list({ search, categories, currency, sparkline, page, limit }) · t.v1.assets.get('bitcoin') · .summary('bitcoin') · .instruments('bitcoin')
|
|
80
|
+
t.v1.search('bitcoin')
|
|
81
|
+
t.v1.prices.latest({ assets }) · t.v1.prices.historical({ assets, start, end })
|
|
82
|
+
t.v1.candles({ asset, start, end, interval })
|
|
83
|
+
t.v1.market.tickers.latest({ assets, venues, kinds })
|
|
84
|
+
t.v1.market.perps.stats.latest({ assets, venues })
|
|
85
|
+
t.v1.market.perps.funding.latest({ assets }) · .historical({ assets, start, end, interval })
|
|
86
|
+
t.v1.earn.latest({ assets, venues, sort, stake }) · t.v1.earn.facets() · t.v1.earn.historical({ assets, start, end })
|
|
87
|
+
t.v1.venues.list() · .get('binance') · t.v1.networks.list() · .get('ethereum')
|
|
88
|
+
|
|
89
|
+
// /v2: published series and snapshots, typed per id
|
|
90
|
+
t.v2.series.list() · .get(id) · .data(id, { start, end, ...filters }) · .latest(id) · .instances(id)
|
|
91
|
+
t.v2.snapshots.list() · .get(id) · .data(id, { ...filters })
|
|
92
|
+
|
|
93
|
+
// /live: live market data (market:read, Ultra)
|
|
94
|
+
t.live.book('bitcoin', { depth }) · t.live.asset('bitcoin') · t.live.profile('bitcoin', { venue })
|
|
95
|
+
t.live.opportunities() · t.live.opportunities('bitcoin')
|
|
96
|
+
t.live.funding() · t.live.funding.history(pair) · t.live.funding.perps()
|
|
97
|
+
t.live.spreads.history(pair, { start, end }) · t.live.exchanges()
|
|
98
|
+
t.live.stream(topic, { depth, signal })
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
The [API reference](https://api.tribulnation.com/docs) describes every parameter and field.
|
|
102
|
+
|
|
103
|
+
`/v2` records are typed by series id:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
const page = await t.v2.series.data('perp.funding.settlements', {
|
|
107
|
+
assets: 'bitcoin',
|
|
108
|
+
venues: 'binance',
|
|
109
|
+
start: new Date(Date.now() - 7 * 86_400_000)
|
|
110
|
+
})
|
|
111
|
+
page.data[0]?.rate // number: PerpFundingSettlementsRecord
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## Pagination
|
|
115
|
+
|
|
116
|
+
`pages()` follows the cursor until the last page: `meta.page.next_cursor`, on every paged
|
|
117
|
+
route (`/v1`, `/v2`, `/me` and `/live`):
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { pages } from '@tribulnation/terminal'
|
|
121
|
+
|
|
122
|
+
for await (const page of pages(t.v1.candles, { asset: 'bitcoin', start: '2026-01-01', end: '2026-10-31' })) {
|
|
123
|
+
console.log(page.data.length)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// A read with a positional argument: wrap it.
|
|
127
|
+
for await (const page of pages((p) => t.v2.series.data('perp.funding.settlements', p), { asset: 'bitcoin' })) {
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## The live socket
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
const stop = new AbortController()
|
|
135
|
+
for await (const frame of t.live.stream('book:bitcoin', { depth: 10, signal: stop.signal })) {
|
|
136
|
+
if (frame.t === 'view') console.log(frame.books?.[0]?.bid)
|
|
137
|
+
else console.log('control:', frame.state) // 'stale' or 'reconnecting'
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
The topics are `book:<asset>`, `asset:<asset>`, `rates`, `rates:<c>` and `page:<strategy>[:<n>]`.
|
|
142
|
+
|
|
143
|
+
The server closes every socket within a minute (code 4001) so that it can check the key
|
|
144
|
+
and plan again. The stream reconnects at once, and nothing is lost: the first frame after a
|
|
145
|
+
reconnect is the topic's latest build. The stream also:
|
|
146
|
+
|
|
147
|
+
- sends `ping` every 20 s;
|
|
148
|
+
- backs off exponentially, up to 30 s, after any other drop;
|
|
149
|
+
- stops with `LiveClosed` on 4401 (the key was revoked), 4003 (the topic is not in your
|
|
150
|
+
plan) and 4004 (unknown topic).
|
|
151
|
+
|
|
152
|
+
If the upgrade is refused, the stream throws the matching `ApiError`. A refusal with 429 or
|
|
153
|
+
5xx is retried after its `Retry-After`.
|
|
154
|
+
|
|
155
|
+
`t.live.book()` and `t.live.asset()` start the build when nobody is watching the asset.
|
|
156
|
+
While it builds, the API answers 503 `warming`, and the client retries for up to
|
|
157
|
+
`wait` seconds (10 by default).
|
|
158
|
+
|
|
159
|
+
## Errors
|
|
160
|
+
|
|
161
|
+
Every API error is an `ApiError` with `status`, `code` (the closed `ApiErrorCode` set),
|
|
162
|
+
`message`, `details` (which parameter a 400 refused) and `retryAfter`. Each status has its
|
|
163
|
+
own subclass:
|
|
164
|
+
|
|
165
|
+
| Class | Status |
|
|
166
|
+
|---|---|
|
|
167
|
+
| `BadRequest` | 400 |
|
|
168
|
+
| `AuthError` | 401 |
|
|
169
|
+
| `Forbidden` (an `AuthError`) | 403 |
|
|
170
|
+
| `NotFound` | 404 |
|
|
171
|
+
| `RateLimited` | 429 |
|
|
172
|
+
| `Unavailable` | 502, 503, 504 |
|
|
173
|
+
| `ApiError` | anything else |
|
|
174
|
+
|
|
175
|
+
The client's own errors:
|
|
176
|
+
|
|
177
|
+
- `NetworkError`: the API was unreachable, timed out (60 s by default) or did not answer JSON.
|
|
178
|
+
- `Redirected` (a `NetworkError`): the client never follows a redirect, because the key
|
|
179
|
+
would go along with it.
|
|
180
|
+
- `NotLoggedIn` (an `AuthError`, status 401): no key was found; nothing was sent.
|
|
181
|
+
- `LiveClosed`: the socket was ended for good.
|
|
182
|
+
|
|
183
|
+
All of them extend `TerminalError`, and they nest as in the Python client: `instanceof
|
|
184
|
+
AuthError` catches a missing key, a refused key and a 403 alike.
|
|
185
|
+
|
|
186
|
+
The live stream retries drops for as long as you iterate. It gives up with a
|
|
187
|
+
`TerminalError` when it never opens in 5 tries, or when the runtime's `WebSocket` turns
|
|
188
|
+
out not to send the `Authorization` header; pass `{ webSocket }` (the `ws` package) then. Any messages that contain something shaped like a key have it cut out.
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
import { RateLimited } from '@tribulnation/terminal'
|
|
192
|
+
|
|
193
|
+
try {
|
|
194
|
+
await t.v1.prices.latest({ assets: 'bitcoin' })
|
|
195
|
+
} catch (e) {
|
|
196
|
+
if (e instanceof RateLimited) await new Promise((r) => setTimeout(r, (e.retryAfter ?? 1) * 1000))
|
|
197
|
+
else throw e
|
|
198
|
+
}
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
## Runtimes
|
|
202
|
+
|
|
203
|
+
| Runtime | REST | Live socket |
|
|
204
|
+
|---|---|---|
|
|
205
|
+
| Node 18, 20 | yes | with an injected WebSocket (`{ webSocket: WebSocket }` from the `ws` package) |
|
|
206
|
+
| Node 22+, Deno, Bun | yes | yes (global `WebSocket`) |
|
|
207
|
+
| Cloudflare Workers | yes | yes (fetch upgrade, detected) |
|
|
208
|
+
| Browsers | not supported | not supported |
|
|
209
|
+
|
|
210
|
+
Browsers are not supported. API keys are secrets, so the API sends no CORS headers, and a
|
|
211
|
+
browser WebSocket cannot send `Authorization`. Call the API from your server.
|
|
212
|
+
|
|
213
|
+
## Options
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
new Terminal({
|
|
217
|
+
apiKey, // default TN_API_KEY
|
|
218
|
+
baseUrl, // default TN_API_BASE, else https://api.tribulnation.com (https only; http only to localhost)
|
|
219
|
+
fetch, // default globalThis.fetch
|
|
220
|
+
webSocket, // a WebSocket constructor taking (url, { headers }), or 'fetch'
|
|
221
|
+
userAgent,
|
|
222
|
+
timeoutMs, // default 60 000
|
|
223
|
+
onLastAnswer // a portfolio read answered with the stored last answer; default console.warn once per path
|
|
224
|
+
})
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
The key is sent only in the `Authorization` header and only to `baseUrl`. It is never sent
|
|
228
|
+
over plain HTTP to another host.
|
|
229
|
+
|
|
230
|
+
## License
|
|
231
|
+
|
|
232
|
+
MIT
|
package/dist/answer.d.ts
ADDED
package/dist/answer.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { WebSocketLike } from './livestream.js';
|
|
2
|
+
/** The package version, sent in the user agent. */
|
|
3
|
+
export declare const VERSION = "0.1.2";
|
|
4
|
+
/** The API host when none is given and `TN_API_BASE` is unset. */
|
|
5
|
+
export declare const DEFAULT_BASE_URL = "https://api.tribulnation.com";
|
|
6
|
+
/** Portfolio reads recompute a window and can take tens of seconds. */
|
|
7
|
+
export declare const DEFAULT_TIMEOUT_MS = 60000;
|
|
8
|
+
/** One query value: a list is sent comma-joined, a boolean as `1`/`0`, a `Date` as
|
|
9
|
+
* ISO-8601 UTC; `null` and `undefined` are left out. */
|
|
10
|
+
export type QueryValue = string | number | boolean | Date | readonly (string | number)[] | null | undefined;
|
|
11
|
+
/** Query parameters by their wire name. */
|
|
12
|
+
export type Params = Record<string, QueryValue>;
|
|
13
|
+
/** An instant: a `Date`, epoch milliseconds, or a string sent as it is. */
|
|
14
|
+
export type Instant = Date | number | string;
|
|
15
|
+
export type TerminalOptions = {
|
|
16
|
+
/** A `tn_key_` API key (create one on /integrations). Default: `TN_API_KEY` from the
|
|
17
|
+
* environment; without one, the first call throws `NotLoggedIn`. */
|
|
18
|
+
apiKey?: string | undefined;
|
|
19
|
+
/** The API host. Default `TN_API_BASE`, else `https://api.tribulnation.com`. https only;
|
|
20
|
+
* plain http only to localhost. */
|
|
21
|
+
baseUrl?: string | undefined;
|
|
22
|
+
/** The `fetch` to use (default `globalThis.fetch`). */
|
|
23
|
+
fetch?: typeof fetch | undefined;
|
|
24
|
+
/** How the live socket is opened: a `WebSocket` constructor taking `(url, {headers})`
|
|
25
|
+
* (default the global one on Node 22+, Deno, Bun), or `'fetch'` for a fetch upgrade
|
|
26
|
+
* (Cloudflare Workers, detected by default). */
|
|
27
|
+
webSocket?: WebSocketLike | 'fetch' | undefined;
|
|
28
|
+
/** The `User-Agent` sent (where the runtime lets one be set). */
|
|
29
|
+
userAgent?: string | undefined;
|
|
30
|
+
/** Milliseconds a request may take (default 60 000). */
|
|
31
|
+
timeoutMs?: number | undefined;
|
|
32
|
+
/** Called when a portfolio answer is the stored last one (`X-Portfolio-Last-Answer`):
|
|
33
|
+
* the live sync failed or was slow. Default: `console.warn` once per path. */
|
|
34
|
+
onLastAnswer?: (path: string, detail: string) => void | undefined;
|
|
35
|
+
};
|
|
36
|
+
/** An API base without its trailing slash.
|
|
37
|
+
*
|
|
38
|
+
* @throws TypeError: not https (plain http only to localhost), or it has a path or query. */
|
|
39
|
+
export declare function checkBase(base: string): string;
|
|
40
|
+
/** One query value as the API reads it. */
|
|
41
|
+
export declare function wire(value: Exclude<QueryValue, null | undefined>): string;
|
|
42
|
+
/** The query string of `params` (leading `?`, or empty), in their order. */
|
|
43
|
+
export declare function queryString(params: Params | undefined): string;
|
|
44
|
+
/** An instant as ISO-8601 UTC to the second (`2026-10-01T00:00:00Z`), as `/v1` and `/v2`
|
|
45
|
+
* read `from`/`to` instants; a string goes as it is. */
|
|
46
|
+
export declare function instant(value: Instant | undefined): string | undefined;
|
|
47
|
+
/** A calendar day (`2026-10-01`, UTC), as `/v1` reads date ranges; a string goes as it is. */
|
|
48
|
+
export declare function day(value: Instant | undefined): string | undefined;
|
|
49
|
+
/** An instant as epoch milliseconds, as `/me` reads `start`/`end`; a string of digits goes
|
|
50
|
+
* as it is, another string is parsed as a date. */
|
|
51
|
+
export declare function epochMs(value: Instant | undefined): number | string | undefined;
|
|
52
|
+
/** A path segment, escaped (`:` kept, as topics and series ids use it). */
|
|
53
|
+
export declare const segment: (s: string) => string;
|
|
54
|
+
/** Refuse anything but an API read path (`/me`, `/me/…`, `/v1/…`, `/v2/…`, `/live/…`).
|
|
55
|
+
*
|
|
56
|
+
* @throws TypeError: another path, a query in it, or a `..` segment (escaped too). */
|
|
57
|
+
export declare function checkPath(path: string): string;
|
|
58
|
+
/** The API host with one key: what every endpoint calls. */
|
|
59
|
+
export declare class Transport {
|
|
60
|
+
#private;
|
|
61
|
+
/** The API host this client reads. */
|
|
62
|
+
readonly baseUrl: string;
|
|
63
|
+
readonly webSocket: WebSocketLike | 'fetch' | undefined;
|
|
64
|
+
constructor(opts?: TerminalOptions);
|
|
65
|
+
/** The key, or `NotLoggedIn`. */
|
|
66
|
+
key(): string;
|
|
67
|
+
/** `fetch`, as the runtime has it. */
|
|
68
|
+
fetch(): typeof fetch;
|
|
69
|
+
/** GET `path` with the key; the JSON answer, or the error it means.
|
|
70
|
+
*
|
|
71
|
+
* @throws ApiError (by status), NetworkError, Redirected, NotLoggedIn. */
|
|
72
|
+
get<T>(path: string, params?: Params): Promise<T>;
|
|
73
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The transport every endpoint group shares: one API host, one key, `fetch`. HTTPS only
|
|
3
|
+
* (plain http only to localhost), redirects never followed (the key would go along), the
|
|
4
|
+
* key only in the `Authorization` header and only to the configured host.
|
|
5
|
+
*/
|
|
6
|
+
import { apiErrorFrom, NetworkError, NotLoggedIn, Redirected, TerminalError } from "./errors.js";
|
|
7
|
+
/** The package version, sent in the user agent. */
|
|
8
|
+
export const VERSION = '0.1.2';
|
|
9
|
+
/** The API host when none is given and `TN_API_BASE` is unset. */
|
|
10
|
+
export const DEFAULT_BASE_URL = 'https://api.tribulnation.com';
|
|
11
|
+
/** Portfolio reads recompute a window and can take tens of seconds. */
|
|
12
|
+
export const DEFAULT_TIMEOUT_MS = 60_000;
|
|
13
|
+
const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
|
|
14
|
+
/** The environment, where the runtime has one (Node, Bun, Deno with `--allow-env`). */
|
|
15
|
+
function env(name) {
|
|
16
|
+
const g = globalThis;
|
|
17
|
+
try {
|
|
18
|
+
const v = g.process?.env?.[name] ?? g.Deno?.env?.get(name);
|
|
19
|
+
return v === undefined || v.trim() === '' ? undefined : v.trim();
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return undefined; // Deno without env permission
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** An API base without its trailing slash.
|
|
26
|
+
*
|
|
27
|
+
* @throws TypeError: not https (plain http only to localhost), or it has a path or query. */
|
|
28
|
+
export function checkBase(base) {
|
|
29
|
+
let url;
|
|
30
|
+
try {
|
|
31
|
+
url = new URL(base.trim());
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
throw new TypeError(`the API base is not a URL: ${JSON.stringify(base)}`);
|
|
35
|
+
}
|
|
36
|
+
const local = url.protocol === 'http:' && LOCAL_HOSTS.has(url.hostname);
|
|
37
|
+
if (url.protocol !== 'https:' && !local)
|
|
38
|
+
throw new TypeError(`the API must be https:// (plain http only to localhost), not ${JSON.stringify(base)}`);
|
|
39
|
+
if ((url.pathname !== '/' && url.pathname !== '') || url.search || url.hash || url.username)
|
|
40
|
+
throw new TypeError(`the API is a host, without a path: ${JSON.stringify(base)}`);
|
|
41
|
+
return `${url.protocol}//${url.host}`;
|
|
42
|
+
}
|
|
43
|
+
/** One query value as the API reads it. */
|
|
44
|
+
export function wire(value) {
|
|
45
|
+
if (Array.isArray(value))
|
|
46
|
+
return value.map((v) => String(v)).join(',');
|
|
47
|
+
if (value instanceof Date)
|
|
48
|
+
return isoSeconds(value);
|
|
49
|
+
if (typeof value === 'boolean')
|
|
50
|
+
return value ? '1' : '0';
|
|
51
|
+
return String(value);
|
|
52
|
+
}
|
|
53
|
+
/** The query string of `params` (leading `?`, or empty), in their order. */
|
|
54
|
+
export function queryString(params) {
|
|
55
|
+
if (!params)
|
|
56
|
+
return '';
|
|
57
|
+
const q = new URLSearchParams();
|
|
58
|
+
for (const [k, v] of Object.entries(params))
|
|
59
|
+
if (v !== undefined && v !== null)
|
|
60
|
+
q.append(k, wire(v));
|
|
61
|
+
const s = q.toString().replace(/%2C/gi, ',').replace(/%3A/gi, ':');
|
|
62
|
+
return s ? `?${s}` : '';
|
|
63
|
+
}
|
|
64
|
+
function asDate(value, what) {
|
|
65
|
+
const d = value instanceof Date ? value : new Date(value);
|
|
66
|
+
if (Number.isNaN(d.getTime()))
|
|
67
|
+
throw new TypeError(`${what} is not a valid time`);
|
|
68
|
+
return d;
|
|
69
|
+
}
|
|
70
|
+
const isoSeconds = (d) => asDate(d, 'a Date')
|
|
71
|
+
.toISOString()
|
|
72
|
+
.replace(/\.\d{3}Z$/, 'Z');
|
|
73
|
+
/** An instant as ISO-8601 UTC to the second (`2026-10-01T00:00:00Z`), as `/v1` and `/v2`
|
|
74
|
+
* read `from`/`to` instants; a string goes as it is. */
|
|
75
|
+
export function instant(value) {
|
|
76
|
+
if (value === undefined)
|
|
77
|
+
return undefined;
|
|
78
|
+
return typeof value === 'string' ? value : isoSeconds(asDate(value, 'the instant'));
|
|
79
|
+
}
|
|
80
|
+
/** A calendar day (`2026-10-01`, UTC), as `/v1` reads date ranges; a string goes as it is. */
|
|
81
|
+
export function day(value) {
|
|
82
|
+
if (value === undefined)
|
|
83
|
+
return undefined;
|
|
84
|
+
return typeof value === 'string' ? value : isoSeconds(asDate(value, 'the day')).slice(0, 10);
|
|
85
|
+
}
|
|
86
|
+
/** An instant as epoch milliseconds, as `/me` reads `start`/`end`; a string of digits goes
|
|
87
|
+
* as it is, another string is parsed as a date. */
|
|
88
|
+
export function epochMs(value) {
|
|
89
|
+
if (value === undefined)
|
|
90
|
+
return undefined;
|
|
91
|
+
if (typeof value === 'string') {
|
|
92
|
+
if (/^\d+$/.test(value))
|
|
93
|
+
return value;
|
|
94
|
+
const t = Date.parse(value);
|
|
95
|
+
if (Number.isNaN(t))
|
|
96
|
+
throw new TypeError(`not a time: ${JSON.stringify(value)}`);
|
|
97
|
+
return t;
|
|
98
|
+
}
|
|
99
|
+
return asDate(value, 'the instant').getTime();
|
|
100
|
+
}
|
|
101
|
+
/** A path segment, escaped (`:` kept, as topics and series ids use it). */
|
|
102
|
+
export const segment = (s) => {
|
|
103
|
+
if (typeof s !== 'string' || s === '')
|
|
104
|
+
throw new TypeError('an id must be a non-empty string');
|
|
105
|
+
if (s === '.' || s === '..')
|
|
106
|
+
throw new TypeError(`not an id: ${JSON.stringify(s)}`);
|
|
107
|
+
return encodeURIComponent(s).replace(/%3A/gi, ':');
|
|
108
|
+
};
|
|
109
|
+
/** Refuse anything but an API read path (`/me`, `/me/…`, `/v1/…`, `/v2/…`, `/live/…`).
|
|
110
|
+
*
|
|
111
|
+
* @throws TypeError: another path, a query in it, or a `..` segment (escaped too). */
|
|
112
|
+
export function checkPath(path) {
|
|
113
|
+
if (typeof path !== 'string' ||
|
|
114
|
+
!(path === '/me' || /^\/(?:me|v1|v2|live)\//.test(path)) ||
|
|
115
|
+
/[?#\\]/.test(path) ||
|
|
116
|
+
path.includes('..') ||
|
|
117
|
+
/%2e/i.test(path))
|
|
118
|
+
throw new TypeError('the path starts with /me, /v1/, /v2/ or /live/; parameters go in the params object');
|
|
119
|
+
return path;
|
|
120
|
+
}
|
|
121
|
+
/** The API host with one key: what every endpoint calls. */
|
|
122
|
+
export class Transport {
|
|
123
|
+
/** The API host this client reads. */
|
|
124
|
+
baseUrl;
|
|
125
|
+
#key;
|
|
126
|
+
#fetch;
|
|
127
|
+
#userAgent;
|
|
128
|
+
#timeoutMs;
|
|
129
|
+
#onLastAnswer;
|
|
130
|
+
webSocket;
|
|
131
|
+
constructor(opts = {}) {
|
|
132
|
+
this.baseUrl = checkBase(opts.baseUrl ?? env('TN_API_BASE') ?? DEFAULT_BASE_URL);
|
|
133
|
+
const key = opts.apiKey ?? env('TN_API_KEY');
|
|
134
|
+
this.#key = key === undefined ? undefined : key.trim();
|
|
135
|
+
if (this.#key !== undefined && (this.#key === '' || /\s/.test(this.#key)))
|
|
136
|
+
throw new TypeError('the API key is empty or has whitespace in it');
|
|
137
|
+
this.#fetch = opts.fetch;
|
|
138
|
+
this.#userAgent = opts.userAgent ?? `tribulnation-terminal-ts/${VERSION}`;
|
|
139
|
+
this.#timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
140
|
+
const warned = new Set();
|
|
141
|
+
this.#onLastAnswer =
|
|
142
|
+
opts.onLastAnswer ??
|
|
143
|
+
((path, detail) => {
|
|
144
|
+
if (warned.has(path))
|
|
145
|
+
return;
|
|
146
|
+
warned.add(path);
|
|
147
|
+
console.warn(`@tribulnation/terminal: ${path} is the stored last answer (${detail}); the live sync failed or was slow`);
|
|
148
|
+
});
|
|
149
|
+
this.webSocket = opts.webSocket;
|
|
150
|
+
}
|
|
151
|
+
/** The key, or `NotLoggedIn`. */
|
|
152
|
+
key() {
|
|
153
|
+
if (this.#key === undefined)
|
|
154
|
+
throw new NotLoggedIn('no API key: pass { apiKey } or set TN_API_KEY (create a key on /integrations)');
|
|
155
|
+
return this.#key;
|
|
156
|
+
}
|
|
157
|
+
/** `fetch`, as the runtime has it. */
|
|
158
|
+
fetch() {
|
|
159
|
+
const f = this.#fetch ?? globalThis.fetch;
|
|
160
|
+
if (typeof f !== 'function')
|
|
161
|
+
throw new TerminalError('no fetch: pass { fetch } to Terminal');
|
|
162
|
+
return f;
|
|
163
|
+
}
|
|
164
|
+
/** GET `path` with the key; the JSON answer, or the error it means.
|
|
165
|
+
*
|
|
166
|
+
* @throws ApiError (by status), NetworkError, Redirected, NotLoggedIn. */
|
|
167
|
+
async get(path, params) {
|
|
168
|
+
const key = this.key();
|
|
169
|
+
const url = this.baseUrl + path + queryString(params);
|
|
170
|
+
const headers = {
|
|
171
|
+
authorization: `Bearer ${key}`,
|
|
172
|
+
accept: 'application/json'
|
|
173
|
+
};
|
|
174
|
+
if (this.#userAgent)
|
|
175
|
+
headers['user-agent'] = this.#userAgent;
|
|
176
|
+
let res;
|
|
177
|
+
try {
|
|
178
|
+
res = await this.fetch()(url, {
|
|
179
|
+
method: 'GET',
|
|
180
|
+
headers,
|
|
181
|
+
redirect: 'manual',
|
|
182
|
+
signal: timeout(this.#timeoutMs)
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
catch (e) {
|
|
186
|
+
const name = e?.name;
|
|
187
|
+
if (name === 'TimeoutError' || name === 'AbortError')
|
|
188
|
+
throw new NetworkError(`${this.baseUrl} did not answer in ${this.#timeoutMs / 1000} s`);
|
|
189
|
+
throw new NetworkError(`cannot reach ${this.baseUrl}: ${name ?? 'error'}`);
|
|
190
|
+
}
|
|
191
|
+
if (res.type === 'opaqueredirect' || (res.status >= 300 && res.status < 400))
|
|
192
|
+
throw new Redirected(`${this.baseUrl} answered a redirect (${res.status}); not followed, so the key stays here`);
|
|
193
|
+
const text = await res.text().catch(() => '');
|
|
194
|
+
if (res.status >= 400) {
|
|
195
|
+
let body = null;
|
|
196
|
+
try {
|
|
197
|
+
body = JSON.parse(text);
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
// not JSON: the status says it
|
|
201
|
+
}
|
|
202
|
+
throw apiErrorFrom(res.status, body, res.headers.get('retry-after'));
|
|
203
|
+
}
|
|
204
|
+
const stale = res.headers.get('x-portfolio-last-answer');
|
|
205
|
+
if (stale)
|
|
206
|
+
this.#onLastAnswer(path, stale);
|
|
207
|
+
try {
|
|
208
|
+
return JSON.parse(text);
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
throw new NetworkError(`${this.baseUrl}${path} answered no JSON (${res.status})`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
function timeout(ms) {
|
|
216
|
+
const t = AbortSignal.timeout;
|
|
217
|
+
return ms > 0 && typeof t === 'function' ? t.call(AbortSignal, ms) : undefined;
|
|
218
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Errors, as the Python client raises them (`tribulnation.terminal.core.exc`): one class
|
|
3
|
+
* per answer the API gives (its envelope `{error: {code, message}}`), plus the refusals
|
|
4
|
+
* the client makes before sending anything. Every message has anything shaped like a key
|
|
5
|
+
* cut out (`scrub`).
|
|
6
|
+
*/
|
|
7
|
+
import type { ApiErrorCode } from './types.gen.js';
|
|
8
|
+
/** Text with anything shaped like a key or token cut out, and no control characters. */
|
|
9
|
+
export declare function scrub(text: string): string;
|
|
10
|
+
/** The base of every error this client throws. */
|
|
11
|
+
export declare class TerminalError extends Error {
|
|
12
|
+
constructor(message: string);
|
|
13
|
+
}
|
|
14
|
+
/** The API answered an error (`status` 4xx or 5xx). */
|
|
15
|
+
export declare class ApiError extends TerminalError {
|
|
16
|
+
/** The HTTP status. */
|
|
17
|
+
readonly status: number;
|
|
18
|
+
/** The envelope's `error.code` (`'error'` when the body had none). */
|
|
19
|
+
readonly code: ApiErrorCode | (string & {});
|
|
20
|
+
/** Per-parameter complaints of a 400. */
|
|
21
|
+
readonly details?: Record<string, string>;
|
|
22
|
+
/** `Retry-After`, seconds (429, 503 `warming`). */
|
|
23
|
+
readonly retryAfter?: number;
|
|
24
|
+
constructor(message: string, init: {
|
|
25
|
+
status: number;
|
|
26
|
+
code?: string;
|
|
27
|
+
details?: Record<string, string>;
|
|
28
|
+
retryAfter?: number;
|
|
29
|
+
});
|
|
30
|
+
toString(): string;
|
|
31
|
+
}
|
|
32
|
+
/** 400: a parameter the API refuses (`details` names it). */
|
|
33
|
+
export declare class BadRequest extends ApiError {
|
|
34
|
+
}
|
|
35
|
+
/** 401: no key, or the key is invalid, expired or revoked. */
|
|
36
|
+
export declare class AuthError extends ApiError {
|
|
37
|
+
}
|
|
38
|
+
/** 403: the key lacks the scope (`market:read`), or the plan leaves the data out. An
|
|
39
|
+
* `AuthError`, as in the Python client. */
|
|
40
|
+
export declare class Forbidden extends AuthError {
|
|
41
|
+
}
|
|
42
|
+
/** 404: no such route or resource (someone else's plot is 404 too). */
|
|
43
|
+
export declare class NotFound extends ApiError {
|
|
44
|
+
}
|
|
45
|
+
/** 429: too many requests; `retryAfter` says how long to wait. */
|
|
46
|
+
export declare class RateLimited extends ApiError {
|
|
47
|
+
}
|
|
48
|
+
/** 502, 503 or 504: the service (or what it reads) did not answer; `warming` is a live
|
|
49
|
+
* snapshot being built. */
|
|
50
|
+
export declare class Unavailable extends ApiError {
|
|
51
|
+
}
|
|
52
|
+
/** No answer: unreachable, timed out, or not JSON. */
|
|
53
|
+
export declare class NetworkError extends TerminalError {
|
|
54
|
+
}
|
|
55
|
+
/** The API answered a redirect. It is never followed: the key would go along. A
|
|
56
|
+
* `NetworkError`, as in the Python client. */
|
|
57
|
+
export declare class Redirected extends NetworkError {
|
|
58
|
+
}
|
|
59
|
+
/** No key: none passed and no `TN_API_KEY`. Thrown before anything is sent; an `AuthError`
|
|
60
|
+
* (`status` 401, `code` `'unauthorized'`), as in the Python client. */
|
|
61
|
+
export declare class NotLoggedIn extends AuthError {
|
|
62
|
+
constructor(message: string);
|
|
63
|
+
}
|
|
64
|
+
/** The live socket was ended for good: `code` 4401 (revoked key), 4003 (topic not in the
|
|
65
|
+
* plan) or 4004 (unknown topic). */
|
|
66
|
+
export declare class LiveClosed extends TerminalError {
|
|
67
|
+
readonly code: number;
|
|
68
|
+
readonly reason: string;
|
|
69
|
+
constructor(code: number, reason: string);
|
|
70
|
+
}
|
|
71
|
+
/** The error class of an HTTP status. */
|
|
72
|
+
export declare function errorClass(status: number): typeof ApiError;
|
|
73
|
+
/** `Retry-After` in seconds, or undefined (a date or garbage is ignored). */
|
|
74
|
+
export declare function retryAfterSeconds(header: string | null | undefined): number | undefined;
|
|
75
|
+
/** The error an error answer means: this API's envelope, or an OAuth error body. */
|
|
76
|
+
export declare function apiErrorFrom(status: number, body: unknown, retryAfter: string | null | undefined): ApiError;
|