anongto 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +123 -2
- package/dist/index.cjs +431 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +444 -0
- package/dist/index.d.ts +444 -0
- package/dist/index.js +408 -0
- package/dist/index.js.map +1 -0
- package/package.json +57 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AnonGTO
|
|
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,124 @@
|
|
|
1
|
-
#
|
|
1
|
+
# anongto (TypeScript / JavaScript)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The JavaScript client for the [AnonGTO Solver API](https://anongto.com/api/): heads-up NLHE strategies and EVs from preflop to river, in under a second. Amounts are in big blinds.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install anongto
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Zero runtime dependencies. ESM and CommonJS, full TypeScript types. It uses the global `fetch` and Web Crypto, so it runs on Node 18+, Bun, Deno, Cloudflare Workers, Vercel Edge and in browsers (keep your key on a server, though).
|
|
10
|
+
|
|
11
|
+
## Quick start
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { AnonGTO } from 'anongto';
|
|
15
|
+
|
|
16
|
+
const client = new AnonGTO(); // reads process.env.ANONGTO_API_KEY; create one and reuse it
|
|
17
|
+
|
|
18
|
+
// custom ranges: your own ranges, pot, stack and sizes for one postflop street
|
|
19
|
+
const answer = await client.solve({
|
|
20
|
+
board: 'Jh9s4d',
|
|
21
|
+
pot_bb: 5.5,
|
|
22
|
+
stack_bb: 97.5,
|
|
23
|
+
ranges: { oop: '22-99, A2s-A9s, K9s+, QTs+', ip: '22+, A2s+, K2s+, ATo+' },
|
|
24
|
+
bet_sizes: ['33%', '75%'],
|
|
25
|
+
line: ['check'], // this street's actions so far, out of position first
|
|
26
|
+
detail: 'classes',
|
|
27
|
+
});
|
|
28
|
+
console.log(answer.to_act, answer.ev_bb);
|
|
29
|
+
for (const a of answer.actions) console.log(a.action, a.frequency, a.ev_bb);
|
|
30
|
+
console.log(answer.hands?.['AKs']?.strategy);
|
|
31
|
+
console.log(client.lastQuota); // { limit: 2000, remaining: 1987, ... }
|
|
32
|
+
|
|
33
|
+
// chart mode: name one of our preflop charts and the actions so far
|
|
34
|
+
const spot = await client.solve({
|
|
35
|
+
chart: '6m-nl500-o2_5-d100',
|
|
36
|
+
preflop: ['BTN raise 2.5', 'BB call'],
|
|
37
|
+
board: 'Jh9s4d2c',
|
|
38
|
+
flop: ['check', 'bet 1.28', 'call'],
|
|
39
|
+
});
|
|
40
|
+
console.log(spot.source, spot.positions); // typed as ChartSolveResponse
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`solve` takes a discriminated union: a body with `chart` is a `ChartSolveRequest` (and returns a `ChartSolveResponse`), any other is a `CustomSolveRequest`. Field names are the API's own (snake_case). The full reference is at https://anongto.com/api/docs/.
|
|
44
|
+
|
|
45
|
+
CommonJS: `const { AnonGTO } = require('anongto');`
|
|
46
|
+
|
|
47
|
+
## Every method
|
|
48
|
+
|
|
49
|
+
| Method | Endpoint |
|
|
50
|
+
|---|---|
|
|
51
|
+
| `solve(body)` | `POST /v1/solve` |
|
|
52
|
+
| `charts()` | `GET /v1/charts` (no key) |
|
|
53
|
+
| `demo({ preset?, detail? })` | `GET /v1/demo` (no key) |
|
|
54
|
+
| `status()` | `GET /v1/status` (no key) |
|
|
55
|
+
| `account()` | `GET /v1/account` |
|
|
56
|
+
| `rotateKey({ useNewKey? })` | `POST /v1/account/rotate` (the client switches to the new key) |
|
|
57
|
+
| `rollWebhookSecret()` | `POST /v1/account/webhook-secret` |
|
|
58
|
+
| `batches.create({ requests, webhook_url?, metadata? })` | `POST /v1/batches` |
|
|
59
|
+
| `batches.get(id)`, `batches.list()`, `batches.cancel(id)` | `GET /v1/batches/{id}`, `GET /v1/batches`, `POST /v1/batches/{id}/cancel` |
|
|
60
|
+
| `batches.results(id)` | every page of `GET /v1/batches/{id}/results`, as an async iterator |
|
|
61
|
+
| `batches.resultsPage(id, { offset, limit })` | one page |
|
|
62
|
+
| `batches.wait(id, { poll?, timeout? })` | polls until `completed` or `cancelled` (seconds) |
|
|
63
|
+
|
|
64
|
+
Every method takes a last `{ signal?, timeout?, maxRetries? }` argument.
|
|
65
|
+
|
|
66
|
+
## Batches
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
const batch = await client.batches.create({
|
|
70
|
+
requests: ['Jh9s4d', 'As7c2d', 'KhQh5s'].map((board) => ({
|
|
71
|
+
board, pot_bb: 5.5, stack_bb: 97.5, ranges: { oop: '22+', ip: '22+' }, detail: 'summary' as const,
|
|
72
|
+
})),
|
|
73
|
+
metadata: { study: 'single-raised pots' },
|
|
74
|
+
});
|
|
75
|
+
await client.batches.wait(batch.id, { timeout: 600 });
|
|
76
|
+
for await (const item of client.batches.results(batch.id)) {
|
|
77
|
+
if (item.status === 'done') console.log(item.index, item.response.actions);
|
|
78
|
+
else if (item.status === 'failed') console.log(item.index, item.error.code);
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Webhooks
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { verifyWebhook, WebhookVerificationError } from 'anongto';
|
|
86
|
+
|
|
87
|
+
const raw = await request.text(); // the raw body, before parsing
|
|
88
|
+
const event = await verifyWebhook(raw, request.headers.get('AnonGTO-Signature'), secret, 300);
|
|
89
|
+
if (event.type === 'batch.completed') console.log(event.data.batch.id);
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
`secret` is `(await client.account()).webhook_secret`. It throws `WebhookVerificationError` on a bad signature, a malformed header, or a timestamp more than `toleranceSec` (default 300, 0 to skip) from now. `signWebhook(body, secret)` makes a valid header for your tests.
|
|
93
|
+
|
|
94
|
+
## Errors and retries
|
|
95
|
+
|
|
96
|
+
| Class | Status | Codes |
|
|
97
|
+
|---|---|---|
|
|
98
|
+
| `AuthenticationError` | 401 | `unauthorized`; `missing_api_key` (thrown before sending) |
|
|
99
|
+
| `PermissionDeniedError` | 403 | `forbidden`, `not_in_plan` |
|
|
100
|
+
| `NotFoundError` | 404 | `not_found` |
|
|
101
|
+
| `InvalidRequestError` | 400, 413, 422 | `invalid_range`, `unknown_field`, `line_not_in_tree`, `flop_not_stored`, ... |
|
|
102
|
+
| `RateLimitError` | 429 | `rate_limited`, `quota_exceeded`, `too_many_batches`; `.retryAfter`, `.quotaExceeded`, `.rateLimited` |
|
|
103
|
+
| `ServiceUnavailableError` | 503, 504 | `busy`, `timeout`, `not_ready`; `.retryAfter` |
|
|
104
|
+
| `InternalServerError` | 500, other | `internal` |
|
|
105
|
+
| `APIConnectionError`, `APITimeoutError` | none | no answer in time |
|
|
106
|
+
|
|
107
|
+
All extend `AnonGTOError` with `.status`, `.code` (typed as the `ErrorCode` union), `.message` (the API's message), `.headers`, `.requestId` and `.body`.
|
|
108
|
+
|
|
109
|
+
The client retries (`maxRetries: 2` by default) only on 429 `rate_limited` (after `Retry-After`), 503 `busy` and 504. It never retries `quota_exceeded`.
|
|
110
|
+
|
|
111
|
+
## Options
|
|
112
|
+
|
|
113
|
+
`new AnonGTO({ apiKey, baseURL = 'https://api.anongto.com', timeout = 60000, maxRetries = 2, maxRetryWait = 60, fetch, defaultHeaders })`. `ANONGTO_BASE_URL` overrides the base URL where there is a `process.env`.
|
|
114
|
+
|
|
115
|
+
## Development
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
npm install
|
|
119
|
+
npm test # vitest, mocked fetch
|
|
120
|
+
npm run typecheck
|
|
121
|
+
npm run build # tsup: dist/index.js (ESM), dist/index.cjs (CJS), .d.ts
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
The API is for study and analysis tools, not for use during play.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
APIConnectionError: () => APIConnectionError,
|
|
24
|
+
APITimeoutError: () => APITimeoutError,
|
|
25
|
+
AnonGTO: () => AnonGTO,
|
|
26
|
+
AnonGTOError: () => AnonGTOError,
|
|
27
|
+
AuthenticationError: () => AuthenticationError,
|
|
28
|
+
Batches: () => Batches,
|
|
29
|
+
DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
|
|
30
|
+
InternalServerError: () => InternalServerError,
|
|
31
|
+
InvalidRequestError: () => InvalidRequestError,
|
|
32
|
+
NotFoundError: () => NotFoundError,
|
|
33
|
+
PermissionDeniedError: () => PermissionDeniedError,
|
|
34
|
+
RateLimitError: () => RateLimitError,
|
|
35
|
+
SIGNATURE_HEADER: () => SIGNATURE_HEADER,
|
|
36
|
+
ServiceUnavailableError: () => ServiceUnavailableError,
|
|
37
|
+
VERSION: () => VERSION,
|
|
38
|
+
WebhookVerificationError: () => WebhookVerificationError,
|
|
39
|
+
default: () => AnonGTO,
|
|
40
|
+
signWebhook: () => signWebhook,
|
|
41
|
+
verifyWebhook: () => verifyWebhook
|
|
42
|
+
});
|
|
43
|
+
module.exports = __toCommonJS(index_exports);
|
|
44
|
+
|
|
45
|
+
// src/errors.ts
|
|
46
|
+
var AnonGTOError = class extends Error {
|
|
47
|
+
/** The HTTP status; null when no response arrived. */
|
|
48
|
+
status;
|
|
49
|
+
/** The API's error code, e.g. "invalid_range" or "quota_exceeded" (`message` is the API's message, unprefixed). */
|
|
50
|
+
code;
|
|
51
|
+
/** The response headers (empty when no response arrived). */
|
|
52
|
+
headers;
|
|
53
|
+
/** The X-Request-Id header, when the server sent one. */
|
|
54
|
+
requestId;
|
|
55
|
+
/** The parsed JSON body, when there was one. */
|
|
56
|
+
body;
|
|
57
|
+
constructor(message, init = {}) {
|
|
58
|
+
super(message, init.cause !== void 0 ? { cause: init.cause } : void 0);
|
|
59
|
+
this.name = new.target.name;
|
|
60
|
+
this.status = init.status ?? null;
|
|
61
|
+
this.code = init.code ?? null;
|
|
62
|
+
this.headers = init.headers ?? new Headers();
|
|
63
|
+
this.requestId = this.headers.get("x-request-id");
|
|
64
|
+
this.body = init.body;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
var APIConnectionError = class extends AnonGTOError {
|
|
68
|
+
};
|
|
69
|
+
var APITimeoutError = class extends APIConnectionError {
|
|
70
|
+
};
|
|
71
|
+
var AuthenticationError = class extends AnonGTOError {
|
|
72
|
+
};
|
|
73
|
+
var PermissionDeniedError = class extends AnonGTOError {
|
|
74
|
+
};
|
|
75
|
+
var NotFoundError = class extends AnonGTOError {
|
|
76
|
+
};
|
|
77
|
+
var InvalidRequestError = class extends AnonGTOError {
|
|
78
|
+
};
|
|
79
|
+
var InternalServerError = class extends AnonGTOError {
|
|
80
|
+
};
|
|
81
|
+
var retryAfterOf = (h) => {
|
|
82
|
+
const v = h.get("retry-after");
|
|
83
|
+
if (v === null) return null;
|
|
84
|
+
const n = Number(v);
|
|
85
|
+
return Number.isFinite(n) ? Math.max(0, n) : null;
|
|
86
|
+
};
|
|
87
|
+
var RateLimitError = class extends AnonGTOError {
|
|
88
|
+
/** Seconds, from Retry-After. */
|
|
89
|
+
retryAfter;
|
|
90
|
+
constructor(message, init = {}) {
|
|
91
|
+
super(message, init);
|
|
92
|
+
this.retryAfter = retryAfterOf(this.headers);
|
|
93
|
+
}
|
|
94
|
+
get quotaExceeded() {
|
|
95
|
+
return this.code === "quota_exceeded";
|
|
96
|
+
}
|
|
97
|
+
get rateLimited() {
|
|
98
|
+
return this.code === "rate_limited";
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
var ServiceUnavailableError = class extends AnonGTOError {
|
|
102
|
+
retryAfter;
|
|
103
|
+
constructor(message, init = {}) {
|
|
104
|
+
super(message, init);
|
|
105
|
+
this.retryAfter = retryAfterOf(this.headers);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
function errorFor(status, body, headers) {
|
|
109
|
+
let code = null;
|
|
110
|
+
let message = `HTTP ${status}`;
|
|
111
|
+
const e = body?.error;
|
|
112
|
+
if (e && typeof e === "object") {
|
|
113
|
+
const { code: c, message: m } = e;
|
|
114
|
+
if (typeof c === "string") code = c;
|
|
115
|
+
if (typeof m === "string" && m) message = m;
|
|
116
|
+
} else if (typeof e === "string") message = e;
|
|
117
|
+
const init = { status, code, headers, body };
|
|
118
|
+
if (status === 401) return new AuthenticationError(message, init);
|
|
119
|
+
if (status === 403) return new PermissionDeniedError(message, init);
|
|
120
|
+
if (status === 404) return new NotFoundError(message, init);
|
|
121
|
+
if (status === 400 || status === 413 || status === 422) return new InvalidRequestError(message, init);
|
|
122
|
+
if (status === 429) return new RateLimitError(message, init);
|
|
123
|
+
if (status === 503 || status === 504) return new ServiceUnavailableError(message, init);
|
|
124
|
+
return new InternalServerError(message, init);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// src/version.ts
|
|
128
|
+
var VERSION = "0.1.0";
|
|
129
|
+
|
|
130
|
+
// src/client.ts
|
|
131
|
+
var DEFAULT_BASE_URL = "https://api.anongto.com";
|
|
132
|
+
var env = (name) => {
|
|
133
|
+
const p = globalThis.process;
|
|
134
|
+
return p?.env?.[name] || void 0;
|
|
135
|
+
};
|
|
136
|
+
var sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
137
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
138
|
+
const t = setTimeout(() => {
|
|
139
|
+
signal?.removeEventListener("abort", onAbort);
|
|
140
|
+
resolve();
|
|
141
|
+
}, ms);
|
|
142
|
+
const onAbort = () => {
|
|
143
|
+
clearTimeout(t);
|
|
144
|
+
reject(signal.reason);
|
|
145
|
+
};
|
|
146
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
147
|
+
});
|
|
148
|
+
var batchPath = (id) => {
|
|
149
|
+
if (typeof id !== "string" || !id || id.includes("/")) throw new TypeError(`not a batch id: ${JSON.stringify(id)}`);
|
|
150
|
+
return `/v1/batches/${encodeURIComponent(id)}`;
|
|
151
|
+
};
|
|
152
|
+
var FINISHED = /* @__PURE__ */ new Set(["completed", "cancelled"]);
|
|
153
|
+
function quotaFrom(h) {
|
|
154
|
+
if (h.get("x-quota-limit") === null && h.get("x-quota-remaining") === null) return null;
|
|
155
|
+
const n = (k) => {
|
|
156
|
+
const v = h.get(k);
|
|
157
|
+
if (v === null) return null;
|
|
158
|
+
const x = Number(v);
|
|
159
|
+
return Number.isFinite(x) ? x : null;
|
|
160
|
+
};
|
|
161
|
+
return {
|
|
162
|
+
limit: n("x-quota-limit"),
|
|
163
|
+
remaining: n("x-quota-remaining"),
|
|
164
|
+
totalLimit: n("x-quota-total-limit"),
|
|
165
|
+
totalRemaining: n("x-quota-total-remaining"),
|
|
166
|
+
serverTiming: h.get("server-timing")
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
var Batches = class {
|
|
170
|
+
constructor(client) {
|
|
171
|
+
this.client = client;
|
|
172
|
+
}
|
|
173
|
+
client;
|
|
174
|
+
/** POST /v1/batches: many solve bodies answered in the background (202, status "queued"). */
|
|
175
|
+
create(body, opts) {
|
|
176
|
+
return this.client.request("POST", "/v1/batches", { body, ...opts });
|
|
177
|
+
}
|
|
178
|
+
/** GET /v1/batches/{id}: its progress. */
|
|
179
|
+
get(id, opts) {
|
|
180
|
+
return this.client.request("GET", batchPath(id), opts);
|
|
181
|
+
}
|
|
182
|
+
/** GET /v1/batches: this key's last 50 batches, newest first. */
|
|
183
|
+
async list(opts) {
|
|
184
|
+
return (await this.client.request("GET", "/v1/batches", opts)).batches;
|
|
185
|
+
}
|
|
186
|
+
/** POST /v1/batches/{id}/cancel: items not started yet are dropped. */
|
|
187
|
+
cancel(id, opts) {
|
|
188
|
+
return this.client.request("POST", `${batchPath(id)}/cancel`, opts);
|
|
189
|
+
}
|
|
190
|
+
/** GET /v1/batches/{id}/results: one page (limit up to 500). */
|
|
191
|
+
resultsPage(id, page = {}, opts) {
|
|
192
|
+
const offset = Math.max(0, Math.floor(page.offset ?? 0));
|
|
193
|
+
const limit = Math.min(500, Math.max(1, Math.floor(page.limit ?? 500)));
|
|
194
|
+
return this.client.request("GET", `${batchPath(id)}/results`, { ...opts, query: { offset, limit } });
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Every result of a batch, in order, page after page: `for await (const r of client.batches.results(id))`.
|
|
198
|
+
* Items not answered yet have status "queued"; call `wait` first to get them all answered.
|
|
199
|
+
*/
|
|
200
|
+
async *results(id, opts = {}) {
|
|
201
|
+
let offset = 0;
|
|
202
|
+
while (offset !== null) {
|
|
203
|
+
const page = await this.resultsPage(id, { offset, limit: opts.pageSize ?? 500 }, opts);
|
|
204
|
+
yield* page.results;
|
|
205
|
+
offset = typeof page.next_offset === "number" && page.next_offset > offset ? page.next_offset : null;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Poll until the batch is "completed" or "cancelled" and return it. A key out of quota waits ("waiting_for_quota")
|
|
210
|
+
* until 00:00 UTC: set `timeout` (seconds) to stop waiting.
|
|
211
|
+
*/
|
|
212
|
+
async wait(id, opts = {}) {
|
|
213
|
+
const poll = (opts.poll ?? 2) * 1e3;
|
|
214
|
+
const deadline = opts.timeout === void 0 ? null : Date.now() + opts.timeout * 1e3;
|
|
215
|
+
const reqOpts = { signal: opts.signal, maxRetries: opts.maxRetries };
|
|
216
|
+
for (; ; ) {
|
|
217
|
+
const b = await this.get(id, reqOpts);
|
|
218
|
+
if (FINISHED.has(b.status)) return b;
|
|
219
|
+
if (deadline !== null && Date.now() + poll > deadline)
|
|
220
|
+
throw new APITimeoutError(`batch ${id} still ${b.status} after ${opts.timeout}s (${b.done} done of ${b.total})`, { code: "timeout" });
|
|
221
|
+
await this.client.sleep(poll, opts.signal);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
var AnonGTO = class {
|
|
226
|
+
apiKey;
|
|
227
|
+
baseURL;
|
|
228
|
+
timeout;
|
|
229
|
+
maxRetries;
|
|
230
|
+
maxRetryWait;
|
|
231
|
+
/** Quota from the last response that carried X-Quota-* headers (solves, and their refusals). */
|
|
232
|
+
lastQuota = null;
|
|
233
|
+
batches;
|
|
234
|
+
fetchImpl;
|
|
235
|
+
defaultHeaders;
|
|
236
|
+
/** @internal tests replace it */
|
|
237
|
+
sleep = sleep;
|
|
238
|
+
constructor(opts = {}) {
|
|
239
|
+
this.apiKey = opts.apiKey !== void 0 ? opts.apiKey || null : env("ANONGTO_API_KEY") ?? null;
|
|
240
|
+
this.baseURL = (opts.baseURL ?? env("ANONGTO_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
241
|
+
this.timeout = opts.timeout ?? 6e4;
|
|
242
|
+
this.maxRetries = Math.max(0, Math.floor(opts.maxRetries ?? 2));
|
|
243
|
+
this.maxRetryWait = opts.maxRetryWait ?? 60;
|
|
244
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
245
|
+
if (!f) throw new Error("no fetch: use Node 18+ or pass { fetch }");
|
|
246
|
+
this.fetchImpl = opts.fetch ? f : (input, init) => globalThis.fetch(input, init);
|
|
247
|
+
this.defaultHeaders = opts.defaultHeaders ?? {};
|
|
248
|
+
this.batches = new Batches(this);
|
|
249
|
+
}
|
|
250
|
+
solve(body, opts) {
|
|
251
|
+
return this.request("POST", "/v1/solve", { body, ...opts });
|
|
252
|
+
}
|
|
253
|
+
/** GET /v1/charts (no key): the charts chart mode answers from, and their lines with stored flops. */
|
|
254
|
+
charts(opts) {
|
|
255
|
+
return this.request("GET", "/v1/charts", { ...opts, auth: false });
|
|
256
|
+
}
|
|
257
|
+
/** GET /v1/demo (no key): a saved answer for a fixed spot; without a preset, the list of presets. */
|
|
258
|
+
demo(params = {}, opts) {
|
|
259
|
+
return this.request("GET", "/v1/demo", { ...opts, auth: false, query: params });
|
|
260
|
+
}
|
|
261
|
+
/** GET /v1/status (no key): is every part up, and the uptime of the last 90 days. */
|
|
262
|
+
status(opts) {
|
|
263
|
+
return this.request("GET", "/v1/status", { ...opts, auth: false });
|
|
264
|
+
}
|
|
265
|
+
/** GET /v1/account: this key's tier, limits, usage by day and street, and webhook secret. */
|
|
266
|
+
account(opts) {
|
|
267
|
+
return this.request("GET", "/v1/account", opts);
|
|
268
|
+
}
|
|
269
|
+
/** POST /v1/account/rotate: a new key (the old one works until previous_key_stops_at). The client switches to it unless useNewKey is false. */
|
|
270
|
+
async rotateKey(opts = {}) {
|
|
271
|
+
const out = await this.request("POST", "/v1/account/rotate", opts);
|
|
272
|
+
if (opts.useNewKey !== false && out.key) this.apiKey = out.key;
|
|
273
|
+
return out;
|
|
274
|
+
}
|
|
275
|
+
/** POST /v1/account/webhook-secret: a new webhook signing secret (the old one stops at once). */
|
|
276
|
+
rollWebhookSecret(opts) {
|
|
277
|
+
return this.request("POST", "/v1/account/webhook-secret", opts);
|
|
278
|
+
}
|
|
279
|
+
/** @internal one call, with the retry rules */
|
|
280
|
+
async request(method, path, o = {}) {
|
|
281
|
+
const headers = { accept: "application/json", ...this.defaultHeaders };
|
|
282
|
+
if (typeof globalThis.document === "undefined") headers["user-agent"] = `anongto-js/${VERSION}`;
|
|
283
|
+
if (o.auth !== false && !this.apiKey)
|
|
284
|
+
throw new AuthenticationError("no API key: pass new AnonGTO({ apiKey }) or set ANONGTO_API_KEY (get one at https://anongto.com/api/)", { code: "missing_api_key" });
|
|
285
|
+
if (this.apiKey) headers.authorization = `Bearer ${this.apiKey}`;
|
|
286
|
+
let url = this.baseURL + path;
|
|
287
|
+
if (o.query) {
|
|
288
|
+
const q = new URLSearchParams();
|
|
289
|
+
for (const [k, v] of Object.entries(o.query)) if (v !== void 0 && v !== null) q.set(k, String(v));
|
|
290
|
+
const s = q.toString();
|
|
291
|
+
if (s) url += `?${s}`;
|
|
292
|
+
}
|
|
293
|
+
let body;
|
|
294
|
+
if (o.body !== void 0 || method === "POST") {
|
|
295
|
+
body = o.body === void 0 ? "{}" : JSON.stringify(o.body);
|
|
296
|
+
headers["content-type"] = "application/json";
|
|
297
|
+
}
|
|
298
|
+
const maxRetries = Math.max(0, o.maxRetries ?? this.maxRetries);
|
|
299
|
+
const timeout = o.timeout ?? this.timeout;
|
|
300
|
+
for (let attempt = 0; ; attempt++) {
|
|
301
|
+
const ctl = new AbortController();
|
|
302
|
+
const onAbort = () => ctl.abort(o.signal.reason);
|
|
303
|
+
if (o.signal?.aborted) throw o.signal.reason;
|
|
304
|
+
o.signal?.addEventListener("abort", onAbort, { once: true });
|
|
305
|
+
let timedOut = false;
|
|
306
|
+
const timer = setTimeout(() => {
|
|
307
|
+
timedOut = true;
|
|
308
|
+
ctl.abort();
|
|
309
|
+
}, timeout);
|
|
310
|
+
let res;
|
|
311
|
+
let text;
|
|
312
|
+
try {
|
|
313
|
+
res = await this.fetchImpl(url, { method, headers, body, signal: ctl.signal });
|
|
314
|
+
text = await res.text();
|
|
315
|
+
} catch (e) {
|
|
316
|
+
if (timedOut) throw new APITimeoutError(`no answer from ${url} within ${timeout} ms`, { code: "timeout", cause: e });
|
|
317
|
+
if (o.signal?.aborted) throw e;
|
|
318
|
+
throw new APIConnectionError(`could not reach ${url}: ${e?.message ?? e}`, { code: "connection_error", cause: e });
|
|
319
|
+
} finally {
|
|
320
|
+
clearTimeout(timer);
|
|
321
|
+
o.signal?.removeEventListener("abort", onAbort);
|
|
322
|
+
}
|
|
323
|
+
const q = quotaFrom(res.headers);
|
|
324
|
+
if (q) this.lastQuota = q;
|
|
325
|
+
let parsed = void 0;
|
|
326
|
+
if (text) {
|
|
327
|
+
try {
|
|
328
|
+
parsed = JSON.parse(text);
|
|
329
|
+
} catch {
|
|
330
|
+
parsed = void 0;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
if (res.ok) {
|
|
334
|
+
if (parsed === void 0 && text) throw new AnonGTOError("the answer was not JSON", { status: res.status, headers: res.headers });
|
|
335
|
+
return parsed;
|
|
336
|
+
}
|
|
337
|
+
const err = errorFor(res.status, parsed, res.headers);
|
|
338
|
+
const wait = this.retryWait(err, attempt, maxRetries);
|
|
339
|
+
if (wait === null) throw err;
|
|
340
|
+
await this.sleep(wait, o.signal);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
/** ms to wait before retrying, or null to throw */
|
|
344
|
+
retryWait(err, attempt, maxRetries) {
|
|
345
|
+
if (attempt >= maxRetries) return null;
|
|
346
|
+
const retryable = err.status === 429 && err.code === "rate_limited" || err.status === 503 && err.code === "busy" || err.status === 504;
|
|
347
|
+
if (!retryable) return null;
|
|
348
|
+
const after = err instanceof RateLimitError || err instanceof ServiceUnavailableError ? err.retryAfter : null;
|
|
349
|
+
if (after !== null) return after <= this.maxRetryWait ? after * 1e3 : null;
|
|
350
|
+
return Math.min(8e3, 500 * 2 ** attempt) * (0.75 + Math.random() * 0.5);
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
// src/webhooks.ts
|
|
355
|
+
var SIGNATURE_HEADER = "AnonGTO-Signature";
|
|
356
|
+
var WebhookVerificationError = class extends Error {
|
|
357
|
+
constructor(message) {
|
|
358
|
+
super(message);
|
|
359
|
+
this.name = "WebhookVerificationError";
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
var enc = new TextEncoder();
|
|
363
|
+
var bytesOf = (p) => typeof p === "string" ? enc.encode(p) : p instanceof Uint8Array ? p : new Uint8Array(p);
|
|
364
|
+
async function subtle() {
|
|
365
|
+
const c = globalThis.crypto;
|
|
366
|
+
if (c?.subtle) return c.subtle;
|
|
367
|
+
const mod = "node:crypto";
|
|
368
|
+
const nodeCrypto = await import(
|
|
369
|
+
/* @vite-ignore */
|
|
370
|
+
/* webpackIgnore: true */
|
|
371
|
+
mod
|
|
372
|
+
);
|
|
373
|
+
if (nodeCrypto.webcrypto?.subtle) return nodeCrypto.webcrypto.subtle;
|
|
374
|
+
throw new WebhookVerificationError("no Web Crypto (crypto.subtle) in this runtime");
|
|
375
|
+
}
|
|
376
|
+
async function hmacHex(secret, t, body) {
|
|
377
|
+
const s = await subtle();
|
|
378
|
+
const key = await s.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
379
|
+
const prefix = enc.encode(`${t}.`);
|
|
380
|
+
const msg = new Uint8Array(prefix.length + body.length);
|
|
381
|
+
msg.set(prefix, 0);
|
|
382
|
+
msg.set(body, prefix.length);
|
|
383
|
+
const mac = new Uint8Array(await s.sign("HMAC", key, msg));
|
|
384
|
+
let hex = "";
|
|
385
|
+
for (const b of mac) hex += b.toString(16).padStart(2, "0");
|
|
386
|
+
return hex;
|
|
387
|
+
}
|
|
388
|
+
function safeEqual(a, b) {
|
|
389
|
+
if (a.length !== b.length) return false;
|
|
390
|
+
let d = 0;
|
|
391
|
+
for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
392
|
+
return d === 0;
|
|
393
|
+
}
|
|
394
|
+
function parseHeader(header) {
|
|
395
|
+
let t = null;
|
|
396
|
+
const sigs = [];
|
|
397
|
+
for (const part of header.split(",")) {
|
|
398
|
+
const i = part.indexOf("=");
|
|
399
|
+
if (i < 0) continue;
|
|
400
|
+
const k = part.slice(0, i).trim();
|
|
401
|
+
const v = part.slice(i + 1).trim();
|
|
402
|
+
if (k === "t") {
|
|
403
|
+
if (!/^\d+$/.test(v)) throw new WebhookVerificationError("signature header: t is not a number");
|
|
404
|
+
t = Number(v);
|
|
405
|
+
} else if (k === "v1") sigs.push(v.toLowerCase());
|
|
406
|
+
}
|
|
407
|
+
if (t === null || !sigs.length) throw new WebhookVerificationError("signature header: expected t=<unix seconds>,v1=<hex>");
|
|
408
|
+
return { t, sigs };
|
|
409
|
+
}
|
|
410
|
+
async function signWebhook(payload, secret, timestamp = Math.floor(Date.now() / 1e3)) {
|
|
411
|
+
return `t=${timestamp},v1=${await hmacHex(secret, timestamp, bytesOf(payload))}`;
|
|
412
|
+
}
|
|
413
|
+
async function verifyWebhook(payload, header, secret, toleranceSec = 300) {
|
|
414
|
+
if (!secret) throw new WebhookVerificationError("no webhook secret");
|
|
415
|
+
if (!header) throw new WebhookVerificationError(`no ${SIGNATURE_HEADER} header`);
|
|
416
|
+
const { t, sigs } = parseHeader(header);
|
|
417
|
+
if (toleranceSec > 0 && Math.abs(Date.now() / 1e3 - t) > toleranceSec)
|
|
418
|
+
throw new WebhookVerificationError(`signature timestamp outside the tolerance of ${toleranceSec}s`);
|
|
419
|
+
const body = bytesOf(payload);
|
|
420
|
+
const want = await hmacHex(secret, t, body);
|
|
421
|
+
if (!sigs.some((s) => safeEqual(want, s))) throw new WebhookVerificationError("signature does not match");
|
|
422
|
+
let event;
|
|
423
|
+
try {
|
|
424
|
+
event = JSON.parse(new TextDecoder().decode(body));
|
|
425
|
+
} catch {
|
|
426
|
+
throw new WebhookVerificationError("the body is not JSON");
|
|
427
|
+
}
|
|
428
|
+
if (!event || typeof event !== "object" || !("type" in event)) throw new WebhookVerificationError("the body is not a webhook event");
|
|
429
|
+
return event;
|
|
430
|
+
}
|
|
431
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/version.ts","../src/client.ts","../src/webhooks.ts"],"sourcesContent":["export { AnonGTO, AnonGTO as default, Batches, DEFAULT_BASE_URL } from './client.js';\nexport type { ClientOptions, FetchLike, RequestOptions, WaitOptions } from './client.js';\nexport {\n AnonGTOError,\n APIConnectionError,\n APITimeoutError,\n AuthenticationError,\n InternalServerError,\n InvalidRequestError,\n NotFoundError,\n PermissionDeniedError,\n RateLimitError,\n ServiceUnavailableError,\n} from './errors.js';\nexport { SIGNATURE_HEADER, WebhookVerificationError, signWebhook, verifyWebhook } from './webhooks.js';\nexport { VERSION } from './version.js';\nexport type * from './types.js';\n","import type { ErrorCode } from './types.js';\n\nexport interface AnonGTOErrorInit {\n status?: number | null;\n code?: ErrorCode | null;\n headers?: Headers;\n body?: unknown;\n cause?: unknown;\n}\n\n/** Base class of every error the client throws. */\nexport class AnonGTOError extends Error {\n /** The HTTP status; null when no response arrived. */\n readonly status: number | null;\n /** The API's error code, e.g. \"invalid_range\" or \"quota_exceeded\" (`message` is the API's message, unprefixed). */\n readonly code: ErrorCode | null;\n /** The response headers (empty when no response arrived). */\n readonly headers: Headers;\n /** The X-Request-Id header, when the server sent one. */\n readonly requestId: string | null;\n /** The parsed JSON body, when there was one. */\n readonly body: unknown;\n\n constructor(message: string, init: AnonGTOErrorInit = {}) {\n super(message, init.cause !== undefined ? { cause: init.cause } : undefined);\n this.name = new.target.name;\n this.status = init.status ?? null;\n this.code = init.code ?? null;\n this.headers = init.headers ?? new Headers();\n this.requestId = this.headers.get('x-request-id');\n this.body = init.body;\n }\n}\n\n/** The request never got an answer (DNS, refused connection, reset). */\nexport class APIConnectionError extends AnonGTOError {}\n/** The request took longer than the timeout. */\nexport class APITimeoutError extends APIConnectionError {}\n/** 401: no key, or an unknown, expired or revoked one (code \"missing_api_key\" when none was set). */\nexport class AuthenticationError extends AnonGTOError {}\n/** 403: the key may not do this (forbidden, not_in_plan). */\nexport class PermissionDeniedError extends AnonGTOError {}\n/** 404: no such batch (for this key) or route. */\nexport class NotFoundError extends AnonGTOError {}\n/** 400, 413 or 422: the body is wrong, too large, or the spot cannot be answered. */\nexport class InvalidRequestError extends AnonGTOError {}\n/** 500 or any other unexpected status. */\nexport class InternalServerError extends AnonGTOError {}\n\nconst retryAfterOf = (h: Headers): number | null => {\n const v = h.get('retry-after');\n if (v === null) return null;\n const n = Number(v);\n return Number.isFinite(n) ? Math.max(0, n) : null;\n};\n\n/**\n * 429. `code` tells the cases apart: \"rate_limited\" (too fast; retried after Retry-After), \"quota_exceeded\" (the daily\n * quota or lifetime cap is used; never retried), \"too_many_batches\".\n */\nexport class RateLimitError extends AnonGTOError {\n /** Seconds, from Retry-After. */\n readonly retryAfter: number | null;\n constructor(message: string, init: AnonGTOErrorInit = {}) {\n super(message, init);\n this.retryAfter = retryAfterOf(this.headers);\n }\n get quotaExceeded(): boolean {\n return this.code === 'quota_exceeded';\n }\n get rateLimited(): boolean {\n return this.code === 'rate_limited';\n }\n}\n\n/** 503 or 504: busy, timeout or not_ready. \"busy\" and 504 are retried. */\nexport class ServiceUnavailableError extends AnonGTOError {\n readonly retryAfter: number | null;\n constructor(message: string, init: AnonGTOErrorInit = {}) {\n super(message, init);\n this.retryAfter = retryAfterOf(this.headers);\n }\n}\n\n/** The typed error for a non-2xx response. */\nexport function errorFor(status: number, body: unknown, headers: Headers): AnonGTOError {\n let code: ErrorCode | null = null;\n let message = `HTTP ${status}`;\n const e = (body as { error?: unknown } | null)?.error;\n if (e && typeof e === 'object') {\n const { code: c, message: m } = e as { code?: unknown; message?: unknown };\n if (typeof c === 'string') code = c;\n if (typeof m === 'string' && m) message = m;\n } else if (typeof e === 'string') message = e;\n const init = { status, code, headers, body };\n if (status === 401) return new AuthenticationError(message, init);\n if (status === 403) return new PermissionDeniedError(message, init);\n if (status === 404) return new NotFoundError(message, init);\n if (status === 400 || status === 413 || status === 422) return new InvalidRequestError(message, init);\n if (status === 429) return new RateLimitError(message, init);\n if (status === 503 || status === 504) return new ServiceUnavailableError(message, init);\n return new InternalServerError(message, init);\n}\n","export const VERSION = '0.1.0';\n","import {\n AnonGTOError,\n APIConnectionError,\n APITimeoutError,\n AuthenticationError,\n RateLimitError,\n ServiceUnavailableError,\n errorFor,\n} from './errors.js';\nimport type {\n AccountResponse,\n Batch,\n BatchResult,\n BatchResultsPage,\n ChartSolveRequest,\n ChartSolveResponse,\n ChartsResponse,\n CreateBatchRequest,\n CustomSolveRequest,\n CustomSolveResponse,\n DemoResponse,\n Detail,\n QuotaInfo,\n RotateKeyResponse,\n SolveRequest,\n SolveResponse,\n StatusResponse,\n WebhookSecretResponse,\n} from './types.js';\nimport { VERSION } from './version.js';\n\nexport const DEFAULT_BASE_URL = 'https://api.anongto.com';\n\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\nexport interface ClientOptions {\n /** Your agto_… key. Defaults to process.env.ANONGTO_API_KEY where there is a process. Not needed for charts, demo, status. */\n apiKey?: string | null;\n /** Defaults to process.env.ANONGTO_BASE_URL or https://api.anongto.com. */\n baseURL?: string;\n /** Milliseconds per attempt. Default 60000. */\n timeout?: number;\n /** Retries on 429 rate_limited (after Retry-After), 503 busy and 504; never on quota_exceeded. Default 2. */\n maxRetries?: number;\n /** The longest Retry-After (seconds) the client waits for; a longer one is thrown. Default 60. */\n maxRetryWait?: number;\n /** A fetch of your own (default: the global fetch). */\n fetch?: FetchLike;\n /** Extra headers on every request. */\n defaultHeaders?: Record<string, string>;\n}\n\nexport interface RequestOptions {\n signal?: AbortSignal;\n timeout?: number;\n maxRetries?: number;\n}\n\nexport interface WaitOptions extends RequestOptions {\n /** Seconds between polls. Default 2. */\n poll?: number;\n /** Seconds to wait at most; then an APITimeoutError. Default: no limit. */\n timeout?: number;\n}\n\nconst env = (name: string): string | undefined => {\n const p = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;\n return p?.env?.[name] || undefined;\n};\nconst sleep = (ms: number, signal?: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason);\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal!.reason);\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\nconst batchPath = (id: string) => {\n if (typeof id !== 'string' || !id || id.includes('/')) throw new TypeError(`not a batch id: ${JSON.stringify(id)}`);\n return `/v1/batches/${encodeURIComponent(id)}`;\n};\nconst FINISHED = new Set(['completed', 'cancelled']);\n\nfunction quotaFrom(h: Headers): QuotaInfo | null {\n if (h.get('x-quota-limit') === null && h.get('x-quota-remaining') === null) return null;\n const n = (k: string) => {\n const v = h.get(k);\n if (v === null) return null;\n const x = Number(v);\n return Number.isFinite(x) ? x : null;\n };\n return {\n limit: n('x-quota-limit'),\n remaining: n('x-quota-remaining'),\n totalLimit: n('x-quota-total-limit'),\n totalRemaining: n('x-quota-total-remaining'),\n serverTiming: h.get('server-timing'),\n };\n}\n\n/** The batch routes: `client.batches.create(...)`, `.get`, `.list`, `.cancel`, `.results` (async iterator), `.wait`. */\nexport class Batches {\n constructor(private readonly client: AnonGTO) {}\n\n /** POST /v1/batches: many solve bodies answered in the background (202, status \"queued\"). */\n create(body: CreateBatchRequest, opts?: RequestOptions): Promise<Batch> {\n return this.client.request<Batch>('POST', '/v1/batches', { body, ...opts });\n }\n /** GET /v1/batches/{id}: its progress. */\n get(id: string, opts?: RequestOptions): Promise<Batch> {\n return this.client.request<Batch>('GET', batchPath(id), opts);\n }\n /** GET /v1/batches: this key's last 50 batches, newest first. */\n async list(opts?: RequestOptions): Promise<Batch[]> {\n return (await this.client.request<{ batches: Batch[] }>('GET', '/v1/batches', opts)).batches;\n }\n /** POST /v1/batches/{id}/cancel: items not started yet are dropped. */\n cancel(id: string, opts?: RequestOptions): Promise<Batch> {\n return this.client.request<Batch>('POST', `${batchPath(id)}/cancel`, opts);\n }\n /** GET /v1/batches/{id}/results: one page (limit up to 500). */\n resultsPage(id: string, page: { offset?: number; limit?: number } = {}, opts?: RequestOptions): Promise<BatchResultsPage> {\n const offset = Math.max(0, Math.floor(page.offset ?? 0));\n const limit = Math.min(500, Math.max(1, Math.floor(page.limit ?? 500)));\n return this.client.request<BatchResultsPage>('GET', `${batchPath(id)}/results`, { ...opts, query: { offset, limit } });\n }\n /**\n * Every result of a batch, in order, page after page: `for await (const r of client.batches.results(id))`.\n * Items not answered yet have status \"queued\"; call `wait` first to get them all answered.\n */\n async *results(id: string, opts: RequestOptions & { pageSize?: number } = {}): AsyncGenerator<BatchResult, void, undefined> {\n let offset: number | null = 0;\n while (offset !== null) {\n const page: BatchResultsPage = await this.resultsPage(id, { offset, limit: opts.pageSize ?? 500 }, opts);\n yield* page.results;\n offset = typeof page.next_offset === 'number' && page.next_offset > offset ? page.next_offset : null;\n }\n }\n /**\n * Poll until the batch is \"completed\" or \"cancelled\" and return it. A key out of quota waits (\"waiting_for_quota\")\n * until 00:00 UTC: set `timeout` (seconds) to stop waiting.\n */\n async wait(id: string, opts: WaitOptions = {}): Promise<Batch> {\n const poll = (opts.poll ?? 2) * 1000;\n const deadline = opts.timeout === undefined ? null : Date.now() + opts.timeout * 1000;\n const reqOpts: RequestOptions = { signal: opts.signal, maxRetries: opts.maxRetries };\n for (;;) {\n const b = await this.get(id, reqOpts);\n if (FINISHED.has(b.status)) return b;\n if (deadline !== null && Date.now() + poll > deadline)\n throw new APITimeoutError(`batch ${id} still ${b.status} after ${opts.timeout}s (${b.done} done of ${b.total})`, { code: 'timeout' });\n await this.client.sleep(poll, opts.signal);\n }\n }\n}\n\n/** A client for the AnonGTO Solver API. Create one and reuse it. */\nexport class AnonGTO {\n apiKey: string | null;\n readonly baseURL: string;\n readonly timeout: number;\n readonly maxRetries: number;\n readonly maxRetryWait: number;\n /** Quota from the last response that carried X-Quota-* headers (solves, and their refusals). */\n lastQuota: QuotaInfo | null = null;\n readonly batches: Batches;\n private readonly fetchImpl: FetchLike;\n private readonly defaultHeaders: Record<string, string>;\n /** @internal tests replace it */\n sleep: (ms: number, signal?: AbortSignal) => Promise<void> = sleep;\n\n constructor(opts: ClientOptions = {}) {\n this.apiKey = opts.apiKey !== undefined ? opts.apiKey || null : env('ANONGTO_API_KEY') ?? null;\n this.baseURL = (opts.baseURL ?? env('ANONGTO_BASE_URL') ?? DEFAULT_BASE_URL).replace(/\\/+$/, '');\n this.timeout = opts.timeout ?? 60_000;\n this.maxRetries = Math.max(0, Math.floor(opts.maxRetries ?? 2));\n this.maxRetryWait = opts.maxRetryWait ?? 60;\n const f = opts.fetch ?? (globalThis.fetch as FetchLike | undefined);\n if (!f) throw new Error('no fetch: use Node 18+ or pass { fetch }');\n this.fetchImpl = opts.fetch ? f : (input, init) => globalThis.fetch(input, init);\n this.defaultHeaders = opts.defaultHeaders ?? {};\n this.batches = new Batches(this);\n }\n\n /** POST /v1/solve: one decision. A body with `chart` is chart mode; any other is custom ranges. */\n solve(body: ChartSolveRequest, opts?: RequestOptions): Promise<ChartSolveResponse>;\n solve(body: CustomSolveRequest, opts?: RequestOptions): Promise<CustomSolveResponse>;\n solve(body: SolveRequest, opts?: RequestOptions): Promise<SolveResponse>;\n solve(body: SolveRequest, opts?: RequestOptions): Promise<SolveResponse> {\n return this.request<SolveResponse>('POST', '/v1/solve', { body, ...opts });\n }\n /** GET /v1/charts (no key): the charts chart mode answers from, and their lines with stored flops. */\n charts(opts?: RequestOptions): Promise<ChartsResponse> {\n return this.request<ChartsResponse>('GET', '/v1/charts', { ...opts, auth: false });\n }\n /** GET /v1/demo (no key): a saved answer for a fixed spot; without a preset, the list of presets. */\n demo(params: { preset?: string; detail?: Detail } = {}, opts?: RequestOptions): Promise<DemoResponse> {\n return this.request<DemoResponse>('GET', '/v1/demo', { ...opts, auth: false, query: params });\n }\n /** GET /v1/status (no key): is every part up, and the uptime of the last 90 days. */\n status(opts?: RequestOptions): Promise<StatusResponse> {\n return this.request<StatusResponse>('GET', '/v1/status', { ...opts, auth: false });\n }\n /** GET /v1/account: this key's tier, limits, usage by day and street, and webhook secret. */\n account(opts?: RequestOptions): Promise<AccountResponse> {\n return this.request<AccountResponse>('GET', '/v1/account', opts);\n }\n /** POST /v1/account/rotate: a new key (the old one works until previous_key_stops_at). The client switches to it unless useNewKey is false. */\n async rotateKey(opts: RequestOptions & { useNewKey?: boolean } = {}): Promise<RotateKeyResponse> {\n const out = await this.request<RotateKeyResponse>('POST', '/v1/account/rotate', opts);\n if (opts.useNewKey !== false && out.key) this.apiKey = out.key;\n return out;\n }\n /** POST /v1/account/webhook-secret: a new webhook signing secret (the old one stops at once). */\n rollWebhookSecret(opts?: RequestOptions): Promise<WebhookSecretResponse> {\n return this.request<WebhookSecretResponse>('POST', '/v1/account/webhook-secret', opts);\n }\n\n /** @internal one call, with the retry rules */\n async request<T>(\n method: 'GET' | 'POST',\n path: string,\n o: RequestOptions & { body?: unknown; query?: Record<string, string | number | undefined>; auth?: boolean } = {},\n ): Promise<T> {\n const headers: Record<string, string> = { accept: 'application/json', ...this.defaultHeaders };\n // servers and edge runtimes only: in a browser an extra header would fail the CORS preflight\n if (typeof (globalThis as { document?: unknown }).document === 'undefined') headers['user-agent'] = `anongto-js/${VERSION}`;\n if (o.auth !== false && !this.apiKey)\n throw new AuthenticationError('no API key: pass new AnonGTO({ apiKey }) or set ANONGTO_API_KEY (get one at https://anongto.com/api/)', { code: 'missing_api_key' });\n if (this.apiKey) headers.authorization = `Bearer ${this.apiKey}`;\n let url = this.baseURL + path;\n if (o.query) {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(o.query)) if (v !== undefined && v !== null) q.set(k, String(v));\n const s = q.toString();\n if (s) url += `?${s}`;\n }\n let body: string | undefined;\n if (o.body !== undefined || method === 'POST') {\n body = o.body === undefined ? '{}' : JSON.stringify(o.body);\n headers['content-type'] = 'application/json';\n }\n\n const maxRetries = Math.max(0, o.maxRetries ?? this.maxRetries);\n const timeout = o.timeout ?? this.timeout;\n for (let attempt = 0; ; attempt++) {\n const ctl = new AbortController();\n const onAbort = () => ctl.abort(o.signal!.reason);\n if (o.signal?.aborted) throw o.signal.reason;\n o.signal?.addEventListener('abort', onAbort, { once: true });\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n ctl.abort();\n }, timeout);\n let res: Response;\n let text: string;\n try {\n res = await this.fetchImpl(url, { method, headers, body, signal: ctl.signal });\n text = await res.text();\n } catch (e) {\n if (timedOut) throw new APITimeoutError(`no answer from ${url} within ${timeout} ms`, { code: 'timeout', cause: e });\n if (o.signal?.aborted) throw e;\n throw new APIConnectionError(`could not reach ${url}: ${(e as Error)?.message ?? e}`, { code: 'connection_error', cause: e });\n } finally {\n clearTimeout(timer);\n o.signal?.removeEventListener('abort', onAbort);\n }\n const q = quotaFrom(res.headers);\n if (q) this.lastQuota = q;\n let parsed: unknown = undefined;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = undefined;\n }\n }\n if (res.ok) {\n if (parsed === undefined && text) throw new AnonGTOError('the answer was not JSON', { status: res.status, headers: res.headers });\n return parsed as T;\n }\n const err = errorFor(res.status, parsed, res.headers);\n const wait = this.retryWait(err, attempt, maxRetries);\n if (wait === null) throw err;\n await this.sleep(wait, o.signal);\n }\n }\n\n /** ms to wait before retrying, or null to throw */\n private retryWait(err: AnonGTOError, attempt: number, maxRetries: number): number | null {\n if (attempt >= maxRetries) return null;\n const retryable =\n (err.status === 429 && err.code === 'rate_limited') || (err.status === 503 && err.code === 'busy') || err.status === 504;\n if (!retryable) return null;\n const after = err instanceof RateLimitError || err instanceof ServiceUnavailableError ? err.retryAfter : null;\n if (after !== null) return after <= this.maxRetryWait ? after * 1000 : null;\n return Math.min(8000, 500 * 2 ** attempt) * (0.75 + Math.random() * 0.5);\n }\n}\n","/**\n * Batch webhooks: check the AnonGTO-Signature header before trusting a delivery. Uses Web Crypto, so it runs in Node 18+,\n * Deno, Bun, Cloudflare Workers, Vercel Edge and browsers.\n *\n * Header: `t=<unix seconds>,v1=<hex HMAC-SHA256(secret, \"<t>.<raw body>\")>`; the secret is the key's `webhook_secret`\n * (`client.account()`). Verify the raw body exactly as received, before parsing it.\n */\nimport type { WebhookEvent } from './types.js';\n\nexport const SIGNATURE_HEADER = 'AnonGTO-Signature';\n\nexport class WebhookVerificationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WebhookVerificationError';\n }\n}\n\ntype Payload = string | Uint8Array | ArrayBuffer;\n\nconst enc = new TextEncoder();\nconst bytesOf = (p: Payload): Uint8Array => (typeof p === 'string' ? enc.encode(p) : p instanceof Uint8Array ? p : new Uint8Array(p));\n\nasync function subtle(): Promise<SubtleCrypto> {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c?.subtle) return c.subtle;\n // Node 18 without the global: node:crypto's webcrypto (the specifier is hidden from bundlers targeting the edge)\n const mod = 'node:crypto';\n const nodeCrypto = (await import(/* @vite-ignore */ /* webpackIgnore: true */ mod)) as { webcrypto?: Crypto };\n if (nodeCrypto.webcrypto?.subtle) return nodeCrypto.webcrypto.subtle;\n throw new WebhookVerificationError('no Web Crypto (crypto.subtle) in this runtime');\n}\n\nasync function hmacHex(secret: string, t: number, body: Uint8Array): Promise<string> {\n const s = await subtle();\n const key = await s.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);\n const prefix = enc.encode(`${t}.`);\n const msg = new Uint8Array(prefix.length + body.length);\n msg.set(prefix, 0);\n msg.set(body, prefix.length);\n const mac = new Uint8Array(await s.sign('HMAC', key, msg));\n let hex = '';\n for (const b of mac) hex += b.toString(16).padStart(2, '0');\n return hex;\n}\n\n/** constant time for equal lengths */\nfunction safeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let d = 0;\n for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return d === 0;\n}\n\nfunction parseHeader(header: string): { t: number; sigs: string[] } {\n let t: number | null = null;\n const sigs: string[] = [];\n for (const part of header.split(',')) {\n const i = part.indexOf('=');\n if (i < 0) continue;\n const k = part.slice(0, i).trim();\n const v = part.slice(i + 1).trim();\n if (k === 't') {\n if (!/^\\d+$/.test(v)) throw new WebhookVerificationError('signature header: t is not a number');\n t = Number(v);\n } else if (k === 'v1') sigs.push(v.toLowerCase());\n }\n if (t === null || !sigs.length) throw new WebhookVerificationError('signature header: expected t=<unix seconds>,v1=<hex>');\n return { t, sigs };\n}\n\n/** The header value AnonGTO would send for this body (for tests of your receiver). */\nexport async function signWebhook(payload: Payload, secret: string, timestamp = Math.floor(Date.now() / 1000)): Promise<string> {\n return `t=${timestamp},v1=${await hmacHex(secret, timestamp, bytesOf(payload))}`;\n}\n\n/**\n * Check a webhook delivery and return the parsed event; throws WebhookVerificationError when the signature does not\n * match, the header is malformed, or the timestamp is more than `toleranceSec` away from now (0 skips that check).\n */\nexport async function verifyWebhook(\n payload: Payload,\n header: string | null | undefined,\n secret: string,\n toleranceSec = 300,\n): Promise<WebhookEvent> {\n if (!secret) throw new WebhookVerificationError('no webhook secret');\n if (!header) throw new WebhookVerificationError(`no ${SIGNATURE_HEADER} header`);\n const { t, sigs } = parseHeader(header);\n if (toleranceSec > 0 && Math.abs(Date.now() / 1000 - t) > toleranceSec)\n throw new WebhookVerificationError(`signature timestamp outside the tolerance of ${toleranceSec}s`);\n const body = bytesOf(payload);\n const want = await hmacHex(secret, t, body);\n if (!sigs.some((s) => safeEqual(want, s))) throw new WebhookVerificationError('signature does not match');\n let event: unknown;\n try {\n event = JSON.parse(new TextDecoder().decode(body));\n } catch {\n throw new WebhookVerificationError('the body is not JSON');\n }\n if (!event || typeof event !== 'object' || !('type' in event)) throw new WebhookVerificationError('the body is not a webhook event');\n return event as WebhookEvent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWO,IAAM,eAAN,cAA2B,MAAM;AAAA;AAAA,EAE7B;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,SAAiB,OAAyB,CAAC,GAAG;AACxD,UAAM,SAAS,KAAK,UAAU,SAAY,EAAE,OAAO,KAAK,MAAM,IAAI,MAAS;AAC3E,SAAK,OAAO,WAAW;AACvB,SAAK,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