@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,2258 @@
1
+ /* woocommerce connector module (MIT License). Built from src/vendors/woocommerce; 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 points = Array.from(text);
70
+ if (points.length <= max) return text;
71
+ return `${points.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 points = Array.from(text.length > MAX_CUT_POINTS ? text.slice(0, MAX_CUT_POINTS) : text);
170
+ if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.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: points.slice(0, count).join("")
177
+ });
178
+ let low = 0;
179
+ let high = points.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 points = Array.from(clean);
357
+ if (points.length <= MAX_NAME) return clean || "file";
358
+ const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
359
+ return points.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/woocommerce/store.ts
1091
+ function basicAuth(user, password) {
1092
+ let binary = "";
1093
+ for (const byte of utf8Bytes(`${user}:${password}`)) binary += String.fromCharCode(byte);
1094
+ return `Basic ${btoa(binary)}`;
1095
+ }
1096
+ function storePath(value) {
1097
+ const site = parseSiteUrl(value ?? "");
1098
+ if (!site.ok) return "";
1099
+ return site.url.pathname.replace(/\/(?:wp-admin|wp-json|wp-login\.php)(?:\/.*)?$/i, "").replace(/\/+$/, "");
1100
+ }
1101
+ var NOT_FOUND = "Check that the store URL is the address of the site the store runs on (Settings \u2192 General in its admin, with its subdirectory if it has one; not the shop page), that WooCommerce is active, and that permalinks are not set to Plain.";
1102
+ var HINTS = {
1103
+ woocommerce_rest_authentication_error: "Check the consumer key and secret (WooCommerce \u2192 Settings \u2192 Advanced \u2192 REST API); a change needs a key with Read/Write permissions.",
1104
+ woocommerce_rest_cannot_view: "The key's user may not read this, or the site's server drops the Authorization header: the key needs a user with the Shop manager or Administrator role.",
1105
+ woocommerce_rest_cannot_create: "The key needs Read/Write permissions and a user with the Shop manager or Administrator role.",
1106
+ woocommerce_rest_cannot_edit: "The key needs Read/Write permissions and a user with the Shop manager or Administrator role.",
1107
+ woocommerce_rest_cannot_delete: "The key needs Read/Write permissions and a user with the Shop manager or Administrator role.",
1108
+ rest_no_route: NOT_FOUND
1109
+ };
1110
+ function withHint(error) {
1111
+ if (!(error instanceof ToolFailure)) return error;
1112
+ const { vendorCode: vendorCode2, status } = error.details;
1113
+ const hint = (vendorCode2 !== void 0 ? HINTS[vendorCode2] : void 0) ?? (status === 404 && vendorCode2 === void 0 ? NOT_FOUND : void 0);
1114
+ return hint ? new ToolFailure(`${error.message} ${hint}`, error.details) : error;
1115
+ }
1116
+ function restPath(h, route) {
1117
+ return `${storePath(h.credentials["storeurl"])}/wp-json${route}`;
1118
+ }
1119
+ async function wc(h, route, request = {}) {
1120
+ try {
1121
+ return await h.api({ ...request, origin: h.originOf("storeurl"), path: restPath(h, `/wc/v3${route}`) });
1122
+ } catch (error) {
1123
+ throw withHint(error);
1124
+ }
1125
+ }
1126
+ function totalItems(response) {
1127
+ const value = Number(response.headers.get("x-wp-total"));
1128
+ return response.headers.has("x-wp-total") && Number.isFinite(value) ? value : void 0;
1129
+ }
1130
+ function hasMore(response, page, count, perPage) {
1131
+ const pages = Number(response.headers.get("x-wp-totalpages"));
1132
+ return response.headers.has("x-wp-totalpages") && Number.isFinite(pages) ? page < pages : count >= perPage;
1133
+ }
1134
+ function invalidCursor() {
1135
+ return new ToolFailure("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.");
1136
+ }
1137
+ function listPosition(h, schema, args) {
1138
+ const state = h.cursor(args["cursor"]);
1139
+ if (!state) {
1140
+ const { cursor: _cursor, ...filters } = args;
1141
+ return { page: 1, skip: 0, filters };
1142
+ }
1143
+ let parsed;
1144
+ try {
1145
+ parsed = JSON.parse(String(state["f"] ?? "{}"));
1146
+ } catch {
1147
+ throw invalidCursor();
1148
+ }
1149
+ const checked = validateArguments(schema, parsed);
1150
+ const page = Number(state["p"]);
1151
+ const skip = Number(state["o"]);
1152
+ if (!checked.ok || "cursor" in checked.value || !Number.isInteger(page) || page < 1 || !Number.isInteger(skip) || skip < 0) throw invalidCursor();
1153
+ return { page, skip, filters: checked.value };
1154
+ }
1155
+ function pageCursors(h, position, more) {
1156
+ const f = JSON.stringify(position.filters);
1157
+ return {
1158
+ resumeAt: (index) => h.makeCursor({ p: position.page, o: position.skip + index, f }),
1159
+ ...more ? { nextPage: h.makeCursor({ p: position.page + 1, o: 0, f }) } : {}
1160
+ };
1161
+ }
1162
+ function compact(value) {
1163
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
1164
+ }
1165
+ var NAMED = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: "\xA0", hellip: "\u2026", ndash: "\u2013", mdash: "\u2014", rsquo: "\u2019", lsquo: "\u2018", rdquo: "\u201D", ldquo: "\u201C" };
1166
+ function decodeEntities(text) {
1167
+ return text.replace(/&(#[xX][0-9a-fA-F]{1,6}|#\d{1,7}|[A-Za-z]{2,8});/g, (whole, body) => {
1168
+ if (body.startsWith("#")) {
1169
+ const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
1170
+ return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : whole;
1171
+ }
1172
+ return NAMED[body.toLowerCase()] ?? whole;
1173
+ });
1174
+ }
1175
+ function plainText(html, max) {
1176
+ if (typeof html !== "string") return void 0;
1177
+ const text = decodeEntities(html.replace(/<[^>]*>/g, " ")).replace(/\s+/g, " ").trim();
1178
+ if (!text) return void 0;
1179
+ const points = Array.from(text);
1180
+ return points.length > max ? `${points.slice(0, max - 1).join("")}\u2026` : text;
1181
+ }
1182
+ function cutHtml(html, max) {
1183
+ if (typeof html !== "string" || !html) return {};
1184
+ const points = Array.from(html);
1185
+ return points.length > max ? { text: points.slice(0, max).join(""), cut: true } : { text: html };
1186
+ }
1187
+ function refuse(sentence) {
1188
+ throw new ToolFailure(`${sentence} Nothing was sent.`);
1189
+ }
1190
+ function phpFieldName(name2) {
1191
+ return (name2.split("\0")[0] ?? "").replace(/^ +/, "").replace(/[ .[]/g, "_");
1192
+ }
1193
+ function isJsonBody(request) {
1194
+ if (request.body === void 0) return true;
1195
+ const media = (request.contentType ?? "").trim().toLowerCase().split(/[;,\s]/)[0] ?? "";
1196
+ return media === "application/json" || /^application\/[a-z0-9!#$&^_.-]+\+json$/.test(media);
1197
+ }
1198
+ function withoutSecrets(value, depth = 0) {
1199
+ if (typeof value !== "object" || value === null || depth > 32) return value;
1200
+ if (Array.isArray(value)) return value.map((item) => withoutSecrets(item, depth + 1));
1201
+ const out = {};
1202
+ for (const [key, item] of Object.entries(value)) out[key] = withoutSecrets(item, depth + 1);
1203
+ if (out["type"] === "password" && "value" in out) {
1204
+ delete out["value"];
1205
+ out["value_hidden"] = true;
1206
+ }
1207
+ return out;
1208
+ }
1209
+ function termSearch(name2) {
1210
+ const parts = name2.split(/[&<>]/).map((part) => part.trim()).filter(Boolean);
1211
+ return parts.sort((a, b) => b.length - a.length)[0];
1212
+ }
1213
+ function termKey(name2) {
1214
+ return decodeEntities(name2).replace(/\s+/g, " ").trim().toLowerCase();
1215
+ }
1216
+
1217
+ // src/vendors/woocommerce/index.ts
1218
+ var PRICE = (what) => ({ type: "string", pattern: "^\\d{1,12}(\\.\\d{1,6})?$", description: what });
1219
+ var PRICE_OR_CLEAR = (what) => ({ type: "string", pattern: "^(\\d{1,12}(\\.\\d{1,6})?)?$", description: what });
1220
+ var ID_LIST = (what) => ({ type: "array", items: { type: "integer", minimum: 1 }, maxItems: 100, uniqueItems: true, description: what });
1221
+ var CURSOR_SCHEMA = { type: "string", description: "nextCursor from the previous result (the other arguments then come from it)." };
1222
+ var PER_PAGE = (fallback) => ({ type: "integer", minimum: 1, maximum: 100, default: fallback, description: `1 to 100 (default ${fallback}).` });
1223
+ var DATE = { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2})?)?$", description: "2026-11-01 or 2026-11-01T00:00:00, store time." };
1224
+ function orderDate(value, end) {
1225
+ if (typeof value !== "string") return void 0;
1226
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return `${value}T${end ? "23:59:59" : "00:00:00"}`;
1227
+ return /T\d{2}:\d{2}$/.test(value) ? `${value}:00` : value;
1228
+ }
1229
+ function withTermObjects(body) {
1230
+ for (const key of ["categories", "tags"]) {
1231
+ const ids = body[key];
1232
+ if (Array.isArray(ids)) body[key] = ids.map((id) => ({ id }));
1233
+ }
1234
+ return body;
1235
+ }
1236
+ var IMAGE = {
1237
+ type: "object",
1238
+ properties: {
1239
+ src: { type: "string", format: "uri", maxLength: 2e3, description: "A public image URL (WooCommerce downloads it)." },
1240
+ id: { type: "integer", minimum: 1, description: "Or a media library id." },
1241
+ alt: { type: "string", maxLength: 500 }
1242
+ },
1243
+ additionalProperties: false
1244
+ };
1245
+ var ATTRIBUTE = {
1246
+ type: "object",
1247
+ properties: {
1248
+ id: { type: "integer", minimum: 0, description: "A global attribute id; leave out for a custom one." },
1249
+ name: { type: "string", maxLength: 200, description: 'E.g. "Size".' },
1250
+ options: { type: "array", items: { type: "string", maxLength: 200 }, maxItems: 100, description: 'E.g. ["S", "M"].' },
1251
+ visible: { type: "boolean" },
1252
+ variation: { type: "boolean", description: "Used for variations." }
1253
+ },
1254
+ additionalProperties: false
1255
+ };
1256
+ var STOCK_STATUS = { type: "string", enum: ["instock", "outofstock", "onbackorder"] };
1257
+ var SHARED_FIELDS = {
1258
+ sku: { type: "string", maxLength: 100, description: "Unique: WooCommerce refuses one another product has." },
1259
+ regular_price: PRICE_OR_CLEAR('E.g. "49.00".'),
1260
+ sale_price: PRICE_OR_CLEAR('"" ends the sale.'),
1261
+ manage_stock: { type: "boolean", description: "Track stock." },
1262
+ stock_quantity: { type: "integer", minimum: -1e6, maximum: 1e9 },
1263
+ stock_status: STOCK_STATUS,
1264
+ weight: { type: "string", maxLength: 20, description: "In the store's unit." },
1265
+ description: { type: "string", maxLength: 2e5, description: "HTML." }
1266
+ };
1267
+ var PRODUCT_FIELDS = {
1268
+ name: { type: "string", minLength: 1, maxLength: 500 },
1269
+ short_description: { type: "string", maxLength: 2e4, description: "HTML." },
1270
+ categories: ID_LIST("Category ids; replaces the current ones."),
1271
+ tags: ID_LIST("Tag ids; replaces the current ones."),
1272
+ images: { type: "array", items: IMAGE, maxItems: 20, description: "The first is the main image; replaces the current ones." }
1273
+ };
1274
+ var MORE_FIELDS = {
1275
+ type: "object",
1276
+ description: 'Other fields of the WooCommerce product (or variation) API, e.g. {"date_on_sale_to": "2026-12-31", "backorders": "notify", "low_stock_amount": 5, "dimensions": {"length": "10"}, "shipping_class": "bulky", "tax_class": "reduced-rate", "catalog_visibility": "hidden", "featured": true, "slug": "blue-mug"}.'
1277
+ };
1278
+ var NEW_VARIATION = {
1279
+ type: "object",
1280
+ properties: {
1281
+ attributes: {
1282
+ type: "array",
1283
+ minItems: 1,
1284
+ maxItems: 10,
1285
+ items: {
1286
+ type: "object",
1287
+ properties: { id: { type: "integer", minimum: 0 }, name: { type: "string", maxLength: 200 }, option: { type: "string", maxLength: 200 } },
1288
+ required: ["option"],
1289
+ additionalProperties: false
1290
+ },
1291
+ description: 'One value per variation attribute: [{"name": "Size", "option": "M"}].'
1292
+ },
1293
+ regular_price: SHARED_FIELDS["regular_price"],
1294
+ sale_price: SHARED_FIELDS["sale_price"],
1295
+ sku: SHARED_FIELDS["sku"],
1296
+ manage_stock: SHARED_FIELDS["manage_stock"],
1297
+ stock_quantity: SHARED_FIELDS["stock_quantity"],
1298
+ stock_status: STOCK_STATUS,
1299
+ image: IMAGE
1300
+ },
1301
+ required: ["attributes"],
1302
+ additionalProperties: false
1303
+ };
1304
+ var CREATE_KEYS = ["type", "status", "attributes", "variations", ...Object.keys(SHARED_FIELDS), ...Object.keys(PRODUCT_FIELDS)];
1305
+ var UPDATE_KEYS = ["variation_id", "expected_stock_quantity", "status", "image", ...Object.keys(SHARED_FIELDS), ...Object.keys(PRODUCT_FIELDS)];
1306
+ var PRODUCT_STATUS = { type: "string", enum: ["draft", "pending", "private", "publish"], description: "publish puts it on sale in the shop." };
1307
+ var ORDER_STATUSES = ["pending", "processing", "on-hold", "completed", "cancelled", "refunded", "failed", "trash", "checkout-draft"];
1308
+ function trimCategories(list) {
1309
+ return Array.isArray(list) && list.length ? list.map((item) => compact({ id: item?.id, name: typeof item?.name === "string" ? decodeEntities(item.name) : void 0 })) : void 0;
1310
+ }
1311
+ function trimListProduct(product) {
1312
+ return compact({
1313
+ id: product?.id,
1314
+ name: typeof product?.name === "string" ? truncate(decodeEntities(product.name), 300) : void 0,
1315
+ type: product?.type,
1316
+ status: product?.status,
1317
+ sku: product?.sku,
1318
+ price: product?.price,
1319
+ regular_price: product?.regular_price,
1320
+ sale_price: product?.sale_price,
1321
+ on_sale: product?.on_sale === true ? true : void 0,
1322
+ stock_status: product?.stock_status,
1323
+ manage_stock: product?.manage_stock,
1324
+ stock_quantity: product?.manage_stock === true ? product?.stock_quantity : void 0,
1325
+ variations: Array.isArray(product?.variations) && product.variations.length ? product.variations.length : void 0,
1326
+ categories: trimCategories(product?.categories),
1327
+ featured: product?.featured === true ? true : void 0,
1328
+ total_sales: product?.total_sales,
1329
+ permalink: product?.permalink,
1330
+ date_modified: product?.date_modified
1331
+ });
1332
+ }
1333
+ function trimImages(images) {
1334
+ return Array.isArray(images) && images.length ? images.slice(0, 20).map((image) => compact({ id: image?.id, src: image?.src, alt: image?.alt })) : void 0;
1335
+ }
1336
+ function trimAttributes(attributes) {
1337
+ return Array.isArray(attributes) && attributes.length ? attributes.map((attribute) => compact({
1338
+ id: attribute?.id || void 0,
1339
+ name: attribute?.name,
1340
+ option: attribute?.option,
1341
+ options: Array.isArray(attribute?.options) ? attribute.options : void 0,
1342
+ variation: attribute?.variation,
1343
+ visible: attribute?.visible
1344
+ })) : void 0;
1345
+ }
1346
+ function trimDimensions(dimensions) {
1347
+ return dimensions && (dimensions.length || dimensions.width || dimensions.height) ? compact({ length: dimensions.length, width: dimensions.width, height: dimensions.height }) : void 0;
1348
+ }
1349
+ function trimProduct(product) {
1350
+ const description = cutHtml(product?.description, 8e3);
1351
+ const short = cutHtml(product?.short_description, 2e3);
1352
+ return compact({
1353
+ ...trimListProduct(product),
1354
+ stock_quantity: product?.stock_quantity ?? void 0,
1355
+ slug: product?.slug,
1356
+ catalog_visibility: product?.catalog_visibility,
1357
+ description: description.text,
1358
+ description_cut: description.cut,
1359
+ short_description: short.text,
1360
+ short_description_cut: short.cut,
1361
+ tags: trimCategories(product?.tags),
1362
+ images: trimImages(product?.images),
1363
+ attributes: trimAttributes(product?.attributes),
1364
+ default_attributes: trimAttributes(product?.default_attributes),
1365
+ backorders: product?.backorders,
1366
+ low_stock_amount: product?.low_stock_amount ?? void 0,
1367
+ weight: product?.weight,
1368
+ dimensions: trimDimensions(product?.dimensions),
1369
+ shipping_class: product?.shipping_class,
1370
+ tax_status: product?.tax_status,
1371
+ tax_class: product?.tax_class,
1372
+ virtual: product?.virtual === true ? true : void 0,
1373
+ downloadable: product?.downloadable === true ? true : void 0,
1374
+ external_url: product?.external_url,
1375
+ date_on_sale_from: product?.date_on_sale_from,
1376
+ date_on_sale_to: product?.date_on_sale_to,
1377
+ date_created: product?.date_created,
1378
+ variation_ids: Array.isArray(product?.variations) && product.variations.length ? product.variations.slice(0, 200) : void 0,
1379
+ variations: void 0
1380
+ });
1381
+ }
1382
+ function trimVariation(variation) {
1383
+ return compact({
1384
+ id: variation?.id,
1385
+ sku: variation?.sku,
1386
+ status: variation?.status,
1387
+ attributes: Array.isArray(variation?.attributes) ? variation.attributes.map((attribute) => `${attribute?.name}: ${attribute?.option}`).join(", ") : void 0,
1388
+ price: variation?.price,
1389
+ regular_price: variation?.regular_price,
1390
+ sale_price: variation?.sale_price,
1391
+ stock_status: variation?.stock_status,
1392
+ manage_stock: variation?.manage_stock,
1393
+ stock_quantity: variation?.stock_quantity ?? void 0,
1394
+ backorders: variation?.backorders,
1395
+ low_stock_amount: variation?.low_stock_amount ?? void 0,
1396
+ weight: variation?.weight,
1397
+ image: variation?.image?.src
1398
+ });
1399
+ }
1400
+ function money(value) {
1401
+ return value === "0.00" || value === "0" ? void 0 : value;
1402
+ }
1403
+ function trimLineItem(item) {
1404
+ return compact({
1405
+ id: item?.id,
1406
+ name: item?.name,
1407
+ product_id: item?.product_id || void 0,
1408
+ variation_id: item?.variation_id || void 0,
1409
+ sku: item?.sku,
1410
+ quantity: item?.quantity,
1411
+ price: item?.price,
1412
+ subtotal: item?.subtotal,
1413
+ total: item?.total,
1414
+ total_tax: money(item?.total_tax)
1415
+ });
1416
+ }
1417
+ function trimListOrder(order) {
1418
+ const items = Array.isArray(order?.line_items) ? order.line_items : [];
1419
+ return compact({
1420
+ id: order?.id,
1421
+ number: order?.number,
1422
+ status: order?.status,
1423
+ date_created: order?.date_created,
1424
+ date_paid: order?.date_paid,
1425
+ date_completed: order?.date_completed,
1426
+ total: order?.total,
1427
+ currency: order?.currency,
1428
+ customer_id: order?.customer_id || void 0,
1429
+ payment_method_title: order?.payment_method_title,
1430
+ items: items.slice(0, 10).map((item) => compact({ name: item?.name, quantity: item?.quantity, total: item?.total, product_id: item?.product_id || void 0 })),
1431
+ more_items: items.length > 10 ? items.length - 10 : void 0,
1432
+ refunded: Array.isArray(order?.refunds) && order.refunds.length ? order.refunds.reduce((sum, refund) => sum - Number(refund?.total ?? 0), 0).toFixed(2) : void 0
1433
+ });
1434
+ }
1435
+ function trimAddress(address) {
1436
+ if (!address || typeof address !== "object") return void 0;
1437
+ const value = compact({
1438
+ first_name: address.first_name,
1439
+ last_name: address.last_name,
1440
+ company: address.company,
1441
+ address_1: address.address_1,
1442
+ address_2: address.address_2,
1443
+ city: address.city,
1444
+ state: address.state,
1445
+ postcode: address.postcode,
1446
+ country: address.country,
1447
+ email: address.email,
1448
+ phone: address.phone
1449
+ });
1450
+ return Object.keys(value).length ? value : void 0;
1451
+ }
1452
+ function trimOrder(order, withCustomer) {
1453
+ return compact({
1454
+ id: order?.id,
1455
+ number: order?.number,
1456
+ status: order?.status,
1457
+ currency: order?.currency,
1458
+ date_created: order?.date_created,
1459
+ date_modified: order?.date_modified,
1460
+ date_paid: order?.date_paid,
1461
+ date_completed: order?.date_completed,
1462
+ total: order?.total,
1463
+ total_tax: money(order?.total_tax),
1464
+ shipping_total: money(order?.shipping_total),
1465
+ discount_total: money(order?.discount_total),
1466
+ prices_include_tax: order?.prices_include_tax,
1467
+ payment_method: order?.payment_method,
1468
+ payment_method_title: order?.payment_method_title,
1469
+ transaction_id: order?.transaction_id,
1470
+ customer_id: order?.customer_id || void 0,
1471
+ customer_note: order?.customer_note,
1472
+ created_via: order?.created_via,
1473
+ line_items: Array.isArray(order?.line_items) ? order.line_items.slice(0, 100).map(trimLineItem) : void 0,
1474
+ shipping_lines: Array.isArray(order?.shipping_lines) && order.shipping_lines.length ? order.shipping_lines.map((line) => compact({ id: line?.id, method_title: line?.method_title, method_id: line?.method_id, total: line?.total })) : void 0,
1475
+ fee_lines: Array.isArray(order?.fee_lines) && order.fee_lines.length ? order.fee_lines.map((line) => compact({ id: line?.id, name: line?.name, total: line?.total })) : void 0,
1476
+ coupon_lines: Array.isArray(order?.coupon_lines) && order.coupon_lines.length ? order.coupon_lines.map((line) => compact({ code: line?.code, discount: line?.discount })) : void 0,
1477
+ refunds: Array.isArray(order?.refunds) && order.refunds.length ? order.refunds.map((refund) => compact({ id: refund?.id, reason: refund?.reason, total: refund?.total })) : void 0,
1478
+ billing: withCustomer ? trimAddress(order?.billing) : void 0,
1479
+ shipping: withCustomer ? trimAddress(order?.shipping) : void 0
1480
+ });
1481
+ }
1482
+ function trimCoupon(coupon) {
1483
+ const list = (value) => Array.isArray(value) && value.length ? value : void 0;
1484
+ return compact({
1485
+ id: coupon?.id,
1486
+ code: coupon?.code,
1487
+ status: coupon?.status,
1488
+ discount_type: coupon?.discount_type,
1489
+ amount: coupon?.amount,
1490
+ description: coupon?.description,
1491
+ date_expires: coupon?.date_expires,
1492
+ usage_count: coupon?.usage_count,
1493
+ usage_limit: coupon?.usage_limit ?? void 0,
1494
+ usage_limit_per_user: coupon?.usage_limit_per_user ?? void 0,
1495
+ limit_usage_to_x_items: coupon?.limit_usage_to_x_items ?? void 0,
1496
+ individual_use: coupon?.individual_use === true ? true : void 0,
1497
+ free_shipping: coupon?.free_shipping === true ? true : void 0,
1498
+ exclude_sale_items: coupon?.exclude_sale_items === true ? true : void 0,
1499
+ minimum_amount: money(coupon?.minimum_amount),
1500
+ maximum_amount: money(coupon?.maximum_amount),
1501
+ product_ids: list(coupon?.product_ids),
1502
+ excluded_product_ids: list(coupon?.excluded_product_ids),
1503
+ product_categories: list(coupon?.product_categories),
1504
+ excluded_product_categories: list(coupon?.excluded_product_categories),
1505
+ email_restrictions: list(coupon?.email_restrictions),
1506
+ date_created: coupon?.date_created
1507
+ });
1508
+ }
1509
+ function trimCustomer(customer) {
1510
+ return compact({
1511
+ id: customer?.id,
1512
+ email: customer?.email,
1513
+ first_name: customer?.first_name,
1514
+ last_name: customer?.last_name,
1515
+ username: customer?.username,
1516
+ role: customer?.role,
1517
+ is_paying_customer: customer?.is_paying_customer,
1518
+ orders_count: customer?.orders_count,
1519
+ total_spent: customer?.total_spent,
1520
+ date_created: customer?.date_created
1521
+ });
1522
+ }
1523
+ function trimTerm(term) {
1524
+ return compact({
1525
+ id: term?.id,
1526
+ name: typeof term?.name === "string" ? decodeEntities(term.name) : void 0,
1527
+ slug: term?.slug,
1528
+ count: term?.count,
1529
+ parent: term?.parent || void 0,
1530
+ type: term?.type,
1531
+ description: plainText(term?.description, 200),
1532
+ image: term?.image?.src
1533
+ });
1534
+ }
1535
+ function productBody(args, skip, own = []) {
1536
+ const body = {};
1537
+ for (const [key, value] of Object.entries(args)) {
1538
+ if (value === void 0 || skip.includes(key) || key === "more_fields") continue;
1539
+ body[key] = value;
1540
+ }
1541
+ const more = args["more_fields"];
1542
+ if (more && typeof more === "object") {
1543
+ const clash = Object.keys(more).filter((key) => own.includes(key) || key === "id");
1544
+ if (clash.length) refuse(`more_fields must not repeat ${clash.join(", ")}: give ${clash.length > 1 ? "them as arguments" : "it as an argument"}.`);
1545
+ Object.assign(body, more);
1546
+ }
1547
+ return body;
1548
+ }
1549
+ function cause(error) {
1550
+ return error.message.replace(/\s*Nothing was changed\.?\s*$/, "").replace(/\.$/, "");
1551
+ }
1552
+ var LIST_PRODUCTS_SCHEMA = {
1553
+ type: "object",
1554
+ properties: {
1555
+ search: { type: "string", minLength: 1, maxLength: 200, description: "Words in the name or description." },
1556
+ sku: { type: "string", minLength: 1, maxLength: 100, description: "Exact SKU (several: comma-separated)." },
1557
+ status: { type: "string", enum: ["any", "draft", "pending", "private", "publish"], default: "any" },
1558
+ type: { type: "string", enum: ["simple", "grouped", "external", "variable"] },
1559
+ category: { type: "integer", minimum: 1, description: "Category id." },
1560
+ tag: { type: "integer", minimum: 1, description: "Tag id." },
1561
+ stock_status: STOCK_STATUS,
1562
+ on_sale: { type: "boolean" },
1563
+ featured: { type: "boolean" },
1564
+ orderby: { type: "string", enum: ["date", "modified", "id", "title", "slug", "price", "popularity", "rating", "menu_order"], default: "date", description: "popularity: by sales." },
1565
+ order: { type: "string", enum: ["desc", "asc"], default: "desc" },
1566
+ per_page: PER_PAGE(20),
1567
+ cursor: CURSOR_SCHEMA
1568
+ },
1569
+ additionalProperties: false
1570
+ };
1571
+ var LIST_ORDERS_SCHEMA = {
1572
+ type: "object",
1573
+ properties: {
1574
+ status: { type: "array", items: { type: "string", enum: [...ORDER_STATUSES] }, minItems: 1, uniqueItems: true, description: 'E.g. ["processing", "on-hold"]; default all but trash.' },
1575
+ customer: { type: "integer", minimum: 0, description: "Customer id (0: guests)." },
1576
+ product: { type: "integer", minimum: 1, description: "Orders with this product id." },
1577
+ search: { type: "string", minLength: 1, maxLength: 200, description: "Order number, name, email or address words." },
1578
+ after: { ...DATE, description: "Created after this moment, store time: 2026-11-01 (from the start of that day) or 2026-11-01T09:30:00." },
1579
+ before: { ...DATE, description: "Created before this moment, store time: 2026-11-30 (up to the end of that day) or 2026-11-30T18:00:00." },
1580
+ orderby: { type: "string", enum: ["date", "modified", "id"], default: "date" },
1581
+ order: { type: "string", enum: ["desc", "asc"], default: "desc" },
1582
+ per_page: PER_PAGE(20),
1583
+ cursor: CURSOR_SCHEMA
1584
+ },
1585
+ additionalProperties: false
1586
+ };
1587
+ var LIST_COUPONS_SCHEMA = {
1588
+ type: "object",
1589
+ properties: {
1590
+ code: { type: "string", minLength: 1, maxLength: 100, description: "An exact code." },
1591
+ search: { type: "string", minLength: 1, maxLength: 200, description: "Part of a code." },
1592
+ orderby: { type: "string", enum: ["date", "modified", "id", "title"], default: "date" },
1593
+ order: { type: "string", enum: ["desc", "asc"], default: "desc" },
1594
+ per_page: PER_PAGE(20),
1595
+ cursor: CURSOR_SCHEMA
1596
+ },
1597
+ additionalProperties: false
1598
+ };
1599
+ var LIST_CUSTOMERS_SCHEMA = {
1600
+ type: "object",
1601
+ properties: {
1602
+ search: { type: "string", minLength: 1, maxLength: 200, description: "Part of a name, email or user name." },
1603
+ email: { type: "string", minLength: 3, maxLength: 200, description: "An exact email." },
1604
+ role: { type: "string", enum: ["customer", "all", "subscriber", "shop_manager", "administrator"], default: "customer" },
1605
+ orderby: { type: "string", enum: ["registered_date", "id", "name"], default: "registered_date" },
1606
+ order: { type: "string", enum: ["desc", "asc"], default: "desc" },
1607
+ per_page: PER_PAGE(20),
1608
+ cursor: CURSOR_SCHEMA
1609
+ },
1610
+ additionalProperties: false
1611
+ };
1612
+ var TERM_ROUTES = {
1613
+ categories: "/products/categories",
1614
+ tags: "/products/tags",
1615
+ attributes: "/products/attributes",
1616
+ attribute_terms: "/products/attributes/{id}/terms",
1617
+ shipping_classes: "/products/shipping_classes"
1618
+ };
1619
+ function termRoute(taxonomy, attributeId) {
1620
+ if (taxonomy === "attribute_terms") {
1621
+ if (attributeId === void 0) refuse("attribute_terms needs attribute_id (from list_terms attributes).");
1622
+ return `/products/attributes/${attributeId}/terms`;
1623
+ }
1624
+ if (attributeId !== void 0) refuse("attribute_id is for attribute_terms only.");
1625
+ return TERM_ROUTES[taxonomy];
1626
+ }
1627
+ var LIST_TERMS_SCHEMA = {
1628
+ type: "object",
1629
+ properties: {
1630
+ taxonomy: {
1631
+ type: "string",
1632
+ enum: ["categories", "tags", "attributes", "attribute_terms", "shipping_classes"],
1633
+ default: "categories",
1634
+ description: "attributes: global product attributes; attribute_terms: an attribute's values."
1635
+ },
1636
+ attribute_id: { type: "integer", minimum: 1, description: "For attribute_terms." },
1637
+ search: { type: "string", minLength: 1, maxLength: 200, description: "Part of the name." },
1638
+ slug: { type: "string", pattern: "^[A-Za-z0-9%_-]{1,200}$" },
1639
+ parent: { type: "integer", minimum: 0, description: "Categories: children of this id (0: top level)." },
1640
+ hide_empty: { type: "boolean", default: false },
1641
+ per_page: PER_PAGE(100),
1642
+ cursor: CURSOR_SCHEMA
1643
+ },
1644
+ additionalProperties: false
1645
+ };
1646
+ var REPORT_ROUTES = {
1647
+ sales: "/reports/sales",
1648
+ top_sellers: "/reports/top_sellers",
1649
+ orders_totals: "/reports/orders/totals",
1650
+ products_totals: "/reports/products/totals",
1651
+ customers_totals: "/reports/customers/totals",
1652
+ coupons_totals: "/reports/coupons/totals",
1653
+ reviews_totals: "/reports/reviews/totals"
1654
+ };
1655
+ var BLOCKED_WRITES = {
1656
+ webhooks: "Webhooks cannot be created or changed through this connector.",
1657
+ system_status: "System status tools cannot be run through this connector."
1658
+ };
1659
+ function storeGuard(request) {
1660
+ for (const key of Object.keys(request.query)) {
1661
+ if (/^(?:_method|rest_route)/i.test(phpFieldName(key))) {
1662
+ refuse(`The query parameter ${JSON.stringify(key)} is not allowed: WordPress would read it as _method or rest_route, which change a request's method or route. Give the route as the path and the method as method.`);
1663
+ }
1664
+ }
1665
+ if (request.segments.some((segment) => /[/\\]/.test(segment))) {
1666
+ refuse("A path segment must not hold an encoded slash or backslash (%2F, %5C): give each part of the route as its own segment.");
1667
+ }
1668
+ const [namespace, version, resource] = request.segments.map((segment) => segment.toLowerCase());
1669
+ if (namespace === "wc-analytics") {
1670
+ if (request.method !== "GET") refuse("The /wc-analytics/ reports are read-only here.");
1671
+ return;
1672
+ }
1673
+ if (namespace !== "wc" || version !== "v3") refuse("The path must start with /wc/v3/ (or /wc-analytics/ for reports).");
1674
+ if (resource === "payment_gateways") refuse("Payment gateways cannot be read or changed through this connector: their settings hold the store's payment credentials.");
1675
+ if (request.method !== "GET" && resource && Object.hasOwn(BLOCKED_WRITES, resource)) refuse(BLOCKED_WRITES[resource]);
1676
+ }
1677
+ async function findTerm(h, route, name2, slug, parent) {
1678
+ const query = slug ? { slug, per_page: 10 } : { search: termSearch(name2), per_page: 100 };
1679
+ const { data } = await wc(h, route, { query: { ...query, parent } });
1680
+ const terms = Array.isArray(data) ? data : [];
1681
+ const wanted = termKey(name2);
1682
+ return terms.find((term) => (parent === void 0 || Number(term?.parent ?? 0) === parent) && (slug !== void 0 && term?.slug === slug || termKey(String(term?.name ?? "")) === wanted));
1683
+ }
1684
+ var connector = defineConnector({
1685
+ vendor: "woocommerce",
1686
+ label: "WooCommerce",
1687
+ origins: [],
1688
+ originFields: ["storeurl"],
1689
+ credentials: ["storeurl", "consumerkey", "consumersecret"],
1690
+ credentialLabels: { storeurl: "WooCommerce store URL", consumerkey: "WooCommerce consumer key", consumersecret: "WooCommerce consumer secret" },
1691
+ authHeaders: (credentials) => ({ authorization: basicAuth(credentials["consumerkey"] ?? "", credentials["consumersecret"] ?? "") }),
1692
+ tools: [
1693
+ {
1694
+ name: "list_products",
1695
+ kind: "read",
1696
+ title: "List WooCommerce products",
1697
+ description: "Lists the store's products, newest first by default: id, name, type, status, SKU, prices, sale, stock, number of variations, categories, sales count and link. Filters: search words, exact SKU, status, type, category, tag, stock status, sale. Pass nextCursor back as cursor for more. Use it to check the connection.",
1698
+ inputSchema: LIST_PRODUCTS_SCHEMA,
1699
+ async run(args, h) {
1700
+ const position = listPosition(h, LIST_PRODUCTS_SCHEMA, args);
1701
+ const f = position.filters;
1702
+ const perPage = Number(f["per_page"] ?? 20);
1703
+ const response = await wc(h, "/products", {
1704
+ query: {
1705
+ _fields: "id,name,type,status,sku,price,regular_price,sale_price,on_sale,stock_status,manage_stock,stock_quantity,variations,categories,featured,total_sales,permalink,date_modified",
1706
+ search: f["search"],
1707
+ sku: f["sku"],
1708
+ status: f["status"] ?? "any",
1709
+ type: f["type"],
1710
+ category: f["category"],
1711
+ tag: f["tag"],
1712
+ stock_status: f["stock_status"],
1713
+ on_sale: f["on_sale"],
1714
+ featured: f["featured"],
1715
+ orderby: f["orderby"] ?? "date",
1716
+ order: f["order"] ?? "desc",
1717
+ per_page: perPage,
1718
+ page: position.page
1719
+ }
1720
+ });
1721
+ const products = Array.isArray(response.data) ? response.data : [];
1722
+ return h.page({
1723
+ key: "products",
1724
+ items: products.map(trimListProduct).slice(position.skip),
1725
+ extra: compact({ total: totalItems(response), page: position.page }),
1726
+ ...pageCursors(h, position, hasMore(response, position.page, products.length, perPage))
1727
+ });
1728
+ }
1729
+ },
1730
+ {
1731
+ name: "get_product",
1732
+ kind: "read",
1733
+ title: "Get a WooCommerce product",
1734
+ description: "One product with everything needed to edit it: prices, stock (and who manages it), description, images, categories, tags, attributes, shipping and tax fields, and for a variable product its variations with their attributes, prices and stock. Pass nextCursor back as cursor, with the same id, for more variations.",
1735
+ inputSchema: {
1736
+ type: "object",
1737
+ properties: {
1738
+ id: { type: "integer", minimum: 1, description: "The product id." },
1739
+ include_variations: { type: "boolean", default: true, description: "For a variable product, list its variations too (default true)." },
1740
+ cursor: CURSOR_SCHEMA
1741
+ },
1742
+ required: ["id"],
1743
+ additionalProperties: false
1744
+ },
1745
+ async run(args, h) {
1746
+ const state = h.cursor(args.cursor);
1747
+ const page = typeof state?.["p"] === "number" && state["p"] >= 1 ? state["p"] : 1;
1748
+ const skip = typeof state?.["o"] === "number" && state["o"] >= 0 ? state["o"] : 0;
1749
+ const { data: product } = await wc(h, `/products/${args.id}`);
1750
+ const result2 = trimProduct(product);
1751
+ if (product?.type !== "variable" || !args.include_variations) return result2;
1752
+ const response = await wc(h, `/products/${args.id}/variations`, { query: { per_page: 100, page } });
1753
+ const variations = Array.isArray(response.data) ? response.data : [];
1754
+ return h.page({
1755
+ key: "variations",
1756
+ items: variations.map(trimVariation).slice(skip),
1757
+ extra: result2,
1758
+ resumeAt: (index) => h.makeCursor({ p: page, o: skip + index }),
1759
+ ...hasMore(response, page, variations.length, 100) ? { nextPage: h.makeCursor({ p: page + 1, o: 0 }) } : {}
1760
+ });
1761
+ }
1762
+ },
1763
+ {
1764
+ name: "create_product",
1765
+ kind: "create",
1766
+ check: "list_products",
1767
+ title: "Create a WooCommerce product",
1768
+ description: "Creates a product, as a draft unless status says otherwise (publish puts it on sale). Images come from public URLs (WooCommerce downloads them). For a variable product, give attributes with variation: true and the variations to create with it; they are created right after the product, and the result says if any failed. WooCommerce refuses an SKU another product has.",
1769
+ inputSchema: {
1770
+ type: "object",
1771
+ properties: {
1772
+ ...PRODUCT_FIELDS,
1773
+ type: { type: "string", enum: ["simple", "variable", "grouped", "external"], default: "simple" },
1774
+ status: { ...PRODUCT_STATUS, default: "draft" },
1775
+ ...SHARED_FIELDS,
1776
+ attributes: { type: "array", items: ATTRIBUTE, maxItems: 50, description: "For a variable product, those with variation: true." },
1777
+ variations: { type: "array", items: NEW_VARIATION, maxItems: 100, description: "Variable products: the variations to create with it." },
1778
+ more_fields: MORE_FIELDS
1779
+ },
1780
+ required: ["name"],
1781
+ additionalProperties: false
1782
+ },
1783
+ async run(args, h) {
1784
+ const variations = args["variations"];
1785
+ if (variations?.length && args["type"] !== "variable") refuse("variations are for type variable only.");
1786
+ const { data: product } = await wc(h, "/products", { method: "POST", json: withTermObjects(productBody(args, ["variations"], CREATE_KEYS)), write: true });
1787
+ const result2 = trimProduct(product);
1788
+ if (!variations?.length) return result2;
1789
+ const id = product?.id;
1790
+ if (typeof id !== "number") throw new ToolFailure("WooCommerce answered without the new product's id, so its variations were not sent. Look for the product with list_products.");
1791
+ let batch;
1792
+ try {
1793
+ ({ data: batch } = await wc(h, `/products/${id}/variations/batch`, { method: "POST", json: { create: variations }, write: true }));
1794
+ } catch (error) {
1795
+ const made = `WooCommerce created the product (id ${id}, status ${String(product?.status)})`;
1796
+ if (error instanceof OutcomeUnknown) throw new OutcomeUnknown(`${made}, but its variations got no clear answer (${cause(error)}).`);
1797
+ if (error instanceof ToolFailure) {
1798
+ throw new ToolFailure(
1799
+ `${made}, but not its variations: ${cause(error)}. Add them with api_request (POST /wc/v3/products/${id}/variations/batch).`,
1800
+ error.details
1801
+ );
1802
+ }
1803
+ throw error;
1804
+ }
1805
+ const created = Array.isArray(batch?.create) ? batch.create : [];
1806
+ const failed = created.map((item, index) => ({ index, item })).filter(({ item }) => item?.error).map(({ index, item }) => `variation ${index + 1}: ${String(item.error?.message ?? item.error?.code ?? "refused")}`);
1807
+ return compact({
1808
+ ...result2,
1809
+ variations: created.filter((item) => !item?.error).map(trimVariation),
1810
+ variation_errors: failed.length ? failed : void 0
1811
+ });
1812
+ }
1813
+ },
1814
+ {
1815
+ name: "update_product",
1816
+ kind: "update",
1817
+ check: "get_product",
1818
+ title: "Update a WooCommerce product or variation",
1819
+ description: "Changes a product, or one of its variations with variation_id: prices, sale, stock, status (publish puts it on sale), text, images, categories and the rest. Only the fields given change. With expected_stock_quantity, the current stock is read first and nothing changes if it moved. Stock is changed where it is managed: a variation whose stock its parent manages is refused.",
1820
+ inputSchema: {
1821
+ type: "object",
1822
+ properties: {
1823
+ id: { type: "integer", minimum: 1, description: "The product id." },
1824
+ variation_id: { type: "integer", minimum: 1, description: "Change this variation of the product instead." },
1825
+ expected_stock_quantity: { type: "integer", description: "The stock read before deciding; nothing is sent if it changed." },
1826
+ ...PRODUCT_FIELDS,
1827
+ status: PRODUCT_STATUS,
1828
+ ...SHARED_FIELDS,
1829
+ image: { ...IMAGE, description: "Variations only." },
1830
+ more_fields: MORE_FIELDS
1831
+ },
1832
+ required: ["id"],
1833
+ additionalProperties: false
1834
+ },
1835
+ async run(args, h) {
1836
+ const variationId = args["variation_id"];
1837
+ const route = variationId !== void 0 ? `/products/${args["id"]}/variations/${variationId}` : `/products/${args["id"]}`;
1838
+ if (variationId !== void 0) {
1839
+ const productOnly = Object.keys(PRODUCT_FIELDS).filter((key) => args[key] !== void 0);
1840
+ if (productOnly.length) refuse(`${productOnly.join(", ")} ${productOnly.length > 1 ? "are" : "is"} for the product, not a variation.`);
1841
+ if (args["status"] !== void 0 && !["publish", "private"].includes(args["status"])) refuse("A variation's status is publish or private.");
1842
+ } else if (args["image"] !== void 0) {
1843
+ refuse("image is for variations: a product takes images.");
1844
+ }
1845
+ const body = withTermObjects(productBody(args, ["id", "variation_id", "expected_stock_quantity"], UPDATE_KEYS));
1846
+ if (!Object.keys(body).length) refuse("Nothing to change: give at least one field besides id.");
1847
+ let previous;
1848
+ if (args["stock_quantity"] !== void 0 || args["expected_stock_quantity"] !== void 0) {
1849
+ ({ data: previous } = await wc(h, route));
1850
+ const current = previous?.stock_quantity ?? null;
1851
+ if (args["expected_stock_quantity"] !== void 0 && current !== args["expected_stock_quantity"]) {
1852
+ refuse(`The stock is ${current === null ? "not tracked" : current} now, not ${args["expected_stock_quantity"]}: it changed since it was read. Read it again and decide again.`);
1853
+ }
1854
+ if (args["stock_quantity"] !== void 0 && args["manage_stock"] === void 0) {
1855
+ if (previous?.manage_stock === "parent") refuse("This variation's stock is managed by its parent product: change the stock on the product (without variation_id), or pass manage_stock: true to manage it on the variation from now on.");
1856
+ if (previous?.manage_stock === false) refuse("This item does not track stock: pass manage_stock: true with stock_quantity to start tracking it.");
1857
+ }
1858
+ }
1859
+ const { data } = await wc(h, route, { method: "PUT", json: body, write: true });
1860
+ const trimmed2 = variationId !== void 0 ? trimVariation(data) : trimProduct(data);
1861
+ return compact({ ...trimmed2, previous_stock_quantity: previous !== void 0 ? previous?.stock_quantity ?? null : void 0 });
1862
+ }
1863
+ },
1864
+ {
1865
+ name: "list_orders",
1866
+ kind: "read",
1867
+ title: "List WooCommerce orders",
1868
+ description: "Lists orders, newest first: number, status, dates, total, currency, customer id, payment method, the items with quantities and refunds. Filters: statuses, customer, product, dates, search words. No addresses or contact details (get_order has them on request). Pass nextCursor back as cursor for more.",
1869
+ inputSchema: LIST_ORDERS_SCHEMA,
1870
+ async run(args, h) {
1871
+ const position = listPosition(h, LIST_ORDERS_SCHEMA, args);
1872
+ const f = position.filters;
1873
+ const perPage = Number(f["per_page"] ?? 20);
1874
+ const response = await wc(h, "/orders", {
1875
+ query: {
1876
+ _fields: "id,number,status,currency,date_created,date_paid,date_completed,total,customer_id,payment_method_title,line_items,refunds",
1877
+ status: Array.isArray(f["status"]) ? f["status"].join(",") : void 0,
1878
+ customer: f["customer"],
1879
+ product: f["product"],
1880
+ search: f["search"],
1881
+ after: orderDate(f["after"], false),
1882
+ before: orderDate(f["before"], true),
1883
+ orderby: f["orderby"] ?? "date",
1884
+ order: f["order"] ?? "desc",
1885
+ per_page: perPage,
1886
+ page: position.page
1887
+ }
1888
+ });
1889
+ const orders = Array.isArray(response.data) ? response.data : [];
1890
+ return h.page({
1891
+ key: "orders",
1892
+ items: orders.map(trimListOrder).slice(position.skip),
1893
+ extra: compact({ total: totalItems(response), page: position.page }),
1894
+ ...pageCursors(h, position, hasMore(response, position.page, orders.length, perPage))
1895
+ });
1896
+ }
1897
+ },
1898
+ {
1899
+ name: "get_order",
1900
+ kind: "read",
1901
+ title: "Get a WooCommerce order",
1902
+ description: "One order with its line items (ids for refunds), shipping, fees, coupons, totals, payment method and refunds; with include_notes its notes, and with include_customer_details the billing and shipping names, addresses, email and phone.",
1903
+ inputSchema: {
1904
+ type: "object",
1905
+ properties: {
1906
+ id: { type: "integer", minimum: 1, description: "The order id." },
1907
+ include_notes: { type: "boolean", default: false, description: "Add the order notes." },
1908
+ include_customer_details: { type: "boolean", default: false, description: "Add billing and shipping addresses, email and phone." }
1909
+ },
1910
+ required: ["id"],
1911
+ additionalProperties: false
1912
+ },
1913
+ async run(args, h) {
1914
+ const { data: order } = await wc(h, `/orders/${args.id}`);
1915
+ const result2 = trimOrder(order, args.include_customer_details);
1916
+ if (!args.include_notes) return result2;
1917
+ const { data: notes } = await wc(h, `/orders/${args.id}/notes`);
1918
+ return compact({
1919
+ ...result2,
1920
+ notes: (Array.isArray(notes) ? notes : []).slice(0, 30).map((note) => compact({
1921
+ id: note?.id,
1922
+ date_created: note?.date_created,
1923
+ author: note?.author,
1924
+ note: plainText(note?.note, 400),
1925
+ customer_note: note?.customer_note === true ? true : void 0
1926
+ }))
1927
+ });
1928
+ }
1929
+ },
1930
+ {
1931
+ name: "update_order",
1932
+ kind: "update",
1933
+ check: "get_order",
1934
+ title: "Update a WooCommerce order",
1935
+ description: "Changes an order's status (processing, on-hold, completed, cancelled, ...), customer note, or billing and shipping details. Only the fields given change. WooCommerce may email the customer on a status change (completed, for example) and restocks items of a cancelled order. Refunds go through create_refund.",
1936
+ inputSchema: {
1937
+ type: "object",
1938
+ properties: {
1939
+ id: { type: "integer", minimum: 1, description: "The order id." },
1940
+ status: { type: "string", enum: ["pending", "processing", "on-hold", "completed", "cancelled", "failed"], description: "The new status." },
1941
+ customer_note: { type: "string", maxLength: 5e3, description: "The note the customer left at checkout." },
1942
+ billing: { type: "object", description: "Billing fields to change: first_name, last_name, company, address_1, address_2, city, state, postcode, country, email, phone." },
1943
+ shipping: { type: "object", description: "Shipping fields to change: first_name, last_name, company, address_1, address_2, city, state, postcode, country, phone." },
1944
+ transaction_id: { type: "string", maxLength: 200, description: "The payment's transaction id." }
1945
+ },
1946
+ required: ["id"],
1947
+ additionalProperties: false
1948
+ },
1949
+ async run(args, h) {
1950
+ const body = productBody(args, ["id"]);
1951
+ if (!Object.keys(body).length) refuse("Nothing to change: give at least one field besides id.");
1952
+ const { data } = await wc(h, `/orders/${args["id"]}`, { method: "PUT", json: body, write: true });
1953
+ return trimOrder(data, false);
1954
+ }
1955
+ },
1956
+ {
1957
+ name: "add_order_note",
1958
+ kind: "create",
1959
+ check: "get_order",
1960
+ title: "Add a note to a WooCommerce order",
1961
+ description: "Adds a note to an order. A private note (default) is for the store's staff; with customer_note: true WooCommerce emails it to the customer as well.",
1962
+ inputSchema: {
1963
+ type: "object",
1964
+ properties: {
1965
+ id: { type: "integer", minimum: 1, description: "The order id." },
1966
+ note: { type: "string", minLength: 1, maxLength: 5e3, description: "The note." },
1967
+ customer_note: { type: "boolean", default: false, description: "true emails the note to the customer." }
1968
+ },
1969
+ required: ["id", "note"],
1970
+ additionalProperties: false
1971
+ },
1972
+ async run(args, h) {
1973
+ const { data } = await wc(h, `/orders/${args.id}/notes`, { method: "POST", json: { note: args.note, customer_note: args.customer_note }, write: true });
1974
+ return compact({ id: data?.id, order_id: args.id, date_created: data?.date_created, customer_note: data?.customer_note === true, note: plainText(data?.note, 1e3) });
1975
+ }
1976
+ },
1977
+ {
1978
+ // A write, not a create: with refund_payment it sends money back through the gateway, which cannot be undone.
1979
+ name: "create_refund",
1980
+ kind: "write",
1981
+ check: "get_order",
1982
+ title: "Refund a WooCommerce order",
1983
+ description: "Records a refund on an order: an amount, a reason, and optionally which line items (ids from get_order) and quantities. By default it only records the refund; refund_payment: true also sends the money back through the payment gateway, and restock_items: true puts the refunded items back in stock. A refund cannot be undone. Not retried: after an unclear outcome, look at the order's refunds with get_order before trying again.",
1984
+ inputSchema: {
1985
+ type: "object",
1986
+ properties: {
1987
+ order_id: { type: "integer", minimum: 1, description: "The order id." },
1988
+ amount: PRICE('E.g. "12.50"; at most what is left to refund.'),
1989
+ reason: { type: "string", maxLength: 1e3, description: "Shown on the order." },
1990
+ line_items: {
1991
+ type: "array",
1992
+ maxItems: 100,
1993
+ description: "The refunded line items (ids from get_order).",
1994
+ items: {
1995
+ type: "object",
1996
+ properties: {
1997
+ id: { type: "integer", minimum: 1 },
1998
+ quantity: { type: "integer", minimum: 1 },
1999
+ refund_total: PRICE("Amount before tax."),
2000
+ refund_tax: {
2001
+ type: "array",
2002
+ maxItems: 20,
2003
+ items: {
2004
+ type: "object",
2005
+ properties: { id: { type: "integer", minimum: 1, description: "Tax rate id." }, refund_total: PRICE("Tax refunded.") },
2006
+ required: ["id", "refund_total"],
2007
+ additionalProperties: false
2008
+ }
2009
+ }
2010
+ },
2011
+ required: ["id"],
2012
+ additionalProperties: false
2013
+ }
2014
+ },
2015
+ refund_payment: { type: "boolean", default: false, description: "Also refund through the payment gateway (default: record only)." },
2016
+ restock_items: { type: "boolean", default: false, description: "Put the refunded items back in stock." }
2017
+ },
2018
+ required: ["order_id", "amount"],
2019
+ additionalProperties: false
2020
+ },
2021
+ async run(args, h) {
2022
+ const { data } = await wc(h, `/orders/${args.order_id}/refunds`, {
2023
+ method: "POST",
2024
+ json: compact({
2025
+ amount: args.amount,
2026
+ reason: args.reason,
2027
+ line_items: args.line_items,
2028
+ api_refund: args.refund_payment,
2029
+ api_restock: args.restock_items
2030
+ }),
2031
+ write: true
2032
+ });
2033
+ return compact({
2034
+ id: data?.id,
2035
+ order_id: args.order_id,
2036
+ amount: data?.amount,
2037
+ reason: data?.reason,
2038
+ date_created: data?.date_created,
2039
+ refunded_payment: data?.refunded_payment ?? args.refund_payment,
2040
+ restocked: args.restock_items,
2041
+ line_items: Array.isArray(data?.line_items) && data.line_items.length ? data.line_items.map(trimLineItem) : void 0
2042
+ });
2043
+ }
2044
+ },
2045
+ {
2046
+ name: "list_coupons",
2047
+ kind: "read",
2048
+ title: "List WooCommerce coupons",
2049
+ description: "Lists coupons with their code, discount type and amount, expiry, usage and limits, and restrictions. Look up an exact code before creating one. Pass nextCursor back as cursor for more.",
2050
+ inputSchema: LIST_COUPONS_SCHEMA,
2051
+ async run(args, h) {
2052
+ const position = listPosition(h, LIST_COUPONS_SCHEMA, args);
2053
+ const f = position.filters;
2054
+ const perPage = Number(f["per_page"] ?? 20);
2055
+ const response = await wc(h, "/coupons", {
2056
+ query: { code: f["code"], search: f["search"], orderby: f["orderby"] ?? "date", order: f["order"] ?? "desc", per_page: perPage, page: position.page }
2057
+ });
2058
+ const coupons = Array.isArray(response.data) ? response.data : [];
2059
+ return h.page({
2060
+ key: "coupons",
2061
+ items: coupons.map(trimCoupon).slice(position.skip),
2062
+ extra: compact({ total: totalItems(response), page: position.page }),
2063
+ ...pageCursors(h, position, hasMore(response, position.page, coupons.length, perPage))
2064
+ });
2065
+ }
2066
+ },
2067
+ {
2068
+ name: "create_coupon",
2069
+ kind: "create",
2070
+ check: "list_coupons",
2071
+ title: "Create a WooCommerce coupon",
2072
+ description: "Creates a coupon: its code, a percent, fixed cart or fixed product discount, and optional expiry, usage limits, minimum and maximum spend, products, categories and allowed emails. It works as soon as it is created. WooCommerce refuses a code that exists already.",
2073
+ inputSchema: {
2074
+ type: "object",
2075
+ properties: {
2076
+ code: { type: "string", minLength: 1, maxLength: 100, description: "What customers enter (stored in lower case)." },
2077
+ discount_type: { type: "string", enum: ["percent", "fixed_cart", "fixed_product"], description: "fixed_cart: an amount off the cart; fixed_product: off each product." },
2078
+ amount: PRICE("A percentage for percent, an amount otherwise."),
2079
+ description: { type: "string", maxLength: 1e3, description: "A note for the staff." },
2080
+ date_expires: { ...DATE, description: "The day it expires." },
2081
+ individual_use: { type: "boolean", description: "Not combinable with other coupons." },
2082
+ usage_limit: { type: "integer", minimum: 1, description: "Uses in all." },
2083
+ usage_limit_per_user: { type: "integer", minimum: 1 },
2084
+ limit_usage_to_x_items: { type: "integer", minimum: 1 },
2085
+ free_shipping: { type: "boolean" },
2086
+ exclude_sale_items: { type: "boolean" },
2087
+ minimum_amount: PRICE("Smallest order subtotal."),
2088
+ maximum_amount: PRICE("Largest order subtotal."),
2089
+ product_ids: ID_LIST("Only these products."),
2090
+ excluded_product_ids: ID_LIST("Not these products."),
2091
+ product_categories: ID_LIST("Only these category ids."),
2092
+ excluded_product_categories: ID_LIST("Not these category ids."),
2093
+ email_restrictions: { type: "array", items: { type: "string", minLength: 3, maxLength: 200 }, maxItems: 100, description: "Allowed billing emails (* wildcards)." }
2094
+ },
2095
+ required: ["code", "discount_type", "amount"],
2096
+ additionalProperties: false
2097
+ },
2098
+ async run(args, h) {
2099
+ const { data } = await wc(h, "/coupons", { method: "POST", json: productBody(args, []), write: true });
2100
+ return trimCoupon(data);
2101
+ }
2102
+ },
2103
+ {
2104
+ name: "list_customers",
2105
+ kind: "read",
2106
+ title: "List WooCommerce customers",
2107
+ description: "Lists customers (store users) with id, email, name, user name, role and whether they have paid for an order. Look up an exact email before creating a customer. Pass nextCursor back as cursor for more.",
2108
+ inputSchema: LIST_CUSTOMERS_SCHEMA,
2109
+ async run(args, h) {
2110
+ const position = listPosition(h, LIST_CUSTOMERS_SCHEMA, args);
2111
+ const f = position.filters;
2112
+ const perPage = Number(f["per_page"] ?? 20);
2113
+ const response = await wc(h, "/customers", {
2114
+ query: { search: f["search"], email: f["email"], role: f["role"] ?? "customer", orderby: f["orderby"] ?? "registered_date", order: f["order"] ?? "desc", per_page: perPage, page: position.page }
2115
+ });
2116
+ const customers = Array.isArray(response.data) ? response.data : [];
2117
+ return h.page({
2118
+ key: "customers",
2119
+ items: customers.map(trimCustomer).slice(position.skip),
2120
+ extra: compact({ total: totalItems(response), page: position.page }),
2121
+ ...pageCursors(h, position, hasMore(response, position.page, customers.length, perPage))
2122
+ });
2123
+ }
2124
+ },
2125
+ {
2126
+ name: "get_report",
2127
+ kind: "read",
2128
+ title: "Get a WooCommerce report",
2129
+ description: "A store report: sales (totals for a period with a line per day or month: sales, orders, items, tax, shipping, refunds, discounts), top_sellers (best-selling products), or the counts of orders, products, customers, coupons and reviews by status or type. Sales and top sellers take a period or a date range. Pass nextCursor back as cursor for more lines.",
2130
+ inputSchema: {
2131
+ type: "object",
2132
+ properties: {
2133
+ report: {
2134
+ type: "string",
2135
+ enum: Object.keys(REPORT_ROUTES),
2136
+ description: "sales, top_sellers, orders_totals, products_totals, customers_totals, coupons_totals or reviews_totals."
2137
+ },
2138
+ period: { type: "string", enum: ["week", "month", "last_month", "year"], description: "sales and top_sellers: the period (default this week)." },
2139
+ date_min: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "sales and top_sellers: the first day, 2026-11-01." },
2140
+ date_max: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "sales and top_sellers: the last day." },
2141
+ cursor: CURSOR_SCHEMA
2142
+ },
2143
+ required: ["report"],
2144
+ additionalProperties: false
2145
+ },
2146
+ async run(args, h) {
2147
+ const state = h.cursor(args.cursor);
2148
+ const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
2149
+ const dated = args.report === "sales" || args.report === "top_sellers";
2150
+ if (!dated && (args.period || args.date_min || args.date_max)) refuse(`${args.report} takes no period or dates.`);
2151
+ if (args.period && (args.date_min || args.date_max)) refuse("Give period or date_min and date_max, not both.");
2152
+ const { data } = await wc(h, REPORT_ROUTES[args.report], {
2153
+ query: dated ? { period: args.period, date_min: args.date_min, date_max: args.date_max } : {}
2154
+ });
2155
+ const rows = Array.isArray(data) ? data : [];
2156
+ const resumeAt = (index) => h.makeCursor({ o: skip + index });
2157
+ if (args.report === "sales") {
2158
+ const { totals, ...summary } = rows[0] ?? {};
2159
+ const lines = Object.entries(typeof totals === "object" && totals !== null ? totals : {}).map(([date, values]) => compact({
2160
+ date,
2161
+ sales: values?.sales,
2162
+ orders: values?.orders,
2163
+ items: values?.items,
2164
+ tax: money(values?.tax),
2165
+ shipping: money(values?.shipping),
2166
+ discount: money(values?.discount),
2167
+ customers: values?.customers || void 0
2168
+ }));
2169
+ return h.page({ key: "totals", items: lines.slice(skip), extra: { report: "sales", summary }, resumeAt });
2170
+ }
2171
+ if (args.report === "top_sellers") {
2172
+ const sellers = rows.map((row) => compact({ product_id: row?.product_id, title: row?.title ?? row?.name, quantity: row?.quantity }));
2173
+ return h.page({ key: "top_sellers", items: sellers.slice(skip), extra: { report: "top_sellers" }, resumeAt });
2174
+ }
2175
+ const counts = rows.map((row) => compact({ slug: row?.slug, name: row?.name, total: row?.total }));
2176
+ return h.page({ key: "counts", items: counts.slice(skip), extra: { report: args.report }, resumeAt });
2177
+ }
2178
+ },
2179
+ {
2180
+ name: "list_terms",
2181
+ kind: "read",
2182
+ title: "List WooCommerce categories, tags, attributes or shipping classes",
2183
+ description: "Lists product categories, tags, global attributes, an attribute's values (attribute_terms with attribute_id) or shipping classes, with ids, names, slugs and product counts. Look up a slug or name before creating a term. Pass nextCursor back as cursor for more.",
2184
+ inputSchema: LIST_TERMS_SCHEMA,
2185
+ async run(args, h) {
2186
+ const position = listPosition(h, LIST_TERMS_SCHEMA, args);
2187
+ const f = position.filters;
2188
+ const taxonomy = String(f["taxonomy"] ?? "categories");
2189
+ const route = termRoute(taxonomy, f["attribute_id"]);
2190
+ if (taxonomy !== "categories" && f["parent"] !== void 0) refuse("parent is for categories only.");
2191
+ const paged = taxonomy !== "attributes";
2192
+ const perPage = Number(f["per_page"] ?? 100);
2193
+ const response = await wc(h, route, {
2194
+ query: paged ? { search: f["search"], slug: f["slug"], parent: f["parent"], hide_empty: f["hide_empty"] ? true : void 0, per_page: perPage, page: position.page } : {}
2195
+ });
2196
+ const terms = Array.isArray(response.data) ? response.data : [];
2197
+ return h.page({
2198
+ key: taxonomy,
2199
+ items: terms.map(trimTerm).slice(position.skip),
2200
+ extra: compact({ total: totalItems(response), page: paged ? position.page : void 0 }),
2201
+ ...pageCursors(h, position, paged && hasMore(response, position.page, terms.length, perPage))
2202
+ });
2203
+ }
2204
+ },
2205
+ {
2206
+ name: "create_term",
2207
+ kind: "create",
2208
+ check: "list_terms",
2209
+ title: "Create a WooCommerce category, tag, attribute value or shipping class",
2210
+ description: "Creates a product category, tag, attribute value (attribute_terms with attribute_id) or shipping class, and returns its id. When one with that name or slug already exists, this returns it with existing: true instead of making a second.",
2211
+ inputSchema: {
2212
+ type: "object",
2213
+ properties: {
2214
+ taxonomy: { type: "string", enum: ["categories", "tags", "attribute_terms", "shipping_classes"], description: "categories, tags, attribute_terms or shipping_classes." },
2215
+ attribute_id: { type: "integer", minimum: 1, description: "For attribute_terms: the attribute id." },
2216
+ name: { type: "string", minLength: 1, maxLength: 200, description: "The name." },
2217
+ slug: { type: "string", pattern: "^[A-Za-z0-9%_-]{1,200}$", description: "The slug (default: made from the name)." },
2218
+ parent: { type: "integer", minimum: 0, description: "Categories only: the parent category id." },
2219
+ description: { type: "string", maxLength: 2e3, description: "A description." }
2220
+ },
2221
+ required: ["taxonomy", "name"],
2222
+ additionalProperties: false
2223
+ },
2224
+ async run(args, h) {
2225
+ const route = termRoute(args.taxonomy, args.attribute_id);
2226
+ if (args.taxonomy !== "categories" && args.parent !== void 0) refuse("parent is for categories only.");
2227
+ try {
2228
+ const { data } = await wc(h, route, { method: "POST", json: compact({ name: args.name, slug: args.slug, parent: args.parent, description: args.description }), write: true });
2229
+ return { ...trimTerm(data), existing: false };
2230
+ } catch (error) {
2231
+ if (!(error instanceof ToolFailure) || error.details.vendorCode !== "term_exists") throw error;
2232
+ }
2233
+ const existing = await findTerm(h, route, args.name, args.slug, args.taxonomy === "categories" ? args.parent ?? 0 : void 0);
2234
+ if (!existing) throw new ToolFailure("WooCommerce says this term already exists, but it was not found by name: look for it with list_terms. Nothing was changed.");
2235
+ return { ...trimTerm(existing), existing: true };
2236
+ }
2237
+ },
2238
+ // The rest of the WooCommerce REST API v3: customers, variations, batches, settings, shipping, taxes, deletions.
2239
+ ...apiTools({
2240
+ label: "WooCommerce",
2241
+ description: "The WooCommerce REST API v3 of the connected store: paths start with /wc/v3/, such as /wc/v3/customers/12, /wc/v3/products/34/variations/batch or /wc/v3/settings/general (GET also reads /wc-analytics/ reports); bodies are JSON (json, or body with a JSON content_type). DELETE moves products, orders and coupons to the trash; force=true deletes for good (needed for customers, terms and others without a trash). Webhooks, payment gateways and system status tools are out of reach, and password-type setting values are left out of replies. Reference: https://woocommerce.github.io/woocommerce-rest-api-docs/.",
2242
+ guard: storeGuard,
2243
+ send: async (request, h) => {
2244
+ if (!isJsonBody(request)) {
2245
+ refuse("The body must be JSON: give it as json, or as body with a JSON content_type. A form body is refused, since WordPress could read a route from it.");
2246
+ }
2247
+ try {
2248
+ const response = await h.api({ ...request, origin: h.originOf("storeurl"), path: restPath(h, request.path) });
2249
+ return { ...response, data: withoutSecrets(response.data) };
2250
+ } catch (error) {
2251
+ throw withHint(error);
2252
+ }
2253
+ },
2254
+ responseHeaders: ["x-wp-total", "x-wp-totalpages"]
2255
+ })
2256
+ ]
2257
+ });
2258
+ module.exports = connector;