sarvam-agents-client 0.5.0 → 0.5.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/dist/compat/core/agents.d.ts +53 -0
- package/dist/compat/core/agents.js +338 -0
- package/dist/compat/core/data.d.ts +10 -0
- package/dist/compat/core/data.js +275 -0
- package/dist/compat/core/errors.d.ts +37 -0
- package/dist/compat/core/errors.js +155 -0
- package/dist/compat/core/events.d.ts +107 -0
- package/dist/compat/core/events.js +160 -0
- package/dist/compat/core/files.d.ts +65 -0
- package/dist/compat/core/files.js +851 -0
- package/dist/compat/core/history.d.ts +9 -0
- package/dist/compat/core/history.js +112 -0
- package/dist/compat/core/http.d.ts +112 -0
- package/dist/compat/core/http.js +753 -0
- package/dist/compat/core/ids.d.ts +4 -0
- package/dist/compat/core/ids.js +36 -0
- package/dist/compat/core/index.d.ts +14 -0
- package/dist/compat/core/index.js +30 -0
- package/dist/compat/core/models.d.ts +20 -0
- package/dist/compat/core/models.js +75 -0
- package/dist/compat/core/paging.d.ts +14 -0
- package/dist/compat/core/paging.js +124 -0
- package/dist/compat/core/refusals.d.ts +9 -0
- package/dist/compat/core/refusals.js +25 -0
- package/dist/compat/core/sessions.d.ts +65 -0
- package/dist/compat/core/sessions.js +317 -0
- package/dist/compat/core/toolResults.d.ts +43 -0
- package/dist/compat/core/toolResults.js +208 -0
- package/dist/compat/core/turns.d.ts +104 -0
- package/dist/compat/core/turns.js +504 -0
- package/dist/compat/core/warnings.d.ts +6 -0
- package/dist/compat/core/warnings.js +26 -0
- package/dist/compat/index.d.ts +3 -0
- package/dist/compat/index.js +9 -0
- package/dist/compat/openai/client.d.ts +62 -0
- package/dist/compat/openai/client.js +108 -0
- package/dist/compat/openai/errors.d.ts +72 -0
- package/dist/compat/openai/errors.js +150 -0
- package/dist/compat/openai/index.d.ts +14 -0
- package/dist/compat/openai/index.js +42 -0
- package/dist/compat/openai/pages.d.ts +19 -0
- package/dist/compat/openai/pages.js +39 -0
- package/dist/compat/openai/resources/agents.d.ts +36 -0
- package/dist/compat/openai/resources/agents.js +549 -0
- package/dist/compat/openai/resources/events.d.ts +23 -0
- package/dist/compat/openai/resources/events.js +485 -0
- package/dist/compat/openai/resources/sessions.d.ts +33 -0
- package/dist/compat/openai/resources/sessions.js +283 -0
- package/dist/compat/openai/stream.d.ts +40 -0
- package/dist/compat/openai/stream.js +585 -0
- package/dist/compat/openai/types.d.ts +125 -0
- package/dist/compat/openai/types.js +98 -0
- package/dist/compose/agent.d.ts +2 -0
- package/dist/compose/agent.js +27 -0
- package/dist/compose/functionTool.d.ts +2 -0
- package/dist/compose/functionTool.js +46 -0
- package/dist/compose/output.d.ts +2 -0
- package/dist/compose/output.js +15 -7
- package/dist/esm/compat/core/agents.d.ts +53 -0
- package/dist/esm/compat/core/agents.js +334 -0
- package/dist/esm/compat/core/data.d.ts +10 -0
- package/dist/esm/compat/core/data.js +272 -0
- package/dist/esm/compat/core/errors.d.ts +37 -0
- package/dist/esm/compat/core/errors.js +146 -0
- package/dist/esm/compat/core/events.d.ts +107 -0
- package/dist/esm/compat/core/events.js +156 -0
- package/dist/esm/compat/core/files.d.ts +65 -0
- package/dist/esm/compat/core/files.js +829 -0
- package/dist/esm/compat/core/history.d.ts +9 -0
- package/dist/esm/compat/core/history.js +109 -0
- package/dist/esm/compat/core/http.d.ts +112 -0
- package/dist/esm/compat/core/http.js +746 -0
- package/dist/esm/compat/core/ids.d.ts +4 -0
- package/dist/esm/compat/core/ids.js +30 -0
- package/dist/esm/compat/core/index.d.ts +14 -0
- package/dist/esm/compat/core/index.js +14 -0
- package/dist/esm/compat/core/models.d.ts +20 -0
- package/dist/esm/compat/core/models.js +71 -0
- package/dist/esm/compat/core/paging.d.ts +14 -0
- package/dist/esm/compat/core/paging.js +118 -0
- package/dist/esm/compat/core/refusals.d.ts +9 -0
- package/dist/esm/compat/core/refusals.js +21 -0
- package/dist/esm/compat/core/sessions.d.ts +65 -0
- package/dist/esm/compat/core/sessions.js +312 -0
- package/dist/esm/compat/core/toolResults.d.ts +43 -0
- package/dist/esm/compat/core/toolResults.js +203 -0
- package/dist/esm/compat/core/turns.d.ts +104 -0
- package/dist/esm/compat/core/turns.js +497 -0
- package/dist/esm/compat/core/warnings.d.ts +6 -0
- package/dist/esm/compat/core/warnings.js +20 -0
- package/dist/esm/compat/index.d.ts +3 -0
- package/dist/esm/compat/index.js +3 -0
- package/dist/esm/compat/openai/client.d.ts +62 -0
- package/dist/esm/compat/openai/client.js +104 -0
- package/dist/esm/compat/openai/errors.d.ts +72 -0
- package/dist/esm/compat/openai/errors.js +130 -0
- package/dist/esm/compat/openai/index.d.ts +14 -0
- package/dist/esm/compat/openai/index.js +17 -0
- package/dist/esm/compat/openai/pages.d.ts +19 -0
- package/dist/esm/compat/openai/pages.js +35 -0
- package/dist/esm/compat/openai/resources/agents.d.ts +36 -0
- package/dist/esm/compat/openai/resources/agents.js +540 -0
- package/dist/esm/compat/openai/resources/events.d.ts +23 -0
- package/dist/esm/compat/openai/resources/events.js +479 -0
- package/dist/esm/compat/openai/resources/sessions.d.ts +33 -0
- package/dist/esm/compat/openai/resources/sessions.js +278 -0
- package/dist/esm/compat/openai/stream.d.ts +40 -0
- package/dist/esm/compat/openai/stream.js +579 -0
- package/dist/esm/compat/openai/types.d.ts +125 -0
- package/dist/esm/compat/openai/types.js +91 -0
- package/dist/esm/compose/agent.d.ts +2 -0
- package/dist/esm/compose/agent.js +28 -2
- package/dist/esm/compose/functionTool.d.ts +2 -0
- package/dist/esm/compose/functionTool.js +45 -0
- package/dist/esm/compose/output.d.ts +2 -0
- package/dist/esm/compose/output.js +14 -7
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +5 -1
- package/package.json +53 -11
- package/src/compat/core/agents.ts +437 -0
- package/src/compat/core/data.ts +283 -0
- package/src/compat/core/errors.ts +162 -0
- package/src/compat/core/events.ts +198 -0
- package/src/compat/core/files.ts +913 -0
- package/src/compat/core/history.ts +116 -0
- package/src/compat/core/http.ts +827 -0
- package/src/compat/core/ids.ts +35 -0
- package/src/compat/core/index.ts +14 -0
- package/src/compat/core/models.ts +85 -0
- package/src/compat/core/paging.ts +119 -0
- package/src/compat/core/refusals.ts +31 -0
- package/src/compat/core/sessions.ts +358 -0
- package/src/compat/core/toolResults.ts +235 -0
- package/src/compat/core/turns.ts +622 -0
- package/src/compat/core/warnings.ts +23 -0
- package/src/compat/index.ts +3 -0
- package/src/compat/openai/client.ts +177 -0
- package/src/compat/openai/errors.ts +165 -0
- package/src/compat/openai/index.ts +65 -0
- package/src/compat/openai/pages.ts +55 -0
- package/src/compat/openai/resources/agents.ts +603 -0
- package/src/compat/openai/resources/events.ts +523 -0
- package/src/compat/openai/resources/sessions.ts +369 -0
- package/src/compat/openai/stream.ts +599 -0
- package/src/compat/openai/types.ts +217 -0
- package/src/compose/agent.ts +30 -3
- package/src/compose/functionTool.ts +44 -0
- package/src/compose/output.ts +14 -8
- package/src/index.ts +3 -0
|
@@ -0,0 +1,753 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Http = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_TIMEOUT_MS = exports.DEFAULT_BASE_URL = void 0;
|
|
4
|
+
exports.resolveClientConfig = resolveClientConfig;
|
|
5
|
+
exports.createPinnedLookup = createPinnedLookup;
|
|
6
|
+
exports.pinnedNodeFetch = pinnedNodeFetch;
|
|
7
|
+
/** HTTP config, key/URL resolution, retry loop, timeouts, default/per-call options, and Configuration wrapper. */
|
|
8
|
+
const node_async_hooks_1 = require("node:async_hooks");
|
|
9
|
+
const node_crypto_1 = require("node:crypto");
|
|
10
|
+
const promises_1 = require("node:dns/promises");
|
|
11
|
+
const httpMod = require("node:http");
|
|
12
|
+
const httpsMod = require("node:https");
|
|
13
|
+
const node_net_1 = require("node:net");
|
|
14
|
+
const node_stream_1 = require("node:stream");
|
|
15
|
+
const runtime_js_1 = require("../../runtime.js");
|
|
16
|
+
const errors_js_1 = require("../../compose/errors.js");
|
|
17
|
+
const errors_js_2 = require("./errors.js");
|
|
18
|
+
exports.DEFAULT_BASE_URL = "https://chat.sarvamclaw.sarvam.ai";
|
|
19
|
+
exports.DEFAULT_TIMEOUT_MS = 600000;
|
|
20
|
+
exports.DEFAULT_MAX_RETRIES = 2;
|
|
21
|
+
const MAX_BACKOFF_MS = 8000;
|
|
22
|
+
const PROVIDER_KEY_PREFIXES = ["sk-ant-", "sk-proj-", "sk-"];
|
|
23
|
+
const RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
|
|
24
|
+
const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
|
|
25
|
+
const STRIPPED_HEADERS = new Set(["openai-beta", "anthropic-beta", "anthropic-version"]);
|
|
26
|
+
function looksLikeProviderKey(key) {
|
|
27
|
+
return PROVIDER_KEY_PREFIXES.some((p) => key.startsWith(p));
|
|
28
|
+
}
|
|
29
|
+
function resolveClientConfig(input = {}) {
|
|
30
|
+
var _a, _b, _c, _d, _e;
|
|
31
|
+
const env = typeof process !== "undefined" ? process.env : {};
|
|
32
|
+
const key = input.apiKey || env["SARVAM_API_KEY"] || env["SARVAM_AGENTS_TOKEN"] || "";
|
|
33
|
+
if (!key) {
|
|
34
|
+
throw new errors_js_2.CoreAPIError("Missing Sarvam API key: pass apiKey or set SARVAM_API_KEY (OPENAI_API_KEY and ANTHROPIC_API_KEY are never read).", { status: 401, code: "authentication_error" });
|
|
35
|
+
}
|
|
36
|
+
if (looksLikeProviderKey(key)) {
|
|
37
|
+
throw new errors_js_2.CoreAPIError("Provider-shaped API key rejected locally: pass a Sarvam API key via apiKey or SARVAM_API_KEY.", { status: 401, code: "authentication_error" });
|
|
38
|
+
}
|
|
39
|
+
const rawUrl = input.baseURL || env["SARVAM_BASE_URL"] || exports.DEFAULT_BASE_URL;
|
|
40
|
+
const baseURL = rawUrl.replace(/\/+$/, "");
|
|
41
|
+
const timeout = (_a = input.timeout) !== null && _a !== void 0 ? _a : exports.DEFAULT_TIMEOUT_MS;
|
|
42
|
+
const maxRetries = Math.max(0, Math.floor((_b = input.maxRetries) !== null && _b !== void 0 ? _b : exports.DEFAULT_MAX_RETRIES));
|
|
43
|
+
return {
|
|
44
|
+
apiKey: key,
|
|
45
|
+
baseURL,
|
|
46
|
+
timeout,
|
|
47
|
+
maxRetries,
|
|
48
|
+
defaultHeaders: { ...((_c = input.defaultHeaders) !== null && _c !== void 0 ? _c : {}) },
|
|
49
|
+
defaultQuery: { ...((_d = input.defaultQuery) !== null && _d !== void 0 ? _d : {}) },
|
|
50
|
+
fetch: input.fetch,
|
|
51
|
+
provider: (_e = input.provider) !== null && _e !== void 0 ? _e : "openai",
|
|
52
|
+
allowPrivateRemoteUrls: Boolean(input.allowPrivateRemoteUrls),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function getHeader(headers, name) {
|
|
56
|
+
const low = name.toLowerCase();
|
|
57
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
58
|
+
if (k.toLowerCase() === low)
|
|
59
|
+
return v;
|
|
60
|
+
}
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
function parseRetryAfterMs(headers) {
|
|
64
|
+
const msRaw = getHeader(headers, "retry-after-ms");
|
|
65
|
+
if (msRaw !== null) {
|
|
66
|
+
const ms = Number(msRaw.trim());
|
|
67
|
+
if (Number.isFinite(ms))
|
|
68
|
+
return Math.max(0, Math.min(ms, 60000));
|
|
69
|
+
}
|
|
70
|
+
const raw = getHeader(headers, "retry-after");
|
|
71
|
+
if (raw === null)
|
|
72
|
+
return null;
|
|
73
|
+
const trimmed = raw.trim();
|
|
74
|
+
const secs = Number(trimmed);
|
|
75
|
+
if (Number.isFinite(secs))
|
|
76
|
+
return Math.max(0, Math.min(secs * 1000, 60000));
|
|
77
|
+
const dateMs = Date.parse(trimmed);
|
|
78
|
+
if (!Number.isNaN(dateMs)) {
|
|
79
|
+
return Math.max(0, Math.min(dateMs - Date.now(), 60000));
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
function shouldRetry(err) {
|
|
84
|
+
if (err instanceof errors_js_2.CoreUserAbortError)
|
|
85
|
+
return false;
|
|
86
|
+
if (err instanceof errors_js_2.CoreConnectionError)
|
|
87
|
+
return true;
|
|
88
|
+
const xRetry = getHeader(err.headers, "x-should-retry");
|
|
89
|
+
if (xRetry !== null) {
|
|
90
|
+
const low = xRetry.trim().toLowerCase();
|
|
91
|
+
if (low === "false")
|
|
92
|
+
return false;
|
|
93
|
+
if (low === "true")
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
if (err.status !== null && RETRYABLE_STATUSES.has(err.status))
|
|
97
|
+
return true;
|
|
98
|
+
if (err.status === 409 && err.code === "lock_timeout")
|
|
99
|
+
return true;
|
|
100
|
+
if (err.status !== null && err.status >= 500)
|
|
101
|
+
return true;
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
function headersToRecord(h) {
|
|
105
|
+
const out = {};
|
|
106
|
+
h.forEach((v, k) => { out[k.toLowerCase()] = v; });
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
function mergeUrlQuery(urlStr, extra) {
|
|
110
|
+
const entries = Object.entries(extra);
|
|
111
|
+
if (entries.length === 0)
|
|
112
|
+
return urlStr;
|
|
113
|
+
const u = new URL(urlStr);
|
|
114
|
+
for (const [k, v] of entries) {
|
|
115
|
+
if (v !== undefined && v !== null && !u.searchParams.has(k)) {
|
|
116
|
+
u.searchParams.set(k, String(v));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return u.toString();
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Create a Node `net.LookupFunction` that always resolves directly to ``pinnedIp`` without
|
|
123
|
+
* issuing a second DNS lookup, supporting both `{ all: true }` (Node 20+ autoSelectFamily)
|
|
124
|
+
* and single-address callback forms.
|
|
125
|
+
*/
|
|
126
|
+
function createPinnedLookup(pinnedIp) {
|
|
127
|
+
const family = (0, node_net_1.isIP)(pinnedIp);
|
|
128
|
+
if (family !== 4 && family !== 6) {
|
|
129
|
+
throw new Error(`Invalid pinned IP address: ${pinnedIp}`);
|
|
130
|
+
}
|
|
131
|
+
return (_hostname, options, callback) => {
|
|
132
|
+
const cb = typeof options === "function" ? options : callback;
|
|
133
|
+
if (!cb)
|
|
134
|
+
return;
|
|
135
|
+
const wantAll = typeof options === "object" && options !== null && Boolean(options.all);
|
|
136
|
+
if (wantAll) {
|
|
137
|
+
cb(null, [{ address: pinnedIp, family }]);
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
cb(null, pinnedIp, family);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
function normalizeInitHeaders(raw) {
|
|
145
|
+
const out = {};
|
|
146
|
+
if (!raw)
|
|
147
|
+
return out;
|
|
148
|
+
if (raw instanceof Headers) {
|
|
149
|
+
raw.forEach((v, k) => {
|
|
150
|
+
out[k] = v;
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
else if (Array.isArray(raw)) {
|
|
154
|
+
for (const [k, v] of raw) {
|
|
155
|
+
out[k] = v;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
160
|
+
if (v !== undefined)
|
|
161
|
+
out[k] = String(v);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return out;
|
|
165
|
+
}
|
|
166
|
+
function incomingHeadersToWeb(res) {
|
|
167
|
+
var _a;
|
|
168
|
+
const headers = new Headers();
|
|
169
|
+
if (Array.isArray(res.rawHeaders) && res.rawHeaders.length >= 2) {
|
|
170
|
+
for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
|
|
171
|
+
const k = res.rawHeaders[i];
|
|
172
|
+
const v = res.rawHeaders[i + 1];
|
|
173
|
+
if (k)
|
|
174
|
+
headers.append(k, v);
|
|
175
|
+
}
|
|
176
|
+
return headers;
|
|
177
|
+
}
|
|
178
|
+
for (const [k, v] of Object.entries((_a = res.headers) !== null && _a !== void 0 ? _a : {})) {
|
|
179
|
+
if (v === undefined)
|
|
180
|
+
continue;
|
|
181
|
+
if (Array.isArray(v)) {
|
|
182
|
+
for (const item of v)
|
|
183
|
+
headers.append(k, item);
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
headers.append(k, v);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return headers;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Issue an HTTP/HTTPS request pinned to ``pinnedIp`` via Node's stdlib ``node:http`` / ``node:https``
|
|
193
|
+
* while preserving the original ``Host`` header, TLS SNI (``servername``), and certificate hostname
|
|
194
|
+
* verification (closing the DNS rebinding TOCTOU gap).
|
|
195
|
+
*/
|
|
196
|
+
function pinnedNodeFetch(url, init, pinnedIp, signal, transport) {
|
|
197
|
+
var _a, _b, _c;
|
|
198
|
+
const parsed = new URL(url);
|
|
199
|
+
const isHttps = parsed.protocol === "https:";
|
|
200
|
+
const unbracketedHost = parsed.hostname.startsWith("[") && parsed.hostname.endsWith("]")
|
|
201
|
+
? parsed.hostname.slice(1, -1)
|
|
202
|
+
: parsed.hostname;
|
|
203
|
+
const hostIsIp = (0, node_net_1.isIP)(unbracketedHost) !== 0;
|
|
204
|
+
const method = ((_a = init.method) !== null && _a !== void 0 ? _a : "GET").toUpperCase();
|
|
205
|
+
const reqHeaders = normalizeInitHeaders(init.headers);
|
|
206
|
+
const hasHost = Object.keys(reqHeaders).some((k) => k.toLowerCase() === "host");
|
|
207
|
+
if (!hasHost) {
|
|
208
|
+
reqHeaders["Host"] = parsed.host;
|
|
209
|
+
}
|
|
210
|
+
const reqOpts = {
|
|
211
|
+
protocol: parsed.protocol,
|
|
212
|
+
hostname: unbracketedHost,
|
|
213
|
+
port: parsed.port || undefined,
|
|
214
|
+
path: `${parsed.pathname || "/"}${parsed.search}`,
|
|
215
|
+
method,
|
|
216
|
+
headers: reqHeaders,
|
|
217
|
+
lookup: createPinnedLookup(pinnedIp),
|
|
218
|
+
signal,
|
|
219
|
+
...(isHttps && !hostIsIp ? { servername: unbracketedHost } : {}),
|
|
220
|
+
};
|
|
221
|
+
const requestFn = isHttps
|
|
222
|
+
? ((_b = transport === null || transport === void 0 ? void 0 : transport.httpsRequest) !== null && _b !== void 0 ? _b : httpsMod.request)
|
|
223
|
+
: ((_c = transport === null || transport === void 0 ? void 0 : transport.httpRequest) !== null && _c !== void 0 ? _c : httpMod.request);
|
|
224
|
+
return new Promise((resolve, reject) => {
|
|
225
|
+
let settled = false;
|
|
226
|
+
const finishResolve = (r) => {
|
|
227
|
+
if (settled)
|
|
228
|
+
return;
|
|
229
|
+
settled = true;
|
|
230
|
+
resolve(r);
|
|
231
|
+
};
|
|
232
|
+
const finishReject = (err) => {
|
|
233
|
+
if (settled)
|
|
234
|
+
return;
|
|
235
|
+
settled = true;
|
|
236
|
+
reject(err);
|
|
237
|
+
};
|
|
238
|
+
const req = requestFn(reqOpts, (res) => {
|
|
239
|
+
var _a, _b;
|
|
240
|
+
const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 500;
|
|
241
|
+
const respHeaders = incomingHeadersToWeb(res);
|
|
242
|
+
const statusText = (_b = res.statusMessage) !== null && _b !== void 0 ? _b : "";
|
|
243
|
+
if (NULL_BODY_STATUSES.has(status) || method === "HEAD") {
|
|
244
|
+
res.resume();
|
|
245
|
+
finishResolve(new Response(null, { status, statusText, headers: respHeaders }));
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (signal) {
|
|
249
|
+
const onAbort = () => {
|
|
250
|
+
const reason = signal.reason instanceof Error
|
|
251
|
+
? signal.reason
|
|
252
|
+
: Object.assign(new Error("Request was aborted."), { name: "AbortError" });
|
|
253
|
+
res.destroy(reason);
|
|
254
|
+
req.destroy(reason);
|
|
255
|
+
};
|
|
256
|
+
if (signal.aborted) {
|
|
257
|
+
onAbort();
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
261
|
+
const detach = () => {
|
|
262
|
+
signal.removeEventListener("abort", onAbort);
|
|
263
|
+
};
|
|
264
|
+
res.once("end", detach);
|
|
265
|
+
res.once("close", detach);
|
|
266
|
+
res.once("error", detach);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
const webStream = node_stream_1.Readable.toWeb(res);
|
|
270
|
+
finishResolve(new Response(webStream, { status, statusText, headers: respHeaders }));
|
|
271
|
+
});
|
|
272
|
+
req.on("error", (err) => {
|
|
273
|
+
finishReject(err);
|
|
274
|
+
});
|
|
275
|
+
const body = init.body;
|
|
276
|
+
if (body === undefined || body === null) {
|
|
277
|
+
req.end();
|
|
278
|
+
}
|
|
279
|
+
else if (typeof body === "string") {
|
|
280
|
+
req.end(body);
|
|
281
|
+
}
|
|
282
|
+
else if (body instanceof Uint8Array) {
|
|
283
|
+
req.end(Buffer.from(body.buffer, body.byteOffset, body.byteLength));
|
|
284
|
+
}
|
|
285
|
+
else if (body instanceof ArrayBuffer) {
|
|
286
|
+
req.end(Buffer.from(body));
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
req.end(String(body));
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
class Http {
|
|
294
|
+
constructor(input, opts = {}) {
|
|
295
|
+
var _a, _b;
|
|
296
|
+
this.reqStore = new node_async_hooks_1.AsyncLocalStorage();
|
|
297
|
+
this.config = resolveClientConfig(input);
|
|
298
|
+
this.sleepFn = (_a = opts.sleep) !== null && _a !== void 0 ? _a : ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
299
|
+
this.resolveHostFn = opts.resolveHost;
|
|
300
|
+
if (opts.jitter) {
|
|
301
|
+
this.jitterFn = opts.jitter;
|
|
302
|
+
}
|
|
303
|
+
else if (opts.sleep) {
|
|
304
|
+
this.jitterFn = (ms) => ms;
|
|
305
|
+
}
|
|
306
|
+
else {
|
|
307
|
+
this.jitterFn = (ms) => Math.floor(ms * (0.75 + Math.random() * 0.5));
|
|
308
|
+
}
|
|
309
|
+
const headers = {
|
|
310
|
+
"X-Panja-Origin": "managed_agents",
|
|
311
|
+
Authorization: `Bearer ${this.config.apiKey}`,
|
|
312
|
+
};
|
|
313
|
+
for (const [k, v] of Object.entries(this.config.defaultHeaders)) {
|
|
314
|
+
if (STRIPPED_HEADERS.has(k.toLowerCase()))
|
|
315
|
+
continue;
|
|
316
|
+
headers[k] = v;
|
|
317
|
+
}
|
|
318
|
+
const baseFetch = (_b = this.config.fetch) !== null && _b !== void 0 ? _b : globalThis.fetch.bind(globalThis);
|
|
319
|
+
this.baseFetch = baseFetch;
|
|
320
|
+
const httpSelf = this;
|
|
321
|
+
const wrappedFetch = async (reqInput, init) => {
|
|
322
|
+
var _a, _b, _c, _d;
|
|
323
|
+
const ov = httpSelf.reqStore.getStore();
|
|
324
|
+
const mergedQuery = {
|
|
325
|
+
...httpSelf.config.defaultQuery,
|
|
326
|
+
...((_a = ov === null || ov === void 0 ? void 0 : ov.query) !== null && _a !== void 0 ? _a : {}),
|
|
327
|
+
};
|
|
328
|
+
const rawUrl = typeof reqInput === "string"
|
|
329
|
+
? reqInput
|
|
330
|
+
: reqInput instanceof URL
|
|
331
|
+
? reqInput.toString()
|
|
332
|
+
: reqInput.url;
|
|
333
|
+
const finalUrl = mergeUrlQuery(rawUrl, mergedQuery);
|
|
334
|
+
const finalHeaders = new Headers(init === null || init === void 0 ? void 0 : init.headers);
|
|
335
|
+
if (ov === null || ov === void 0 ? void 0 : ov.headers) {
|
|
336
|
+
for (const [hk, hv] of Object.entries(ov.headers)) {
|
|
337
|
+
if (STRIPPED_HEADERS.has(hk.toLowerCase()))
|
|
338
|
+
continue;
|
|
339
|
+
finalHeaders.set(hk, hv);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
// Attach Idempotency-Key ONLY when explicitly scoped to this single write via http.call({ idempotencyKey }).
|
|
343
|
+
if ((ov === null || ov === void 0 ? void 0 : ov._callIdempotencyKey) && !finalHeaders.has("idempotency-key")) {
|
|
344
|
+
finalHeaders.set("Idempotency-Key", ov._callIdempotencyKey);
|
|
345
|
+
}
|
|
346
|
+
const timeoutMs = (_b = ov === null || ov === void 0 ? void 0 : ov.timeout) !== null && _b !== void 0 ? _b : httpSelf.config.timeout;
|
|
347
|
+
const ovSignal = ov === null || ov === void 0 ? void 0 : ov.signal;
|
|
348
|
+
const initSignal = (_c = init === null || init === void 0 ? void 0 : init.signal) !== null && _c !== void 0 ? _c : undefined;
|
|
349
|
+
const hasTimeout = timeoutMs > 0 && Number.isFinite(timeoutMs);
|
|
350
|
+
if (ovSignal === null || ovSignal === void 0 ? void 0 : ovSignal.aborted) {
|
|
351
|
+
throw new errors_js_2.CoreUserAbortError("Request was aborted.");
|
|
352
|
+
}
|
|
353
|
+
if (initSignal === null || initSignal === void 0 ? void 0 : initSignal.aborted) {
|
|
354
|
+
const reason = initSignal.reason;
|
|
355
|
+
if (reason instanceof Error)
|
|
356
|
+
throw reason;
|
|
357
|
+
const abortErr = new Error("Request was aborted.");
|
|
358
|
+
abortErr.name = "AbortError";
|
|
359
|
+
throw abortErr;
|
|
360
|
+
}
|
|
361
|
+
let controller = null;
|
|
362
|
+
let timer = null;
|
|
363
|
+
let onOvAbort = null;
|
|
364
|
+
let onInitAbort = null;
|
|
365
|
+
let effectiveSignal;
|
|
366
|
+
let timedOut = false;
|
|
367
|
+
let userAborted = false;
|
|
368
|
+
let initAborted = false;
|
|
369
|
+
let settled = false;
|
|
370
|
+
let rejectRace = null;
|
|
371
|
+
let racePromise = null;
|
|
372
|
+
if (hasTimeout || ovSignal || initSignal) {
|
|
373
|
+
controller = new AbortController();
|
|
374
|
+
effectiveSignal = controller.signal;
|
|
375
|
+
racePromise = new Promise((_resolve, reject) => {
|
|
376
|
+
rejectRace = reject;
|
|
377
|
+
});
|
|
378
|
+
// Prevent unhandled rejection if fetch/body completes before any race consumer attaches.
|
|
379
|
+
racePromise.catch(() => { });
|
|
380
|
+
if (ovSignal) {
|
|
381
|
+
onOvAbort = () => {
|
|
382
|
+
userAborted = true;
|
|
383
|
+
if (initSignal && onInitAbort)
|
|
384
|
+
initSignal.removeEventListener("abort", onInitAbort);
|
|
385
|
+
const abortErr = new errors_js_2.CoreUserAbortError("Request was aborted.");
|
|
386
|
+
controller === null || controller === void 0 ? void 0 : controller.abort(abortErr);
|
|
387
|
+
if (!settled && rejectRace)
|
|
388
|
+
rejectRace(abortErr);
|
|
389
|
+
};
|
|
390
|
+
ovSignal.addEventListener("abort", onOvAbort, { once: true });
|
|
391
|
+
}
|
|
392
|
+
if (initSignal) {
|
|
393
|
+
onInitAbort = () => {
|
|
394
|
+
initAborted = true;
|
|
395
|
+
if (ovSignal && onOvAbort)
|
|
396
|
+
ovSignal.removeEventListener("abort", onOvAbort);
|
|
397
|
+
const reason = initSignal.reason instanceof Error
|
|
398
|
+
? initSignal.reason
|
|
399
|
+
: Object.assign(new Error("Request was aborted."), { name: "AbortError" });
|
|
400
|
+
controller === null || controller === void 0 ? void 0 : controller.abort(reason);
|
|
401
|
+
if (!settled && rejectRace)
|
|
402
|
+
rejectRace(reason);
|
|
403
|
+
};
|
|
404
|
+
initSignal.addEventListener("abort", onInitAbort, { once: true });
|
|
405
|
+
}
|
|
406
|
+
if (hasTimeout) {
|
|
407
|
+
timer = setTimeout(() => {
|
|
408
|
+
timedOut = true;
|
|
409
|
+
const err = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
410
|
+
err.name = "TimeoutError";
|
|
411
|
+
controller === null || controller === void 0 ? void 0 : controller.abort(err);
|
|
412
|
+
if (!settled && rejectRace) {
|
|
413
|
+
rejectRace(new errors_js_2.CoreTimeoutError(`Request timed out after ${timeoutMs}ms.`));
|
|
414
|
+
}
|
|
415
|
+
}, timeoutMs);
|
|
416
|
+
if (typeof timer.unref === "function") {
|
|
417
|
+
timer.unref();
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
const cleanupTimerAndListeners = (removeSignalListeners) => {
|
|
422
|
+
settled = true;
|
|
423
|
+
if (timer !== null) {
|
|
424
|
+
clearTimeout(timer);
|
|
425
|
+
timer = null;
|
|
426
|
+
}
|
|
427
|
+
if (removeSignalListeners) {
|
|
428
|
+
if (ovSignal && onOvAbort)
|
|
429
|
+
ovSignal.removeEventListener("abort", onOvAbort);
|
|
430
|
+
if (initSignal && onInitAbort)
|
|
431
|
+
initSignal.removeEventListener("abort", onInitAbort);
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
try {
|
|
435
|
+
const fetchPromise = baseFetch(finalUrl, {
|
|
436
|
+
...init,
|
|
437
|
+
headers: finalHeaders,
|
|
438
|
+
signal: effectiveSignal,
|
|
439
|
+
});
|
|
440
|
+
// If a custom fetch ignores AbortSignal and resolves after timeout/abort, cancel its body.
|
|
441
|
+
fetchPromise.then((lateResp) => {
|
|
442
|
+
var _a;
|
|
443
|
+
if (timedOut || userAborted || initAborted) {
|
|
444
|
+
try {
|
|
445
|
+
void ((_a = lateResp.body) === null || _a === void 0 ? void 0 : _a.cancel().catch(() => { }));
|
|
446
|
+
}
|
|
447
|
+
catch (_b) {
|
|
448
|
+
// Ignore cancel errors on already-locked/closed streams.
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}, () => { });
|
|
452
|
+
const resp = await (racePromise ? Promise.race([fetchPromise, racePromise]) : fetchPromise);
|
|
453
|
+
if (ov === null || ov === void 0 ? void 0 : ov._rawBox) {
|
|
454
|
+
ov._rawBox.snap = { status: resp.status, headers: headersToRecord(resp.headers) };
|
|
455
|
+
}
|
|
456
|
+
const contentType = ((_d = resp.headers.get("content-type")) !== null && _d !== void 0 ? _d : "").toLowerCase();
|
|
457
|
+
const isEventStream = contentType.includes("text/event-stream");
|
|
458
|
+
if (isEventStream) {
|
|
459
|
+
// SSE streams have their own idle timeout and can legitimately stay open longer than
|
|
460
|
+
// a single-request timeout; clear the request timer once headers arrive while keeping
|
|
461
|
+
// BOTH caller and stream-close signals wired so either aborts the underlying socket.
|
|
462
|
+
cleanupTimerAndListeners(!resp.body);
|
|
463
|
+
return resp;
|
|
464
|
+
}
|
|
465
|
+
if (resp.body && !NULL_BODY_STATUSES.has(resp.status)) {
|
|
466
|
+
// Keep the request timeout active until the full non-streaming body finishes arriving.
|
|
467
|
+
try {
|
|
468
|
+
const buf = await (racePromise
|
|
469
|
+
? Promise.race([resp.arrayBuffer(), racePromise])
|
|
470
|
+
: resp.arrayBuffer());
|
|
471
|
+
cleanupTimerAndListeners(true);
|
|
472
|
+
const buffered = new Response(buf, {
|
|
473
|
+
status: resp.status,
|
|
474
|
+
statusText: resp.statusText,
|
|
475
|
+
headers: resp.headers,
|
|
476
|
+
});
|
|
477
|
+
if (resp.url) {
|
|
478
|
+
try {
|
|
479
|
+
Object.defineProperty(buffered, "url", { value: resp.url });
|
|
480
|
+
}
|
|
481
|
+
catch (_e) {
|
|
482
|
+
// Ignore if runtime makes Response.url non-configurable.
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return buffered;
|
|
486
|
+
}
|
|
487
|
+
catch (bodyErr) {
|
|
488
|
+
try {
|
|
489
|
+
void resp.body.cancel().catch(() => { });
|
|
490
|
+
}
|
|
491
|
+
catch (_f) {
|
|
492
|
+
// Ignore cancel errors on already-locked/closed streams.
|
|
493
|
+
}
|
|
494
|
+
throw bodyErr;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
cleanupTimerAndListeners(true);
|
|
498
|
+
return resp;
|
|
499
|
+
}
|
|
500
|
+
catch (err) {
|
|
501
|
+
cleanupTimerAndListeners(true);
|
|
502
|
+
if (userAborted || (ovSignal === null || ovSignal === void 0 ? void 0 : ovSignal.aborted)) {
|
|
503
|
+
throw new errors_js_2.CoreUserAbortError("Request was aborted.");
|
|
504
|
+
}
|
|
505
|
+
if (timedOut) {
|
|
506
|
+
throw new errors_js_2.CoreTimeoutError(`Request timed out after ${timeoutMs}ms.`);
|
|
507
|
+
}
|
|
508
|
+
throw err;
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
this.sdkConfig = new runtime_js_1.Configuration({
|
|
512
|
+
basePath: this.config.baseURL,
|
|
513
|
+
accessToken: this.config.apiKey,
|
|
514
|
+
headers,
|
|
515
|
+
fetchApi: wrappedFetch,
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
newIdempotencyKey() {
|
|
519
|
+
return (0, node_crypto_1.randomUUID)();
|
|
520
|
+
}
|
|
521
|
+
async resolveHost(host) {
|
|
522
|
+
if (this.resolveHostFn) {
|
|
523
|
+
return [...(await this.resolveHostFn(host))];
|
|
524
|
+
}
|
|
525
|
+
const entries = await (0, promises_1.lookup)(host, { all: true });
|
|
526
|
+
const ips = [];
|
|
527
|
+
for (const entry of entries) {
|
|
528
|
+
if (entry.address && !ips.includes(entry.address)) {
|
|
529
|
+
ips.push(entry.address);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
return ips;
|
|
533
|
+
}
|
|
534
|
+
effectiveRemoteTimeoutMs(maxMs) {
|
|
535
|
+
var _a;
|
|
536
|
+
const ov = this.reqStore.getStore();
|
|
537
|
+
const configured = (_a = ov === null || ov === void 0 ? void 0 : ov.timeout) !== null && _a !== void 0 ? _a : this.config.timeout;
|
|
538
|
+
if (configured > 0 && Number.isFinite(configured)) {
|
|
539
|
+
return Math.min(configured, maxMs);
|
|
540
|
+
}
|
|
541
|
+
return maxMs;
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Issue a raw HTTP request WITHOUT Sarvam Authorization, X-Panja-Origin, defaultHeaders, defaultQuery,
|
|
545
|
+
* or Idempotency-Key. Honors per-call AbortSignal and timeout (optionally capped by maxTimeoutMs or
|
|
546
|
+
* pinned by timeoutOverrideMs), and returns the raw unbuffered Response plus a cleanup handle and
|
|
547
|
+
* deadline race promise so callers can stream and cap response bodies safely.
|
|
548
|
+
*
|
|
549
|
+
* When ``opts.pinnedIp`` is supplied and no custom ``fetch`` override was provided, connects
|
|
550
|
+
* directly to ``opts.pinnedIp`` via ``node:http``/``node:https`` with original ``Host`` and TLS
|
|
551
|
+
* ``servername`` to eliminate the DNS rebinding TOCTOU window.
|
|
552
|
+
*/
|
|
553
|
+
async externalFetch(url, init = {}, opts = {}) {
|
|
554
|
+
var _a, _b;
|
|
555
|
+
const ov = this.reqStore.getStore();
|
|
556
|
+
const ovSignal = ov === null || ov === void 0 ? void 0 : ov.signal;
|
|
557
|
+
if (ovSignal === null || ovSignal === void 0 ? void 0 : ovSignal.aborted) {
|
|
558
|
+
throw new errors_js_2.CoreUserAbortError("Request was aborted.");
|
|
559
|
+
}
|
|
560
|
+
const configuredTimeout = (_a = ov === null || ov === void 0 ? void 0 : ov.timeout) !== null && _a !== void 0 ? _a : this.config.timeout;
|
|
561
|
+
let timeoutMs = (_b = opts.timeoutOverrideMs) !== null && _b !== void 0 ? _b : configuredTimeout;
|
|
562
|
+
if (opts.timeoutOverrideMs === undefined && opts.maxTimeoutMs !== undefined) {
|
|
563
|
+
timeoutMs = timeoutMs > 0 && Number.isFinite(timeoutMs)
|
|
564
|
+
? Math.min(timeoutMs, opts.maxTimeoutMs)
|
|
565
|
+
: opts.maxTimeoutMs;
|
|
566
|
+
}
|
|
567
|
+
const hasTimeout = timeoutMs > 0 && Number.isFinite(timeoutMs);
|
|
568
|
+
let controller = null;
|
|
569
|
+
let timer = null;
|
|
570
|
+
let onOvAbort = null;
|
|
571
|
+
let timedOut = false;
|
|
572
|
+
let userAborted = false;
|
|
573
|
+
let settled = false;
|
|
574
|
+
let rejectRace = null;
|
|
575
|
+
let racePromise = null;
|
|
576
|
+
if (hasTimeout || ovSignal) {
|
|
577
|
+
controller = new AbortController();
|
|
578
|
+
racePromise = new Promise((_resolve, reject) => {
|
|
579
|
+
rejectRace = reject;
|
|
580
|
+
});
|
|
581
|
+
racePromise.catch(() => { });
|
|
582
|
+
if (ovSignal) {
|
|
583
|
+
onOvAbort = () => {
|
|
584
|
+
userAborted = true;
|
|
585
|
+
const abortErr = new errors_js_2.CoreUserAbortError("Request was aborted.");
|
|
586
|
+
controller === null || controller === void 0 ? void 0 : controller.abort(abortErr);
|
|
587
|
+
if (!settled && rejectRace)
|
|
588
|
+
rejectRace(abortErr);
|
|
589
|
+
};
|
|
590
|
+
ovSignal.addEventListener("abort", onOvAbort, { once: true });
|
|
591
|
+
}
|
|
592
|
+
if (hasTimeout) {
|
|
593
|
+
timer = setTimeout(() => {
|
|
594
|
+
timedOut = true;
|
|
595
|
+
const err = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
596
|
+
err.name = "TimeoutError";
|
|
597
|
+
controller === null || controller === void 0 ? void 0 : controller.abort(err);
|
|
598
|
+
if (!settled && rejectRace) {
|
|
599
|
+
rejectRace(new errors_js_2.CoreTimeoutError(`Request timed out after ${timeoutMs}ms.`));
|
|
600
|
+
}
|
|
601
|
+
}, timeoutMs);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
const cleanup = () => {
|
|
605
|
+
settled = true;
|
|
606
|
+
if (timer !== null) {
|
|
607
|
+
clearTimeout(timer);
|
|
608
|
+
timer = null;
|
|
609
|
+
}
|
|
610
|
+
if (ovSignal && onOvAbort) {
|
|
611
|
+
ovSignal.removeEventListener("abort", onOvAbort);
|
|
612
|
+
onOvAbort = null;
|
|
613
|
+
}
|
|
614
|
+
};
|
|
615
|
+
try {
|
|
616
|
+
const fetchPromise = opts.pinnedIp && !this.config.fetch
|
|
617
|
+
? pinnedNodeFetch(url, init, opts.pinnedIp, controller === null || controller === void 0 ? void 0 : controller.signal)
|
|
618
|
+
: this.baseFetch(url, {
|
|
619
|
+
...init,
|
|
620
|
+
redirect: "manual",
|
|
621
|
+
signal: controller === null || controller === void 0 ? void 0 : controller.signal,
|
|
622
|
+
});
|
|
623
|
+
fetchPromise.then((lateResp) => {
|
|
624
|
+
var _a;
|
|
625
|
+
if (timedOut || userAborted) {
|
|
626
|
+
try {
|
|
627
|
+
void ((_a = lateResp.body) === null || _a === void 0 ? void 0 : _a.cancel().catch(() => { }));
|
|
628
|
+
}
|
|
629
|
+
catch (_b) {
|
|
630
|
+
// ignore
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}, () => { });
|
|
634
|
+
const response = await (racePromise ? Promise.race([fetchPromise, racePromise]) : fetchPromise);
|
|
635
|
+
return { response, racePromise, cleanup };
|
|
636
|
+
}
|
|
637
|
+
catch (err) {
|
|
638
|
+
cleanup();
|
|
639
|
+
if (userAborted || (ovSignal === null || ovSignal === void 0 ? void 0 : ovSignal.aborted)) {
|
|
640
|
+
throw new errors_js_2.CoreUserAbortError("Request was aborted.");
|
|
641
|
+
}
|
|
642
|
+
if (timedOut) {
|
|
643
|
+
throw new errors_js_2.CoreTimeoutError(`Request timed out after ${timeoutMs}ms.`);
|
|
644
|
+
}
|
|
645
|
+
throw err;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
withRequestOptions(opts, fn) {
|
|
649
|
+
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
650
|
+
if (!opts)
|
|
651
|
+
return fn();
|
|
652
|
+
const parent = this.reqStore.getStore();
|
|
653
|
+
const merged = {
|
|
654
|
+
timeout: (_a = opts.timeout) !== null && _a !== void 0 ? _a : parent === null || parent === void 0 ? void 0 : parent.timeout,
|
|
655
|
+
maxRetries: (_b = opts.maxRetries) !== null && _b !== void 0 ? _b : parent === null || parent === void 0 ? void 0 : parent.maxRetries,
|
|
656
|
+
headers: { ...((_c = parent === null || parent === void 0 ? void 0 : parent.headers) !== null && _c !== void 0 ? _c : {}), ...((_d = opts.headers) !== null && _d !== void 0 ? _d : {}) },
|
|
657
|
+
query: { ...((_e = parent === null || parent === void 0 ? void 0 : parent.query) !== null && _e !== void 0 ? _e : {}), ...((_f = opts.query) !== null && _f !== void 0 ? _f : {}) },
|
|
658
|
+
signal: (_g = opts.signal) !== null && _g !== void 0 ? _g : parent === null || parent === void 0 ? void 0 : parent.signal,
|
|
659
|
+
idempotencyKey: (_h = opts.idempotencyKey) !== null && _h !== void 0 ? _h : parent === null || parent === void 0 ? void 0 : parent.idempotencyKey,
|
|
660
|
+
_callIdempotencyKey: parent === null || parent === void 0 ? void 0 : parent._callIdempotencyKey,
|
|
661
|
+
_rawBox: parent === null || parent === void 0 ? void 0 : parent._rawBox,
|
|
662
|
+
};
|
|
663
|
+
return this.reqStore.run(merged, fn);
|
|
664
|
+
}
|
|
665
|
+
async captureRawResponse(fn) {
|
|
666
|
+
const parent = this.reqStore.getStore();
|
|
667
|
+
const box = { snap: null };
|
|
668
|
+
const ctx = {
|
|
669
|
+
...(parent !== null && parent !== void 0 ? parent : {}),
|
|
670
|
+
_rawBox: box,
|
|
671
|
+
};
|
|
672
|
+
const data = await this.reqStore.run(ctx, fn);
|
|
673
|
+
return { data, raw: box.snap };
|
|
674
|
+
}
|
|
675
|
+
async call(fn, opts = {}) {
|
|
676
|
+
var _a, _b, _c;
|
|
677
|
+
const ov = this.reqStore.getStore();
|
|
678
|
+
const idempotent = (_a = opts.idempotent) !== null && _a !== void 0 ? _a : true;
|
|
679
|
+
const configuredMax = (_c = (_b = opts.maxRetries) !== null && _b !== void 0 ? _b : ov === null || ov === void 0 ? void 0 : ov.maxRetries) !== null && _c !== void 0 ? _c : this.config.maxRetries;
|
|
680
|
+
const limit = idempotent ? Math.max(0, configuredMax) : 0;
|
|
681
|
+
let attempt = 0;
|
|
682
|
+
for (;;) {
|
|
683
|
+
try {
|
|
684
|
+
if (opts.idempotencyKey !== undefined) {
|
|
685
|
+
const ctx = {
|
|
686
|
+
...(ov !== null && ov !== void 0 ? ov : {}),
|
|
687
|
+
_callIdempotencyKey: opts.idempotencyKey,
|
|
688
|
+
};
|
|
689
|
+
return await this.reqStore.run(ctx, fn);
|
|
690
|
+
}
|
|
691
|
+
return await fn();
|
|
692
|
+
}
|
|
693
|
+
catch (raw) {
|
|
694
|
+
if (raw instanceof errors_js_1.UserError || raw instanceof errors_js_1.NotSupportedByServerError)
|
|
695
|
+
throw raw;
|
|
696
|
+
const err = await this.toCoreError(raw);
|
|
697
|
+
if (attempt >= limit || !shouldRetry(err))
|
|
698
|
+
throw err;
|
|
699
|
+
const retryAfter = parseRetryAfterMs(err.headers);
|
|
700
|
+
const delay = retryAfter !== null && retryAfter !== void 0 ? retryAfter : this.jitterFn(Math.min(500 * 2 ** attempt, MAX_BACKOFF_MS));
|
|
701
|
+
await this.sleepFn(delay);
|
|
702
|
+
attempt += 1;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
async toCoreError(raw) {
|
|
707
|
+
var _a, _b;
|
|
708
|
+
if (raw instanceof errors_js_2.CoreAPIError)
|
|
709
|
+
return raw;
|
|
710
|
+
if (raw instanceof runtime_js_1.ResponseError) {
|
|
711
|
+
const hdrs = headersToRecord(raw.response.headers);
|
|
712
|
+
let text = "";
|
|
713
|
+
try {
|
|
714
|
+
text = await raw.response.clone().text();
|
|
715
|
+
}
|
|
716
|
+
catch (_c) {
|
|
717
|
+
text = "";
|
|
718
|
+
}
|
|
719
|
+
return (0, errors_js_2.mapPanjaError)(raw.response.status, text, hdrs);
|
|
720
|
+
}
|
|
721
|
+
if (raw instanceof runtime_js_1.FetchError) {
|
|
722
|
+
const cause = raw.cause;
|
|
723
|
+
if (cause instanceof errors_js_2.CoreAPIError)
|
|
724
|
+
return cause;
|
|
725
|
+
if (cause instanceof Error) {
|
|
726
|
+
if (cause.name === "TimeoutError") {
|
|
727
|
+
return new errors_js_2.CoreTimeoutError(`Request timed out: ${cause.message}`);
|
|
728
|
+
}
|
|
729
|
+
if (cause.name === "AbortError") {
|
|
730
|
+
const ov = this.reqStore.getStore();
|
|
731
|
+
if ((_a = ov === null || ov === void 0 ? void 0 : ov.signal) === null || _a === void 0 ? void 0 : _a.aborted)
|
|
732
|
+
return new errors_js_2.CoreUserAbortError("Request was aborted.");
|
|
733
|
+
return new errors_js_2.CoreTimeoutError(`Request timed out: ${cause.message}`);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
return new errors_js_2.CoreConnectionError(`Connection error: ${raw.message}`);
|
|
737
|
+
}
|
|
738
|
+
if (raw instanceof Error) {
|
|
739
|
+
if (raw.name === "TimeoutError") {
|
|
740
|
+
return new errors_js_2.CoreTimeoutError(`Request timed out: ${raw.message}`);
|
|
741
|
+
}
|
|
742
|
+
if (raw.name === "AbortError") {
|
|
743
|
+
const ov = this.reqStore.getStore();
|
|
744
|
+
if ((_b = ov === null || ov === void 0 ? void 0 : ov.signal) === null || _b === void 0 ? void 0 : _b.aborted)
|
|
745
|
+
return new errors_js_2.CoreUserAbortError("Request was aborted.");
|
|
746
|
+
return new errors_js_2.CoreTimeoutError(`Request timed out: ${raw.message}`);
|
|
747
|
+
}
|
|
748
|
+
return new errors_js_2.CoreConnectionError(`Connection error: ${raw.message}`);
|
|
749
|
+
}
|
|
750
|
+
return new errors_js_2.CoreConnectionError(`Connection error: ${String(raw)}`);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
exports.Http = Http;
|