@wiro-ai/wiro-agent-connectors 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +1131 -34
  3. package/dist/cli.js +15 -12
  4. package/dist/core/credentials.d.ts +21 -0
  5. package/dist/core/credentials.js +45 -0
  6. package/dist/core/origins.d.ts +18 -0
  7. package/dist/core/origins.js +40 -0
  8. package/dist/core/upload-hosts.d.ts +15 -0
  9. package/dist/core/upload-hosts.js +43 -0
  10. package/dist/host/describe.d.ts +10 -0
  11. package/dist/host/describe.js +38 -0
  12. package/dist/host/env.d.ts +25 -2
  13. package/dist/host/env.js +24 -7
  14. package/dist/host/guarded-fetch.d.ts +36 -9
  15. package/dist/host/guarded-fetch.js +175 -52
  16. package/dist/host/index.d.ts +8 -5
  17. package/dist/host/index.js +12 -1
  18. package/dist/host/load.js +31 -1
  19. package/dist/host/server.d.ts +13 -2
  20. package/dist/host/server.js +15 -2
  21. package/dist/types.d.ts +96 -5
  22. package/dist/vendors/adapty.js +1303 -0
  23. package/dist/vendors/adjust.js +1372 -0
  24. package/dist/vendors/apollo.js +2499 -0
  25. package/dist/vendors/apple-appstore.js +2798 -0
  26. package/dist/vendors/beehiiv.js +1965 -0
  27. package/dist/vendors/blogger.js +1687 -0
  28. package/dist/vendors/bluesky.js +850 -127
  29. package/dist/vendors/brevo.js +2195 -0
  30. package/dist/vendors/calendarific.js +1116 -0
  31. package/dist/vendors/devto.js +685 -92
  32. package/dist/vendors/facebook-pages.js +2185 -0
  33. package/dist/vendors/firebase.js +1333 -0
  34. package/dist/vendors/ga4.js +1585 -0
  35. package/dist/vendors/gmail.js +1962 -0
  36. package/dist/vendors/google-ads.js +2201 -0
  37. package/dist/vendors/google-business.js +1621 -0
  38. package/dist/vendors/google-calendar.js +1936 -0
  39. package/dist/vendors/google-drive.js +2654 -0
  40. package/dist/vendors/google-merchant-center.js +1742 -0
  41. package/dist/vendors/google-play.js +1856 -0
  42. package/dist/vendors/google-search-console.js +1572 -0
  43. package/dist/vendors/hashnode.js +1722 -0
  44. package/dist/vendors/instagram.js +2249 -0
  45. package/dist/vendors/kaggle.js +2043 -0
  46. package/dist/vendors/keepa.js +2087 -0
  47. package/dist/vendors/linkedin.js +1588 -0
  48. package/dist/vendors/mailchimp.js +2402 -0
  49. package/dist/vendors/mastodon.js +1836 -0
  50. package/dist/vendors/meta-ads.js +2375 -0
  51. package/dist/vendors/notion.js +1950 -0
  52. package/dist/vendors/pinterest.js +1744 -0
  53. package/dist/vendors/qiita.js +1552 -0
  54. package/dist/vendors/reddit.js +1791 -0
  55. package/dist/vendors/revenuecat.js +1593 -0
  56. package/dist/vendors/roasit.js +1460 -0
  57. package/dist/vendors/sendgrid.js +2188 -0
  58. package/dist/vendors/serper.js +901 -179
  59. package/dist/vendors/shopify.js +2511 -0
  60. package/dist/vendors/threads.js +1869 -0
  61. package/dist/vendors/tiktok.js +2199 -0
  62. package/dist/vendors/tumblr.js +1793 -0
  63. package/dist/vendors/twitter.js +1650 -0
  64. package/dist/vendors/woocommerce.js +2258 -0
  65. package/dist/vendors/wordpress.js +1904 -0
  66. package/dist/vendors/youtube.js +2542 -0
  67. package/package.json +1 -1
@@ -0,0 +1,2087 @@
1
+ /* keepa connector module (MIT License). Built from src/vendors/keepa; do not edit. */
2
+ "use strict";
3
+
4
+ // src/core/errors.ts
5
+ var ToolFailure = class extends Error {
6
+ details;
7
+ constructor(message, details = {}) {
8
+ super(message);
9
+ this.name = "ToolFailure";
10
+ this.details = details;
11
+ }
12
+ };
13
+ var OutcomeUnknown = class extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = "OutcomeUnknown";
17
+ }
18
+ };
19
+
20
+ // src/core/accounts.ts
21
+ function allowedAccounts(accounts, key) {
22
+ if (accounts === null) return null;
23
+ const list = accounts?.[key];
24
+ return Array.isArray(list) ? list.map(String) : [];
25
+ }
26
+ function requireAccounts(accounts, key, ids, label = "account") {
27
+ const allowed = allowedAccounts(accounts, key);
28
+ if (allowed === null) return;
29
+ const requested = (Array.isArray(ids) ? ids : [ids]).map(String);
30
+ const refused = requested.filter((id) => !allowed.includes(id));
31
+ if (!refused.length) return;
32
+ throw new ToolFailure(
33
+ `The ${label} ${refused.join(", ")} ${refused.length > 1 ? "are" : "is"} not among the ${label}s chosen for this connection. ` + (allowed.length ? `Use one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`) + " Nothing was sent."
34
+ );
35
+ }
36
+
37
+ // src/core/text.ts
38
+ var encoder = new TextEncoder();
39
+ var decoder = new TextDecoder();
40
+ function utf8Bytes(text) {
41
+ return encoder.encode(text);
42
+ }
43
+ function utf8Length(text) {
44
+ return encoder.encode(text).length;
45
+ }
46
+ function utf8Decode(bytes) {
47
+ return decoder.decode(bytes);
48
+ }
49
+ function base64Encode(bytes) {
50
+ let binary = "";
51
+ for (let i = 0; i < bytes.length; i += 32768) {
52
+ binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
53
+ }
54
+ return btoa(binary);
55
+ }
56
+ function base64UrlEncode(bytes) {
57
+ return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
58
+ }
59
+ function base64UrlDecode(text) {
60
+ if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
61
+ const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
62
+ const binary = atob(padded);
63
+ const bytes = new Uint8Array(binary.length);
64
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
65
+ return bytes;
66
+ }
67
+ function truncate(text, max) {
68
+ if (text.length <= max) return text;
69
+ const points2 = Array.from(text);
70
+ if (points2.length <= max) return text;
71
+ return `${points2.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
72
+ }
73
+ function cleanVendorText(text, max = 300) {
74
+ if (typeof text !== "string") return void 0;
75
+ if (/^\s*</.test(text)) return void 0;
76
+ const line = text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
77
+ return line ? truncate(line, max) : void 0;
78
+ }
79
+ function formatNumber(value) {
80
+ return value.toLocaleString("en-US");
81
+ }
82
+
83
+ // src/core/output.ts
84
+ var OUTPUT_LIMIT_BYTES = 32 * 1024;
85
+ function jsonSize(value) {
86
+ return utf8Length(JSON.stringify(value) ?? "");
87
+ }
88
+ function cutStrings(value, max) {
89
+ if (typeof value === "string") return truncate(value, max);
90
+ if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
91
+ if (typeof value === "object" && value !== null) {
92
+ const out = {};
93
+ for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
94
+ return out;
95
+ }
96
+ return value;
97
+ }
98
+ function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
99
+ if (jsonSize(value) <= limit) return { value, truncated: false };
100
+ for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
101
+ const cut = cutStrings(value, max);
102
+ if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
103
+ }
104
+ return void 0;
105
+ }
106
+ function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
107
+ const build = (count) => {
108
+ const cut = count < input.items.length;
109
+ const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
110
+ const next = cut ? input.resumeAt(count) : input.nextPage;
111
+ if (next) result2["nextCursor"] = next;
112
+ if (cut) result2["truncated"] = true;
113
+ return result2;
114
+ };
115
+ const all = build(input.items.length);
116
+ if (jsonSize(all) <= limit) return all;
117
+ let low = 1;
118
+ let high = input.items.length - 1;
119
+ while (low < high) {
120
+ const middle = Math.ceil((low + high) / 2);
121
+ if (jsonSize(build(middle)) <= limit) low = middle;
122
+ else high = middle - 1;
123
+ }
124
+ const best = build(low);
125
+ if (jsonSize(best) <= limit) return best;
126
+ const shrunk = shrinkToFit(best, limit);
127
+ if (shrunk) return { ...shrunk.value, truncated: true };
128
+ throw new ToolFailure("The result is too large to return, even one item at a time.");
129
+ }
130
+ function encodeCursor(tool, state) {
131
+ return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
132
+ }
133
+ function decodeCursor(tool, cursor) {
134
+ if (cursor === void 0 || cursor === "") return null;
135
+ try {
136
+ const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
137
+ if (typeof state === "object" && state !== null && state.t === tool) {
138
+ return state;
139
+ }
140
+ } catch {
141
+ }
142
+ throw new ToolFailure(
143
+ "The cursor is not valid for this tool. Pass the nextCursor value of the previous result unchanged, or leave cursor out to start from the beginning."
144
+ );
145
+ }
146
+
147
+ // src/core/api-tools.ts
148
+ var ALL_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
149
+ var TEXT_TYPES = /json|^text\/|xml|javascript|x-www-form-urlencoded|csv|yaml|graphql/i;
150
+ var NOTE_ROOM = 400;
151
+ var MAX_CUT_POINTS = 4e4;
152
+ function isQueryValue(value) {
153
+ return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
154
+ }
155
+ function nothingSent(sentence) {
156
+ return new ToolFailure(`${sentence} Nothing was sent.`);
157
+ }
158
+ function fitReply(reply) {
159
+ if (jsonSize(reply) <= OUTPUT_LIMIT_BYTES) return reply;
160
+ const shrunk = shrinkToFit(reply, OUTPUT_LIMIT_BYTES - NOTE_ROOM);
161
+ if (shrunk) {
162
+ return {
163
+ ...shrunk.value,
164
+ truncated: true,
165
+ note: "Long text values were cut to fit 32 KB: ask for fewer items or fields to see them whole."
166
+ };
167
+ }
168
+ const text = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
169
+ const points2 = Array.from(text.length > MAX_CUT_POINTS ? text.slice(0, MAX_CUT_POINTS) : text);
170
+ if (/^[\ud800-\udbff]$/.test(points2[points2.length - 1] ?? "")) points2.pop();
171
+ const cut = (count) => ({
172
+ status: reply["status"],
173
+ ...reply["headers"] ? { headers: reply["headers"] } : {},
174
+ truncated: true,
175
+ note: `The reply has ${formatNumber(utf8Length(text))} bytes and was cut to fit 32 KB: ask for fewer items (the API's paging or field parameters) to see it whole.`,
176
+ text: points2.slice(0, count).join("")
177
+ });
178
+ let low = 0;
179
+ let high = points2.length;
180
+ while (low < high) {
181
+ const middle = Math.ceil((low + high) / 2);
182
+ if (jsonSize(cut(middle)) <= OUTPUT_LIMIT_BYTES) low = middle;
183
+ else high = middle - 1;
184
+ }
185
+ return cut(low);
186
+ }
187
+ function shapeReply(response, headerNames) {
188
+ const reply = { status: response.status };
189
+ const headers = {};
190
+ for (const name2 of headerNames) {
191
+ const value = response.headers.get(name2);
192
+ if (value) headers[name2] = truncate(value, 2e3);
193
+ }
194
+ if (Object.keys(headers).length) reply["headers"] = headers;
195
+ const type = response.headers.get("content-type") ?? "";
196
+ if (type && !TEXT_TYPES.test(type)) {
197
+ reply["contentType"] = truncate(type, 200);
198
+ reply["note"] = "The reply is a binary file and is not shown.";
199
+ return reply;
200
+ }
201
+ if (response.data !== null && response.data !== void 0 && response.data !== "") reply["data"] = response.data;
202
+ return fitReply(reply);
203
+ }
204
+ function checkAccounts(rule, request, h) {
205
+ const label = rule.label ?? "account";
206
+ const allowed = allowedAccounts(h.ctx.accounts, rule.key);
207
+ if (allowed === null) return;
208
+ const namesNone = nothingSent(
209
+ `This request names none of the ${label}s chosen for this connection. ` + (allowed.length ? `It must name one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`)
210
+ );
211
+ if (rule.ids) {
212
+ const ids = rule.ids(request).map(String);
213
+ if (!ids.length) throw namesNone;
214
+ requireAccounts(h.ctx.accounts, rule.key, ids, label);
215
+ return;
216
+ }
217
+ if (!request.segments.some((segment) => allowed.includes(segment))) throw namesNone;
218
+ }
219
+ function apiTools(options) {
220
+ const { label, basePath } = options;
221
+ const methods = options.methods?.length ? [...new Set(options.methods)] : ALL_METHODS;
222
+ const headerNames = ["link", "location", ...(options.responseHeaders ?? []).map((name2) => name2.toLowerCase())];
223
+ const base = basePath?.replace(/\/+$/, "");
224
+ const pathSchema = {
225
+ type: "string",
226
+ minLength: 1,
227
+ maxLength: 2e3,
228
+ pattern: "^(?!.*//)/[^?#]*$",
229
+ description: `The path${basePath ? `, starting with ${basePath}` : ""}. Query parameters go in query, not in the path.`
230
+ };
231
+ const querySchema = {
232
+ type: "object",
233
+ description: 'Query parameters, e.g. {"page": 2, "fields": "id,name"}. A list repeats the parameter: {"id": [1, 2]} sends id=1&id=2.'
234
+ };
235
+ const originSchema = options.originArgument ? { origin: { type: "string", pattern: "^https://", maxLength: 300, description: options.originArgument } } : {};
236
+ async function run(method, args, h) {
237
+ let origin = h.origins[0];
238
+ if (args.origin !== void 0) {
239
+ let wanted;
240
+ try {
241
+ wanted = new URL(args.origin).origin;
242
+ } catch {
243
+ }
244
+ if (!wanted || !h.origins.includes(wanted)) throw nothingSent(`origin must be one of: ${h.origins.join(", ")}.`);
245
+ origin = wanted;
246
+ }
247
+ const url = new URL(args.path, origin);
248
+ if (url.origin !== origin) throw nothingSent(`The path must stay on ${origin}.`);
249
+ const path = url.pathname;
250
+ if (base !== void 0 && path !== base && !path.startsWith(`${base}/`)) throw nothingSent(`The path must start with ${basePath}.`);
251
+ let segments;
252
+ try {
253
+ segments = path.split("/").slice(1).map((segment) => decodeURIComponent(segment));
254
+ } catch {
255
+ throw nothingSent("The path has a broken percent-escape (a % not followed by two hex digits).");
256
+ }
257
+ if (segments[segments.length - 1] === "") segments.pop();
258
+ const query = {};
259
+ const queryLists = {};
260
+ for (const [key, value] of Object.entries(args.query ?? {})) {
261
+ if (value === void 0 || value === null) continue;
262
+ const list = Array.isArray(value) ? value : [value];
263
+ if (!key || !list.every(isQueryValue)) throw nothingSent(`query.${key} must be text, a number, true or false, or a list of them.`);
264
+ query[key] = Array.isArray(value) ? list : value;
265
+ queryLists[key] = list.map(String);
266
+ }
267
+ const request = { method, origin, path, query };
268
+ if (method !== "GET") {
269
+ if (args.json !== void 0 && args.body !== void 0) throw nothingSent("Give json or body, not both.");
270
+ if (args.body !== void 0 && !args.content_type) throw nothingSent('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
271
+ if (args.json !== void 0 && !args.content_type) {
272
+ request.json = args.json;
273
+ } else if (args.json !== void 0 || args.body !== void 0) {
274
+ request.body = utf8Bytes(args.body ?? JSON.stringify(args.json));
275
+ request.contentType = args.content_type;
276
+ }
277
+ request.write = true;
278
+ }
279
+ const info = { method, origin, path, segments, query: queryLists, ...args.json !== void 0 ? { json: args.json } : {} };
280
+ if (options.accounts) checkAccounts(options.accounts, info, h);
281
+ await options.guard?.(info, h);
282
+ const response = options.send ? await options.send(request, h) : await h.api(request);
283
+ return shapeReply(response, headerNames);
284
+ }
285
+ return [
286
+ {
287
+ name: "api_get",
288
+ kind: "read",
289
+ title: `Call the ${label} API (GET)`,
290
+ description: `${options.description} Sends one GET request with the connection's credentials and returns the HTTP status and the reply, JSON or text, cut to fit 32 KB (use the API's own paging and field parameters for long lists). It changes nothing.`,
291
+ inputSchema: {
292
+ type: "object",
293
+ properties: { path: pathSchema, query: querySchema, ...originSchema },
294
+ required: ["path"],
295
+ additionalProperties: false
296
+ },
297
+ run: (args, h) => run("GET", args, h)
298
+ },
299
+ {
300
+ name: "api_request",
301
+ kind: "write",
302
+ check: "api_get",
303
+ title: `Send a request to the ${label} API`,
304
+ description: `${options.description} Sends one ${methods.join(", ")} request with the connection's credentials, with a JSON body (json) or another body (body and content_type), and returns the HTTP status and the reply. It can create, change or delete data. It is never retried: when the outcome is unclear, check with api_get before sending it again.`,
305
+ inputSchema: {
306
+ type: "object",
307
+ properties: {
308
+ method: { type: "string", enum: methods, description: `The HTTP method: ${methods.join(", ")}.` },
309
+ path: pathSchema,
310
+ query: querySchema,
311
+ json: { type: "object", description: "A JSON object to send as the body (application/json unless content_type says otherwise)." },
312
+ body: { type: "string", maxLength: 1e6, description: 'Any other body, as text, with its content_type, e.g. a form: "name=a&tags=b".' },
313
+ content_type: {
314
+ type: "string",
315
+ pattern: "^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+(\\s*;.*)?$",
316
+ maxLength: 200,
317
+ description: `The body's media type, e.g. "application/x-www-form-urlencoded"; required with body.`
318
+ },
319
+ ...originSchema
320
+ },
321
+ required: ["method", "path"],
322
+ additionalProperties: false
323
+ },
324
+ run: (args, h) => run(args.method, args, h)
325
+ }
326
+ ];
327
+ }
328
+
329
+ // src/core/credentials.ts
330
+ function requiredAlternatives(module2) {
331
+ return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
332
+ }
333
+ function unmetAlternatives(alternatives, has) {
334
+ const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
335
+ if (lacking.some((list) => list.length === 0)) return [];
336
+ return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
337
+ }
338
+ function andList(items) {
339
+ if (items.length <= 2) return items.join(" and ");
340
+ return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
341
+ }
342
+ function orList(items) {
343
+ if (items.length <= 1) return items.join("");
344
+ return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
345
+ }
346
+
347
+ // src/core/files.ts
348
+ var ATTACHMENT_URI = "attachment:///";
349
+ var MAX_NAME = 200;
350
+ function fileLimitOf(ctx) {
351
+ const maxBytes = ctx.files?.maxBytes;
352
+ return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
353
+ }
354
+ function fileName(name2) {
355
+ const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
356
+ const points2 = Array.from(clean);
357
+ if (points2.length <= MAX_NAME) return clean || "file";
358
+ const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
359
+ return points2.slice(0, MAX_NAME - extension.length).join("") + extension;
360
+ }
361
+ function fileType(mimeType) {
362
+ const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
363
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
364
+ }
365
+ function resourceBlock(file) {
366
+ return {
367
+ type: "resource",
368
+ resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
369
+ };
370
+ }
371
+
372
+ // src/core/http.ts
373
+ var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
374
+ var USER_AGENT = "agent-connectors";
375
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
376
+ function errorCode(error) {
377
+ const code = error?.code;
378
+ return typeof code === "string" ? code : void 0;
379
+ }
380
+ function describe(error) {
381
+ const name2 = error?.name;
382
+ const code = errorCode(error);
383
+ if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
384
+ if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
385
+ if (code === "TOO_LARGE") return "the reply was too large";
386
+ return cleanVendorText(error?.message, 200) ?? "a network error";
387
+ }
388
+ function retryAfterSeconds(headers, now = Date.now()) {
389
+ const retryAfter = headers.get("retry-after");
390
+ if (retryAfter) {
391
+ const seconds = Number(retryAfter);
392
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
393
+ const date = Date.parse(retryAfter);
394
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
395
+ }
396
+ const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
397
+ if (reset) {
398
+ const value = Number(reset);
399
+ if (Number.isFinite(value) && value >= 0) {
400
+ return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
401
+ }
402
+ }
403
+ return void 0;
404
+ }
405
+ function vendorCode(data) {
406
+ if (typeof data !== "object" || data === null) return void 0;
407
+ for (const key of ["error", "code"]) {
408
+ const value = data[key];
409
+ if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
410
+ }
411
+ return void 0;
412
+ }
413
+ function vendorMessage(data) {
414
+ if (typeof data === "string") return cleanVendorText(data);
415
+ if (typeof data !== "object" || data === null) return void 0;
416
+ const record = data;
417
+ for (const key of ["message", "error_description", "error", "detail", "title"]) {
418
+ const value = record[key];
419
+ if (typeof value === "string" && value.trim()) return cleanVendorText(value);
420
+ const nested = value?.message;
421
+ if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
422
+ }
423
+ if (Array.isArray(record["errors"])) {
424
+ const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
425
+ if (messages.length) return cleanVendorText(messages.join("; "));
426
+ }
427
+ return void 0;
428
+ }
429
+ var TooLarge = class extends Error {
430
+ constructor(limit) {
431
+ super(`the reply is larger than ${formatNumber(limit)} bytes`);
432
+ this.limit = limit;
433
+ }
434
+ limit;
435
+ };
436
+ async function readCapped(response, maxBytes) {
437
+ const declared = Number(response.headers.get("content-length"));
438
+ if (Number.isFinite(declared) && declared > maxBytes) {
439
+ await response.body?.cancel().catch(() => {
440
+ });
441
+ throw new TooLarge(maxBytes);
442
+ }
443
+ if (!response.body) return new Uint8Array(0);
444
+ const reader = response.body.getReader();
445
+ const chunks = [];
446
+ let total = 0;
447
+ for (; ; ) {
448
+ const { done, value } = await reader.read();
449
+ if (done) break;
450
+ total += value.byteLength;
451
+ if (total > maxBytes) {
452
+ await reader.cancel().catch(() => {
453
+ });
454
+ throw new TooLarge(maxBytes);
455
+ }
456
+ chunks.push(value);
457
+ }
458
+ const bytes = new Uint8Array(total);
459
+ let offset = 0;
460
+ for (const chunk of chunks) {
461
+ bytes.set(chunk, offset);
462
+ offset += chunk.byteLength;
463
+ }
464
+ return bytes;
465
+ }
466
+ function parseBody(bytes, contentType) {
467
+ if (bytes.length === 0) return null;
468
+ const text = utf8Decode(bytes);
469
+ if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text)) {
470
+ try {
471
+ return JSON.parse(text);
472
+ } catch {
473
+ }
474
+ }
475
+ return text;
476
+ }
477
+ function createHttp(env) {
478
+ const { label, ctx } = env;
479
+ const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
480
+ const checkCredentials = env.credentialLabels.length ? `Check that the ${andList(env.credentialLabels)} ${env.credentialLabels.length > 1 ? "are" : "is"} correct and still active.` : `Check that the ${label} credentials are correct and still active.`;
481
+ function failureFor(status, headers, data, request) {
482
+ const message = vendorMessage(data);
483
+ const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
484
+ const retryAfter = retryAfterSeconds(headers);
485
+ const code = vendorCode(data);
486
+ const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
487
+ const custom = request.errors?.[status];
488
+ const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
489
+ if (status >= 500) {
490
+ if (request.write) {
491
+ return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
492
+ }
493
+ return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
494
+ }
495
+ if (status === 429) {
496
+ return new ToolFailure(
497
+ `${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
498
+ { status, ...extra }
499
+ );
500
+ }
501
+ if (status === 401) {
502
+ return new ToolFailure(
503
+ withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
504
+ { status, ...extra }
505
+ );
506
+ }
507
+ if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
508
+ if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
509
+ if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
510
+ return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
511
+ }
512
+ async function api(request) {
513
+ const method = request.method ?? "GET";
514
+ if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
515
+ throw new Error(`read-only tool sent ${method}`);
516
+ }
517
+ const origin = request.origin ?? env.origins[0];
518
+ if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
519
+ const url = new URL(request.path, origin);
520
+ if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
521
+ for (const [key, value] of Object.entries(request.query ?? {})) {
522
+ if (value === void 0 || value === null) continue;
523
+ if (Array.isArray(value)) {
524
+ url.searchParams.delete(key);
525
+ for (const item of value) url.searchParams.append(key, String(item));
526
+ } else {
527
+ url.searchParams.set(key, String(value));
528
+ }
529
+ }
530
+ const headers = {
531
+ accept: "application/json",
532
+ "user-agent": USER_AGENT,
533
+ ...request.auth === false ? {} : env.authHeaders(),
534
+ ...request.headers
535
+ };
536
+ let body;
537
+ if (request.json !== void 0) {
538
+ body = JSON.stringify(request.json);
539
+ headers["content-type"] = "application/json";
540
+ } else if (request.body) {
541
+ body = request.body;
542
+ headers["content-type"] = request.contentType ?? "application/octet-stream";
543
+ }
544
+ const started = Date.now();
545
+ if (request.write) env.onWriteSent();
546
+ let response;
547
+ try {
548
+ response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
549
+ } catch (error) {
550
+ env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
551
+ if (errorCode(error) === "URL_REFUSED") {
552
+ throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
553
+ }
554
+ if (request.write) {
555
+ throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
556
+ }
557
+ if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
558
+ throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
559
+ }
560
+ env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
561
+ let bytes;
562
+ try {
563
+ bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
564
+ } catch (error) {
565
+ if (request.write && (response.ok || response.status >= 500)) {
566
+ throw new OutcomeUnknown(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}), so it is not known whether the change was made.`);
567
+ }
568
+ throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
569
+ }
570
+ const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
571
+ if (response.ok) return { status: response.status, headers: response.headers, data };
572
+ throw failureFor(response.status, response.headers, data, request);
573
+ }
574
+ async function media(rawUrl, options) {
575
+ const { what } = options;
576
+ let url;
577
+ try {
578
+ url = new URL(rawUrl);
579
+ } catch {
580
+ throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
581
+ }
582
+ if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
583
+ const started = Date.now();
584
+ let response;
585
+ try {
586
+ response = await ctx.fetch(url.toString(), {
587
+ method: "GET",
588
+ headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
589
+ ...ctx.signal ? { signal: ctx.signal } : {}
590
+ });
591
+ } catch (error) {
592
+ env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
593
+ if (errorCode(error) === "URL_REFUSED") {
594
+ throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
595
+ }
596
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
597
+ }
598
+ env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
599
+ if (!response.ok) {
600
+ await response.body?.cancel().catch(() => {
601
+ });
602
+ throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
603
+ }
604
+ try {
605
+ const bytes = await readCapped(response, options.maxBytes);
606
+ return { bytes, contentType: response.headers.get("content-type") };
607
+ } catch (error) {
608
+ if (error instanceof TooLarge) {
609
+ throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
610
+ }
611
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
612
+ }
613
+ }
614
+ return { api, media };
615
+ }
616
+
617
+ // src/core/origins.ts
618
+ function parseSiteUrl(value) {
619
+ const text = typeof value === "string" ? value.trim() : "";
620
+ if (!text) return { ok: false, problem: "is empty" };
621
+ let url;
622
+ try {
623
+ url = new URL(text.includes("://") ? text : `https://${text}`);
624
+ } catch {
625
+ return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
626
+ }
627
+ if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
628
+ if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
629
+ if (!url.hostname) return { ok: false, problem: "has no host name" };
630
+ return { ok: true, url, origin: url.origin };
631
+ }
632
+
633
+ // src/core/schema.ts
634
+ var patterns = /* @__PURE__ */ new Map();
635
+ function patternOf(source) {
636
+ let compiled = patterns.get(source);
637
+ if (!compiled) {
638
+ compiled = new RegExp(source, "u");
639
+ patterns.set(source, compiled);
640
+ }
641
+ return compiled;
642
+ }
643
+ function isPlainObject(value) {
644
+ return typeof value === "object" && value !== null && !Array.isArray(value);
645
+ }
646
+ function isHttpUrl(value) {
647
+ try {
648
+ const url = new URL(value);
649
+ return url.protocol === "https:" || url.protocol === "http:";
650
+ } catch {
651
+ return false;
652
+ }
653
+ }
654
+ function name(path) {
655
+ return `\`${path}\``;
656
+ }
657
+ function child(path, key) {
658
+ return path ? `${path}.${key}` : key;
659
+ }
660
+ function checkValue(schema, value, path, issues) {
661
+ switch (schema.type) {
662
+ case "object":
663
+ checkObject(schema, value, path, issues);
664
+ return;
665
+ case "array": {
666
+ if (!Array.isArray(value)) {
667
+ issues.push(`${name(path)} must be an array`);
668
+ return;
669
+ }
670
+ if (schema.minItems !== void 0 && value.length < schema.minItems) {
671
+ issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
672
+ }
673
+ if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
674
+ issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
675
+ }
676
+ if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
677
+ issues.push(`${name(path)} must not repeat an item`);
678
+ }
679
+ if (schema.items) {
680
+ value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
681
+ }
682
+ break;
683
+ }
684
+ case "string": {
685
+ if (typeof value !== "string") {
686
+ issues.push(`${name(path)} must be a string`);
687
+ return;
688
+ }
689
+ const length = Array.from(value).length;
690
+ if (schema.minLength !== void 0 && length < schema.minLength) {
691
+ issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
692
+ }
693
+ if (schema.maxLength !== void 0 && length > schema.maxLength) {
694
+ issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
695
+ }
696
+ if (schema.format === "uri" && !isHttpUrl(value)) {
697
+ issues.push(`${name(path)} must be an absolute http(s) URL`);
698
+ } else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
699
+ issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
700
+ }
701
+ break;
702
+ }
703
+ case "integer":
704
+ case "number": {
705
+ if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
706
+ issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
707
+ return;
708
+ }
709
+ if (schema.minimum !== void 0 && value < schema.minimum) {
710
+ issues.push(`${name(path)} must be at least ${schema.minimum}`);
711
+ }
712
+ if (schema.maximum !== void 0 && value > schema.maximum) {
713
+ issues.push(`${name(path)} must be at most ${schema.maximum}`);
714
+ }
715
+ break;
716
+ }
717
+ case "boolean":
718
+ if (typeof value !== "boolean") {
719
+ issues.push(`${name(path)} must be true or false`);
720
+ return;
721
+ }
722
+ break;
723
+ default:
724
+ break;
725
+ }
726
+ if (schema.enum && !schema.enum.includes(value)) {
727
+ issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
728
+ }
729
+ }
730
+ function checkObject(schema, value, path, issues) {
731
+ if (!isPlainObject(value)) {
732
+ issues.push(`${path ? name(path) : "the arguments"} must be an object`);
733
+ return;
734
+ }
735
+ const properties = schema.properties ?? {};
736
+ for (const key of schema.required ?? []) {
737
+ if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
738
+ }
739
+ const unknown = [];
740
+ for (const [key, item] of Object.entries(value)) {
741
+ const property = properties[key];
742
+ if (!property) {
743
+ if (schema.additionalProperties === false) unknown.push(key);
744
+ continue;
745
+ }
746
+ if (item === void 0 || item === null) continue;
747
+ checkValue(property, item, child(path, key), issues);
748
+ }
749
+ if (unknown.length) {
750
+ const known = Object.keys(properties);
751
+ issues.push(`unknown ${path ? `field${unknown.length > 1 ? "s" : ""} in ${name(path)}` : `argument${unknown.length > 1 ? "s" : ""}`} ${unknown.map((key) => JSON.stringify(key)).join(", ")}` + (known.length ? ` (expected: ${known.join(", ")})` : ""));
752
+ }
753
+ }
754
+ function copyDefault(value) {
755
+ return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
756
+ }
757
+ function validateArguments(schema, args) {
758
+ const input = args === void 0 || args === null ? {} : args;
759
+ if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
760
+ const value = { ...input };
761
+ if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
762
+ const issues = [];
763
+ checkObject(schema, value, "", issues);
764
+ if (issues.length) return { ok: false, issues };
765
+ for (const [key, property] of Object.entries(schema.properties ?? {})) {
766
+ if (value[key] === null) delete value[key];
767
+ if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
768
+ }
769
+ return { ok: true, value };
770
+ }
771
+
772
+ // src/core/upload-hosts.ts
773
+ var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
774
+ function uploadHostProblem(entry) {
775
+ if (typeof entry !== "string") return "must be a host name";
776
+ const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
777
+ const labels = name2.split(".");
778
+ if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
779
+ return "must be a lowercase host name like uploads.example.com, or one with a leading dot like .example.com for every host under it";
780
+ }
781
+ if (labels.length < 2) return "needs at least two labels, like example.com";
782
+ if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
783
+ return void 0;
784
+ }
785
+
786
+ // src/core/connector.ts
787
+ var ANNOTATIONS = {
788
+ read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
789
+ create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
790
+ update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
791
+ delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
792
+ write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
793
+ };
794
+ var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
795
+ var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
796
+ var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
797
+ var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
798
+ var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
799
+ var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
800
+ var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
801
+ function deepFreeze(value) {
802
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
803
+ Object.freeze(value);
804
+ for (const item of Object.values(value)) deepFreeze(item);
805
+ }
806
+ return value;
807
+ }
808
+ function assertDefinition(def) {
809
+ const problem = (message) => {
810
+ throw new Error(`connector "${def.vendor}": ${message}`);
811
+ };
812
+ if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
813
+ if (!def.label?.trim()) problem("label is required");
814
+ const originFields = def.originFields ?? [];
815
+ if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
816
+ for (const origin of def.origins) {
817
+ let url;
818
+ try {
819
+ url = new URL(origin);
820
+ } catch {
821
+ }
822
+ if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
823
+ }
824
+ for (const name2 of def.credentials) {
825
+ if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
826
+ }
827
+ for (const [index, name2] of originFields.entries()) {
828
+ if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
829
+ if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
830
+ }
831
+ const names = /* @__PURE__ */ new Set();
832
+ for (const tool of def.tools) {
833
+ if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
834
+ if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
835
+ names.add(tool.name);
836
+ if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
837
+ if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
838
+ if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
839
+ if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
840
+ problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
841
+ }
842
+ }
843
+ for (const tool of def.tools) {
844
+ if (tool.kind === "read") continue;
845
+ const check = def.tools.find((candidate) => candidate.name === tool.check);
846
+ if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
847
+ }
848
+ assertUploadHosts(def, problem);
849
+ assertRequiredCredentials(def, problem);
850
+ assertAccountPickers(def, problem);
851
+ }
852
+ function assertUploadHosts(def, problem) {
853
+ const hosts = def.uploadHosts;
854
+ if (hosts === void 0) return;
855
+ if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
856
+ hosts.forEach((entry, index) => {
857
+ const wrong = uploadHostProblem(entry);
858
+ if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
859
+ if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
860
+ });
861
+ }
862
+ function assertRequiredCredentials(def, problem) {
863
+ const required = def.requiredCredentials;
864
+ if (required === void 0) return;
865
+ if (!Array.isArray(required) || !required.length) {
866
+ problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
867
+ }
868
+ required.forEach((list, index) => {
869
+ const which = `requiredCredentials[${index}]`;
870
+ if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
871
+ list.forEach((name2, position) => {
872
+ if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
873
+ if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
874
+ });
875
+ });
876
+ const lists = required;
877
+ lists.forEach((list, index) => {
878
+ const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
879
+ if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
880
+ if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
881
+ problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
882
+ }
883
+ });
884
+ }
885
+ function isDotPath(value) {
886
+ return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
887
+ }
888
+ function assertAccountPickers(def, problem) {
889
+ const pickers = def.accountPickers;
890
+ if (pickers === void 0) return;
891
+ if (!Array.isArray(pickers)) problem("accountPickers must be a list");
892
+ const keys = /* @__PURE__ */ new Set();
893
+ for (const item of pickers) {
894
+ if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
895
+ const picker = item;
896
+ const key = picker["key"];
897
+ if (typeof key !== "string" || !PICKER_KEY_PATTERN.test(key)) problem(`account picker ${JSON.stringify(key)}: key must match ^[a-z][a-z0-9_]{0,63}$`);
898
+ if (keys.has(key)) problem(`account picker ${key} is defined twice`);
899
+ keys.add(key);
900
+ const fail = (message) => problem(`account picker ${key}: ${message}`);
901
+ const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
902
+ if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
903
+ const { label, description, multiple, legacyField } = picker;
904
+ if (typeof label !== "string" || !label.trim()) fail("label is required");
905
+ if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
906
+ fail("description, when given, must be a text of 1 to 1024 characters");
907
+ }
908
+ if (typeof multiple !== "boolean") fail("multiple must be true or false");
909
+ const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
910
+ if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
911
+ if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
912
+ for (const field of ["idField", "nameField"]) {
913
+ if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
914
+ }
915
+ if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
916
+ fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
917
+ }
918
+ }
919
+ }
920
+ function copyPicker(picker) {
921
+ return {
922
+ key: picker.key,
923
+ label: picker.label,
924
+ ...picker.description !== void 0 ? { description: picker.description } : {},
925
+ multiple: picker.multiple,
926
+ tool: picker.tool,
927
+ idField: picker.idField,
928
+ nameField: picker.nameField,
929
+ ...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
930
+ };
931
+ }
932
+ function result(payload, isError, files = []) {
933
+ return {
934
+ content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
935
+ ...isError ? { isError: true } : {}
936
+ };
937
+ }
938
+ function failure(message, details = {}) {
939
+ return result({ error: message, ...details }, true);
940
+ }
941
+ function trimmed(values) {
942
+ const out = {};
943
+ if (typeof values !== "object" || values === null) return out;
944
+ for (const [key, value] of Object.entries(values)) {
945
+ if (value === void 0 || value === null) continue;
946
+ const text = String(value).trim();
947
+ if (text) out[key] = text;
948
+ }
949
+ return out;
950
+ }
951
+ function defineConnector(def) {
952
+ assertDefinition(def);
953
+ const { label } = def;
954
+ const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
955
+ const toolList = def.tools.map((tool) => tool.name).join(", ");
956
+ const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
957
+ const required = requiredAlternatives(def);
958
+ const notConnected = (unmet) => {
959
+ const [first] = unmet;
960
+ if (unmet.length === 1 && first) {
961
+ return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
962
+ }
963
+ return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
964
+ };
965
+ const descriptors = def.tools.map((tool) => ({
966
+ name: tool.name,
967
+ title: tool.title,
968
+ description: tool.description,
969
+ inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
970
+ annotations: { ...ANNOTATIONS[tool.kind] }
971
+ }));
972
+ async function call(toolName, args, ctx) {
973
+ const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
974
+ if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
975
+ if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
976
+ const log = (text) => {
977
+ try {
978
+ ctx.log?.(text);
979
+ } catch {
980
+ }
981
+ };
982
+ const given = trimmed(ctx.credentials);
983
+ const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
984
+ const has = (name2) => Boolean(credentials[name2]);
985
+ const unmet = unmetAlternatives(required, has);
986
+ if (unmet.length) return failure(notConnected(unmet));
987
+ const complete = required.filter((list) => list.every(has));
988
+ const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
989
+ const fieldOrigins = /* @__PURE__ */ new Map();
990
+ for (const name2 of def.originFields ?? []) {
991
+ if (!given[name2] && !inUse.includes(name2)) continue;
992
+ const site = parseSiteUrl(given[name2] ?? "");
993
+ if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
994
+ fieldOrigins.set(name2, site.origin);
995
+ }
996
+ const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
997
+ const parsed = validateArguments(tool.inputSchema, args);
998
+ if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
999
+ const frozenCredentials = Object.freeze({ ...credentials });
1000
+ let writeSent = false;
1001
+ const fileLimit = fileLimitOf(ctx);
1002
+ const files = [];
1003
+ let fileBytes = 0;
1004
+ const http = createHttp({
1005
+ vendor: def.vendor,
1006
+ label,
1007
+ tool: tool.name,
1008
+ readOnly: tool.kind === "read",
1009
+ origins,
1010
+ // A 401 names the credentials in use (for a module that needs none, the ones given).
1011
+ credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
1012
+ ctx,
1013
+ authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
1014
+ log,
1015
+ onWriteSent: () => {
1016
+ writeSent = true;
1017
+ }
1018
+ });
1019
+ const helpers = {
1020
+ tool: tool.name,
1021
+ credentials: frozenCredentials,
1022
+ ctx,
1023
+ origins: Object.freeze([...origins]),
1024
+ originOf: (credential) => {
1025
+ const origin = fieldOrigins.get(credential);
1026
+ if (!origin) throw new Error(`${credential} gives no origin in this call`);
1027
+ return origin;
1028
+ },
1029
+ api: http.api,
1030
+ media: http.media,
1031
+ page: (input) => fitPage(input),
1032
+ cursor: (cursor) => decodeCursor(tool.name, cursor),
1033
+ makeCursor: (state) => encodeCursor(tool.name, state),
1034
+ fileLimit: () => fileLimit,
1035
+ file: ({ name: name2, mimeType, bytes }) => {
1036
+ if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
1037
+ const total = fileBytes + bytes.byteLength;
1038
+ if (total > fileLimit) {
1039
+ throw new ToolFailure(files.length ? `The files of this call have ${formatNumber(total)} bytes in all, more than the ${formatNumber(fileLimit)} bytes this host takes from one call.` : `The file has ${formatNumber(bytes.byteLength)} bytes, more than the ${formatNumber(fileLimit)} bytes this host takes.`);
1040
+ }
1041
+ fileBytes = total;
1042
+ const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
1043
+ files.push({ ...info, bytes });
1044
+ return { ...info };
1045
+ },
1046
+ log
1047
+ };
1048
+ try {
1049
+ const data = await tool.run(parsed.value, helpers);
1050
+ const fitted = shrinkToFit(data ?? {});
1051
+ if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
1052
+ const payload = fitted.value;
1053
+ return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
1054
+ } catch (error) {
1055
+ if (error instanceof OutcomeUnknown) {
1056
+ return result({
1057
+ outcome: "unknown",
1058
+ check: tool.check,
1059
+ error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
1060
+ }, true);
1061
+ }
1062
+ if (error instanceof ToolFailure) return failure(error.message, error.details);
1063
+ log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
1064
+ if (writeSent) {
1065
+ return result({
1066
+ outcome: "unknown",
1067
+ check: tool.check,
1068
+ error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
1069
+ }, true);
1070
+ }
1071
+ return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
1072
+ }
1073
+ }
1074
+ return deepFreeze({
1075
+ vendor: def.vendor,
1076
+ origins: [...def.origins],
1077
+ originFields: [...def.originFields ?? []],
1078
+ uploadHosts: [...def.uploadHosts ?? []],
1079
+ credentials: [...def.credentials],
1080
+ requiredCredentials: required.map((list) => [...list]),
1081
+ accountPickers: (def.accountPickers ?? []).map(copyPicker),
1082
+ tools: descriptors,
1083
+ call
1084
+ });
1085
+ }
1086
+
1087
+ // src/core/jwt.ts
1088
+ var TOKEN_EARLY_MS = 5 * 60 * 1e3;
1089
+
1090
+ // src/vendors/keepa/decode.ts
1091
+ var MARKETPLACES = {
1092
+ "amazon.com": { site: "amazon.com", id: 1, currency: "USD", decimals: 2 },
1093
+ "amazon.co.uk": { site: "amazon.co.uk", id: 2, currency: "GBP", decimals: 2 },
1094
+ "amazon.de": { site: "amazon.de", id: 3, currency: "EUR", decimals: 2 },
1095
+ "amazon.fr": { site: "amazon.fr", id: 4, currency: "EUR", decimals: 2 },
1096
+ "amazon.co.jp": { site: "amazon.co.jp", id: 5, currency: "JPY", decimals: 0 },
1097
+ "amazon.ca": { site: "amazon.ca", id: 6, currency: "CAD", decimals: 2 },
1098
+ "amazon.it": { site: "amazon.it", id: 8, currency: "EUR", decimals: 2 },
1099
+ "amazon.es": { site: "amazon.es", id: 9, currency: "EUR", decimals: 2 },
1100
+ "amazon.in": { site: "amazon.in", id: 10, currency: "INR", decimals: 2 },
1101
+ "amazon.com.mx": { site: "amazon.com.mx", id: 11, currency: "MXN", decimals: 2 },
1102
+ "amazon.com.br": { site: "amazon.com.br", id: 12, currency: "BRL", decimals: 2 }
1103
+ };
1104
+ function marketById(id) {
1105
+ return Object.values(MARKETPLACES).find((market) => market.id === id);
1106
+ }
1107
+ var SERIES_NAMES = [
1108
+ "AMAZON",
1109
+ "NEW",
1110
+ "USED",
1111
+ "SALES",
1112
+ "LISTPRICE",
1113
+ "COLLECTIBLE",
1114
+ "REFURBISHED",
1115
+ "NEW_FBM_SHIPPING",
1116
+ "LIGHTNING_DEAL",
1117
+ "WAREHOUSE",
1118
+ "NEW_FBA",
1119
+ "COUNT_NEW",
1120
+ "COUNT_USED",
1121
+ "COUNT_REFURBISHED",
1122
+ "COUNT_COLLECTIBLE",
1123
+ "EXTRA_INFO_UPDATES",
1124
+ "RATING",
1125
+ "COUNT_REVIEWS",
1126
+ "BUY_BOX_SHIPPING",
1127
+ "USED_NEW_SHIPPING",
1128
+ "USED_VERY_GOOD_SHIPPING",
1129
+ "USED_GOOD_SHIPPING",
1130
+ "USED_ACCEPTABLE_SHIPPING",
1131
+ "COLLECTIBLE_NEW_SHIPPING",
1132
+ "COLLECTIBLE_VERY_GOOD_SHIPPING",
1133
+ "COLLECTIBLE_GOOD_SHIPPING",
1134
+ "COLLECTIBLE_ACCEPTABLE_SHIPPING",
1135
+ "REFURBISHED_SHIPPING",
1136
+ "EBAY_NEW_SHIPPING",
1137
+ "EBAY_USED_SHIPPING",
1138
+ "TRADE_IN",
1139
+ "RENT",
1140
+ "BUY_BOX_USED_SHIPPING",
1141
+ "PRIME_EXCL",
1142
+ "COUNT_NEW_FBA",
1143
+ "COUNT_NEW_FBM"
1144
+ ];
1145
+ var ABOUT = {
1146
+ 0: "Amazon's own offer",
1147
+ 1: "lowest New price from any seller, Amazon too",
1148
+ 2: "lowest Used price",
1149
+ 3: "sales rank in the main category, lower is better",
1150
+ 4: "list price",
1151
+ 7: "lowest New price fulfilled by the seller, incl. shipping",
1152
+ 9: "Amazon Warehouse price",
1153
+ 10: "lowest New price fulfilled by Amazon, third-party sellers",
1154
+ 11: "number of New offers",
1155
+ 12: "number of Used offers",
1156
+ 16: "rating in stars",
1157
+ 17: "number of reviews",
1158
+ 18: "Buy Box price incl. shipping",
1159
+ 32: "Used Buy Box price incl. shipping",
1160
+ 33: "lowest Prime exclusive New price"
1161
+ };
1162
+ var TRIPLETS = /* @__PURE__ */ new Set([7, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 32]);
1163
+ var SHIPPING_CHANGE_SERIES = /* @__PURE__ */ new Set([1, 2, 5, 6]);
1164
+ var SHIPPING_CHANGE_DAY = Date.UTC(2026, 1, 23) / 864e5;
1165
+ function kindOf(index) {
1166
+ if (index === 3) return "rank";
1167
+ if (index === 16) return "rating";
1168
+ if ([11, 12, 13, 14, 15, 17, 34, 35].includes(index)) return "count";
1169
+ return "price";
1170
+ }
1171
+ var DAY_MS = 864e5;
1172
+ function keepaMs(keepaTime) {
1173
+ return (keepaTime + 21564e3) * 6e4;
1174
+ }
1175
+ function isoDay(ms) {
1176
+ return new Date(ms).toISOString().slice(0, 10);
1177
+ }
1178
+ function isoMinute(ms) {
1179
+ return `${new Date(ms).toISOString().slice(0, 16)}Z`;
1180
+ }
1181
+ function isNumber(value) {
1182
+ return typeof value === "number" && Number.isFinite(value);
1183
+ }
1184
+ function compact(value) {
1185
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null));
1186
+ }
1187
+ function show(value, kind, decimals) {
1188
+ if (!isNumber(value)) return null;
1189
+ if (value < 0) return kind === "price" ? "no offer" : kind === "rank" ? "no rank" : null;
1190
+ if (kind === "price") return decimals === 0 ? value : value / 100;
1191
+ if (kind === "rating") return value / 10;
1192
+ return value;
1193
+ }
1194
+ function money(value, decimals) {
1195
+ return decimals === 0 ? value : value / 100;
1196
+ }
1197
+ function extreme(point, kind, decimals) {
1198
+ if (!Array.isArray(point) || point.length < 2 || !isNumber(point[0])) return void 0;
1199
+ const value = show(point[1], kind, decimals);
1200
+ return value === null ? void 0 : { value, date: isoDay(keepaMs(point[0])) };
1201
+ }
1202
+ function points(csv, index) {
1203
+ const history = Array.isArray(csv) ? csv[index] : void 0;
1204
+ if (!Array.isArray(history)) return [];
1205
+ const out = [];
1206
+ if (TRIPLETS.has(index)) {
1207
+ for (let k = 0; k + 2 < history.length; k += 3) {
1208
+ const [t, price, shipping] = [history[k], history[k + 1], history[k + 2]];
1209
+ if (!isNumber(t) || !isNumber(price)) continue;
1210
+ out.push({ t: keepaMs(t), v: price < 0 ? -1 : price + Math.max(isNumber(shipping) ? shipping : 0, 0) });
1211
+ }
1212
+ } else {
1213
+ for (let k = 0; k + 1 < history.length; k += 2) {
1214
+ const [t, value] = [history[k], history[k + 1]];
1215
+ if (isNumber(t) && isNumber(value)) out.push({ t: keepaMs(t), v: value });
1216
+ }
1217
+ }
1218
+ return out;
1219
+ }
1220
+ function tokenInfo(data) {
1221
+ const left = isNumber(data?.["tokensLeft"]) ? data["tokensLeft"] : null;
1222
+ const rate = isNumber(data?.["refillRate"]) ? data["refillRate"] : 0;
1223
+ const refillIn = Math.ceil((isNumber(data?.["refillIn"]) ? data["refillIn"] : 0) / 1e3);
1224
+ const info = {
1225
+ used: isNumber(data?.["tokensConsumed"]) ? data["tokensConsumed"] : 0,
1226
+ left,
1227
+ refillRate: rate,
1228
+ refillInSeconds: refillIn
1229
+ };
1230
+ if (left !== null && left < 1 && rate > 0) {
1231
+ const wait = refillIn + (Math.ceil((1 - left) / rate) - 1) * 60;
1232
+ info.nextCallInSeconds = wait;
1233
+ if (isNumber(data["timestamp"])) info.nextCallAround = isoMinute(data["timestamp"] + wait * 1e3);
1234
+ info.note = `Out of tokens: the next call can run in about ${wait < 60 ? `${wait} s` : `${Math.ceil(wait / 60)} min`}${info.nextCallAround ? ` (around ${info.nextCallAround})` : ""}. Do not call again before then.`;
1235
+ } else if (left !== null && left < 1 && !data["error"]) {
1236
+ info.note = "No tokens and no refill rate: the key has no active Keepa API plan.";
1237
+ }
1238
+ if (isNumber(data?.["tokenFlowReduction"]) && data["tokenFlowReduction"] > 0) {
1239
+ info.tokenFlowReduction = data["tokenFlowReduction"];
1240
+ info.note = `${info.note ? `${info.note} ` : ""}Keepa tracking lowers the refill rate by ${data["tokenFlowReduction"]}.`;
1241
+ }
1242
+ return info;
1243
+ }
1244
+ function errorLine(error) {
1245
+ if (typeof error !== "object" || error === null) return void 0;
1246
+ const { type, message, details } = error;
1247
+ const parts = [typeof type === "string" ? type : "error", typeof message === "string" ? `: ${message}` : ""];
1248
+ if (details !== void 0 && details !== null) parts.push(` (${truncate(typeof details === "string" ? details : JSON.stringify(details), 300)})`);
1249
+ return truncate(parts.join(""), 600);
1250
+ }
1251
+ var SUMMARY_SERIES = [
1252
+ [0, "Amazon"],
1253
+ [18, "Buy Box incl. shipping"],
1254
+ [1, "New, lowest (any seller, Amazon too)"],
1255
+ [10, "New, lowest FBA"],
1256
+ [7, "New, lowest FBM incl. shipping"],
1257
+ [2, "Used, lowest"],
1258
+ [9, "Amazon Warehouse"],
1259
+ [4, "List price"],
1260
+ [3, "Sales rank (lower is better)"],
1261
+ [11, "New offers"],
1262
+ [16, "Rating (stars)"],
1263
+ [17, "Reviews"]
1264
+ ];
1265
+ function at(list, index) {
1266
+ return Array.isArray(list) ? list[index] : void 0;
1267
+ }
1268
+ function statRow(stats, index, label, decimals) {
1269
+ const kind = kindOf(index);
1270
+ const now = at(stats["current"], index);
1271
+ const avg30 = at(stats["avg30"], index);
1272
+ const avg90 = at(stats["avg90"], index);
1273
+ const low = at(stats["minInInterval"], index);
1274
+ const high = at(stats["maxInInterval"], index);
1275
+ const ever = at(stats["min"], index);
1276
+ const noValue = (value) => !isNumber(value) || value < 0;
1277
+ if (noValue(now) && noValue(avg30) && noValue(avg90) && low == null && high == null && ever == null) return void 0;
1278
+ return compact({
1279
+ series: SERIES_NAMES[index],
1280
+ label,
1281
+ now: show(now, kind, decimals),
1282
+ avg30: show(avg30, kind, decimals),
1283
+ avg90: show(avg90, kind, decimals),
1284
+ lowestInRange: extreme(low, kind, decimals),
1285
+ highestInRange: extreme(high, kind, decimals),
1286
+ lowestEver: extreme(ever, kind, decimals)
1287
+ });
1288
+ }
1289
+ function lastRow(product, index, label, decimals) {
1290
+ const list = points(product["csv"], index);
1291
+ const last = list[list.length - 1];
1292
+ if (!last) return void 0;
1293
+ return compact({ series: SERIES_NAMES[index], label, value: show(last.v, kindOf(index), decimals), since: isoMinute(last.t) });
1294
+ }
1295
+ var UNKNOWN_MARKET = { site: "unknown marketplace", id: 0, currency: "?", decimals: 2 };
1296
+ function productNote(product) {
1297
+ switch (product["productType"]) {
1298
+ case 1:
1299
+ case 2:
1300
+ return "Digital product: Keepa has no price, rating or offer data for it.";
1301
+ case 3:
1302
+ return "Keepa cannot read prices, ratings or offers for this product; its sales rank and offer counts update less often.";
1303
+ case 4:
1304
+ return "Keepa has no current data for this ASIN (invalid or retired; sometimes temporary).";
1305
+ case 5:
1306
+ return "This is a parent ASIN: prices belong to its variations (see variations).";
1307
+ default:
1308
+ return void 0;
1309
+ }
1310
+ }
1311
+ var CONDITIONS = [
1312
+ "unknown",
1313
+ "New",
1314
+ "Used - Like New",
1315
+ "Used - Very Good",
1316
+ "Used - Good",
1317
+ "Used - Acceptable",
1318
+ "Refurbished",
1319
+ "Collectible - Like New",
1320
+ "Collectible - Very Good",
1321
+ "Collectible - Good",
1322
+ "Collectible - Acceptable",
1323
+ "Rental"
1324
+ ];
1325
+ function isItem(value) {
1326
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1327
+ }
1328
+ function lastValue(list) {
1329
+ if (!Array.isArray(list) || list.length < 2) return void 0;
1330
+ const value = list[list.length - 1];
1331
+ return isNumber(value) ? value : void 0;
1332
+ }
1333
+ function offerRow(offer, decimals) {
1334
+ const csv = Array.isArray(offer["offerCSV"]) ? offer["offerCSV"] : [];
1335
+ const price = csv.length >= 3 ? csv[csv.length - 2] : void 0;
1336
+ const shipping = csv.length >= 3 ? csv[csv.length - 1] : void 0;
1337
+ const stock = lastValue(offer["stockCSV"]);
1338
+ const condition = offer["condition"];
1339
+ return compact({
1340
+ sellerId: typeof offer["sellerId"] === "string" ? truncate(offer["sellerId"], 40) : void 0,
1341
+ condition: isNumber(condition) ? CONDITIONS[condition] ?? `condition ${condition}` : void 0,
1342
+ price: isNumber(price) && price >= 0 ? money(price, decimals) : void 0,
1343
+ shipping: isNumber(shipping) && shipping >= 0 ? money(shipping, decimals) : void 0,
1344
+ isAmazon: offer["isAmazon"] === true || void 0,
1345
+ isFBA: offer["isFBA"] === true || void 0,
1346
+ isPrime: offer["isPrime"] === true || void 0,
1347
+ isWarehouseDeal: offer["isWarehouseDeal"] === true || void 0,
1348
+ isPreorder: offer["isPreorder"] === true || void 0,
1349
+ isMAP: offer["isMAP"] === true || void 0,
1350
+ notShippable: offer["isShippable"] === false || void 0,
1351
+ stock: isNumber(stock) && stock >= 0 ? stock : void 0
1352
+ });
1353
+ }
1354
+ function liveOffers(product, decimals, max) {
1355
+ const offers = product["offers"];
1356
+ if (!Array.isArray(offers) || max <= 0) return void 0;
1357
+ const order = Array.isArray(product["liveOffersOrder"]) ? product["liveOffersOrder"].filter(isNumber) : [];
1358
+ const list = order.slice(0, max).map((index) => offers[index]).filter(isItem).map((offer) => offerRow(offer, decimals));
1359
+ return compact({
1360
+ count: order.length,
1361
+ list,
1362
+ note: product["offersSuccessful"] === false ? "Keepa could not load fresh offers this time (it charged 1 token), so the offer data is the last it had." : void 0
1363
+ });
1364
+ }
1365
+ function stockLevels(product) {
1366
+ const stats = isItem(product["stats"]) ? product["stats"] : {};
1367
+ const amazon = stats["stockAmazon"];
1368
+ const buyBox = stats["stockBuyBox"];
1369
+ const updated = product["lastStockUpdate"];
1370
+ const stock = compact({
1371
+ amazon: isNumber(amazon) && amazon >= 0 ? amazon : void 0,
1372
+ buyBox: isNumber(buyBox) && buyBox >= 0 ? buyBox : void 0,
1373
+ updated: isNumber(updated) && updated > 0 ? isoMinute(keepaMs(updated)) : void 0
1374
+ });
1375
+ return Object.keys(stock).length ? stock : void 0;
1376
+ }
1377
+ function historicalVariations(product, max) {
1378
+ const list = Array.isArray(product["historicalVariations"]) ? product["historicalVariations"].filter((asin) => typeof asin === "string") : [];
1379
+ return list.length ? { count: list.length, asins: list.slice(0, max) } : void 0;
1380
+ }
1381
+ function categoryPath(product) {
1382
+ const tree = Array.isArray(product["categoryTree"]) ? product["categoryTree"] : [];
1383
+ return tree.length ? tree.map((node) => typeof node?.["name"] === "string" ? node["name"] : "?").join(" > ") : void 0;
1384
+ }
1385
+ function salesRankIn(product) {
1386
+ const reference = product["salesRankReference"];
1387
+ if (!isNumber(reference) || reference <= 0) return void 0;
1388
+ const tree = Array.isArray(product["categoryTree"]) ? product["categoryTree"] : [];
1389
+ const node = tree.find((item) => item?.["catId"] === reference);
1390
+ return typeof node?.["name"] === "string" ? node["name"] : `category ${reference}`;
1391
+ }
1392
+ function summarizeProduct(product, nowMs, range, maxOffers = 20) {
1393
+ const market = marketById(product["domainId"]) ?? UNKNOWN_MARKET;
1394
+ const { decimals } = market;
1395
+ const stats = typeof product["stats"] === "object" && product["stats"] !== null ? product["stats"] : null;
1396
+ const variations = product["productType"] === 5 && Array.isArray(product["variations"]) ? product["variations"].map((item) => item?.["asin"]).filter((asin) => typeof asin === "string").slice(0, 20) : void 0;
1397
+ const summary = compact({
1398
+ asin: product["asin"],
1399
+ title: typeof product["title"] === "string" ? truncate(product["title"], 200) : void 0,
1400
+ marketplace: market.site,
1401
+ currency: market.currency,
1402
+ range: range === null ? { to: isoDay(nowMs) } : "days" in range ? { days: range.days, from: isoDay(nowMs - range.days * DAY_MS), to: isoDay(nowMs) } : { from: range.from, to: range.to },
1403
+ lastUpdate: isNumber(product["lastUpdate"]) && product["lastUpdate"] > 0 ? isoMinute(keepaMs(product["lastUpdate"])) : void 0,
1404
+ note: productNote(product),
1405
+ variations: variations?.length ? variations : void 0,
1406
+ brand: typeof product["brand"] === "string" && product["brand"] ? truncate(product["brand"], 120) : void 0,
1407
+ category: categoryPath(product),
1408
+ salesRankIn: salesRankIn(product),
1409
+ boughtPastMonth: isNumber(product["monthlySold"]) && product["monthlySold"] > 0 ? `${product["monthlySold"]}+` : void 0,
1410
+ trackingSince: isNumber(product["trackingSince"]) && product["trackingSince"] > 0 ? isoDay(keepaMs(product["trackingSince"])) : void 0
1411
+ });
1412
+ if (stats) {
1413
+ summary["stats"] = SUMMARY_SERIES.map(([index, label]) => statRow(stats, index, label, decimals)).filter(Boolean);
1414
+ const drops30 = stats["salesRankDrops30"];
1415
+ if (isNumber(drops30) && drops30 >= 0) {
1416
+ summary["salesRankDrops"] = compact({ days30: drops30, days90: isNumber(stats["salesRankDrops90"]) && stats["salesRankDrops90"] >= 0 ? stats["salesRankDrops90"] : void 0 });
1417
+ }
1418
+ const outOfStock = at(stats["outOfStockPercentage90"], 0);
1419
+ if (isNumber(outOfStock) && outOfStock >= 0) summary["amazonOutOfStockPercent90"] = outOfStock;
1420
+ if (isNumber(stats["totalOfferCount"]) && stats["totalOfferCount"] >= 0) summary["offersNow"] = stats["totalOfferCount"];
1421
+ if (isNumber(stats["buyBoxPrice"]) && stats["buyBoxPrice"] >= 0) {
1422
+ summary["buyBox"] = compact({
1423
+ price: money(stats["buyBoxPrice"], decimals),
1424
+ shipping: money(Math.max(isNumber(stats["buyBoxShipping"]) ? stats["buyBoxShipping"] : 0, 0), decimals),
1425
+ sellerId: typeof stats["buyBoxSellerId"] === "string" ? stats["buyBoxSellerId"] : void 0,
1426
+ isAmazon: stats["buyBoxIsAmazon"] === true ? true : void 0,
1427
+ isFBA: stats["buyBoxIsFBA"] === true ? true : void 0
1428
+ });
1429
+ }
1430
+ } else {
1431
+ const last = SUMMARY_SERIES.map(([index, label]) => lastRow(product, index, label, decimals)).filter(Boolean);
1432
+ summary["note"] = [summary["note"], last.length ? "No stats in this reply: these are the last known values; ask with stats for averages, lows and highs." : "No price or rank history in this reply."].filter(Boolean).join(" ");
1433
+ if (last.length) summary["lastKnown"] = last;
1434
+ }
1435
+ return { ...summary, ...paidExtras(product, decimals, maxOffers, 20) };
1436
+ }
1437
+ function paidExtras(product, decimals, maxOffers, maxVariations) {
1438
+ return compact({
1439
+ stock: stockLevels(product),
1440
+ historicalVariations: historicalVariations(product, maxVariations),
1441
+ liveOffers: liveOffers(product, decimals, maxOffers)
1442
+ });
1443
+ }
1444
+ function nowValue(product, index) {
1445
+ const current = product["stats"]?.["current"];
1446
+ if (Array.isArray(current)) return current[index];
1447
+ const history = at(product["csv"], index);
1448
+ return Array.isArray(history) && history.length >= 2 ? history[history.length - 1] : void 0;
1449
+ }
1450
+ var BRIEF_OFFERS = 5;
1451
+ var BRIEF_VARIATIONS = 10;
1452
+ function briefProduct(product) {
1453
+ const { decimals } = marketById(product["domainId"]) ?? UNKNOWN_MARKET;
1454
+ return compact({
1455
+ asin: product["asin"],
1456
+ title: typeof product["title"] === "string" ? truncate(product["title"], 120) : void 0,
1457
+ brand: typeof product["brand"] === "string" && product["brand"] ? truncate(product["brand"], 80) : void 0,
1458
+ newNow: show(nowValue(product, 1), "price", decimals),
1459
+ amazonNow: show(nowValue(product, 0), "price", decimals),
1460
+ salesRank: show(nowValue(product, 3), "rank", decimals),
1461
+ boughtPastMonth: isNumber(product["monthlySold"]) && product["monthlySold"] > 0 ? `${product["monthlySold"]}+` : void 0,
1462
+ note: product["productType"] === 5 ? "parent ASIN: prices belong to its variations" : product["productType"] === 4 ? "Keepa has no current data for it" : void 0,
1463
+ ...paidExtras(product, decimals, BRIEF_OFFERS, BRIEF_VARIATIONS)
1464
+ });
1465
+ }
1466
+ function missingHint(index) {
1467
+ if (index === 18) return " BUY_BOX_SHIPPING needs buybox (or offers).";
1468
+ if (index === 16 || index === 17) return " RATING and COUNT_REVIEWS need rating (or offers).";
1469
+ if ([7, 9, 10, 32, 33, 34, 35].includes(index)) return " The FBA, FBM, Warehouse and offer-count series need offers.";
1470
+ return "";
1471
+ }
1472
+ function historyTable(product, index, days, step, nowMs) {
1473
+ const market = marketById(product["domainId"]) ?? UNKNOWN_MARKET;
1474
+ const { decimals } = market;
1475
+ const kind = kindOf(index);
1476
+ const name2 = SERIES_NAMES[index] ?? `csv ${index}`;
1477
+ const head = compact({
1478
+ series: name2,
1479
+ about: ABOUT[index],
1480
+ currency: kind === "price" ? market.currency : void 0
1481
+ });
1482
+ const raw = at(product["csv"], index);
1483
+ if (!Array.isArray(raw) || raw.length < 2) {
1484
+ return { ...head, note: `Keepa has no ${name2} history for this product in this reply.${missingHint(index)}` };
1485
+ }
1486
+ const all = points(product["csv"], index).filter((point) => point.t <= nowMs);
1487
+ const today = Math.floor(nowMs / DAY_MS);
1488
+ const first = all.length ? Math.floor(all[0].t / DAY_MS) : today;
1489
+ const start = Math.max(today - days + 1, first);
1490
+ let carry = null;
1491
+ for (const point of all) if (point.t < start * DAY_MS) carry = point.v;
1492
+ const changes = /* @__PURE__ */ new Map();
1493
+ for (const point of all) {
1494
+ if (point.t < start * DAY_MS) continue;
1495
+ const day = Math.floor(point.t / DAY_MS);
1496
+ changes.set(day, [...changes.get(day) ?? [], point.v]);
1497
+ }
1498
+ const daily = [];
1499
+ for (let d = start; d <= today; d++) {
1500
+ const inDay = changes.get(d) ?? [];
1501
+ const values = [...carry === null ? [] : [carry], ...inDay];
1502
+ if (values.length) daily.push({ d, values, close: values[values.length - 1] });
1503
+ if (inDay.length) carry = inDay[inDay.length - 1];
1504
+ }
1505
+ const blocks = [];
1506
+ for (const entry of daily) {
1507
+ const block = Math.floor((entry.d - start) / step);
1508
+ const last = blocks[blocks.length - 1];
1509
+ if (last && Math.floor((last.d0 - start) / step) === block) {
1510
+ last.d1 = entry.d;
1511
+ last.values.push(...entry.values);
1512
+ last.close = entry.close;
1513
+ } else {
1514
+ blocks.push({ d0: entry.d, d1: entry.d, values: [...entry.values], close: entry.close });
1515
+ }
1516
+ }
1517
+ const [lowKey, highKey] = kind === "price" ? ["low", "high"] : kind === "rank" ? ["best", "worst"] : ["min", "max"];
1518
+ const gapKey = kind === "price" ? "noOffer" : kind === "rank" ? "noRank" : "noData";
1519
+ const dayText = (day) => isoDay(day * DAY_MS);
1520
+ const rows = blocks.map((block) => {
1521
+ const ok = block.values.filter((value) => value >= 0);
1522
+ return compact({
1523
+ date: block.d0 === block.d1 ? dayText(block.d0) : `${dayText(block.d0)}/${dayText(block.d1)}`,
1524
+ [lowKey]: show(ok.length ? Math.min(...ok) : -1, kind, decimals),
1525
+ [highKey]: show(ok.length ? Math.max(...ok) : -1, kind, decimals),
1526
+ last: show(block.close, kind, decimals),
1527
+ [gapKey]: block.values.some((value) => value < 0) ? true : void 0
1528
+ });
1529
+ });
1530
+ const inRange = all.filter((point) => point.t >= start * DAY_MS && point.v >= 0);
1531
+ let summary;
1532
+ if (inRange.length) {
1533
+ let low = inRange[0];
1534
+ let high = low;
1535
+ for (const point of inRange) {
1536
+ if (point.v < low.v) low = point;
1537
+ if (point.v >= high.v) high = point;
1538
+ }
1539
+ const [lowName, highName] = kind === "rank" ? ["best", "worst"] : kind === "price" ? ["lowest", "highest"] : ["min", "max"];
1540
+ summary = {
1541
+ count: inRange.length,
1542
+ [lowName]: { value: show(low.v, kind, decimals), at: isoMinute(low.t) },
1543
+ [highName]: { value: show(high.v, kind, decimals), at: isoMinute(high.t) }
1544
+ };
1545
+ }
1546
+ return compact({
1547
+ ...head,
1548
+ step: step === 1 ? "day" : `${step} days`,
1549
+ from: dayText(start),
1550
+ to: dayText(today),
1551
+ note: SHIPPING_CHANGE_SERIES.has(index) && start < SHIPPING_CHANGE_DAY ? "Until 2026-02-22 this series is the lowest listing price; from 2026-02-23 Keepa records the lowest price with shipping." : void 0,
1552
+ rows: rows.length ? rows : void 0,
1553
+ changesInRange: summary,
1554
+ empty: rows.length ? void 0 : `Keepa has no ${name2} data in this range.`
1555
+ });
1556
+ }
1557
+ function categoryList(data) {
1558
+ const categories = typeof data?.["categories"] === "object" && data["categories"] !== null ? data["categories"] : {};
1559
+ const parents = typeof data?.["categoryParents"] === "object" && data["categoryParents"] !== null ? data["categoryParents"] : {};
1560
+ const known = { ...parents, ...categories };
1561
+ const chain = (id) => {
1562
+ const names = [];
1563
+ let current = known[String(id)];
1564
+ for (let depth = 0; current && depth <= 12; depth++) {
1565
+ names.unshift(typeof current["name"] === "string" ? current["name"] : "?");
1566
+ current = current["parent"] ? known[String(current["parent"])] : void 0;
1567
+ }
1568
+ return names;
1569
+ };
1570
+ const list = Object.values(categories).filter((item) => typeof item === "object" && item !== null).sort((a, b) => (isNumber(b["productCount"]) ? b["productCount"] : 0) - (isNumber(a["productCount"]) ? a["productCount"] : 0));
1571
+ return list.map((category) => {
1572
+ const { decimals } = marketById(category["domainId"]) ?? UNKNOWN_MARKET;
1573
+ return compact({
1574
+ id: category["catId"],
1575
+ name: typeof category["name"] === "string" ? truncate(category["name"], 200) : void 0,
1576
+ path: truncate(chain(category["catId"]).join(" > "), 600) || void 0,
1577
+ parent: isNumber(category["parent"]) ? category["parent"] : void 0,
1578
+ productCount: isNumber(category["productCount"]) ? category["productCount"] : void 0,
1579
+ subcategories: Array.isArray(category["children"]) ? category["children"].length : 0,
1580
+ avgBuyBox: isNumber(category["avgBuyBox"]) && category["avgBuyBox"] >= 0 ? money(category["avgBuyBox"], decimals) : void 0
1581
+ });
1582
+ });
1583
+ }
1584
+
1585
+ // src/vendors/keepa/index.ts
1586
+ var ORIGIN = "https://api.keepa.com";
1587
+ var KEY_PATTERN = /^[A-Za-z0-9]{64}$/;
1588
+ var MAX_HISTORY_ROWS = 250;
1589
+ var MAX_PRODUCTS_PER_REQUEST = 100;
1590
+ var HISTORY_OFFERS = 10;
1591
+ var BESTSELLERS_MAX_BYTES = 8 * 1024 * 1024;
1592
+ var FINDER_DEFAULT_PER_PAGE = 50;
1593
+ var FINDER_MAX_PER_PAGE = 2e3;
1594
+ var FINDER_MAX_RESULTS = 1e4;
1595
+ var ERRORS = {
1596
+ 400: "Keepa refused a parameter of this call",
1597
+ 402: "Keepa does not accept this API key: it is unknown or has no active API plan. Check the key and the plan on keepa.com/api",
1598
+ 404: "Keepa has no such API path",
1599
+ 405: "Keepa refused a parameter value outside its allowed range"
1600
+ };
1601
+ var SITES = Object.keys(MARKETPLACES);
1602
+ var MARKETPLACE = {
1603
+ type: "string",
1604
+ enum: SITES,
1605
+ description: `The Amazon marketplace: ${SITES.join(", ")}. Keepa covers no other (not amazon.com.tr, amazon.com.au, amazon.nl, amazon.se, amazon.pl, amazon.com.be, amazon.ae, amazon.sa, amazon.sg or amazon.eg).`
1606
+ };
1607
+ var ASIN = { type: "string", pattern: "^[A-Za-z0-9]{10}$", description: 'An ASIN, 10 letters and digits, e.g. "B0F3GWXLTS".' };
1608
+ var UPDATE = {
1609
+ type: "integer",
1610
+ minimum: 0,
1611
+ maximum: 1e6,
1612
+ description: "Refresh a product whose Keepa data is older than this many hours (Keepa's default 1). 0 forces a refresh and costs 1 more token per product."
1613
+ };
1614
+ function offersOption(listed) {
1615
+ return {
1616
+ type: "integer",
1617
+ minimum: 20,
1618
+ maximum: 100,
1619
+ description: `Paid: also load up to this many live offers (20 to 100), with the Buy Box history and the FBA, FBM, Warehouse, rating and review series. ${listed} Costs 6 tokens per 10 offers found instead of 1, and takes 2 to 20 seconds. Only when asked for.`
1620
+ };
1621
+ }
1622
+ var BUYBOX = { type: "boolean", description: "Paid: also load the Buy Box price history and statistics (2 more tokens per product). Only when asked for." };
1623
+ var RATING = { type: "boolean", description: "Paid: also load the rating and review count history (up to 1 more token per product). Only when asked for." };
1624
+ var CURSOR = { type: "string", description: "nextCursor from the previous result." };
1625
+ function marketOf(site) {
1626
+ return MARKETPLACES[site];
1627
+ }
1628
+ function flag(value) {
1629
+ return value ? 1 : void 0;
1630
+ }
1631
+ function linkTemplate(market) {
1632
+ return `https://www.${market.site}/dp/{asin}`;
1633
+ }
1634
+ function apiKey(h) {
1635
+ const key = h.credentials["apikey"] ?? "";
1636
+ if (!KEY_PATTERN.test(key)) {
1637
+ throw new ToolFailure("The Keepa API key must be the 64 letters and digits shown on the Keepa API page, and the one given is not. Copy it again from keepa.com/api. Nothing was sent to Keepa.");
1638
+ }
1639
+ return key;
1640
+ }
1641
+ async function outOfTokens(h, key) {
1642
+ try {
1643
+ const { data } = await h.api({ origin: ORIGIN, path: "/token", query: { key } });
1644
+ const tokens = tokenInfo(data);
1645
+ if (tokens.nextCallInSeconds !== void 0) {
1646
+ const wait = tokens.nextCallInSeconds;
1647
+ return new ToolFailure(
1648
+ `Keepa tokens are used up (HTTP 429): the next call can run in about ${wait < 60 ? `${wait} seconds` : `${Math.ceil(wait / 60)} minutes`}${tokens.nextCallAround ? ` (around ${tokens.nextCallAround})` : ""}. Do not call Keepa again before then.`,
1649
+ { status: 429, retryAfter: wait }
1650
+ );
1651
+ }
1652
+ if (tokens.left !== null && tokens.left >= 1) {
1653
+ return new ToolFailure(`Keepa tokens were used up for this call (HTTP 429); ${tokens.left} tokens are available again now.`, { status: 429 });
1654
+ }
1655
+ } catch {
1656
+ }
1657
+ return new ToolFailure("Keepa tokens are used up (HTTP 429). Wait for the plan's tokens to refill before calling again; get_token_status says when.", { status: 429 });
1658
+ }
1659
+ async function keepaRequest(h, request) {
1660
+ const key = apiKey(h);
1661
+ try {
1662
+ return await h.api({ ...request, query: { ...request.query, key }, errors: ERRORS });
1663
+ } catch (error) {
1664
+ if (error instanceof ToolFailure && error.details.status === 429) throw await outOfTokens(h, key);
1665
+ throw error;
1666
+ }
1667
+ }
1668
+ async function keepaGet(h, path, query, maxBytes) {
1669
+ const { data } = await keepaRequest(h, { origin: ORIGIN, path, query, ...maxBytes !== void 0 ? { maxBytes } : {} });
1670
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
1671
+ throw new ToolFailure("Keepa sent a reply that is not JSON (a compressed reply the host did not unpack, or an error page). Try again later.");
1672
+ }
1673
+ return data;
1674
+ }
1675
+ function common(data) {
1676
+ const warning = errorLine(data["error"]);
1677
+ return { tokens: tokenInfo(data), ...warning ? { warning: `Keepa: ${warning}` } : {} };
1678
+ }
1679
+ var getTokenStatus = {
1680
+ name: "get_token_status",
1681
+ kind: "read",
1682
+ title: "Get the Keepa token balance",
1683
+ description: "The Keepa token balance of the connected key: tokens left (it can be negative after a large call), tokens added per minute, seconds to the next refill and, when the balance is below 1, when the next call can run. Free: it costs no tokens. Check it before an expensive call (a search costs 10 tokens, a best sellers list 50).",
1684
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1685
+ async run(_args, h) {
1686
+ return { tokens: tokenInfo(await keepaGet(h, "/token", {})) };
1687
+ }
1688
+ };
1689
+ var DATE = { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$" };
1690
+ var getProducts = {
1691
+ name: "get_products",
1692
+ kind: "read",
1693
+ title: "Get Amazon products from Keepa",
1694
+ description: "Up to 100 products by ASIN, or by UPC, EAN or ISBN-13 code: what each is (title, brand, category, Amazon's bought-in-past-month bracket), then per series (Amazon, Buy Box, lowest New, FBA, FBM, Used, Warehouse, list price, sales rank, offer count, rating, reviews) the value now, the 30 and 90 day averages, the lowest and highest in the range and the lowest ever, with sales rank drops and the Buy Box now; plus what a paid option adds: the live offers, stock levels, the variations no longer listed. Prices in the marketplace currency. 1 token per product, plus the paid options. With brief, one short row per product. A result over 32 KB is cut, and nextCursor loads the products left out, as many per call as fit (charged again): ask for about 15 products per call with full summaries, a few with offers.",
1695
+ inputSchema: {
1696
+ type: "object",
1697
+ properties: {
1698
+ marketplace: MARKETPLACE,
1699
+ asins: { type: "array", items: ASIN, minItems: 1, maxItems: 100, uniqueItems: true, description: "Up to 100 ASINs." },
1700
+ codes: {
1701
+ type: "array",
1702
+ items: { type: "string", pattern: "^[0-9]{8,14}$", description: "A UPC, EAN, GTIN or ISBN-13, digits only." },
1703
+ minItems: 1,
1704
+ maxItems: 100,
1705
+ uniqueItems: true,
1706
+ description: "Instead of asins: up to 100 UPC, EAN, GTIN or ISBN-13 codes. One code can match several products."
1707
+ },
1708
+ code_limit: { type: "integer", minimum: 1, maximum: 100, description: "With codes: the most products one code may return." },
1709
+ stats_days: { type: "integer", minimum: 1, maximum: 3650, default: 90, description: "The range of the statistics, in days up to now (default 90). Free." },
1710
+ stats_from: { ...DATE, description: "Instead of stats_days: the first day of the range, YYYY-MM-DD (with stats_to)." },
1711
+ stats_to: { ...DATE, description: "The last day of the range, YYYY-MM-DD (with stats_from)." },
1712
+ update_hours: UPDATE,
1713
+ offers: offersOption("Each product lists its live offers in Amazon's order: seller, condition, price, shipping, FBA and Prime, and each offer's stock with stock."),
1714
+ buybox: BUYBOX,
1715
+ stock: {
1716
+ type: "boolean",
1717
+ description: "Paid: also load stock levels: the stock of Amazon's offer and of the Buy Box offer, and with offers each live offer's (usually the first 10). 2 more tokens per product when Keepa has stock data from the last 7 days. Only when asked for."
1718
+ },
1719
+ rating: RATING,
1720
+ historical_variations: {
1721
+ type: "boolean",
1722
+ description: "Paid: also list the variation ASINs that are no longer listed or out of stock (1 more token per product with a parent). Only when asked for."
1723
+ },
1724
+ brief: {
1725
+ type: "boolean",
1726
+ description: "One short row per product (title, brand, New and Amazon price now, sales rank; with the paid options, their stock levels, the first 10 variations no longer listed and the first 5 live offers) instead of the full summary."
1727
+ },
1728
+ cursor: CURSOR
1729
+ },
1730
+ required: ["marketplace"],
1731
+ additionalProperties: false
1732
+ },
1733
+ async run(args, h) {
1734
+ const market = marketOf(args.marketplace);
1735
+ const state = h.cursor(args.cursor);
1736
+ let field;
1737
+ let ids;
1738
+ let pending = [];
1739
+ if (typeof state?.["a"] === "string") {
1740
+ const left = state["a"].split(",").filter(Boolean);
1741
+ const fit = typeof state["n"] === "number" && Number.isInteger(state["n"]) && state["n"] >= 1 ? state["n"] : MAX_PRODUCTS_PER_REQUEST;
1742
+ const batch = Math.min(fit, MAX_PRODUCTS_PER_REQUEST);
1743
+ [field, ids] = ["asin", left.slice(0, batch)];
1744
+ pending = left.slice(batch);
1745
+ } else if (args.asins && args.codes) {
1746
+ throw new ToolFailure("Give asins or codes, not both. Nothing was sent to Keepa.");
1747
+ } else if (args.asins) {
1748
+ [field, ids] = ["asin", args.asins.map((asin) => asin.toUpperCase())];
1749
+ } else if (args.codes) {
1750
+ [field, ids] = ["code", args.codes];
1751
+ } else {
1752
+ throw new ToolFailure("Give asins (up to 100) or codes (UPC, EAN or ISBN-13, up to 100). Nothing was sent to Keepa.");
1753
+ }
1754
+ if (args.code_limit !== void 0 && !args.codes) throw new ToolFailure("code_limit only goes with codes. Nothing was sent to Keepa.");
1755
+ if (args.stats_from === void 0 !== (args.stats_to === void 0)) {
1756
+ throw new ToolFailure("Give stats_from and stats_to together, or neither. Nothing was sent to Keepa.");
1757
+ }
1758
+ const range = args.stats_from && args.stats_to ? { from: args.stats_from, to: args.stats_to } : { days: args.stats_days };
1759
+ const data = await keepaGet(h, "/product", {
1760
+ domain: market.id,
1761
+ [field]: ids.join(","),
1762
+ stats: "days" in range ? range.days : `${range.from},${range.to}`,
1763
+ // The summaries come from the stats: the history arrays would only make the reply larger.
1764
+ history: 0,
1765
+ update: args.update_hours,
1766
+ offers: args.offers,
1767
+ buybox: flag(args.buybox),
1768
+ stock: flag(args.stock),
1769
+ rating: flag(args.rating),
1770
+ "historical-variations": flag(args.historical_variations),
1771
+ "code-limit": field === "code" ? args.code_limit : void 0
1772
+ });
1773
+ const products = Array.isArray(data["products"]) ? data["products"] : [];
1774
+ const nowMs = typeof data["timestamp"] === "number" ? data["timestamp"] : Date.now();
1775
+ const asinsFrom = (index) => products.slice(index).map((product) => product["asin"]).filter((asin) => typeof asin === "string");
1776
+ return h.page({
1777
+ key: "products",
1778
+ // A full summary lists every live offer the call loaded: Keepa loads at most 100, which fit one result.
1779
+ items: products.map((product) => args.brief ? briefProduct(product) : summarizeProduct(product, nowMs, range, args.offers ?? 0)),
1780
+ extra: { marketplace: market.site, currency: market.currency, ...common(data) },
1781
+ // `n`, the size of the next request: how many products fit this result, or all it asked for.
1782
+ resumeAt: (index) => h.makeCursor({ a: [...asinsFrom(index), ...pending].join(","), n: index }),
1783
+ ...pending.length ? { nextPage: h.makeCursor({ a: pending.join(","), n: ids.length }) } : {}
1784
+ });
1785
+ }
1786
+ };
1787
+ var getPriceHistory = {
1788
+ name: "get_price_history",
1789
+ kind: "read",
1790
+ title: "Get the price and sales rank history of an Amazon product from Keepa",
1791
+ description: "Dated tables of one product's price, sales rank, offer count or rating over the last days: one row per UTC day, or per block of days (step 7 for weeks, 30 for months), with the lowest, highest and last value, the value in effect carried over days without a change, and the lowest and highest point in the range; plus the product summary (now, averages, lows, highs). By default daily up to a month, weekly up to half a year, monthly beyond. 1 token, plus the paid options a series needs (BUY_BOX_SHIPPING: buybox; RATING and COUNT_REVIEWS: rating; FBA, FBM and Warehouse: offers).",
1792
+ inputSchema: {
1793
+ type: "object",
1794
+ properties: {
1795
+ marketplace: MARKETPLACE,
1796
+ asin: ASIN,
1797
+ series: {
1798
+ type: "array",
1799
+ items: { type: "string", enum: [...SERIES_NAMES] },
1800
+ minItems: 1,
1801
+ maxItems: 4,
1802
+ uniqueItems: true,
1803
+ default: ["NEW", "SALES"],
1804
+ description: "The series, up to 4 (default NEW and SALES): AMAZON (Amazon's offer), NEW (lowest New), USED, SALES (sales rank), LISTPRICE, BUY_BOX_SHIPPING, NEW_FBA, NEW_FBM_SHIPPING, WAREHOUSE, COUNT_NEW, COUNT_USED, RATING, COUNT_REVIEWS and the rest of Keepa's series."
1805
+ },
1806
+ days: { type: "integer", minimum: 1, maximum: 3650, default: 90, description: "The last this many days, up to now (default 90)." },
1807
+ step: { type: "integer", minimum: 1, maximum: 365, description: "Days per row: 1 for days, 7 for weeks, 30 for months. Default: 1 up to 31 days, 7 up to 186, else 30." },
1808
+ buybox: BUYBOX,
1809
+ rating: RATING,
1810
+ offers: offersOption(`The product summary lists the first ${HISTORY_OFFERS} live offers in Amazon's order.`),
1811
+ update_hours: UPDATE
1812
+ },
1813
+ required: ["marketplace", "asin"],
1814
+ additionalProperties: false
1815
+ },
1816
+ async run(args, h) {
1817
+ const market = marketOf(args.marketplace);
1818
+ const step = args.step ?? (args.days <= 31 ? 1 : args.days <= 186 ? 7 : 30);
1819
+ const rows = Math.ceil(args.days / step) * args.series.length;
1820
+ if (rows > MAX_HISTORY_ROWS) {
1821
+ throw new ToolFailure(
1822
+ `That makes up to ${rows} rows (${Math.ceil(args.days / step)} per series), and the most is ${MAX_HISTORY_ROWS}. Use a larger step (7 for weeks, 30 for months), fewer days or fewer series. Nothing was sent to Keepa.`
1823
+ );
1824
+ }
1825
+ const asin = args.asin.toUpperCase();
1826
+ const data = await keepaGet(h, "/product", {
1827
+ domain: market.id,
1828
+ asin,
1829
+ days: args.days,
1830
+ stats: args.days,
1831
+ update: args.update_hours,
1832
+ offers: args.offers,
1833
+ buybox: flag(args.buybox),
1834
+ rating: flag(args.rating)
1835
+ });
1836
+ const product = Array.isArray(data["products"]) ? data["products"][0] : void 0;
1837
+ if (typeof product !== "object" || product === null) {
1838
+ return { asin, marketplace: market.site, ...common(data), note: "Keepa returned no product for this ASIN on this marketplace." };
1839
+ }
1840
+ const nowMs = typeof data["timestamp"] === "number" ? data["timestamp"] : Date.now();
1841
+ return {
1842
+ ...common(data),
1843
+ product: summarizeProduct(product, nowMs, { days: args.days }, HISTORY_OFFERS),
1844
+ history: args.series.map((name2) => historyTable(product, SERIES_NAMES.indexOf(name2), args.days, step, nowMs))
1845
+ };
1846
+ }
1847
+ };
1848
+ var searchProducts = {
1849
+ name: "search_products",
1850
+ kind: "read",
1851
+ title: "Search Amazon products with Keepa",
1852
+ description: "Searches a marketplace as Amazon's search does and returns up to 20 products in Amazon's order, sponsored results left out, each with ASIN, title, brand, the lowest New and Amazon price now, sales rank and bought-in-past-month bracket. 10 tokens per search. For a product's history, pass its ASIN to get_products or get_price_history.",
1853
+ inputSchema: {
1854
+ type: "object",
1855
+ properties: {
1856
+ marketplace: MARKETPLACE,
1857
+ term: { type: "string", minLength: 1, maxLength: 200, description: 'The search words, e.g. "bluetooth speaker".' },
1858
+ asins_only: { type: "boolean", description: "Return only the ASINs, without product details (same cost)." }
1859
+ },
1860
+ required: ["marketplace", "term"],
1861
+ additionalProperties: false
1862
+ },
1863
+ async run(args, h) {
1864
+ const market = marketOf(args.marketplace);
1865
+ const data = await keepaGet(h, "/search", {
1866
+ domain: market.id,
1867
+ type: "product",
1868
+ term: args.term,
1869
+ ...args.asins_only ? { "asins-only": 1 } : { stats: 30, history: 0 }
1870
+ });
1871
+ const products = Array.isArray(data["products"]) ? data["products"] : [];
1872
+ const asins = Array.isArray(data["asinList"]) ? data["asinList"] : [];
1873
+ return {
1874
+ marketplace: market.site,
1875
+ currency: market.currency,
1876
+ term: args.term,
1877
+ ...common(data),
1878
+ ...args.asins_only || !products.length && asins.length ? { asins: asins.filter((asin) => typeof asin === "string"), linkTemplate: linkTemplate(market) } : { products: products.map(briefProduct) }
1879
+ };
1880
+ }
1881
+ };
1882
+ var getBestSellers = {
1883
+ name: "get_best_sellers",
1884
+ kind: "read",
1885
+ title: "Get an Amazon best sellers list from Keepa",
1886
+ description: "The ranked ASINs of a category's best sellers list, best seller first: by the current sales rank, the average of the last 30, 90 or 180 days (range), or a past month (month and year, within the last 36 months, never the current one). Returns top ASINs from offset with the list's size and when Keepa updated it. A root category or product group list holds up to 500,000 ASINs, a subcategory list up to 10,000. 50 tokens per list, an empty one too; nothing when Keepa has no list. For titles and prices, pass the ASINs to get_products with brief (1 token each).",
1887
+ inputSchema: {
1888
+ type: "object",
1889
+ properties: {
1890
+ marketplace: MARKETPLACE,
1891
+ category: {
1892
+ type: "string",
1893
+ minLength: 1,
1894
+ maxLength: 100,
1895
+ description: 'A category id from search_categories (e.g. "172282"), or a product group name such as "Beauty".'
1896
+ },
1897
+ range: { type: "integer", enum: [30, 90, 180], description: "Rank by the average sales rank of the last 30, 90 or 180 days instead of the current one." },
1898
+ month: { type: "integer", minimum: 1, maximum: 12, description: "The list of a past month (with year)." },
1899
+ year: { type: "integer", minimum: 2e3, maximum: 2100, description: "The year of month." },
1900
+ variations: { type: "boolean", description: "List every variation instead of one per parent." },
1901
+ sublist: { type: "boolean", description: "Rank by the subcategory sales rank instead of the main category's. Not with range, month or year." },
1902
+ offset: { type: "integer", minimum: 0, default: 0, description: "Skip this many entries (default 0): the next part of a long list. Each call loads the list again (50 tokens)." },
1903
+ top: { type: "integer", minimum: 1, maximum: 2e3, default: 20, description: "How many ASINs to return, 1 to 2,000 (default 20)." }
1904
+ },
1905
+ required: ["marketplace", "category"],
1906
+ additionalProperties: false
1907
+ },
1908
+ async run(args, h) {
1909
+ if (args.month === void 0 !== (args.year === void 0)) throw new ToolFailure("Give month and year together. Nothing was sent to Keepa.");
1910
+ if (args.month !== void 0 && args.range !== void 0) throw new ToolFailure("Give range or a month, not both. Nothing was sent to Keepa.");
1911
+ if (args.sublist && (args.range !== void 0 || args.month !== void 0)) {
1912
+ throw new ToolFailure("Keepa takes sublist without range, month and year: ask for the subcategory ranking on its own. Nothing was sent to Keepa.");
1913
+ }
1914
+ const market = marketOf(args.marketplace);
1915
+ const data = await keepaGet(h, "/bestsellers", {
1916
+ domain: market.id,
1917
+ category: args.category,
1918
+ range: args.range,
1919
+ month: args.month,
1920
+ year: args.year,
1921
+ variations: flag(args.variations),
1922
+ sublist: flag(args.sublist)
1923
+ }, BESTSELLERS_MAX_BYTES);
1924
+ const list = typeof data["bestSellersList"] === "object" && data["bestSellersList"] !== null ? data["bestSellersList"] : null;
1925
+ const asins = Array.isArray(list?.asinList) ? list.asinList.filter((asin) => typeof asin === "string") : [];
1926
+ if (!asins.length) {
1927
+ return {
1928
+ marketplace: market.site,
1929
+ category: list?.categoryId ?? args.category,
1930
+ ...common(data),
1931
+ asins: [],
1932
+ // Keepa charges for a list that exists but is empty, and nothing when there is no list.
1933
+ note: list ? "Keepa's best sellers list for that category on this marketplace is empty; the call still used its 50 tokens." : "Keepa has no best sellers list for that category on this marketplace (no tokens were used for it)."
1934
+ };
1935
+ }
1936
+ const end = Math.min(args.offset + args.top, asins.length);
1937
+ return {
1938
+ marketplace: market.site,
1939
+ category: list.categoryId ?? args.category,
1940
+ listUpdated: typeof list.lastUpdate === "number" && list.lastUpdate > 0 ? isoMinute(keepaMs(list.lastUpdate)) : void 0,
1941
+ total: asins.length,
1942
+ offset: args.offset,
1943
+ ...common(data),
1944
+ asins: asins.slice(args.offset, end),
1945
+ linkTemplate: linkTemplate(market),
1946
+ ...end < asins.length ? { nextOffset: end } : {}
1947
+ };
1948
+ }
1949
+ };
1950
+ var INCLUDE_PATH = { type: "boolean", default: true, description: "Add each category's path from the root (default true)." };
1951
+ var searchCategories = {
1952
+ name: "search_categories",
1953
+ kind: "read",
1954
+ title: "Search Amazon categories with Keepa",
1955
+ description: "Finds a marketplace's categories by name: up to 50, largest first, with id, name, path from the root, parent id, product count, subcategory count and average Buy Box price. Every word must match and needs 3 letters or more. Category ids differ per marketplace. 1 token.",
1956
+ inputSchema: {
1957
+ type: "object",
1958
+ properties: {
1959
+ marketplace: MARKETPLACE,
1960
+ term: { type: "string", minLength: 3, maxLength: 200, description: 'The category name words, e.g. "bluetooth speakers".' },
1961
+ include_path: INCLUDE_PATH
1962
+ },
1963
+ required: ["marketplace", "term"],
1964
+ additionalProperties: false
1965
+ },
1966
+ async run(args, h) {
1967
+ if (args.term.trim().split(/\s+/).some((word) => word.length < 3)) {
1968
+ throw new ToolFailure("Every word of term needs 3 letters or more for Keepa's category search. Nothing was sent to Keepa.");
1969
+ }
1970
+ const market = marketOf(args.marketplace);
1971
+ const data = await keepaGet(h, "/search", { domain: market.id, type: "category", term: args.term.trim(), parents: flag(args.include_path) });
1972
+ return { marketplace: market.site, currency: market.currency, ...common(data), categories: categoryList(data) };
1973
+ }
1974
+ };
1975
+ var getCategories = {
1976
+ name: "get_categories",
1977
+ kind: "read",
1978
+ title: "Look up Amazon categories in Keepa",
1979
+ description: "Up to 10 categories of a marketplace by id (0 lists the root categories), with name, path from the root, parent id, product count, subcategory count and average Buy Box price, largest first. 1 token.",
1980
+ inputSchema: {
1981
+ type: "object",
1982
+ properties: {
1983
+ marketplace: MARKETPLACE,
1984
+ category_ids: {
1985
+ type: "array",
1986
+ items: { type: "integer", minimum: 0 },
1987
+ minItems: 1,
1988
+ maxItems: 10,
1989
+ uniqueItems: true,
1990
+ description: "Up to 10 category ids, or [0] for the root categories."
1991
+ },
1992
+ include_path: INCLUDE_PATH
1993
+ },
1994
+ required: ["marketplace", "category_ids"],
1995
+ additionalProperties: false
1996
+ },
1997
+ async run(args, h) {
1998
+ const market = marketOf(args.marketplace);
1999
+ const data = await keepaGet(h, "/category", { domain: market.id, category: args.category_ids.join(","), parents: flag(args.include_path) });
2000
+ return { marketplace: market.site, currency: market.currency, ...common(data), categories: categoryList(data) };
2001
+ }
2002
+ };
2003
+ var findProducts = {
2004
+ name: "find_products",
2005
+ kind: "read",
2006
+ title: "Find Amazon products with the Keepa product finder",
2007
+ description: `Searches Keepa's product database with filters and returns matching ASINs (no titles or prices) with the total count. Filters are ANDed, at least one: rootCategory and categories_include (arrays of ids), title, brand (array), current_<TYPE>_gte and current_<TYPE>_lte with TYPE AMAZON, NEW, USED, SALES or BUY_BOX_SHIPPING, avg90_<TYPE>_lte, deltaPercent90_<TYPE>_gte, monthlySold_gte, salesRankDrops30_gte and more; prices in the smallest currency unit (2500 = 25.00). Sorted by sales rank unless sort says otherwise, e.g. [["current_SALES","asc"]]. 10 tokens plus 1 per 100 ASINs returned.`,
2008
+ inputSchema: {
2009
+ type: "object",
2010
+ properties: {
2011
+ marketplace: MARKETPLACE,
2012
+ selection: {
2013
+ type: "object",
2014
+ description: 'Keepa product finder filters, e.g. {"rootCategory":[172282],"current_SALES_lte":5000,"current_NEW_lte":2500}.'
2015
+ },
2016
+ page: { type: "integer", minimum: 0, maximum: 199, description: "The result page, from 0 (default 0). Keepa reaches only the first 10,000 results: (page + 1) \xD7 per_page at most 10,000." },
2017
+ per_page: { type: "integer", minimum: 50, maximum: 2e3, description: "ASINs per page, 50 to 2,000 (Keepa's default and minimum 50). More ASINs cost more tokens." }
2018
+ },
2019
+ required: ["marketplace", "selection"],
2020
+ additionalProperties: false
2021
+ },
2022
+ async run(args, h) {
2023
+ const filters = Object.keys(args.selection).filter((key) => !["page", "perPage", "sort"].includes(key));
2024
+ if (!filters.length) throw new ToolFailure("selection needs at least one filter, such as rootCategory or current_SALES_lte. Nothing was sent to Keepa.");
2025
+ const perPage = args.per_page ?? args.selection["perPage"] ?? FINDER_DEFAULT_PER_PAGE;
2026
+ const page = args.page ?? args.selection["page"] ?? 0;
2027
+ if (!Number.isInteger(perPage) || perPage < FINDER_DEFAULT_PER_PAGE) {
2028
+ throw new ToolFailure("perPage must be a whole number from 50 to 2,000. Nothing was sent to Keepa.");
2029
+ }
2030
+ if (perPage > FINDER_MAX_PER_PAGE) {
2031
+ throw new ToolFailure("A page of more than 2,000 ASINs does not fit in one result: use per_page up to 2,000 and page for the next ones. Nothing was sent to Keepa.");
2032
+ }
2033
+ if (!Number.isInteger(page) || page < 0) throw new ToolFailure("page must be a whole number from 0. Nothing was sent to Keepa.");
2034
+ if ((page + 1) * perPage > FINDER_MAX_RESULTS) {
2035
+ throw new ToolFailure(
2036
+ `Keepa's product finder reaches only the first 10,000 results, and page ${page} with ${perPage} per page goes past them. Narrow the filters or sort differently instead. Nothing was sent to Keepa.`
2037
+ );
2038
+ }
2039
+ const market = marketOf(args.marketplace);
2040
+ const selection = {
2041
+ ...args.selection,
2042
+ ...args.page !== void 0 ? { page: args.page } : {},
2043
+ ...args.per_page !== void 0 ? { perPage: args.per_page } : {}
2044
+ };
2045
+ const data = await keepaGet(h, "/query", { domain: market.id, selection: JSON.stringify(selection) });
2046
+ const asins = Array.isArray(data["asinList"]) ? data["asinList"].filter((asin) => typeof asin === "string") : [];
2047
+ return {
2048
+ marketplace: market.site,
2049
+ totalResults: typeof data["totalResults"] === "number" ? data["totalResults"] : void 0,
2050
+ page: typeof selection.page === "number" ? selection.page : 0,
2051
+ ...common(data),
2052
+ asins,
2053
+ linkTemplate: linkTemplate(market)
2054
+ };
2055
+ }
2056
+ };
2057
+ var connector = defineConnector({
2058
+ vendor: "keepa",
2059
+ label: "Keepa",
2060
+ origins: [ORIGIN],
2061
+ credentials: ["apikey"],
2062
+ credentialLabels: { apikey: "Keepa API key" },
2063
+ tools: [
2064
+ getTokenStatus,
2065
+ getProducts,
2066
+ getPriceHistory,
2067
+ searchProducts,
2068
+ getBestSellers,
2069
+ searchCategories,
2070
+ getCategories,
2071
+ findProducts,
2072
+ // Keepa's API only reads, except the tracking calls (/tracking), which
2073
+ // change the account's tracked products even by GET: api_get keeps away
2074
+ // from them, and there is no api_request.
2075
+ ...apiTools({
2076
+ label: "Keepa",
2077
+ description: "The Keepa API at https://api.keepa.com with the connected key (added as the key parameter), for the calls the other tools do not make: /seller (seller and storefront), /deal, /topseller, /lightningdeal and the raw /product, with domain (1 = amazon.com, 2 = .co.uk, 3 = .de, 4 = .fr, 5 = .co.jp, 6 = .ca, 8 = .it, 9 = .es, 10 = .in, 11 = .com.mx, 12 = .com.br) and the other parameters in query. Reference: https://keepa.com/#!api. Every call spends tokens as Keepa prices it; /tracking is not reachable.",
2078
+ guard(request) {
2079
+ if (request.segments[0]?.toLowerCase() === "tracking") {
2080
+ throw new ToolFailure("api_get does not reach /tracking: those calls change the account's tracked products. Nothing was sent.");
2081
+ }
2082
+ },
2083
+ send: (request, h) => keepaRequest(h, request)
2084
+ }).filter((tool) => tool.name === "api_get")
2085
+ ]
2086
+ });
2087
+ module.exports = connector;