@tungoai/sdk 0.0.0-stage → 0.3.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 +93 -0
- package/LICENSE +21 -0
- package/README.kk.md +327 -0
- package/README.md +346 -2
- package/README.ru.md +327 -0
- package/dist/cjs/chat.d.ts +85 -0
- package/dist/cjs/chat.js +152 -0
- package/dist/cjs/client.d.ts +117 -0
- package/dist/cjs/client.js +225 -0
- package/dist/cjs/core.d.ts +217 -0
- package/dist/cjs/core.js +779 -0
- package/dist/cjs/errors.d.ts +237 -0
- package/dist/cjs/errors.js +446 -0
- package/dist/cjs/generated/resources.d.ts +1149 -0
- package/dist/cjs/generated/resources.js +1145 -0
- package/dist/cjs/generated/types.d.ts +5435 -0
- package/dist/cjs/generated/types.js +11 -0
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +81 -0
- package/dist/cjs/json.d.ts +16 -0
- package/dist/cjs/json.js +137 -0
- package/dist/cjs/money.d.ts +32 -0
- package/dist/cjs/money.js +141 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +47 -0
- package/dist/cjs/pagination.js +114 -0
- package/dist/cjs/streaming.d.ts +76 -0
- package/dist/cjs/streaming.js +291 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +6 -0
- package/dist/cjs/webhooks.d.ts +79 -0
- package/dist/cjs/webhooks.js +262 -0
- package/dist/esm/chat.d.ts +85 -0
- package/dist/esm/chat.js +144 -0
- package/dist/esm/client.d.ts +117 -0
- package/dist/esm/client.js +221 -0
- package/dist/esm/core.d.ts +217 -0
- package/dist/esm/core.js +763 -0
- package/dist/esm/errors.d.ts +237 -0
- package/dist/esm/errors.js +416 -0
- package/dist/esm/generated/resources.d.ts +1149 -0
- package/dist/esm/generated/resources.js +1129 -0
- package/dist/esm/generated/types.d.ts +5435 -0
- package/dist/esm/generated/types.js +10 -0
- package/dist/esm/index.d.ts +12 -0
- package/dist/esm/index.js +11 -0
- package/dist/esm/json.d.ts +16 -0
- package/dist/esm/json.js +132 -0
- package/dist/esm/money.d.ts +32 -0
- package/dist/esm/money.js +137 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/pagination.d.ts +47 -0
- package/dist/esm/pagination.js +108 -0
- package/dist/esm/streaming.d.ts +76 -0
- package/dist/esm/streaming.js +285 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +3 -0
- package/dist/esm/webhooks.d.ts +79 -0
- package/dist/esm/webhooks.js +253 -0
- package/package.json +67 -4
package/README.md
CHANGED
|
@@ -1,3 +1,347 @@
|
|
|
1
|
-
|
|
1
|
+
<!-- Generated by tungo-sdkgen. Do not edit: the file is rewritten on every generation. -->
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<div align="center">
|
|
4
|
+
|
|
5
|
+
<picture>
|
|
6
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/TungoAI/.github/main/assets/logo02.svg" />
|
|
7
|
+
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/TungoAI/.github/main/assets/logo03.svg" />
|
|
8
|
+
<img alt="Tungo AI" src="https://raw.githubusercontent.com/TungoAI/.github/main/assets/logo03.svg" width="240" />
|
|
9
|
+
</picture>
|
|
10
|
+
|
|
11
|
+
# Tungo SDK for TypeScript
|
|
12
|
+
|
|
13
|
+
**The official TypeScript library for the Tungo Platform API**
|
|
14
|
+
|
|
15
|
+
[](https://www.npmjs.com/package/@tungoai/sdk)
|
|
16
|
+
[](https://github.com/TungoAI/tungo-sdk-typescript/actions/workflows/ci.yml)
|
|
17
|
+
[](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/LICENSE)
|
|
18
|
+
|
|
19
|
+
**English** · [Русский](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/README.ru.md) · [Қазақша](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/README.kk.md)
|
|
20
|
+
|
|
21
|
+
[tungo.kz](https://tungo.kz) · [Quick start](#quick-start) · [API reference](#api-reference) · [Changelog](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md) · [Issues](https://github.com/TungoAI/tungo-sdk-typescript/issues)
|
|
22
|
+
|
|
23
|
+
</div>
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
The official TypeScript library for the Tungo Platform API (`https://api.tungo.kz`): the AI accountant, 1C integration, bank statements, e-invoices, tax forms and automations of [Tungo AI](https://tungo.kz).
|
|
28
|
+
|
|
29
|
+
It is generated from the API's OpenAPI contract, so its methods and models always match the contract it was built from.
|
|
30
|
+
|
|
31
|
+
## Requirements
|
|
32
|
+
|
|
33
|
+
Node.js 20 or newer, Deno, Bun, Cloudflare Workers or a modern browser: the SDK only needs `fetch`, Web Streams and Web Crypto. It has no runtime dependencies, ships ES modules and CommonJS, and includes type declarations. The declarations are tested with TypeScript 5.9; older compilers are not part of the test matrix.
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npm install @tungoai/sdk
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Quick start
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { Tungo } from '@tungoai/sdk';
|
|
45
|
+
|
|
46
|
+
const client = new Tungo(); // reads TUNGO_API_KEY
|
|
47
|
+
|
|
48
|
+
const { data: companies } = await client.companies.list();
|
|
49
|
+
for (const company of companies) {
|
|
50
|
+
console.log(company.id, company.name);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const reply = await client.ask('co_01h455vb4pex5vsknk084sn02q', 'What VAT applies to the last sale?');
|
|
54
|
+
console.log(reply.answer);
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Authentication and configuration
|
|
58
|
+
|
|
59
|
+
Create one client and share it: it is immutable and safe to use from several threads or tasks. Every option can be passed explicitly; three of them fall back to environment variables.
|
|
60
|
+
|
|
61
|
+
| Option | Environment variable | Default |
|
|
62
|
+
| --- | --- | --- |
|
|
63
|
+
| API key | `TUNGO_API_KEY` | none |
|
|
64
|
+
| Base URL | `TUNGO_BASE_URL` | `https://api.tungo.kz` |
|
|
65
|
+
| Webhook secret | `TUNGO_WEBHOOK_SECRET` | none |
|
|
66
|
+
| Timeout | | 60 s (600 s for non-streaming chat turns) |
|
|
67
|
+
| Maximum retries | | 2 |
|
|
68
|
+
| Default headers, HTTP client | | none, built-in |
|
|
69
|
+
|
|
70
|
+
The API key is sent only to operations that require it; public endpoints and incoming hooks never receive it, and it never appears in error messages or debug output. Calling an authenticated operation without a key fails locally, before any request is made.
|
|
71
|
+
|
|
72
|
+
Every method also accepts per-request options: timeout, maximum retries, extra headers, an idempotency key and cancellation.
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { Tungo } from '@tungoai/sdk';
|
|
76
|
+
|
|
77
|
+
const client = new Tungo({
|
|
78
|
+
apiKey: 'tg_...', // default: TUNGO_API_KEY
|
|
79
|
+
baseUrl: 'https://api.tungo.kz', // default: TUNGO_BASE_URL
|
|
80
|
+
webhookSecret: 'whsec_...', // default: TUNGO_WEBHOOK_SECRET
|
|
81
|
+
timeout: 30_000, // milliseconds, covers the whole request
|
|
82
|
+
longRunningTimeout: 300_000, // non-streaming chat turns
|
|
83
|
+
maxRetries: 3,
|
|
84
|
+
defaultHeaders: { 'X-App': 'billing' },
|
|
85
|
+
fetch: (url, init) => fetch(url, init), // any fetch-compatible function: proxy, tracing, mock
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
// Per-request options are the last argument of every method.
|
|
89
|
+
const controller = new AbortController();
|
|
90
|
+
const company = await client.companies.get('co_01h455vb4pex5vsknk084sn02q', {
|
|
91
|
+
timeout: 5_000,
|
|
92
|
+
maxRetries: 0,
|
|
93
|
+
headers: { 'X-Trace-Id': 'trace-123' },
|
|
94
|
+
signal: controller.signal,
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
// Status, headers, request id and rate limit of any call.
|
|
98
|
+
const { data, response } = await client.companies.get(company.id).withResponse();
|
|
99
|
+
console.log(data.name, response.status, response.requestId, response.rateLimit?.remaining);
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
All durations are in milliseconds. A timeout must be greater than zero (0 is rejected); `Infinity`, or a value above 2 147 483 647 ms (the longest timer the platform can count), means no time limit. The client `timeout` covers ordinary calls and `longRunningTimeout` the non-streaming chat turns; a per-request `timeout` wins over both. The `logger` option receives one event per request, response, retry and failure; it contains the method, the path template, the status and the request id, never header values, the API key or a hook token. Rate-limit information is per response (`withResponse()`); the client keeps no shared "last response" state.
|
|
103
|
+
|
|
104
|
+
## Errors
|
|
105
|
+
|
|
106
|
+
Every failure is a subtype of the SDK's base error. An HTTP error response becomes an API error chosen by the `error.type` field of the response body, falling back to the HTTP status when the body is not the API's error envelope:
|
|
107
|
+
|
|
108
|
+
| `error.type` | Status |
|
|
109
|
+
| --- | --- |
|
|
110
|
+
| `invalid_request_error` | 400 |
|
|
111
|
+
| `authentication_error` | 401 |
|
|
112
|
+
| `payment_required_error` | 402 |
|
|
113
|
+
| `permission_error` | 403 |
|
|
114
|
+
| `not_found_error` | 404 |
|
|
115
|
+
| `conflict_error` | 409 |
|
|
116
|
+
| `gone_error` | 410 |
|
|
117
|
+
| `limit_error` | 429 |
|
|
118
|
+
| `api_error` | 500 |
|
|
119
|
+
| `unavailable_error` | 503 |
|
|
120
|
+
|
|
121
|
+
An API error carries the status, type, code, message, request id, field errors, the parsed retry-after delay, the response headers and the raw body. Problems that happen without a response have their own types: connection error, timeout, decode error (a successful response whose body is not valid), and configuration or validation error (raised before any request).
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
import { APIError, ConnectionError, LimitError, NotFoundError, TimeoutError, Tungo } from '@tungoai/sdk';
|
|
125
|
+
|
|
126
|
+
const client = new Tungo();
|
|
127
|
+
|
|
128
|
+
try {
|
|
129
|
+
await client.proposals.approve('co_01h455vb4pex5vsknk084sn02q', 'P-000042');
|
|
130
|
+
} catch (err) {
|
|
131
|
+
if (err instanceof NotFoundError) {
|
|
132
|
+
console.log('No such proposal');
|
|
133
|
+
} else if (err instanceof LimitError) {
|
|
134
|
+
console.log('Retry in', err.retryAfter, 'seconds; the limit resets at', err.extra['resets_at']);
|
|
135
|
+
} else if (err instanceof APIError) {
|
|
136
|
+
// status, error.type, error.code, the API's message, the id to quote to support, field errors
|
|
137
|
+
console.log(err.status, err.type, err.code, err.detail, err.requestId, err.fields);
|
|
138
|
+
} else if (err instanceof TimeoutError || err instanceof ConnectionError) {
|
|
139
|
+
console.log('Network problem:', err.message);
|
|
140
|
+
} else {
|
|
141
|
+
throw err;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The classes are `InvalidRequestError`, `AuthenticationError`, `PaymentRequiredError`, `PermissionError`, `NotFoundError`, `ConflictError`, `GoneError`, `LimitError`, `InternalServerError` (`api_error`) and `UnavailableError`, all extending `APIError`; and `ConnectionError`, `TimeoutError`, `AbortError` (cancellation through your `AbortSignal`; the signal's reason is the `cause`), `DecodeError`, `StreamError`, `ConfigError`, `ValidationError`, `WebhookVerificationError` and `MoneyError`, all extending `TungoError`. `err.message` is an English summary with the status, code and request id; `err.detail` is the API's own message. An error reported by a chat turn inside a successful response (an `error` event of a stream, or `errors` of `client.ask`) is thrown by the chat helpers as the same class by its `error.type` (for example `LimitError`), with `status` undefined because no HTTP error status exists for it, and with what was received in `partialResult`. The Python SDK raises `ChatStreamError` (with `type`, `code`, `request_id`, `extra` and `result`) for the same situation.
|
|
147
|
+
|
|
148
|
+
## Retries and timeouts
|
|
149
|
+
|
|
150
|
+
A request is retried up to 2 times (3 attempts) on connection errors, timeouts and the statuses 408, 429, 500, 502, 503 and 504, but only when repeating it is safe: `GET`, `HEAD`, `PUT` and `DELETE` requests, and `POST` or `PATCH` requests of the operations whose contract declares an `Idempotency-Key`. For those the SDK generates a random key and reuses it for every attempt; you can pass your own. Other operations send no key, not even one you pass, because the API would ignore it.
|
|
151
|
+
|
|
152
|
+
The delay between attempts is `min(0.5 s × 2^attempt, 8 s)` with random jitter. A positive `retry-after-ms` or `Retry-After` response header overrides it; if the server asks for more than 60 s the SDK does not wait and raises the error with the delay filled in.
|
|
153
|
+
|
|
154
|
+
The timeout covers the whole request including reading the body. Streaming calls have no total timeout, only a connect timeout and an idle timeout of 120 s. Cancellation supplied by the caller is combined with the timeout.
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
import { Tungo } from '@tungoai/sdk';
|
|
158
|
+
|
|
159
|
+
const client = new Tungo({ maxRetries: 5, timeout: 20_000 });
|
|
160
|
+
|
|
161
|
+
// Override per request.
|
|
162
|
+
await client.companies.list({ maxRetries: 0, timeout: 2_000 });
|
|
163
|
+
|
|
164
|
+
// A POST is retried only when it carries an Idempotency-Key. The SDK generates one for the
|
|
165
|
+
// operations that declare the header; pass your own to make a retry of your own code safe too.
|
|
166
|
+
await client.proposals.approve('co_01h455vb4pex5vsknk084sn02q', 'P-000042', {}, { idempotencyKey: 'approve-P-000042' });
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
A redirect is never followed, so the API key cannot leak to a host you did not configure: a 3xx answer is an `APIError` with that status. A `Retry-After` of zero, or a date that has already passed, does not trigger an immediate retry: the computed backoff applies.
|
|
170
|
+
|
|
171
|
+
## Pagination
|
|
172
|
+
|
|
173
|
+
List operations use cursor pagination (`{ data, next_cursor }`). The plain method returns one typed page that knows whether there is a next page and can fetch it. The auto-paging variant is a lazy iterator: it requests the next page only when needed, carries your filters over, and stops fetching as soon as you stop iterating.
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
import { Tungo } from '@tungoai/sdk';
|
|
177
|
+
|
|
178
|
+
const client = new Tungo();
|
|
179
|
+
const company = 'co_01h455vb4pex5vsknk084sn02q';
|
|
180
|
+
|
|
181
|
+
// One page.
|
|
182
|
+
const page = await client.proposals.list(company, { status: 'awaiting_approval', limit: 50 });
|
|
183
|
+
console.log(page.data.length, 'of', page.body.total, 'next cursor:', page.nextCursor);
|
|
184
|
+
if (page.hasNextPage()) {
|
|
185
|
+
const next = await page.getNextPage();
|
|
186
|
+
console.log(next.data.length);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Every item of every page, fetched lazily.
|
|
190
|
+
for await (const proposal of client.proposals.listAll(company, { status: 'awaiting_approval' })) {
|
|
191
|
+
console.log(proposal.id);
|
|
192
|
+
if (proposal.id === 'P-000100') break; // no further pages are requested
|
|
193
|
+
}
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
The iteration stops with an error, instead of looping forever, when the server returns a cursor it has already returned in the same walk (the previous one or any earlier one).
|
|
197
|
+
|
|
198
|
+
## Streaming
|
|
199
|
+
|
|
200
|
+
Streaming operations use server-sent events and deliver typed events as they arrive. Leaving the loop early or closing the stream closes the connection. A stream request is retried only before its first byte; an error response is raised as the same typed API error as for ordinary calls. A chat stream that ends before its final event is reported as an error, never as a finished answer.
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
import { Tungo } from '@tungoai/sdk';
|
|
204
|
+
|
|
205
|
+
const client = new Tungo();
|
|
206
|
+
const company = 'co_01h455vb4pex5vsknk084sn02q';
|
|
207
|
+
|
|
208
|
+
const stream = await client.chat.stream(company, { message: 'Check the November bank statement' });
|
|
209
|
+
console.log('dialog', stream.dialogId, 'turn', stream.turnNo);
|
|
210
|
+
for await (const event of stream) {
|
|
211
|
+
switch (event.type) {
|
|
212
|
+
case 'text':
|
|
213
|
+
console.log(event.delta);
|
|
214
|
+
break;
|
|
215
|
+
case 'tool':
|
|
216
|
+
console.log(event.name, event.status);
|
|
217
|
+
break;
|
|
218
|
+
case 'error':
|
|
219
|
+
console.error(event.error.code, event.error.message);
|
|
220
|
+
break;
|
|
221
|
+
case 'done':
|
|
222
|
+
console.log('finished:', event.stop_reason);
|
|
223
|
+
break;
|
|
224
|
+
default:
|
|
225
|
+
break; // a newer API version may send event types this SDK does not know
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Or let the SDK assemble the turn. A mid-stream error event is thrown as a typed APIError.
|
|
230
|
+
const turn = await client.streamChatWithResult(company, 'And for October?', {
|
|
231
|
+
onTextDelta: (delta) => console.log(delta),
|
|
232
|
+
});
|
|
233
|
+
console.log(turn.text, turn.stopReason, turn.costTiyn);
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
`client.chat.listEvents`, `client.batches.listEvents` and `client.feed.listEvents` are plain event streams and work the same way. `stream.close()` closes the connection explicitly; `stream.events()` gives the raw server-sent events and `stream.lastEventId` the id to resume from. The connect timeout of a stream is the request `timeout`; `streamIdleTimeout` (120 s by default) limits the silence between bytes. `finalResult()`, `streamChatWithResult` and `accumulateChatStream` never return a partial turn as a finished one: a stream that ends without its `done` event raises a `DecodeError` (`partialResult` holds what arrived), and a 2xx answer that is not `text/event-stream` raises a `DecodeError` instead of an empty stream. The exception is a finished chat turn that the API replays for a repeated `Idempotency-Key` (`application/json` with `Idempotent-Replayed: true`): its stored result arrives as the events of that turn, ending with `next` (follow-ups and the next action, when it has them) and `done`. Plain iteration simply ends when the stream ends. An `error` event of `client.feed.listEvents` (`feed_failed`) is thrown as a `StreamError` with `code` and `detail`: the feed did not finish, so reconnect from the cursor of the last item.
|
|
237
|
+
|
|
238
|
+
## Webhooks
|
|
239
|
+
|
|
240
|
+
Outgoing webhooks are signed according to the Standard Webhooks specification (Svix). The verify helper takes the raw request body and the headers (`webhook-*` or `svix-*`), checks the HMAC-SHA256 signature in constant time and the timestamp within 300 s of the system clock, and returns the typed event. Any problem is reported as a webhook verification error. If no secret is passed, the client's webhook secret is used.
|
|
241
|
+
|
|
242
|
+
The send-hook helper posts an event to an incoming hook (`/hooks/{token}`) and, when given a secret, signs the exact bytes it sends in the `X-Signature: sha256=<hex>` header. The API key is never sent to hooks.
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
import { Tungo, WebhookVerificationError } from '@tungoai/sdk';
|
|
246
|
+
|
|
247
|
+
const client = new Tungo(); // webhook secret from TUNGO_WEBHOOK_SECRET
|
|
248
|
+
|
|
249
|
+
// A fetch-style handler (Workers, Deno, Bun, Next.js route handlers, Hono, ...).
|
|
250
|
+
export async function handleWebhook(request: Request): Promise<Response> {
|
|
251
|
+
const rawBody = await request.text(); // the exact body: do not parse and re-serialise it
|
|
252
|
+
try {
|
|
253
|
+
const event = await client.verifyWebhook(rawBody, request.headers);
|
|
254
|
+
if (event.type === 'proposal.written') {
|
|
255
|
+
console.log('written to 1C:', event.data.proposal_id);
|
|
256
|
+
}
|
|
257
|
+
return new Response(null, { status: 204 });
|
|
258
|
+
} catch (err) {
|
|
259
|
+
if (err instanceof WebhookVerificationError) {
|
|
260
|
+
return new Response('invalid signature', { status: 400 });
|
|
261
|
+
}
|
|
262
|
+
throw err;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Send an event to an incoming hook; the body is signed with the hook's secret.
|
|
267
|
+
const accepted = await client.sendHook(
|
|
268
|
+
'th_your_hook_token',
|
|
269
|
+
{ id: 'order_1532', amount_tiyn: 4500000 },
|
|
270
|
+
{ secret: 'your hook secret', eventId: 'order_1532' },
|
|
271
|
+
);
|
|
272
|
+
console.log(accepted.event_id, accepted.duplicate);
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
Verification is asynchronous because it uses Web Crypto. `verifyWebhook` accepts a `Headers` object, a plain object such as Node's `req.headers`, a `Map` or an array of pairs. `signHookPayload` and `verifyHookSignature` are exported for servers that receive hooks themselves.
|
|
276
|
+
|
|
277
|
+
## Money
|
|
278
|
+
|
|
279
|
+
The API expresses amounts in tiyn (1/100 of a tenge) as 64-bit integers. The money helper converts decimal strings and exact decimal values to tiyn without floating-point error, rounding half away from zero (`"1.005"` → `101`), and formats tiyn for display (`4500000` → `45 000,00 ₸`). Invalid input raises a typed error.
|
|
280
|
+
|
|
281
|
+
```ts
|
|
282
|
+
import { TungoMoney, isValidBinIin } from '@tungoai/sdk';
|
|
283
|
+
|
|
284
|
+
console.log(TungoMoney.toTiyn('1.005')); // 101
|
|
285
|
+
console.log(TungoMoney.toTiyn(45000.5)); // 4500050
|
|
286
|
+
console.log(TungoMoney.formatTiyn(4500000)); // 45 000,00 ₸
|
|
287
|
+
console.log(TungoMoney.formatTiyn(-50)); // -0,50 ₸
|
|
288
|
+
console.log(TungoMoney.toTiynBigInt('92233720368547758.07')); // 9223372036854775807n
|
|
289
|
+
console.log(isValidBinIin('990140000017')); // true
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
JavaScript numbers are exact only up to 2^53. `toTiyn` returns a `number` and throws a `MoneyError` beyond that range; `toTiynBigInt` covers the whole 64-bit range, and `formatTiyn` accepts a `number`, a `bigint` or a decimal string. In API responses an integer beyond 2^53 is decoded to a `bigint` instead of being silently rounded, and a `bigint` in a request is sent as a plain JSON number. The types say so: an integer field the contract does not bound to 32 bits (tiyn amounts, counters) is `number | bigint`. It is a `number` for every value up to 2^53, so `Number(value)`, `BigInt(value)` or a `typeof value === 'bigint'` check narrows it; the money helpers accept both.
|
|
293
|
+
|
|
294
|
+
## Long-running operations
|
|
295
|
+
|
|
296
|
+
`client.runScenarioAndWait(company, scenarioId)`, `client.waitForRun(company, runId)` and `client.waitForBatch(company, batchId)` poll with a pause that grows from 1 s to 5 s until the run or job reaches a final state. They accept `{ timeout, pollInterval, maxPollInterval, signal }`; when the deadline (10 minutes by default) passes they throw a local `TimeoutError`. The deadline also ends a poll request that is still running, so the wait does not outlive it by a request timeout or by retries.
|
|
297
|
+
|
|
298
|
+
## Runtimes and module formats
|
|
299
|
+
|
|
300
|
+
The package has two builds selected by the `exports` map: ES modules for `import` and CommonJS for `require`, each with its own type declarations, so it type-checks under the `node16`, `nodenext` and `bundler` module resolutions. It uses no Node.js-only API, so the same code runs in Deno (`npm:@tungoai/sdk`), Bun, Cloudflare Workers and browsers. Do not ship an API key to a browser: call the API from your server.
|
|
301
|
+
|
|
302
|
+
## API reference
|
|
303
|
+
|
|
304
|
+
Generated from the Tungo Platform API contract: **13 resources, 90 methods, 22 webhook event types**.
|
|
305
|
+
|
|
306
|
+
| Resource | Description | Methods |
|
|
307
|
+
| --- | --- | --- |
|
|
308
|
+
| `workspaces` | Organisations (workspaces) the API key can access | `list` |
|
|
309
|
+
| `companies` | Companies of an organisation and their profiles | `list` · `get` |
|
|
310
|
+
| `platform` | Platform balance, ledger, usage reports, limits, audit log and model rates | `listUsageRates` · `getAccount` · `getAudit` · `getAuditAll` · `getLedger` · `getLedgerAll` · `listLimits` · `listRequests` · `listRequestsAll` · `getUsage` |
|
|
311
|
+
| `apiKeys` | The current API key and its usage statistics | `getCurrent` · `getCurrentUsage` · `getUsage` |
|
|
312
|
+
| `webhooks` | Outgoing webhooks of an organisation (Svix): endpoints, event catalogue, deliveries and signature check | `listEndpoints` · `listEndpointsAll` · `createEndpoint` · `getEndpoint` · `updateEndpoint` · `deleteEndpoint` · `listEndpointAttempts` · `listEndpointAttemptsAll` · `rotateEndpointSecret` · `testEndpoint` · `listEventTypes` · `listMessages` · `listMessagesAll` · `listMessageAttempts` · `listMessageAttemptsAll` · `resendMessage` · `getUsage` |
|
|
313
|
+
| `chat` | Conversations with the AI accountant: questions, streaming chat (SSE), token counting and history | `list` · `listAll` · `create` · `stream` · `countTokens` · `listMentions` · `getRatingOptions` · `listSuggestions` · `get` · `update` · `delete` · `answer` · `answerStream` · `listEvents` · `rateMessage` · `deleteMessageRating` · `rate` · `dismissRating` · `stop` |
|
|
314
|
+
| `proposals` | Documents proposed by the AI accountant: review, approval for posting to 1C, and rejection | `list` · `listAll` · `approveBatch` · `get` · `approve` · `reject` · `requestApproval` |
|
|
315
|
+
| `feed` | The company's feed of events and proposals (pages and a live SSE stream) | `get` · `getAll` · `listEvents` |
|
|
316
|
+
| `batches` | Processing batches for bank statements, incoming e-invoices and DirectBank | `list` · `listAll` · `createBankStatement` · `createEsfPurchases` · `get` · `listEvents` · `stop` · `getSummary` · `listStatements` · `listStatementsAll` · `pollDirectbank` |
|
|
317
|
+
| `esf` | Incoming and outgoing electronic invoices (the ESF system) | `getIncoming` · `getIncomingAll` · `getOutgoing` · `getOutgoingAll` |
|
|
318
|
+
| `forms` | Tax forms (FNO 100.00 and others): building, ISNA checks and data gaps | `list` · `build` · `listDataGaps` · `getIsna` · `listNotes` |
|
|
319
|
+
| `onec` | Status of the company's connection to its 1C database | `getStatus` |
|
|
320
|
+
| `automations` | Company automations: incoming hooks, scenarios, step chains, runs and the AI autonomy level | `postHook` · `listHooks` · `createHook` · `getHook` · `updateHook` · `deleteHook` · `rotateHook` · `testHook` · `listRuns` · `listRunsAll` · `getRun` · `cancelRun` · `retryRun` · `listScenarios` · `createScenario` · `getScenario` · `putScenario` · `updateScenario` · `deleteScenario` · `runScenario` · `getState` · `putState` · `getAutonomy` · `putAutonomy` |
|
|
321
|
+
|
|
322
|
+
## Other SDKs
|
|
323
|
+
|
|
324
|
+
The same API is available in ten languages. All SDKs are generated from one contract and behave the same way.
|
|
325
|
+
|
|
326
|
+
| Language | Repository | Package |
|
|
327
|
+
| --- | --- | --- |
|
|
328
|
+
| **TypeScript** | [tungo-sdk-typescript](https://github.com/TungoAI/tungo-sdk-typescript) | `@tungoai/sdk` |
|
|
329
|
+
| Python | [tungo-sdk-python](https://github.com/TungoAI/tungo-sdk-python) | `tungoai` |
|
|
330
|
+
| Go | [tungo-sdk-go](https://github.com/TungoAI/tungo-sdk-go) | `github.com/TungoAI/tungo-sdk-go` |
|
|
331
|
+
| Rust | [tungo-sdk-rust](https://github.com/TungoAI/tungo-sdk-rust) | `tungo-sdk` |
|
|
332
|
+
| PHP | [tungo-sdk-php](https://github.com/TungoAI/tungo-sdk-php) | `tungo/sdk` |
|
|
333
|
+
| Java | [tungo-sdk-java](https://github.com/TungoAI/tungo-sdk-java) | `kz.tungo:tungo-sdk` |
|
|
334
|
+
| Kotlin | [tungo-sdk-kotlin](https://github.com/TungoAI/tungo-sdk-kotlin) | `kz.tungo:tungo-sdk-kotlin` |
|
|
335
|
+
| Swift | [tungo-sdk-swift](https://github.com/TungoAI/tungo-sdk-swift) | `TungoSDK` |
|
|
336
|
+
| Ruby | [tungo-sdk-ruby](https://github.com/TungoAI/tungo-sdk-ruby) | `tungo-sdk` |
|
|
337
|
+
| .NET | [tungo-sdk-dotnet](https://github.com/TungoAI/tungo-sdk-dotnet) | `Tungo.Sdk` |
|
|
338
|
+
|
|
339
|
+
## Versioning and support
|
|
340
|
+
|
|
341
|
+
This library follows [Semantic Versioning](https://semver.org/). While the major version is 0, a minor release may contain breaking changes; they are always listed in the [changelog](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md). This README describes version 0.3.0.
|
|
342
|
+
|
|
343
|
+
The code is generated: please report problems and ideas in the [issue tracker](https://github.com/TungoAI/tungo-sdk-typescript/issues) rather than opening pull requests against generated files. To report a vulnerability, follow the [security policy](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/SECURITY.md).
|
|
344
|
+
|
|
345
|
+
## License
|
|
346
|
+
|
|
347
|
+
[MIT](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/LICENSE)
|