@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.
- package/CHANGELOG.md +29 -0
- package/README.md +1131 -34
- package/dist/cli.js +15 -12
- package/dist/core/credentials.d.ts +21 -0
- package/dist/core/credentials.js +45 -0
- package/dist/core/origins.d.ts +18 -0
- package/dist/core/origins.js +40 -0
- package/dist/core/upload-hosts.d.ts +15 -0
- package/dist/core/upload-hosts.js +43 -0
- package/dist/host/describe.d.ts +10 -0
- package/dist/host/describe.js +38 -0
- package/dist/host/env.d.ts +25 -2
- package/dist/host/env.js +24 -7
- package/dist/host/guarded-fetch.d.ts +36 -9
- package/dist/host/guarded-fetch.js +175 -52
- package/dist/host/index.d.ts +8 -5
- package/dist/host/index.js +12 -1
- package/dist/host/load.js +31 -1
- package/dist/host/server.d.ts +13 -2
- package/dist/host/server.js +15 -2
- package/dist/types.d.ts +96 -5
- package/dist/vendors/adapty.js +1303 -0
- package/dist/vendors/adjust.js +1372 -0
- package/dist/vendors/apollo.js +2499 -0
- package/dist/vendors/apple-appstore.js +2798 -0
- package/dist/vendors/beehiiv.js +1965 -0
- package/dist/vendors/blogger.js +1687 -0
- package/dist/vendors/bluesky.js +850 -127
- package/dist/vendors/brevo.js +2195 -0
- package/dist/vendors/calendarific.js +1116 -0
- package/dist/vendors/devto.js +685 -92
- package/dist/vendors/facebook-pages.js +2185 -0
- package/dist/vendors/firebase.js +1333 -0
- package/dist/vendors/ga4.js +1585 -0
- package/dist/vendors/gmail.js +1962 -0
- package/dist/vendors/google-ads.js +2201 -0
- package/dist/vendors/google-business.js +1621 -0
- package/dist/vendors/google-calendar.js +1936 -0
- package/dist/vendors/google-drive.js +2654 -0
- package/dist/vendors/google-merchant-center.js +1742 -0
- package/dist/vendors/google-play.js +1856 -0
- package/dist/vendors/google-search-console.js +1572 -0
- package/dist/vendors/hashnode.js +1722 -0
- package/dist/vendors/instagram.js +2249 -0
- package/dist/vendors/kaggle.js +2043 -0
- package/dist/vendors/keepa.js +2087 -0
- package/dist/vendors/linkedin.js +1588 -0
- package/dist/vendors/mailchimp.js +2402 -0
- package/dist/vendors/mastodon.js +1836 -0
- package/dist/vendors/meta-ads.js +2375 -0
- package/dist/vendors/notion.js +1950 -0
- package/dist/vendors/pinterest.js +1744 -0
- package/dist/vendors/qiita.js +1552 -0
- package/dist/vendors/reddit.js +1791 -0
- package/dist/vendors/revenuecat.js +1593 -0
- package/dist/vendors/roasit.js +1460 -0
- package/dist/vendors/sendgrid.js +2188 -0
- package/dist/vendors/serper.js +901 -179
- package/dist/vendors/shopify.js +2511 -0
- package/dist/vendors/threads.js +1869 -0
- package/dist/vendors/tiktok.js +2199 -0
- package/dist/vendors/tumblr.js +1793 -0
- package/dist/vendors/twitter.js +1650 -0
- package/dist/vendors/woocommerce.js +2258 -0
- package/dist/vendors/wordpress.js +1904 -0
- package/dist/vendors/youtube.js +2542 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1722 @@
|
|
|
1
|
+
/* hashnode connector module (MIT License). Built from src/vendors/hashnode; 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/text.ts
|
|
21
|
+
var encoder = new TextEncoder();
|
|
22
|
+
var decoder = new TextDecoder();
|
|
23
|
+
function utf8Bytes(text) {
|
|
24
|
+
return encoder.encode(text);
|
|
25
|
+
}
|
|
26
|
+
function utf8Length(text) {
|
|
27
|
+
return encoder.encode(text).length;
|
|
28
|
+
}
|
|
29
|
+
function utf8Decode(bytes) {
|
|
30
|
+
return decoder.decode(bytes);
|
|
31
|
+
}
|
|
32
|
+
function base64Encode(bytes) {
|
|
33
|
+
let binary = "";
|
|
34
|
+
for (let i = 0; i < bytes.length; i += 32768) {
|
|
35
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
36
|
+
}
|
|
37
|
+
return btoa(binary);
|
|
38
|
+
}
|
|
39
|
+
function base64UrlEncode(bytes) {
|
|
40
|
+
return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
41
|
+
}
|
|
42
|
+
function base64UrlDecode(text) {
|
|
43
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
|
|
44
|
+
const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
|
|
45
|
+
const binary = atob(padded);
|
|
46
|
+
const bytes = new Uint8Array(binary.length);
|
|
47
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
48
|
+
return bytes;
|
|
49
|
+
}
|
|
50
|
+
function truncate(text, max) {
|
|
51
|
+
if (text.length <= max) return text;
|
|
52
|
+
const points = Array.from(text);
|
|
53
|
+
if (points.length <= max) return text;
|
|
54
|
+
return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
|
|
55
|
+
}
|
|
56
|
+
function cleanVendorText(text, max = 300) {
|
|
57
|
+
if (typeof text !== "string") return void 0;
|
|
58
|
+
if (/^\s*</.test(text)) return void 0;
|
|
59
|
+
const line = text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
|
|
60
|
+
return line ? truncate(line, max) : void 0;
|
|
61
|
+
}
|
|
62
|
+
function formatNumber(value) {
|
|
63
|
+
return value.toLocaleString("en-US");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// src/core/output.ts
|
|
67
|
+
var OUTPUT_LIMIT_BYTES = 32 * 1024;
|
|
68
|
+
function jsonSize(value) {
|
|
69
|
+
return utf8Length(JSON.stringify(value) ?? "");
|
|
70
|
+
}
|
|
71
|
+
function cutStrings(value, max) {
|
|
72
|
+
if (typeof value === "string") return truncate(value, max);
|
|
73
|
+
if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
|
|
74
|
+
if (typeof value === "object" && value !== null) {
|
|
75
|
+
const out = {};
|
|
76
|
+
for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
|
|
82
|
+
if (jsonSize(value) <= limit) return { value, truncated: false };
|
|
83
|
+
for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
|
|
84
|
+
const cut = cutStrings(value, max);
|
|
85
|
+
if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
|
|
86
|
+
}
|
|
87
|
+
return void 0;
|
|
88
|
+
}
|
|
89
|
+
function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
|
|
90
|
+
const build = (count) => {
|
|
91
|
+
const cut = count < input.items.length;
|
|
92
|
+
const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
|
|
93
|
+
const next = cut ? input.resumeAt(count) : input.nextPage;
|
|
94
|
+
if (next) result2["nextCursor"] = next;
|
|
95
|
+
if (cut) result2["truncated"] = true;
|
|
96
|
+
return result2;
|
|
97
|
+
};
|
|
98
|
+
const all = build(input.items.length);
|
|
99
|
+
if (jsonSize(all) <= limit) return all;
|
|
100
|
+
let low = 1;
|
|
101
|
+
let high = input.items.length - 1;
|
|
102
|
+
while (low < high) {
|
|
103
|
+
const middle = Math.ceil((low + high) / 2);
|
|
104
|
+
if (jsonSize(build(middle)) <= limit) low = middle;
|
|
105
|
+
else high = middle - 1;
|
|
106
|
+
}
|
|
107
|
+
const best = build(low);
|
|
108
|
+
if (jsonSize(best) <= limit) return best;
|
|
109
|
+
const shrunk = shrinkToFit(best, limit);
|
|
110
|
+
if (shrunk) return { ...shrunk.value, truncated: true };
|
|
111
|
+
throw new ToolFailure("The result is too large to return, even one item at a time.");
|
|
112
|
+
}
|
|
113
|
+
function encodeCursor(tool, state) {
|
|
114
|
+
return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
|
|
115
|
+
}
|
|
116
|
+
function decodeCursor(tool, cursor) {
|
|
117
|
+
if (cursor === void 0 || cursor === "") return null;
|
|
118
|
+
try {
|
|
119
|
+
const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
|
|
120
|
+
if (typeof state === "object" && state !== null && state.t === tool) {
|
|
121
|
+
return state;
|
|
122
|
+
}
|
|
123
|
+
} catch {
|
|
124
|
+
}
|
|
125
|
+
throw new ToolFailure(
|
|
126
|
+
"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."
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// src/core/credentials.ts
|
|
131
|
+
function requiredAlternatives(module2) {
|
|
132
|
+
return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
|
|
133
|
+
}
|
|
134
|
+
function unmetAlternatives(alternatives, has) {
|
|
135
|
+
const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
|
|
136
|
+
if (lacking.some((list) => list.length === 0)) return [];
|
|
137
|
+
return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
|
|
138
|
+
}
|
|
139
|
+
function andList(items) {
|
|
140
|
+
if (items.length <= 2) return items.join(" and ");
|
|
141
|
+
return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
|
|
142
|
+
}
|
|
143
|
+
function orList(items) {
|
|
144
|
+
if (items.length <= 1) return items.join("");
|
|
145
|
+
return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/core/files.ts
|
|
149
|
+
var ATTACHMENT_URI = "attachment:///";
|
|
150
|
+
var MAX_NAME = 200;
|
|
151
|
+
function fileLimitOf(ctx) {
|
|
152
|
+
const maxBytes = ctx.files?.maxBytes;
|
|
153
|
+
return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
|
|
154
|
+
}
|
|
155
|
+
function fileName(name2) {
|
|
156
|
+
const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
|
|
157
|
+
const points = Array.from(clean);
|
|
158
|
+
if (points.length <= MAX_NAME) return clean || "file";
|
|
159
|
+
const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
|
|
160
|
+
return points.slice(0, MAX_NAME - extension.length).join("") + extension;
|
|
161
|
+
}
|
|
162
|
+
function fileType(mimeType) {
|
|
163
|
+
const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
|
|
164
|
+
return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
|
|
165
|
+
}
|
|
166
|
+
function resourceBlock(file) {
|
|
167
|
+
return {
|
|
168
|
+
type: "resource",
|
|
169
|
+
resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// src/core/http.ts
|
|
174
|
+
var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
175
|
+
var USER_AGENT = "agent-connectors";
|
|
176
|
+
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
177
|
+
function errorCode(error) {
|
|
178
|
+
const code = error?.code;
|
|
179
|
+
return typeof code === "string" ? code : void 0;
|
|
180
|
+
}
|
|
181
|
+
function describe(error) {
|
|
182
|
+
const name2 = error?.name;
|
|
183
|
+
const code = errorCode(error);
|
|
184
|
+
if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
|
|
185
|
+
if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
|
|
186
|
+
if (code === "TOO_LARGE") return "the reply was too large";
|
|
187
|
+
return cleanVendorText(error?.message, 200) ?? "a network error";
|
|
188
|
+
}
|
|
189
|
+
function retryAfterSeconds(headers, now = Date.now()) {
|
|
190
|
+
const retryAfter = headers.get("retry-after");
|
|
191
|
+
if (retryAfter) {
|
|
192
|
+
const seconds = Number(retryAfter);
|
|
193
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
|
|
194
|
+
const date = Date.parse(retryAfter);
|
|
195
|
+
if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
|
|
196
|
+
}
|
|
197
|
+
const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
|
|
198
|
+
if (reset) {
|
|
199
|
+
const value = Number(reset);
|
|
200
|
+
if (Number.isFinite(value) && value >= 0) {
|
|
201
|
+
return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return void 0;
|
|
205
|
+
}
|
|
206
|
+
function vendorCode(data) {
|
|
207
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
208
|
+
for (const key of ["error", "code"]) {
|
|
209
|
+
const value = data[key];
|
|
210
|
+
if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
|
|
211
|
+
}
|
|
212
|
+
return void 0;
|
|
213
|
+
}
|
|
214
|
+
function vendorMessage(data) {
|
|
215
|
+
if (typeof data === "string") return cleanVendorText(data);
|
|
216
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
217
|
+
const record = data;
|
|
218
|
+
for (const key of ["message", "error_description", "error", "detail", "title"]) {
|
|
219
|
+
const value = record[key];
|
|
220
|
+
if (typeof value === "string" && value.trim()) return cleanVendorText(value);
|
|
221
|
+
const nested = value?.message;
|
|
222
|
+
if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
|
|
223
|
+
}
|
|
224
|
+
if (Array.isArray(record["errors"])) {
|
|
225
|
+
const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
|
|
226
|
+
if (messages.length) return cleanVendorText(messages.join("; "));
|
|
227
|
+
}
|
|
228
|
+
return void 0;
|
|
229
|
+
}
|
|
230
|
+
var TooLarge = class extends Error {
|
|
231
|
+
constructor(limit) {
|
|
232
|
+
super(`the reply is larger than ${formatNumber(limit)} bytes`);
|
|
233
|
+
this.limit = limit;
|
|
234
|
+
}
|
|
235
|
+
limit;
|
|
236
|
+
};
|
|
237
|
+
async function readCapped(response, maxBytes) {
|
|
238
|
+
const declared = Number(response.headers.get("content-length"));
|
|
239
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
240
|
+
await response.body?.cancel().catch(() => {
|
|
241
|
+
});
|
|
242
|
+
throw new TooLarge(maxBytes);
|
|
243
|
+
}
|
|
244
|
+
if (!response.body) return new Uint8Array(0);
|
|
245
|
+
const reader = response.body.getReader();
|
|
246
|
+
const chunks = [];
|
|
247
|
+
let total = 0;
|
|
248
|
+
for (; ; ) {
|
|
249
|
+
const { done, value } = await reader.read();
|
|
250
|
+
if (done) break;
|
|
251
|
+
total += value.byteLength;
|
|
252
|
+
if (total > maxBytes) {
|
|
253
|
+
await reader.cancel().catch(() => {
|
|
254
|
+
});
|
|
255
|
+
throw new TooLarge(maxBytes);
|
|
256
|
+
}
|
|
257
|
+
chunks.push(value);
|
|
258
|
+
}
|
|
259
|
+
const bytes = new Uint8Array(total);
|
|
260
|
+
let offset = 0;
|
|
261
|
+
for (const chunk of chunks) {
|
|
262
|
+
bytes.set(chunk, offset);
|
|
263
|
+
offset += chunk.byteLength;
|
|
264
|
+
}
|
|
265
|
+
return bytes;
|
|
266
|
+
}
|
|
267
|
+
function parseBody(bytes, contentType) {
|
|
268
|
+
if (bytes.length === 0) return null;
|
|
269
|
+
const text = utf8Decode(bytes);
|
|
270
|
+
if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text)) {
|
|
271
|
+
try {
|
|
272
|
+
return JSON.parse(text);
|
|
273
|
+
} catch {
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return text;
|
|
277
|
+
}
|
|
278
|
+
function createHttp(env) {
|
|
279
|
+
const { label, ctx } = env;
|
|
280
|
+
const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
|
|
281
|
+
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.`;
|
|
282
|
+
function failureFor(status, headers, data, request) {
|
|
283
|
+
const message = vendorMessage(data);
|
|
284
|
+
const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
|
|
285
|
+
const retryAfter = retryAfterSeconds(headers);
|
|
286
|
+
const code = vendorCode(data);
|
|
287
|
+
const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
|
|
288
|
+
const custom = request.errors?.[status];
|
|
289
|
+
const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
|
|
290
|
+
if (status >= 500) {
|
|
291
|
+
if (request.write) {
|
|
292
|
+
return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
|
|
293
|
+
}
|
|
294
|
+
return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
|
|
295
|
+
}
|
|
296
|
+
if (status === 429) {
|
|
297
|
+
return new ToolFailure(
|
|
298
|
+
`${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
|
|
299
|
+
{ status, ...extra }
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
if (status === 401) {
|
|
303
|
+
return new ToolFailure(
|
|
304
|
+
withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
|
|
305
|
+
{ status, ...extra }
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
|
|
309
|
+
if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
|
|
310
|
+
if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
|
|
311
|
+
return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
|
|
312
|
+
}
|
|
313
|
+
async function api(request) {
|
|
314
|
+
const method = request.method ?? "GET";
|
|
315
|
+
if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
|
|
316
|
+
throw new Error(`read-only tool sent ${method}`);
|
|
317
|
+
}
|
|
318
|
+
const origin = request.origin ?? env.origins[0];
|
|
319
|
+
if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
|
|
320
|
+
const url = new URL(request.path, origin);
|
|
321
|
+
if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
|
|
322
|
+
for (const [key, value] of Object.entries(request.query ?? {})) {
|
|
323
|
+
if (value === void 0 || value === null) continue;
|
|
324
|
+
if (Array.isArray(value)) {
|
|
325
|
+
url.searchParams.delete(key);
|
|
326
|
+
for (const item of value) url.searchParams.append(key, String(item));
|
|
327
|
+
} else {
|
|
328
|
+
url.searchParams.set(key, String(value));
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
const headers = {
|
|
332
|
+
accept: "application/json",
|
|
333
|
+
"user-agent": USER_AGENT,
|
|
334
|
+
...request.auth === false ? {} : env.authHeaders(),
|
|
335
|
+
...request.headers
|
|
336
|
+
};
|
|
337
|
+
let body;
|
|
338
|
+
if (request.json !== void 0) {
|
|
339
|
+
body = JSON.stringify(request.json);
|
|
340
|
+
headers["content-type"] = "application/json";
|
|
341
|
+
} else if (request.body) {
|
|
342
|
+
body = request.body;
|
|
343
|
+
headers["content-type"] = request.contentType ?? "application/octet-stream";
|
|
344
|
+
}
|
|
345
|
+
const started = Date.now();
|
|
346
|
+
if (request.write) env.onWriteSent();
|
|
347
|
+
let response;
|
|
348
|
+
try {
|
|
349
|
+
response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
|
|
350
|
+
} catch (error) {
|
|
351
|
+
env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
|
|
352
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
353
|
+
throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
|
|
354
|
+
}
|
|
355
|
+
if (request.write) {
|
|
356
|
+
throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
|
|
357
|
+
}
|
|
358
|
+
if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
|
|
359
|
+
throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
|
|
360
|
+
}
|
|
361
|
+
env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
|
|
362
|
+
let bytes;
|
|
363
|
+
try {
|
|
364
|
+
bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
|
|
365
|
+
} catch (error) {
|
|
366
|
+
if (request.write && (response.ok || response.status >= 500)) {
|
|
367
|
+
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.`);
|
|
368
|
+
}
|
|
369
|
+
throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
|
|
370
|
+
}
|
|
371
|
+
const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
|
|
372
|
+
if (response.ok) return { status: response.status, headers: response.headers, data };
|
|
373
|
+
throw failureFor(response.status, response.headers, data, request);
|
|
374
|
+
}
|
|
375
|
+
async function media(rawUrl, options) {
|
|
376
|
+
const { what } = options;
|
|
377
|
+
let url;
|
|
378
|
+
try {
|
|
379
|
+
url = new URL(rawUrl);
|
|
380
|
+
} catch {
|
|
381
|
+
throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
|
|
382
|
+
}
|
|
383
|
+
if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
|
|
384
|
+
const started = Date.now();
|
|
385
|
+
let response;
|
|
386
|
+
try {
|
|
387
|
+
response = await ctx.fetch(url.toString(), {
|
|
388
|
+
method: "GET",
|
|
389
|
+
headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
|
|
390
|
+
...ctx.signal ? { signal: ctx.signal } : {}
|
|
391
|
+
});
|
|
392
|
+
} catch (error) {
|
|
393
|
+
env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
|
|
394
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
395
|
+
throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
|
|
396
|
+
}
|
|
397
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
398
|
+
}
|
|
399
|
+
env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
|
|
400
|
+
if (!response.ok) {
|
|
401
|
+
await response.body?.cancel().catch(() => {
|
|
402
|
+
});
|
|
403
|
+
throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
|
|
404
|
+
}
|
|
405
|
+
try {
|
|
406
|
+
const bytes = await readCapped(response, options.maxBytes);
|
|
407
|
+
return { bytes, contentType: response.headers.get("content-type") };
|
|
408
|
+
} catch (error) {
|
|
409
|
+
if (error instanceof TooLarge) {
|
|
410
|
+
throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
|
|
411
|
+
}
|
|
412
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
return { api, media };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// src/core/origins.ts
|
|
419
|
+
function parseSiteUrl(value) {
|
|
420
|
+
const text = typeof value === "string" ? value.trim() : "";
|
|
421
|
+
if (!text) return { ok: false, problem: "is empty" };
|
|
422
|
+
let url;
|
|
423
|
+
try {
|
|
424
|
+
url = new URL(text.includes("://") ? text : `https://${text}`);
|
|
425
|
+
} catch {
|
|
426
|
+
return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
|
|
427
|
+
}
|
|
428
|
+
if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
|
|
429
|
+
if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
|
|
430
|
+
if (!url.hostname) return { ok: false, problem: "has no host name" };
|
|
431
|
+
return { ok: true, url, origin: url.origin };
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// src/core/schema.ts
|
|
435
|
+
var patterns = /* @__PURE__ */ new Map();
|
|
436
|
+
function patternOf(source) {
|
|
437
|
+
let compiled = patterns.get(source);
|
|
438
|
+
if (!compiled) {
|
|
439
|
+
compiled = new RegExp(source, "u");
|
|
440
|
+
patterns.set(source, compiled);
|
|
441
|
+
}
|
|
442
|
+
return compiled;
|
|
443
|
+
}
|
|
444
|
+
function isPlainObject(value) {
|
|
445
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
446
|
+
}
|
|
447
|
+
function isHttpUrl(value) {
|
|
448
|
+
try {
|
|
449
|
+
const url = new URL(value);
|
|
450
|
+
return url.protocol === "https:" || url.protocol === "http:";
|
|
451
|
+
} catch {
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
function name(path) {
|
|
456
|
+
return `\`${path}\``;
|
|
457
|
+
}
|
|
458
|
+
function child(path, key) {
|
|
459
|
+
return path ? `${path}.${key}` : key;
|
|
460
|
+
}
|
|
461
|
+
function checkValue(schema, value, path, issues) {
|
|
462
|
+
switch (schema.type) {
|
|
463
|
+
case "object":
|
|
464
|
+
checkObject(schema, value, path, issues);
|
|
465
|
+
return;
|
|
466
|
+
case "array": {
|
|
467
|
+
if (!Array.isArray(value)) {
|
|
468
|
+
issues.push(`${name(path)} must be an array`);
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
if (schema.minItems !== void 0 && value.length < schema.minItems) {
|
|
472
|
+
issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
|
|
473
|
+
}
|
|
474
|
+
if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
|
|
475
|
+
issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
|
|
476
|
+
}
|
|
477
|
+
if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
|
|
478
|
+
issues.push(`${name(path)} must not repeat an item`);
|
|
479
|
+
}
|
|
480
|
+
if (schema.items) {
|
|
481
|
+
value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
|
|
482
|
+
}
|
|
483
|
+
break;
|
|
484
|
+
}
|
|
485
|
+
case "string": {
|
|
486
|
+
if (typeof value !== "string") {
|
|
487
|
+
issues.push(`${name(path)} must be a string`);
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
const length = Array.from(value).length;
|
|
491
|
+
if (schema.minLength !== void 0 && length < schema.minLength) {
|
|
492
|
+
issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
|
|
493
|
+
}
|
|
494
|
+
if (schema.maxLength !== void 0 && length > schema.maxLength) {
|
|
495
|
+
issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
|
|
496
|
+
}
|
|
497
|
+
if (schema.format === "uri" && !isHttpUrl(value)) {
|
|
498
|
+
issues.push(`${name(path)} must be an absolute http(s) URL`);
|
|
499
|
+
} else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
|
|
500
|
+
issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
|
|
501
|
+
}
|
|
502
|
+
break;
|
|
503
|
+
}
|
|
504
|
+
case "integer":
|
|
505
|
+
case "number": {
|
|
506
|
+
if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
|
|
507
|
+
issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
if (schema.minimum !== void 0 && value < schema.minimum) {
|
|
511
|
+
issues.push(`${name(path)} must be at least ${schema.minimum}`);
|
|
512
|
+
}
|
|
513
|
+
if (schema.maximum !== void 0 && value > schema.maximum) {
|
|
514
|
+
issues.push(`${name(path)} must be at most ${schema.maximum}`);
|
|
515
|
+
}
|
|
516
|
+
break;
|
|
517
|
+
}
|
|
518
|
+
case "boolean":
|
|
519
|
+
if (typeof value !== "boolean") {
|
|
520
|
+
issues.push(`${name(path)} must be true or false`);
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
break;
|
|
524
|
+
default:
|
|
525
|
+
break;
|
|
526
|
+
}
|
|
527
|
+
if (schema.enum && !schema.enum.includes(value)) {
|
|
528
|
+
issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
function checkObject(schema, value, path, issues) {
|
|
532
|
+
if (!isPlainObject(value)) {
|
|
533
|
+
issues.push(`${path ? name(path) : "the arguments"} must be an object`);
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
const properties = schema.properties ?? {};
|
|
537
|
+
for (const key of schema.required ?? []) {
|
|
538
|
+
if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
|
|
539
|
+
}
|
|
540
|
+
const unknown = [];
|
|
541
|
+
for (const [key, item] of Object.entries(value)) {
|
|
542
|
+
const property = properties[key];
|
|
543
|
+
if (!property) {
|
|
544
|
+
if (schema.additionalProperties === false) unknown.push(key);
|
|
545
|
+
continue;
|
|
546
|
+
}
|
|
547
|
+
if (item === void 0 || item === null) continue;
|
|
548
|
+
checkValue(property, item, child(path, key), issues);
|
|
549
|
+
}
|
|
550
|
+
if (unknown.length) {
|
|
551
|
+
const known = Object.keys(properties);
|
|
552
|
+
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(", ")})` : ""));
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
function copyDefault(value) {
|
|
556
|
+
return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
|
|
557
|
+
}
|
|
558
|
+
function validateArguments(schema, args) {
|
|
559
|
+
const input = args === void 0 || args === null ? {} : args;
|
|
560
|
+
if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
|
|
561
|
+
const value = { ...input };
|
|
562
|
+
if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
|
|
563
|
+
const issues = [];
|
|
564
|
+
checkObject(schema, value, "", issues);
|
|
565
|
+
if (issues.length) return { ok: false, issues };
|
|
566
|
+
for (const [key, property] of Object.entries(schema.properties ?? {})) {
|
|
567
|
+
if (value[key] === null) delete value[key];
|
|
568
|
+
if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
|
|
569
|
+
}
|
|
570
|
+
return { ok: true, value };
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// src/core/upload-hosts.ts
|
|
574
|
+
var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
575
|
+
function uploadHostProblem(entry) {
|
|
576
|
+
if (typeof entry !== "string") return "must be a host name";
|
|
577
|
+
const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
|
|
578
|
+
const labels = name2.split(".");
|
|
579
|
+
if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
|
|
580
|
+
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";
|
|
581
|
+
}
|
|
582
|
+
if (labels.length < 2) return "needs at least two labels, like example.com";
|
|
583
|
+
if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
|
|
584
|
+
return void 0;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// src/core/connector.ts
|
|
588
|
+
var ANNOTATIONS = {
|
|
589
|
+
read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
590
|
+
create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
591
|
+
update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
592
|
+
delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
593
|
+
write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
|
|
594
|
+
};
|
|
595
|
+
var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
|
|
596
|
+
var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
597
|
+
var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
598
|
+
var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
599
|
+
var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
|
|
600
|
+
var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
601
|
+
var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
|
|
602
|
+
function deepFreeze(value) {
|
|
603
|
+
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
|
|
604
|
+
Object.freeze(value);
|
|
605
|
+
for (const item of Object.values(value)) deepFreeze(item);
|
|
606
|
+
}
|
|
607
|
+
return value;
|
|
608
|
+
}
|
|
609
|
+
function assertDefinition(def) {
|
|
610
|
+
const problem = (message) => {
|
|
611
|
+
throw new Error(`connector "${def.vendor}": ${message}`);
|
|
612
|
+
};
|
|
613
|
+
if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
|
|
614
|
+
if (!def.label?.trim()) problem("label is required");
|
|
615
|
+
const originFields = def.originFields ?? [];
|
|
616
|
+
if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
|
|
617
|
+
for (const origin of def.origins) {
|
|
618
|
+
let url;
|
|
619
|
+
try {
|
|
620
|
+
url = new URL(origin);
|
|
621
|
+
} catch {
|
|
622
|
+
}
|
|
623
|
+
if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
|
|
624
|
+
}
|
|
625
|
+
for (const name2 of def.credentials) {
|
|
626
|
+
if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
|
|
627
|
+
}
|
|
628
|
+
for (const [index, name2] of originFields.entries()) {
|
|
629
|
+
if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
|
|
630
|
+
if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
|
|
631
|
+
}
|
|
632
|
+
const names = /* @__PURE__ */ new Set();
|
|
633
|
+
for (const tool of def.tools) {
|
|
634
|
+
if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
|
|
635
|
+
if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
|
|
636
|
+
names.add(tool.name);
|
|
637
|
+
if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
|
|
638
|
+
if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
|
|
639
|
+
if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
|
|
640
|
+
if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
|
|
641
|
+
problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
for (const tool of def.tools) {
|
|
645
|
+
if (tool.kind === "read") continue;
|
|
646
|
+
const check = def.tools.find((candidate) => candidate.name === tool.check);
|
|
647
|
+
if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
|
|
648
|
+
}
|
|
649
|
+
assertUploadHosts(def, problem);
|
|
650
|
+
assertRequiredCredentials(def, problem);
|
|
651
|
+
assertAccountPickers(def, problem);
|
|
652
|
+
}
|
|
653
|
+
function assertUploadHosts(def, problem) {
|
|
654
|
+
const hosts = def.uploadHosts;
|
|
655
|
+
if (hosts === void 0) return;
|
|
656
|
+
if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
|
|
657
|
+
hosts.forEach((entry, index) => {
|
|
658
|
+
const wrong = uploadHostProblem(entry);
|
|
659
|
+
if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
|
|
660
|
+
if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
function assertRequiredCredentials(def, problem) {
|
|
664
|
+
const required = def.requiredCredentials;
|
|
665
|
+
if (required === void 0) return;
|
|
666
|
+
if (!Array.isArray(required) || !required.length) {
|
|
667
|
+
problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
|
|
668
|
+
}
|
|
669
|
+
required.forEach((list, index) => {
|
|
670
|
+
const which = `requiredCredentials[${index}]`;
|
|
671
|
+
if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
|
|
672
|
+
list.forEach((name2, position) => {
|
|
673
|
+
if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
|
|
674
|
+
if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
|
|
675
|
+
});
|
|
676
|
+
});
|
|
677
|
+
const lists = required;
|
|
678
|
+
lists.forEach((list, index) => {
|
|
679
|
+
const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
|
|
680
|
+
if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
|
|
681
|
+
if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
|
|
682
|
+
problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
|
|
683
|
+
}
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
function isDotPath(value) {
|
|
687
|
+
return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
|
|
688
|
+
}
|
|
689
|
+
function assertAccountPickers(def, problem) {
|
|
690
|
+
const pickers = def.accountPickers;
|
|
691
|
+
if (pickers === void 0) return;
|
|
692
|
+
if (!Array.isArray(pickers)) problem("accountPickers must be a list");
|
|
693
|
+
const keys = /* @__PURE__ */ new Set();
|
|
694
|
+
for (const item of pickers) {
|
|
695
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
|
|
696
|
+
const picker = item;
|
|
697
|
+
const key = picker["key"];
|
|
698
|
+
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}$`);
|
|
699
|
+
if (keys.has(key)) problem(`account picker ${key} is defined twice`);
|
|
700
|
+
keys.add(key);
|
|
701
|
+
const fail = (message) => problem(`account picker ${key}: ${message}`);
|
|
702
|
+
const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
|
|
703
|
+
if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
|
|
704
|
+
const { label, description, multiple, legacyField } = picker;
|
|
705
|
+
if (typeof label !== "string" || !label.trim()) fail("label is required");
|
|
706
|
+
if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
|
|
707
|
+
fail("description, when given, must be a text of 1 to 1024 characters");
|
|
708
|
+
}
|
|
709
|
+
if (typeof multiple !== "boolean") fail("multiple must be true or false");
|
|
710
|
+
const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
|
|
711
|
+
if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
|
|
712
|
+
if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
|
|
713
|
+
for (const field of ["idField", "nameField"]) {
|
|
714
|
+
if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
|
|
715
|
+
}
|
|
716
|
+
if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
|
|
717
|
+
fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
function copyPicker(picker) {
|
|
722
|
+
return {
|
|
723
|
+
key: picker.key,
|
|
724
|
+
label: picker.label,
|
|
725
|
+
...picker.description !== void 0 ? { description: picker.description } : {},
|
|
726
|
+
multiple: picker.multiple,
|
|
727
|
+
tool: picker.tool,
|
|
728
|
+
idField: picker.idField,
|
|
729
|
+
nameField: picker.nameField,
|
|
730
|
+
...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
function result(payload, isError, files = []) {
|
|
734
|
+
return {
|
|
735
|
+
content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
|
|
736
|
+
...isError ? { isError: true } : {}
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
function failure(message, details = {}) {
|
|
740
|
+
return result({ error: message, ...details }, true);
|
|
741
|
+
}
|
|
742
|
+
function trimmed(values) {
|
|
743
|
+
const out = {};
|
|
744
|
+
if (typeof values !== "object" || values === null) return out;
|
|
745
|
+
for (const [key, value] of Object.entries(values)) {
|
|
746
|
+
if (value === void 0 || value === null) continue;
|
|
747
|
+
const text = String(value).trim();
|
|
748
|
+
if (text) out[key] = text;
|
|
749
|
+
}
|
|
750
|
+
return out;
|
|
751
|
+
}
|
|
752
|
+
function defineConnector(def) {
|
|
753
|
+
assertDefinition(def);
|
|
754
|
+
const { label } = def;
|
|
755
|
+
const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
|
|
756
|
+
const toolList = def.tools.map((tool) => tool.name).join(", ");
|
|
757
|
+
const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
|
|
758
|
+
const required = requiredAlternatives(def);
|
|
759
|
+
const notConnected = (unmet) => {
|
|
760
|
+
const [first] = unmet;
|
|
761
|
+
if (unmet.length === 1 && first) {
|
|
762
|
+
return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
|
|
763
|
+
}
|
|
764
|
+
return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
|
|
765
|
+
};
|
|
766
|
+
const descriptors = def.tools.map((tool) => ({
|
|
767
|
+
name: tool.name,
|
|
768
|
+
title: tool.title,
|
|
769
|
+
description: tool.description,
|
|
770
|
+
inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
|
|
771
|
+
annotations: { ...ANNOTATIONS[tool.kind] }
|
|
772
|
+
}));
|
|
773
|
+
async function call(toolName, args, ctx) {
|
|
774
|
+
const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
|
|
775
|
+
if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
|
|
776
|
+
if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
|
|
777
|
+
const log = (text) => {
|
|
778
|
+
try {
|
|
779
|
+
ctx.log?.(text);
|
|
780
|
+
} catch {
|
|
781
|
+
}
|
|
782
|
+
};
|
|
783
|
+
const given = trimmed(ctx.credentials);
|
|
784
|
+
const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
|
|
785
|
+
const has = (name2) => Boolean(credentials[name2]);
|
|
786
|
+
const unmet = unmetAlternatives(required, has);
|
|
787
|
+
if (unmet.length) return failure(notConnected(unmet));
|
|
788
|
+
const complete = required.filter((list) => list.every(has));
|
|
789
|
+
const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
|
|
790
|
+
const fieldOrigins = /* @__PURE__ */ new Map();
|
|
791
|
+
for (const name2 of def.originFields ?? []) {
|
|
792
|
+
if (!given[name2] && !inUse.includes(name2)) continue;
|
|
793
|
+
const site = parseSiteUrl(given[name2] ?? "");
|
|
794
|
+
if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
|
|
795
|
+
fieldOrigins.set(name2, site.origin);
|
|
796
|
+
}
|
|
797
|
+
const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
|
|
798
|
+
const parsed = validateArguments(tool.inputSchema, args);
|
|
799
|
+
if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
|
|
800
|
+
const frozenCredentials = Object.freeze({ ...credentials });
|
|
801
|
+
let writeSent = false;
|
|
802
|
+
const fileLimit = fileLimitOf(ctx);
|
|
803
|
+
const files = [];
|
|
804
|
+
let fileBytes = 0;
|
|
805
|
+
const http = createHttp({
|
|
806
|
+
vendor: def.vendor,
|
|
807
|
+
label,
|
|
808
|
+
tool: tool.name,
|
|
809
|
+
readOnly: tool.kind === "read",
|
|
810
|
+
origins,
|
|
811
|
+
// A 401 names the credentials in use (for a module that needs none, the ones given).
|
|
812
|
+
credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
|
|
813
|
+
ctx,
|
|
814
|
+
authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
|
|
815
|
+
log,
|
|
816
|
+
onWriteSent: () => {
|
|
817
|
+
writeSent = true;
|
|
818
|
+
}
|
|
819
|
+
});
|
|
820
|
+
const helpers = {
|
|
821
|
+
tool: tool.name,
|
|
822
|
+
credentials: frozenCredentials,
|
|
823
|
+
ctx,
|
|
824
|
+
origins: Object.freeze([...origins]),
|
|
825
|
+
originOf: (credential) => {
|
|
826
|
+
const origin = fieldOrigins.get(credential);
|
|
827
|
+
if (!origin) throw new Error(`${credential} gives no origin in this call`);
|
|
828
|
+
return origin;
|
|
829
|
+
},
|
|
830
|
+
api: http.api,
|
|
831
|
+
media: http.media,
|
|
832
|
+
page: (input) => fitPage(input),
|
|
833
|
+
cursor: (cursor) => decodeCursor(tool.name, cursor),
|
|
834
|
+
makeCursor: (state) => encodeCursor(tool.name, state),
|
|
835
|
+
fileLimit: () => fileLimit,
|
|
836
|
+
file: ({ name: name2, mimeType, bytes }) => {
|
|
837
|
+
if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
|
|
838
|
+
const total = fileBytes + bytes.byteLength;
|
|
839
|
+
if (total > fileLimit) {
|
|
840
|
+
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.`);
|
|
841
|
+
}
|
|
842
|
+
fileBytes = total;
|
|
843
|
+
const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
|
|
844
|
+
files.push({ ...info, bytes });
|
|
845
|
+
return { ...info };
|
|
846
|
+
},
|
|
847
|
+
log
|
|
848
|
+
};
|
|
849
|
+
try {
|
|
850
|
+
const data = await tool.run(parsed.value, helpers);
|
|
851
|
+
const fitted = shrinkToFit(data ?? {});
|
|
852
|
+
if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
|
|
853
|
+
const payload = fitted.value;
|
|
854
|
+
return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
|
|
855
|
+
} catch (error) {
|
|
856
|
+
if (error instanceof OutcomeUnknown) {
|
|
857
|
+
return result({
|
|
858
|
+
outcome: "unknown",
|
|
859
|
+
check: tool.check,
|
|
860
|
+
error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
|
|
861
|
+
}, true);
|
|
862
|
+
}
|
|
863
|
+
if (error instanceof ToolFailure) return failure(error.message, error.details);
|
|
864
|
+
log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
|
|
865
|
+
if (writeSent) {
|
|
866
|
+
return result({
|
|
867
|
+
outcome: "unknown",
|
|
868
|
+
check: tool.check,
|
|
869
|
+
error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
|
|
870
|
+
}, true);
|
|
871
|
+
}
|
|
872
|
+
return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
return deepFreeze({
|
|
876
|
+
vendor: def.vendor,
|
|
877
|
+
origins: [...def.origins],
|
|
878
|
+
originFields: [...def.originFields ?? []],
|
|
879
|
+
uploadHosts: [...def.uploadHosts ?? []],
|
|
880
|
+
credentials: [...def.credentials],
|
|
881
|
+
requiredCredentials: required.map((list) => [...list]),
|
|
882
|
+
accountPickers: (def.accountPickers ?? []).map(copyPicker),
|
|
883
|
+
tools: descriptors,
|
|
884
|
+
call
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
// src/core/jwt.ts
|
|
889
|
+
var TOKEN_EARLY_MS = 5 * 60 * 1e3;
|
|
890
|
+
|
|
891
|
+
// src/vendors/hashnode/graphql.ts
|
|
892
|
+
var MAX_REQUEST_BYTES = 100 * 1024;
|
|
893
|
+
var MAX_ANSWER_BYTES = 8 * 1024 * 1024;
|
|
894
|
+
function compact(value) {
|
|
895
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null));
|
|
896
|
+
}
|
|
897
|
+
async function gql(h, query, variables, options = {}) {
|
|
898
|
+
const body = compact({ query, variables });
|
|
899
|
+
const size = utf8Length(JSON.stringify(body));
|
|
900
|
+
if (size > MAX_REQUEST_BYTES) {
|
|
901
|
+
throw new ToolFailure(
|
|
902
|
+
`Hashnode takes requests up to 100 KB, and this one is ${formatNumber(Math.ceil(size / 1024))} KB: shorten it. ${options.write ? "Nothing was changed." : "Nothing was sent."}`
|
|
903
|
+
);
|
|
904
|
+
}
|
|
905
|
+
const response = await h.api({ method: "POST", path: "/", json: body, maxBytes: MAX_ANSWER_BYTES, ...options.write ? { write: true } : { safe: true } });
|
|
906
|
+
const payload = response.data;
|
|
907
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
|
|
908
|
+
if (options.write) throw new OutcomeUnknown("Hashnode answered without GraphQL JSON, so it is not known whether the change was made.");
|
|
909
|
+
throw new ToolFailure("Hashnode answered without GraphQL JSON. Try again later.");
|
|
910
|
+
}
|
|
911
|
+
return { data: payload.data ?? null, errors: Array.isArray(payload.errors) ? payload.errors : [] };
|
|
912
|
+
}
|
|
913
|
+
function errorText(errors) {
|
|
914
|
+
const messages = errors.map((error) => typeof error?.message === "string" ? error.message : "").filter((message) => message.trim() !== "");
|
|
915
|
+
return cleanVendorText(messages.join("; "));
|
|
916
|
+
}
|
|
917
|
+
function errorCode2(errors) {
|
|
918
|
+
const code = errors[0]?.extensions?.code;
|
|
919
|
+
return typeof code === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(code) ? code : void 0;
|
|
920
|
+
}
|
|
921
|
+
function failFromErrors(errors, write) {
|
|
922
|
+
const code = errorCode2(errors);
|
|
923
|
+
const message = errorText(errors);
|
|
924
|
+
const said = message ? `: ${message.replace(/[.!?]+$/u, "")}` : "";
|
|
925
|
+
const nothing = write ? " Nothing was changed." : "";
|
|
926
|
+
const details = code ? { vendorCode: code } : {};
|
|
927
|
+
if (message && /pro plan/i.test(message)) {
|
|
928
|
+
throw new ToolFailure(
|
|
929
|
+
`Hashnode's API works only for blogs on Hashnode Pro, and this blog is not on it (${code ?? "FORBIDDEN"})${said}. A blog owner turns it on in the blog dashboard under Billing \u2192 Upgrade to Pro ($5 a month or $50 a year per seat); the API works right after checkout. Do not retry before that.${nothing}`,
|
|
930
|
+
details
|
|
931
|
+
);
|
|
932
|
+
}
|
|
933
|
+
switch (code) {
|
|
934
|
+
case "UNAUTHENTICATED":
|
|
935
|
+
throw new ToolFailure(`Hashnode rejected the token (UNAUTHENTICATED)${said}. Check that the Hashnode Personal Access Token is correct and still active.${nothing}`, details);
|
|
936
|
+
case "FORBIDDEN":
|
|
937
|
+
throw new ToolFailure(
|
|
938
|
+
`Hashnode refused the request (FORBIDDEN)${said}. The account may lack the role for it: on a team blog a contributor cannot publish, and submit_draft_for_review hands a draft to the blog's editors.${nothing}`,
|
|
939
|
+
details
|
|
940
|
+
);
|
|
941
|
+
case "NOT_FOUND":
|
|
942
|
+
throw new ToolFailure(`Hashnode found nothing there (NOT_FOUND)${said}. Check the ID or slug.${nothing}`, details);
|
|
943
|
+
case "BAD_USER_INPUT":
|
|
944
|
+
case "GRAPHQL_VALIDATION_FAILED":
|
|
945
|
+
case "GRAPHQL_PARSE_FAILED":
|
|
946
|
+
throw new ToolFailure(`Hashnode rejected the request (${code})${said}.${nothing}`, details);
|
|
947
|
+
default:
|
|
948
|
+
if (write) {
|
|
949
|
+
throw new OutcomeUnknown(`Hashnode answered with an error (${code ?? "no code"})${said}, so it is not known whether the change was made.`);
|
|
950
|
+
}
|
|
951
|
+
throw new ToolFailure(`Hashnode answered with an error (${code ?? "no code"})${said}. Try again later.`, details);
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
function rootField(result2, field, write) {
|
|
955
|
+
const value = result2.data?.[field];
|
|
956
|
+
if (value !== void 0 && value !== null) return value;
|
|
957
|
+
if (result2.errors.length) failFromErrors(result2.errors, write);
|
|
958
|
+
return value ?? null;
|
|
959
|
+
}
|
|
960
|
+
function warningsOf(result2) {
|
|
961
|
+
if (!result2.errors.length) return void 0;
|
|
962
|
+
return result2.errors.slice(0, 5).map((error) => cleanVendorText(String(error?.message ?? "error"), 300) ?? "error");
|
|
963
|
+
}
|
|
964
|
+
var PUNCTUATORS = /* @__PURE__ */ new Set(["!", "$", "&", "(", ")", ":", "=", "@", "[", "]", "{", "|", "}"]);
|
|
965
|
+
var CLOSERS = { "}": "{", ")": "(", "]": "[" };
|
|
966
|
+
var isDigit = (char) => char !== void 0 && char >= "0" && char <= "9";
|
|
967
|
+
var isNameStart = (char) => char !== void 0 && /^[A-Za-z_]$/.test(char);
|
|
968
|
+
var isHex = (char) => char !== void 0 && /^[0-9A-Fa-f]$/.test(char);
|
|
969
|
+
var NotGraphql = class extends Error {
|
|
970
|
+
};
|
|
971
|
+
function readNumber(source, start) {
|
|
972
|
+
let index = start;
|
|
973
|
+
if (source[index] === "-") index++;
|
|
974
|
+
if (source[index] === "0") {
|
|
975
|
+
index++;
|
|
976
|
+
if (isDigit(source[index])) throw new NotGraphql("a number with a leading zero");
|
|
977
|
+
} else if (isDigit(source[index])) {
|
|
978
|
+
while (isDigit(source[index])) index++;
|
|
979
|
+
} else {
|
|
980
|
+
throw new NotGraphql('a "-" without a number');
|
|
981
|
+
}
|
|
982
|
+
if (source[index] === ".") {
|
|
983
|
+
index++;
|
|
984
|
+
if (!isDigit(source[index])) throw new NotGraphql('a number without digits after its "."');
|
|
985
|
+
while (isDigit(source[index])) index++;
|
|
986
|
+
}
|
|
987
|
+
if (source[index] === "e" || source[index] === "E") {
|
|
988
|
+
index++;
|
|
989
|
+
if (source[index] === "+" || source[index] === "-") index++;
|
|
990
|
+
if (!isDigit(source[index])) throw new NotGraphql("a number without digits in its exponent");
|
|
991
|
+
while (isDigit(source[index])) index++;
|
|
992
|
+
}
|
|
993
|
+
if (source[index] === "." || isNameStart(source[index])) throw new NotGraphql('a number followed by a name or a "."');
|
|
994
|
+
return index;
|
|
995
|
+
}
|
|
996
|
+
function readString(source, start) {
|
|
997
|
+
let index = start + 1;
|
|
998
|
+
for (; ; ) {
|
|
999
|
+
const char = source[index];
|
|
1000
|
+
if (char === void 0 || char === "\n" || char === "\r") throw new NotGraphql("a string that is not closed on its line");
|
|
1001
|
+
if (char === '"') return index + 1;
|
|
1002
|
+
if (char !== "\\") {
|
|
1003
|
+
index++;
|
|
1004
|
+
continue;
|
|
1005
|
+
}
|
|
1006
|
+
const escaped = source[index + 1];
|
|
1007
|
+
if (escaped !== void 0 && '"\\/bfnrt'.includes(escaped)) {
|
|
1008
|
+
index += 2;
|
|
1009
|
+
} else if (escaped === "u" && source[index + 2] === "{") {
|
|
1010
|
+
let end = index + 3;
|
|
1011
|
+
while (isHex(source[end])) end++;
|
|
1012
|
+
if (end === index + 3 || source[end] !== "}") throw new NotGraphql("a broken \\u{...} escape in a string");
|
|
1013
|
+
index = end + 1;
|
|
1014
|
+
} else if (escaped === "u" && [2, 3, 4, 5].every((offset) => isHex(source[index + offset]))) {
|
|
1015
|
+
index += 6;
|
|
1016
|
+
} else {
|
|
1017
|
+
throw new NotGraphql("an unknown escape in a string");
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
function readBlockString(source, start) {
|
|
1022
|
+
let index = start + 3;
|
|
1023
|
+
for (; ; ) {
|
|
1024
|
+
if (index >= source.length) throw new NotGraphql("a block string that is not closed");
|
|
1025
|
+
if (source.startsWith('"""', index)) return index + 3;
|
|
1026
|
+
if (source.startsWith('\\"""', index)) {
|
|
1027
|
+
index += 4;
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
index++;
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
function tokenize(source) {
|
|
1034
|
+
const tokens = [];
|
|
1035
|
+
let index = 0;
|
|
1036
|
+
while (index < source.length) {
|
|
1037
|
+
const char = source[index];
|
|
1038
|
+
if (char === " " || char === " " || char === "\n" || char === "\r" || char === "," || char === "\uFEFF") {
|
|
1039
|
+
index++;
|
|
1040
|
+
} else if (char === "#") {
|
|
1041
|
+
while (index < source.length && source[index] !== "\n" && source[index] !== "\r") index++;
|
|
1042
|
+
} else if (char === '"') {
|
|
1043
|
+
const end = source.startsWith('"""', index) ? readBlockString(source, index) : readString(source, index);
|
|
1044
|
+
tokens.push({ kind: "string", value: "" });
|
|
1045
|
+
index = end;
|
|
1046
|
+
} else if (isNameStart(char)) {
|
|
1047
|
+
let end = index + 1;
|
|
1048
|
+
while (end < source.length && /^[A-Za-z0-9_]$/.test(source[end])) end++;
|
|
1049
|
+
tokens.push({ kind: "name", value: source.slice(index, end) });
|
|
1050
|
+
index = end;
|
|
1051
|
+
} else if (char === "-" || isDigit(char)) {
|
|
1052
|
+
const end = readNumber(source, index);
|
|
1053
|
+
tokens.push({ kind: "number", value: source.slice(index, end) });
|
|
1054
|
+
index = end;
|
|
1055
|
+
} else if (source.startsWith("...", index)) {
|
|
1056
|
+
tokens.push({ kind: "punctuator", value: "..." });
|
|
1057
|
+
index += 3;
|
|
1058
|
+
} else if (PUNCTUATORS.has(char)) {
|
|
1059
|
+
tokens.push({ kind: "punctuator", value: char });
|
|
1060
|
+
index++;
|
|
1061
|
+
} else {
|
|
1062
|
+
throw new NotGraphql(`the character ${JSON.stringify(char)}`);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
return tokens;
|
|
1066
|
+
}
|
|
1067
|
+
function parseDocument(source) {
|
|
1068
|
+
let tokens;
|
|
1069
|
+
try {
|
|
1070
|
+
tokens = tokenize(source);
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
if (error instanceof NotGraphql) return { ok: false, problem: `it has ${error.message}` };
|
|
1073
|
+
throw error;
|
|
1074
|
+
}
|
|
1075
|
+
let index = 0;
|
|
1076
|
+
const is = (kind, value) => tokens[index]?.kind === kind && (value === void 0 || tokens[index]?.value === value);
|
|
1077
|
+
const skipGroup = () => {
|
|
1078
|
+
const open = [];
|
|
1079
|
+
do {
|
|
1080
|
+
const token = tokens[index];
|
|
1081
|
+
if (!token) return false;
|
|
1082
|
+
if (token.kind === "punctuator") {
|
|
1083
|
+
if (token.value === "{" || token.value === "(" || token.value === "[") open.push(token.value);
|
|
1084
|
+
else if (CLOSERS[token.value] && open.pop() !== CLOSERS[token.value]) return false;
|
|
1085
|
+
}
|
|
1086
|
+
index++;
|
|
1087
|
+
} while (open.length);
|
|
1088
|
+
return true;
|
|
1089
|
+
};
|
|
1090
|
+
const skipDirectives = () => {
|
|
1091
|
+
while (is("punctuator", "@")) {
|
|
1092
|
+
index++;
|
|
1093
|
+
if (!is("name")) return false;
|
|
1094
|
+
index++;
|
|
1095
|
+
if (is("punctuator", "(") && !skipGroup()) return false;
|
|
1096
|
+
}
|
|
1097
|
+
return true;
|
|
1098
|
+
};
|
|
1099
|
+
const operations = [];
|
|
1100
|
+
let fragments = 0;
|
|
1101
|
+
const broken = (what) => ({ ok: false, problem: what });
|
|
1102
|
+
while (index < tokens.length) {
|
|
1103
|
+
if (is("punctuator", "{")) {
|
|
1104
|
+
if (!skipGroup()) return broken("its brackets do not match");
|
|
1105
|
+
operations.push({ type: "query" });
|
|
1106
|
+
} else if (is("name", "query") || is("name", "mutation") || is("name", "subscription")) {
|
|
1107
|
+
const type = tokens[index].value;
|
|
1108
|
+
index++;
|
|
1109
|
+
let name2;
|
|
1110
|
+
if (is("name")) {
|
|
1111
|
+
name2 = tokens[index].value;
|
|
1112
|
+
index++;
|
|
1113
|
+
}
|
|
1114
|
+
if (is("punctuator", "(") && !skipGroup()) return broken("its brackets do not match");
|
|
1115
|
+
if (!skipDirectives()) return broken("a directive is cut short");
|
|
1116
|
+
if (!is("punctuator", "{")) return broken(`the ${type}${name2 ? ` ${name2}` : ""} has no selection set`);
|
|
1117
|
+
if (!skipGroup()) return broken("its brackets do not match");
|
|
1118
|
+
operations.push({ type, ...name2 ? { name: name2 } : {} });
|
|
1119
|
+
} else if (is("name", "fragment")) {
|
|
1120
|
+
index++;
|
|
1121
|
+
if (!is("name") || is("name", "on")) return broken("a fragment has no name");
|
|
1122
|
+
index++;
|
|
1123
|
+
if (!is("name", "on")) return broken("a fragment has no type condition (on Type)");
|
|
1124
|
+
index++;
|
|
1125
|
+
if (!is("name")) return broken("a fragment has no type condition (on Type)");
|
|
1126
|
+
index++;
|
|
1127
|
+
if (!skipDirectives()) return broken("a directive is cut short");
|
|
1128
|
+
if (!is("punctuator", "{") || !skipGroup()) return broken("a fragment has no selection set");
|
|
1129
|
+
fragments++;
|
|
1130
|
+
} else {
|
|
1131
|
+
return broken("a definition that is not a query, mutation, subscription or fragment");
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
const names = new Set(tokens.filter((token) => token.kind === "name").map((token) => token.value));
|
|
1135
|
+
return { ok: true, document: { operations, fragments, names } };
|
|
1136
|
+
}
|
|
1137
|
+
function fitAnswer(answer) {
|
|
1138
|
+
const limit = 31 * 1024;
|
|
1139
|
+
const shrunk = shrinkToFit(answer, limit);
|
|
1140
|
+
if (shrunk) return shrunk.truncated ? { ...shrunk.value, truncated: true } : answer;
|
|
1141
|
+
const text = JSON.stringify(answer["data"]) ?? "";
|
|
1142
|
+
const window = textWindow(text, 0, 28 * 1024);
|
|
1143
|
+
return {
|
|
1144
|
+
truncated: true,
|
|
1145
|
+
note: `The answer has ${formatNumber(utf8Length(text))} bytes and was cut to fit 32 KB: ask for fewer fields or items (first) to see it whole.`,
|
|
1146
|
+
text: window.text
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
var TEXT_WINDOW_BYTES = 24e3;
|
|
1150
|
+
function textWindow(text, offset, budget = TEXT_WINDOW_BYTES) {
|
|
1151
|
+
const start = Math.max(0, Math.min(Math.floor(offset), text.length));
|
|
1152
|
+
const rest = text.length - start;
|
|
1153
|
+
const size = (count2) => utf8Length(JSON.stringify(text.slice(start, start + count2)));
|
|
1154
|
+
let count = Math.min(rest, budget);
|
|
1155
|
+
if (size(count) > budget) {
|
|
1156
|
+
let low = 0;
|
|
1157
|
+
let high = count;
|
|
1158
|
+
while (low < high) {
|
|
1159
|
+
const middle = Math.ceil((low + high) / 2);
|
|
1160
|
+
if (size(middle) <= budget) low = middle;
|
|
1161
|
+
else high = middle - 1;
|
|
1162
|
+
}
|
|
1163
|
+
count = low;
|
|
1164
|
+
}
|
|
1165
|
+
if (count < rest) {
|
|
1166
|
+
const lineBreak = text.lastIndexOf("\n", start + count - 1);
|
|
1167
|
+
if (lineBreak >= start + Math.floor(count / 2)) count = lineBreak + 1 - start;
|
|
1168
|
+
const code = text.charCodeAt(start + count - 1);
|
|
1169
|
+
if (code >= 55296 && code <= 56319) count -= 1;
|
|
1170
|
+
}
|
|
1171
|
+
const end = start + Math.max(count, 0);
|
|
1172
|
+
return { text: text.slice(start, end), offset: start, ...end < text.length ? { next: end } : {} };
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
// src/vendors/hashnode/index.ts
|
|
1176
|
+
var DRAFT_FIELDS = "id title subtitle slug updatedAt canonicalUrl coverImage { url } tags { slug } series { name }";
|
|
1177
|
+
var POST_FIELDS = "id title slug url publishedAt";
|
|
1178
|
+
var PUBLICATION = "query Publication($host: String!) { publication(host: $host) { id title url isTeam } }";
|
|
1179
|
+
var ME = "query Me { me { id username publications(first: 50) { edges { node { id title url } } } } }";
|
|
1180
|
+
var POSTS = `query Posts($host: String!, $first: Int!, $after: String) { publication(host: $host) { id title
|
|
1181
|
+
posts(first: $first, after: $after) { totalDocuments pageInfo { hasNextPage endCursor } edges { node {
|
|
1182
|
+
id title slug url publishedAt updatedAt views reactionCount responseCount replyCount readTimeInMinutes tags { slug } series { name } } } } } }`;
|
|
1183
|
+
var DRAFTS = `query Drafts($host: String!, $first: Int!, $after: String) { publication(host: $host) { id title
|
|
1184
|
+
drafts(first: $first, after: $after) { totalDocuments pageInfo { hasNextPage endCursor } edges { node {
|
|
1185
|
+
id title subtitle updatedAt scheduledDate readTimeInMinutes canonicalUrl coverImage { url } tags { slug } series { name } } } } } }`;
|
|
1186
|
+
var DRAFT = `query Draft($id: ObjectId!) { draft(id: $id) { id title subtitle slug updatedAt readTimeInMinutes canonicalUrl isSubmittedForReview
|
|
1187
|
+
content { markdown } coverImage { url } tags { slug name } series { id name } seo { title description } } }`;
|
|
1188
|
+
var POST_DETAIL = `id title subtitle slug url publishedAt updatedAt canonicalUrl views reactionCount responseCount replyCount readTimeInMinutes
|
|
1189
|
+
content { markdown } coverImage { url } tags { slug name } series { id name } seo { title description }`;
|
|
1190
|
+
var POST_BY_SLUG = `query Post($host: String!, $slug: String!) { publication(host: $host) { id post(slug: $slug) { ${POST_DETAIL} } } }`;
|
|
1191
|
+
var POST_BY_ID = `query PostById($id: ID!) { post(id: $id) { ${POST_DETAIL} publication { id title url } } }`;
|
|
1192
|
+
var SERIES = "query Series($host: String!) { publication(host: $host) { id seriesList(first: 50) { edges { node { id name slug } } } } }";
|
|
1193
|
+
var CREATE_DRAFT = `mutation CreateDraft($input: CreateDraftInput!) { createDraft(input: $input) { draft { ${DRAFT_FIELDS} } } }`;
|
|
1194
|
+
var UPDATE_DRAFT = `mutation UpdateDraft($input: UpdateDraftInput!) { updateDraft(input: $input) { draft { ${DRAFT_FIELDS} } } }`;
|
|
1195
|
+
var PUBLISH_DRAFT = `mutation PublishDraft($input: PublishDraftInput!) { publishDraft(input: $input) { post { ${POST_FIELDS} } } }`;
|
|
1196
|
+
var PUBLISH_POST = `mutation PublishPost($input: PublishPostInput!) { publishPost(input: $input) { post { ${POST_FIELDS} } } }`;
|
|
1197
|
+
var UPDATE_POST = "mutation UpdatePost($input: UpdatePostInput!) { updatePost(input: $input) { post { id title slug url updatedAt } } }";
|
|
1198
|
+
var SUBMIT_DRAFT = "mutation SubmitDraft($input: SubmitDraftForReviewInput!) { submitDraftForReview(input: $input) { draft { id title isSubmittedForReview } } }";
|
|
1199
|
+
var DELETING_FIELDS = ["removePost", "deleteDraft"];
|
|
1200
|
+
var OBJECT_ID = { type: "string", pattern: "^[0-9a-fA-F]{24}$", description: "A Hashnode ID: 24 hexadecimal characters." };
|
|
1201
|
+
var CURSOR_SCHEMA = { type: "string", description: "nextCursor from the previous result." };
|
|
1202
|
+
var TAG_SCHEMA = {
|
|
1203
|
+
type: "array",
|
|
1204
|
+
maxItems: 15,
|
|
1205
|
+
items: {
|
|
1206
|
+
type: "object",
|
|
1207
|
+
properties: {
|
|
1208
|
+
slug: { type: "string", pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$", maxLength: 100, description: "Lowercase words joined by hyphens, e.g. web-development." },
|
|
1209
|
+
name: { type: "string", minLength: 1, maxLength: 100, description: "The display name, e.g. Web Development (default: the slug)." }
|
|
1210
|
+
},
|
|
1211
|
+
required: ["slug"],
|
|
1212
|
+
additionalProperties: false
|
|
1213
|
+
},
|
|
1214
|
+
description: "Up to 15 tags (about 5 that fit is best). An unknown slug creates a new tag, so prefer common ones such as javascript or ai. When given, they replace all tags."
|
|
1215
|
+
};
|
|
1216
|
+
var COMMON_FIELDS = {
|
|
1217
|
+
title: { type: "string", minLength: 1, maxLength: 250, description: "The title." },
|
|
1218
|
+
subtitle: { type: "string", maxLength: 250, description: "A subtitle." },
|
|
1219
|
+
content_markdown: {
|
|
1220
|
+
type: "string",
|
|
1221
|
+
minLength: 1,
|
|
1222
|
+
maxLength: 1e5,
|
|
1223
|
+
description: "The body in Markdown. Start sections at ##: the title is the page heading. Hashnode takes requests up to 100 KB."
|
|
1224
|
+
},
|
|
1225
|
+
tags: TAG_SCHEMA,
|
|
1226
|
+
cover_image_url: { type: "string", format: "uri", maxLength: 2e3, description: "The cover, as a public https image URL." },
|
|
1227
|
+
original_article_url: {
|
|
1228
|
+
type: "string",
|
|
1229
|
+
format: "uri",
|
|
1230
|
+
maxLength: 2e3,
|
|
1231
|
+
description: "The original post's URL when the article first appeared elsewhere (a cross-post), so search engines credit it."
|
|
1232
|
+
},
|
|
1233
|
+
series_id: { ...OBJECT_ID, description: "A series of the blog, from list_series. The API cannot create a series." },
|
|
1234
|
+
slug: { type: "string", pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$", maxLength: 250, description: "The URL slug (default: made from the title)." },
|
|
1235
|
+
meta_title: { type: "string", maxLength: 250, description: "An SEO title, when it should differ from the title." },
|
|
1236
|
+
meta_description: { type: "string", maxLength: 500, description: "An SEO description for search results." },
|
|
1237
|
+
meta_image_url: { type: "string", format: "uri", maxLength: 2e3, description: "A social image URL, when it should differ from the cover." },
|
|
1238
|
+
table_of_contents: { type: "boolean", description: "true adds a table of contents." },
|
|
1239
|
+
delist: { type: "boolean", description: "true keeps the post out of Hashnode's feeds (still reachable by its URL). Only when asked." },
|
|
1240
|
+
published_at: {
|
|
1241
|
+
type: "string",
|
|
1242
|
+
maxLength: 40,
|
|
1243
|
+
description: "Only to backdate a post moved from another blog to its original date (ISO 8601). It does not schedule."
|
|
1244
|
+
}
|
|
1245
|
+
};
|
|
1246
|
+
function tagsInput(tags) {
|
|
1247
|
+
return tags?.map((tag) => ({ slug: tag.slug, name: tag.name ?? tag.slug }));
|
|
1248
|
+
}
|
|
1249
|
+
function draftInput(args) {
|
|
1250
|
+
const meta = compact({ title: args.meta_title, description: args.meta_description, image: args.meta_image_url });
|
|
1251
|
+
const settings = compact({ enableTableOfContent: args.table_of_contents, delist: args.delist, activateNewsletter: args.send_newsletter });
|
|
1252
|
+
return compact({
|
|
1253
|
+
title: args.title,
|
|
1254
|
+
subtitle: args.subtitle,
|
|
1255
|
+
contentMarkdown: args.content_markdown,
|
|
1256
|
+
tags: tagsInput(args.tags),
|
|
1257
|
+
coverImageOptions: args.cover_image_url !== void 0 ? { coverImageURL: args.cover_image_url } : void 0,
|
|
1258
|
+
originalArticleURL: args.original_article_url,
|
|
1259
|
+
seriesId: args.series_id,
|
|
1260
|
+
slug: args.slug,
|
|
1261
|
+
metaTags: Object.keys(meta).length ? meta : void 0,
|
|
1262
|
+
settings: Object.keys(settings).length ? settings : void 0,
|
|
1263
|
+
publishedAt: args.published_at
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
function postInput(args) {
|
|
1267
|
+
return compact({
|
|
1268
|
+
title: args.title,
|
|
1269
|
+
subtitle: args.subtitle,
|
|
1270
|
+
contentMarkdown: args.content_markdown,
|
|
1271
|
+
tags: tagsInput(args.tags),
|
|
1272
|
+
coverImage: args.cover_image_url,
|
|
1273
|
+
originalArticleURL: args.original_article_url,
|
|
1274
|
+
seriesId: args.series_id,
|
|
1275
|
+
slug: args.slug,
|
|
1276
|
+
metaTitle: args.meta_title,
|
|
1277
|
+
metaDescription: args.meta_description,
|
|
1278
|
+
ogImage: args.meta_image_url,
|
|
1279
|
+
enableToc: args.table_of_contents,
|
|
1280
|
+
isDelisted: args.delist,
|
|
1281
|
+
publishedAt: args.published_at
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
function editorUrl(id) {
|
|
1285
|
+
return typeof id === "string" && /^[0-9a-fA-F]{24}$/.test(id) ? `https://hashnode.com/draft/${id}` : void 0;
|
|
1286
|
+
}
|
|
1287
|
+
function trimDraft(draft) {
|
|
1288
|
+
return compact({
|
|
1289
|
+
id: draft?.id,
|
|
1290
|
+
title: draft?.title ?? void 0,
|
|
1291
|
+
subtitle: draft?.subtitle ?? void 0,
|
|
1292
|
+
slug: draft?.slug ?? void 0,
|
|
1293
|
+
updated_at: draft?.updatedAt ?? void 0,
|
|
1294
|
+
scheduled_date: draft?.scheduledDate ?? void 0,
|
|
1295
|
+
read_time_minutes: draft?.readTimeInMinutes ?? void 0,
|
|
1296
|
+
canonical_url: draft?.canonicalUrl ?? void 0,
|
|
1297
|
+
cover_image: draft?.coverImage?.url ?? void 0,
|
|
1298
|
+
tags: Array.isArray(draft?.tags) ? draft.tags.map((tag) => tag?.slug) : void 0,
|
|
1299
|
+
series: draft?.series?.name ?? void 0,
|
|
1300
|
+
submitted_for_review: draft?.isSubmittedForReview === true ? true : void 0,
|
|
1301
|
+
editor_url: editorUrl(draft?.id)
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
1304
|
+
function trimPost(post) {
|
|
1305
|
+
return compact({
|
|
1306
|
+
id: post?.id,
|
|
1307
|
+
title: post?.title,
|
|
1308
|
+
subtitle: post?.subtitle ?? void 0,
|
|
1309
|
+
slug: post?.slug,
|
|
1310
|
+
url: post?.url,
|
|
1311
|
+
published_at: post?.publishedAt ?? void 0,
|
|
1312
|
+
updated_at: post?.updatedAt ?? void 0,
|
|
1313
|
+
canonical_url: post?.canonicalUrl ?? void 0,
|
|
1314
|
+
views: typeof post?.views === "number" ? post.views : void 0,
|
|
1315
|
+
reactions: post?.reactionCount ?? void 0,
|
|
1316
|
+
comments: post?.responseCount ?? void 0,
|
|
1317
|
+
replies: post?.replyCount ?? void 0,
|
|
1318
|
+
read_time_minutes: post?.readTimeInMinutes ?? void 0,
|
|
1319
|
+
cover_image: post?.coverImage?.url ?? void 0,
|
|
1320
|
+
tags: Array.isArray(post?.tags) ? post.tags.map((tag) => tag?.slug) : void 0,
|
|
1321
|
+
series: post?.series?.name ?? void 0
|
|
1322
|
+
});
|
|
1323
|
+
}
|
|
1324
|
+
async function findBlog(h) {
|
|
1325
|
+
const host = h.credentials["publicationhost"];
|
|
1326
|
+
const result2 = await gql(h, PUBLICATION, { host });
|
|
1327
|
+
const publication = rootField(result2, "publication", false);
|
|
1328
|
+
if (!publication?.id) {
|
|
1329
|
+
throw new ToolFailure(
|
|
1330
|
+
`Hashnode has no blog at ${host}. The blog address must be the bare host the browser shows, such as yourname.hashnode.dev or blog.example.com; list_my_blogs lists the blogs this account owns. Nothing was changed.`
|
|
1331
|
+
);
|
|
1332
|
+
}
|
|
1333
|
+
return publication;
|
|
1334
|
+
}
|
|
1335
|
+
function cursorState(h, cursor) {
|
|
1336
|
+
const state = h.cursor(cursor);
|
|
1337
|
+
return {
|
|
1338
|
+
...typeof state?.["a"] === "string" && state["a"] ? { after: state["a"] } : {},
|
|
1339
|
+
skip: typeof state?.["o"] === "number" ? state["o"] : 0
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
function connectionPage(h, key, connection, items, after, skip, extra) {
|
|
1343
|
+
const next = connection?.pageInfo?.hasNextPage === true && typeof connection?.pageInfo?.endCursor === "string" ? connection.pageInfo.endCursor : void 0;
|
|
1344
|
+
return h.page({
|
|
1345
|
+
key,
|
|
1346
|
+
items: items.slice(skip),
|
|
1347
|
+
extra,
|
|
1348
|
+
resumeAt: (index) => h.makeCursor({ ...after ? { a: after } : {}, o: skip + index }),
|
|
1349
|
+
...next ? { nextPage: h.makeCursor({ a: next, o: 0 }) } : {}
|
|
1350
|
+
});
|
|
1351
|
+
}
|
|
1352
|
+
function withMarkdown(h, base, markdown, cursor) {
|
|
1353
|
+
const text = typeof markdown === "string" ? markdown : "";
|
|
1354
|
+
const state = h.cursor(cursor);
|
|
1355
|
+
const window = textWindow(text, typeof state?.["o"] === "number" ? state["o"] : 0, TEXT_WINDOW_BYTES);
|
|
1356
|
+
return compact({
|
|
1357
|
+
...base,
|
|
1358
|
+
markdown: window.text,
|
|
1359
|
+
markdown_offset: window.offset || void 0,
|
|
1360
|
+
markdown_length: text.length,
|
|
1361
|
+
nextCursor: window.next !== void 0 ? h.makeCursor({ o: window.next }) : void 0
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
function mutationResult(result2, field, inner) {
|
|
1365
|
+
const value = rootField(result2, field, true)?.[inner];
|
|
1366
|
+
if (!value || typeof value !== "object") {
|
|
1367
|
+
throw new OutcomeUnknown(`Hashnode answered without the ${inner}, so it is not known whether the change was made.`);
|
|
1368
|
+
}
|
|
1369
|
+
return value;
|
|
1370
|
+
}
|
|
1371
|
+
function oneOperation(query, tool) {
|
|
1372
|
+
const parsed = parseDocument(query);
|
|
1373
|
+
if (!parsed.ok) throw new ToolFailure(`The document is not GraphQL that ${tool} can send: ${parsed.problem}. Nothing was sent.`);
|
|
1374
|
+
const { document } = parsed;
|
|
1375
|
+
if (document.operations.some((operation) => operation.type === "subscription")) {
|
|
1376
|
+
throw new ToolFailure("Subscriptions are not supported. Nothing was sent.");
|
|
1377
|
+
}
|
|
1378
|
+
if (document.operations.length > 1) {
|
|
1379
|
+
throw new ToolFailure(`${tool} sends one operation per call (and the fragments it uses): send each one on its own. Nothing was sent.`);
|
|
1380
|
+
}
|
|
1381
|
+
return { document, type: document.operations[0]?.type ?? "none" };
|
|
1382
|
+
}
|
|
1383
|
+
function failedWhole(result2) {
|
|
1384
|
+
if (!result2.errors.length) return false;
|
|
1385
|
+
const data = result2.data;
|
|
1386
|
+
if (data === null || typeof data !== "object") return true;
|
|
1387
|
+
const values = Object.values(data);
|
|
1388
|
+
return values.length === 0 || values.every((value) => value === null);
|
|
1389
|
+
}
|
|
1390
|
+
function needSomething(input, idField) {
|
|
1391
|
+
if (Object.keys(input).filter((key) => key !== idField).length === 0) {
|
|
1392
|
+
throw new ToolFailure("Nothing to change: give at least one field besides the ID. Nothing was changed.");
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
var connector = defineConnector({
|
|
1396
|
+
vendor: "hashnode",
|
|
1397
|
+
label: "Hashnode",
|
|
1398
|
+
origins: ["https://gql-beta.hashnode.com"],
|
|
1399
|
+
credentials: ["token", "publicationhost"],
|
|
1400
|
+
credentialLabels: { token: "Hashnode Personal Access Token", publicationhost: "Hashnode blog address" },
|
|
1401
|
+
normalizeCredentials: (credentials) => ({
|
|
1402
|
+
...credentials,
|
|
1403
|
+
token: (credentials["token"] ?? "").replace(/^Bearer\s+/i, ""),
|
|
1404
|
+
publicationhost: (credentials["publicationhost"] ?? "").toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//, "").split(/[/?#]/)[0].replace(/\.$/, "")
|
|
1405
|
+
}),
|
|
1406
|
+
authHeaders: (credentials) => ({ authorization: credentials["token"] }),
|
|
1407
|
+
tools: [
|
|
1408
|
+
{
|
|
1409
|
+
name: "get_blog",
|
|
1410
|
+
kind: "read",
|
|
1411
|
+
title: "Get the Hashnode blog",
|
|
1412
|
+
description: "Finds the blog at the saved address: its ID, title, URL and whether it is a team blog. It also tells whether the blog is on Hashnode Pro, which Hashnode's API needs for every call on a blog.",
|
|
1413
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
1414
|
+
async run(_args, h) {
|
|
1415
|
+
const blog = await findBlog(h);
|
|
1416
|
+
return compact({ id: blog.id, title: blog.title, url: blog.url ?? void 0, is_team: blog.isTeam === true, host: h.credentials["publicationhost"] });
|
|
1417
|
+
}
|
|
1418
|
+
},
|
|
1419
|
+
{
|
|
1420
|
+
name: "list_my_blogs",
|
|
1421
|
+
kind: "read",
|
|
1422
|
+
title: "List my Hashnode blogs",
|
|
1423
|
+
description: "The token's own account and the blogs it owns, with their IDs and URLs: to find the right blog address when the saved one is not found.",
|
|
1424
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
1425
|
+
async run(_args, h) {
|
|
1426
|
+
const me = rootField(await gql(h, ME, void 0), "me", false);
|
|
1427
|
+
if (!me) throw new ToolFailure("Hashnode returned no account for this token: check that the Hashnode Personal Access Token is correct.");
|
|
1428
|
+
const blogs = Array.isArray(me?.publications?.edges) ? me.publications.edges.map((edge) => compact({ id: edge?.node?.id, title: edge?.node?.title, url: edge?.node?.url ?? void 0 })) : [];
|
|
1429
|
+
return { account: compact({ id: me.id, username: me.username }), blogs };
|
|
1430
|
+
}
|
|
1431
|
+
},
|
|
1432
|
+
{
|
|
1433
|
+
name: "list_posts",
|
|
1434
|
+
kind: "read",
|
|
1435
|
+
title: "List Hashnode posts with stats",
|
|
1436
|
+
description: "The blog's published posts, newest first, with views, reactions, comments and replies (lifetime numbers; views may be missing when Hashnode does not report them, which is not zero). Hashnode may serve a list up to about 25 seconds old. Pass nextCursor back as cursor for more.",
|
|
1437
|
+
inputSchema: {
|
|
1438
|
+
type: "object",
|
|
1439
|
+
properties: {
|
|
1440
|
+
first: { type: "integer", minimum: 1, maximum: 100, default: 20, description: "Posts per page, 1 to 100 (default 20)." },
|
|
1441
|
+
cursor: CURSOR_SCHEMA
|
|
1442
|
+
},
|
|
1443
|
+
additionalProperties: false
|
|
1444
|
+
},
|
|
1445
|
+
async run(args, h) {
|
|
1446
|
+
const { after, skip } = cursorState(h, args.cursor);
|
|
1447
|
+
const result2 = await gql(h, POSTS, compact({ host: h.credentials["publicationhost"], first: args.first, after }));
|
|
1448
|
+
const publication = rootField(result2, "publication", false);
|
|
1449
|
+
if (!publication) throw new ToolFailure(`Hashnode has no blog at ${h.credentials["publicationhost"]}: check the blog address (list_my_blogs lists your blogs).`);
|
|
1450
|
+
const connection = publication.posts;
|
|
1451
|
+
const posts = Array.isArray(connection?.edges) ? connection.edges.map((edge) => trimPost(edge?.node)) : [];
|
|
1452
|
+
return connectionPage(h, "posts", connection, posts, after, skip, compact({ blog: publication.title, total: connection?.totalDocuments, warnings: warningsOf(result2) }));
|
|
1453
|
+
}
|
|
1454
|
+
},
|
|
1455
|
+
{
|
|
1456
|
+
name: "list_drafts",
|
|
1457
|
+
kind: "read",
|
|
1458
|
+
title: "List my Hashnode drafts",
|
|
1459
|
+
description: "The token account's own drafts on the blog, newest first, with their editor links (they open for a signed-in member of the blog). Pass nextCursor back as cursor for more.",
|
|
1460
|
+
inputSchema: {
|
|
1461
|
+
type: "object",
|
|
1462
|
+
properties: {
|
|
1463
|
+
first: { type: "integer", minimum: 1, maximum: 50, default: 20, description: "Drafts per page, 1 to 50 (default 20)." },
|
|
1464
|
+
cursor: CURSOR_SCHEMA
|
|
1465
|
+
},
|
|
1466
|
+
additionalProperties: false
|
|
1467
|
+
},
|
|
1468
|
+
async run(args, h) {
|
|
1469
|
+
const { after, skip } = cursorState(h, args.cursor);
|
|
1470
|
+
const result2 = await gql(h, DRAFTS, compact({ host: h.credentials["publicationhost"], first: args.first, after }));
|
|
1471
|
+
const publication = rootField(result2, "publication", false);
|
|
1472
|
+
if (!publication) throw new ToolFailure(`Hashnode has no blog at ${h.credentials["publicationhost"]}: check the blog address (list_my_blogs lists your blogs).`);
|
|
1473
|
+
const connection = publication.drafts;
|
|
1474
|
+
const drafts = Array.isArray(connection?.edges) ? connection.edges.map((edge) => trimDraft(edge?.node)) : [];
|
|
1475
|
+
return connectionPage(h, "drafts", connection, drafts, after, skip, compact({ blog: publication.title, total: connection?.totalDocuments, warnings: warningsOf(result2) }));
|
|
1476
|
+
}
|
|
1477
|
+
},
|
|
1478
|
+
{
|
|
1479
|
+
name: "get_draft",
|
|
1480
|
+
kind: "read",
|
|
1481
|
+
title: "Read a Hashnode draft",
|
|
1482
|
+
description: "One draft with its Markdown, tags, cover, series, SEO fields and editor link: to show it before publishing or to edit it. A long body comes in windows: pass nextCursor back as cursor. A draft this account may not see answers NOT_FOUND.",
|
|
1483
|
+
inputSchema: {
|
|
1484
|
+
type: "object",
|
|
1485
|
+
properties: { draft_id: { ...OBJECT_ID, description: "The draft ID, from create_draft or list_drafts." }, cursor: CURSOR_SCHEMA },
|
|
1486
|
+
required: ["draft_id"],
|
|
1487
|
+
additionalProperties: false
|
|
1488
|
+
},
|
|
1489
|
+
async run(args, h) {
|
|
1490
|
+
const result2 = await gql(h, DRAFT, { id: args.draft_id });
|
|
1491
|
+
const draft = rootField(result2, "draft", false);
|
|
1492
|
+
if (!draft) throw new ToolFailure("Hashnode found no draft with that ID that this account can see.");
|
|
1493
|
+
const base = compact({
|
|
1494
|
+
...trimDraft(draft),
|
|
1495
|
+
tags: Array.isArray(draft.tags) ? draft.tags.map((tag) => compact({ slug: tag?.slug, name: tag?.name })) : void 0,
|
|
1496
|
+
series: draft.series ? compact({ id: draft.series.id, name: draft.series.name }) : void 0,
|
|
1497
|
+
seo: draft.seo && (draft.seo.title || draft.seo.description) ? compact({ title: draft.seo.title, description: draft.seo.description }) : void 0,
|
|
1498
|
+
published: false
|
|
1499
|
+
});
|
|
1500
|
+
return withMarkdown(h, base, draft.content?.markdown, args.cursor);
|
|
1501
|
+
}
|
|
1502
|
+
},
|
|
1503
|
+
{
|
|
1504
|
+
name: "get_post",
|
|
1505
|
+
kind: "read",
|
|
1506
|
+
title: "Read a Hashnode post",
|
|
1507
|
+
description: "One published post, by its slug on the blog (the last part of its URL) or by its ID: stats, tags, cover, series and its Markdown. A long body comes in windows: pass nextCursor back as cursor.",
|
|
1508
|
+
inputSchema: {
|
|
1509
|
+
type: "object",
|
|
1510
|
+
properties: {
|
|
1511
|
+
slug: { type: "string", minLength: 1, maxLength: 250, description: "The post's slug on the blog." },
|
|
1512
|
+
post_id: { ...OBJECT_ID, description: "The post ID instead of the slug." },
|
|
1513
|
+
cursor: CURSOR_SCHEMA
|
|
1514
|
+
},
|
|
1515
|
+
additionalProperties: false
|
|
1516
|
+
},
|
|
1517
|
+
async run(args, h) {
|
|
1518
|
+
if (args.slug === void 0 === (args.post_id === void 0)) throw new ToolFailure("Give slug or post_id (one of them). Nothing was sent.");
|
|
1519
|
+
let post;
|
|
1520
|
+
if (args.post_id !== void 0) {
|
|
1521
|
+
post = rootField(await gql(h, POST_BY_ID, { id: args.post_id }), "post", false);
|
|
1522
|
+
} else {
|
|
1523
|
+
const publication = rootField(await gql(h, POST_BY_SLUG, { host: h.credentials["publicationhost"], slug: args.slug }), "publication", false);
|
|
1524
|
+
if (!publication) throw new ToolFailure(`Hashnode has no blog at ${h.credentials["publicationhost"]}: check the blog address.`);
|
|
1525
|
+
post = publication.post;
|
|
1526
|
+
}
|
|
1527
|
+
if (!post) throw new ToolFailure("Hashnode found no post there: check the slug or the ID.");
|
|
1528
|
+
const base = compact({
|
|
1529
|
+
...trimPost(post),
|
|
1530
|
+
tags: Array.isArray(post.tags) ? post.tags.map((tag) => compact({ slug: tag?.slug, name: tag?.name })) : void 0,
|
|
1531
|
+
series: post.series ? compact({ id: post.series.id, name: post.series.name }) : void 0,
|
|
1532
|
+
seo: post.seo && (post.seo.title || post.seo.description) ? compact({ title: post.seo.title, description: post.seo.description }) : void 0,
|
|
1533
|
+
blog: post.publication ? compact({ id: post.publication.id, title: post.publication.title, url: post.publication.url }) : void 0
|
|
1534
|
+
});
|
|
1535
|
+
return withMarkdown(h, base, post.content?.markdown, args.cursor);
|
|
1536
|
+
}
|
|
1537
|
+
},
|
|
1538
|
+
{
|
|
1539
|
+
name: "list_series",
|
|
1540
|
+
kind: "read",
|
|
1541
|
+
title: "List the Hashnode blog's series",
|
|
1542
|
+
description: "The blog's series with their IDs, for series_id on a draft or a post. The API cannot create a series: that is done in the blog dashboard.",
|
|
1543
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
1544
|
+
async run(_args, h) {
|
|
1545
|
+
const publication = rootField(await gql(h, SERIES, { host: h.credentials["publicationhost"] }), "publication", false);
|
|
1546
|
+
if (!publication) throw new ToolFailure(`Hashnode has no blog at ${h.credentials["publicationhost"]}: check the blog address.`);
|
|
1547
|
+
const series = Array.isArray(publication.seriesList?.edges) ? publication.seriesList.edges.map((edge) => compact({ id: edge?.node?.id, name: edge?.node?.name, slug: edge?.node?.slug })) : [];
|
|
1548
|
+
return { series };
|
|
1549
|
+
}
|
|
1550
|
+
},
|
|
1551
|
+
{
|
|
1552
|
+
name: "create_draft",
|
|
1553
|
+
kind: "create",
|
|
1554
|
+
check: "list_drafts",
|
|
1555
|
+
title: "Save a Hashnode draft",
|
|
1556
|
+
description: "Saves a post as a draft on the blog; nothing becomes public. Returns the draft ID and its editor link. publish_draft publishes it later. send_newsletter emails the blog's newsletter subscribers when the post goes live: set it only when asked to.",
|
|
1557
|
+
inputSchema: {
|
|
1558
|
+
type: "object",
|
|
1559
|
+
properties: {
|
|
1560
|
+
...COMMON_FIELDS,
|
|
1561
|
+
send_newsletter: { type: "boolean", description: "true emails the blog's newsletter subscribers when the post is published. Only when asked." }
|
|
1562
|
+
},
|
|
1563
|
+
required: ["title", "content_markdown"],
|
|
1564
|
+
additionalProperties: false
|
|
1565
|
+
},
|
|
1566
|
+
async run(args, h) {
|
|
1567
|
+
const blog = await findBlog(h);
|
|
1568
|
+
const result2 = await gql(h, CREATE_DRAFT, { input: { publicationId: blog.id, ...draftInput(args) } }, { write: true });
|
|
1569
|
+
const draft = mutationResult(result2, "createDraft", "draft");
|
|
1570
|
+
return compact({ saved: "draft, not published", ...trimDraft(draft), blog: blog.title, warnings: warningsOf(result2) });
|
|
1571
|
+
}
|
|
1572
|
+
},
|
|
1573
|
+
{
|
|
1574
|
+
name: "update_draft",
|
|
1575
|
+
kind: "update",
|
|
1576
|
+
check: "get_draft",
|
|
1577
|
+
title: "Edit a Hashnode draft",
|
|
1578
|
+
description: "Changes a draft: only the fields given change; tags, when given, replace all tags, and content_markdown replaces the whole body (read it with get_draft first). Nothing becomes public.",
|
|
1579
|
+
inputSchema: {
|
|
1580
|
+
type: "object",
|
|
1581
|
+
properties: {
|
|
1582
|
+
draft_id: { ...OBJECT_ID, description: "The draft ID." },
|
|
1583
|
+
...COMMON_FIELDS,
|
|
1584
|
+
send_newsletter: { type: "boolean", description: "true emails the blog's newsletter subscribers when the post is published. Only when asked." }
|
|
1585
|
+
},
|
|
1586
|
+
required: ["draft_id"],
|
|
1587
|
+
additionalProperties: false
|
|
1588
|
+
},
|
|
1589
|
+
async run(args, h) {
|
|
1590
|
+
const input = { draftId: args.draft_id, ...draftInput(args) };
|
|
1591
|
+
needSomething(input, "draftId");
|
|
1592
|
+
const result2 = await gql(h, UPDATE_DRAFT, { input }, { write: true });
|
|
1593
|
+
const draft = mutationResult(result2, "updateDraft", "draft");
|
|
1594
|
+
return compact({ saved: "draft, not published", ...trimDraft(draft), warnings: warningsOf(result2) });
|
|
1595
|
+
}
|
|
1596
|
+
},
|
|
1597
|
+
{
|
|
1598
|
+
name: "publish_draft",
|
|
1599
|
+
kind: "update",
|
|
1600
|
+
check: "list_posts",
|
|
1601
|
+
title: "Publish a Hashnode draft",
|
|
1602
|
+
description: "Publishes a saved draft: Hashnode turns it into a live post on the blog and removes the draft. Returns the post's URL on the blog.",
|
|
1603
|
+
inputSchema: {
|
|
1604
|
+
type: "object",
|
|
1605
|
+
properties: { draft_id: { ...OBJECT_ID, description: "The draft ID." } },
|
|
1606
|
+
required: ["draft_id"],
|
|
1607
|
+
additionalProperties: false
|
|
1608
|
+
},
|
|
1609
|
+
async run(args, h) {
|
|
1610
|
+
const result2 = await gql(h, PUBLISH_DRAFT, { input: { draftId: args.draft_id } }, { write: true });
|
|
1611
|
+
const post = mutationResult(result2, "publishDraft", "post");
|
|
1612
|
+
return compact({ published: true, ...trimPost(post), warnings: warningsOf(result2) });
|
|
1613
|
+
}
|
|
1614
|
+
},
|
|
1615
|
+
{
|
|
1616
|
+
name: "publish_post",
|
|
1617
|
+
kind: "create",
|
|
1618
|
+
check: "list_posts",
|
|
1619
|
+
title: "Publish a Hashnode post now",
|
|
1620
|
+
description: "Publishes a new post on the blog in one step, with no draft: it is live at once. Use create_draft when the post should be reviewed first. Returns the post's URL on the blog.",
|
|
1621
|
+
inputSchema: {
|
|
1622
|
+
type: "object",
|
|
1623
|
+
properties: COMMON_FIELDS,
|
|
1624
|
+
required: ["title", "content_markdown"],
|
|
1625
|
+
additionalProperties: false
|
|
1626
|
+
},
|
|
1627
|
+
async run(args, h) {
|
|
1628
|
+
const blog = await findBlog(h);
|
|
1629
|
+
const result2 = await gql(h, PUBLISH_POST, { input: { publicationId: blog.id, ...postInput(args) } }, { write: true });
|
|
1630
|
+
const post = mutationResult(result2, "publishPost", "post");
|
|
1631
|
+
return compact({ published: true, ...trimPost(post), warnings: warningsOf(result2) });
|
|
1632
|
+
}
|
|
1633
|
+
},
|
|
1634
|
+
{
|
|
1635
|
+
name: "update_post",
|
|
1636
|
+
kind: "update",
|
|
1637
|
+
check: "get_post",
|
|
1638
|
+
title: "Edit a published Hashnode post",
|
|
1639
|
+
description: "Changes a published post live, at once: only the fields given change; tags, when given, replace all tags, and content_markdown replaces the whole body (read it with get_post first).",
|
|
1640
|
+
inputSchema: {
|
|
1641
|
+
type: "object",
|
|
1642
|
+
properties: { post_id: { ...OBJECT_ID, description: "The post ID, from list_posts." }, ...COMMON_FIELDS },
|
|
1643
|
+
required: ["post_id"],
|
|
1644
|
+
additionalProperties: false
|
|
1645
|
+
},
|
|
1646
|
+
async run(args, h) {
|
|
1647
|
+
const input = { id: args.post_id, ...postInput(args) };
|
|
1648
|
+
needSomething(input, "id");
|
|
1649
|
+
const result2 = await gql(h, UPDATE_POST, { input }, { write: true });
|
|
1650
|
+
const post = mutationResult(result2, "updatePost", "post");
|
|
1651
|
+
return compact({ updated: true, ...trimPost(post), warnings: warningsOf(result2) });
|
|
1652
|
+
}
|
|
1653
|
+
},
|
|
1654
|
+
{
|
|
1655
|
+
name: "submit_draft_for_review",
|
|
1656
|
+
kind: "update",
|
|
1657
|
+
check: "get_draft",
|
|
1658
|
+
title: "Send a Hashnode draft for review",
|
|
1659
|
+
description: "On a team blog where this account is a contributor (it cannot publish), hands a draft to the blog's editors for review.",
|
|
1660
|
+
inputSchema: {
|
|
1661
|
+
type: "object",
|
|
1662
|
+
properties: { draft_id: { ...OBJECT_ID, description: "The draft ID." } },
|
|
1663
|
+
required: ["draft_id"],
|
|
1664
|
+
additionalProperties: false
|
|
1665
|
+
},
|
|
1666
|
+
async run(args, h) {
|
|
1667
|
+
const result2 = await gql(h, SUBMIT_DRAFT, { input: { draftId: args.draft_id } }, { write: true });
|
|
1668
|
+
const draft = mutationResult(result2, "submitDraftForReview", "draft");
|
|
1669
|
+
return compact({ submitted_for_review: draft?.isSubmittedForReview !== false, id: draft?.id, title: draft?.title ?? void 0, warnings: warningsOf(result2) });
|
|
1670
|
+
}
|
|
1671
|
+
},
|
|
1672
|
+
{
|
|
1673
|
+
name: "graphql_query",
|
|
1674
|
+
kind: "read",
|
|
1675
|
+
title: "Run a Hashnode GraphQL query",
|
|
1676
|
+
description: "Any other read of Hashnode's GraphQL API at https://gql-beta.hashnode.com, with the connected token, such as a tag, a user, searchPostsOfPublication, scheduled drafts or a post's comments. One query per call, with any fragments it uses; the endpoint serves its schema by introspection. Returns data, and errors when some fields failed, cut to fit 32 KB (use first to page).",
|
|
1677
|
+
inputSchema: {
|
|
1678
|
+
type: "object",
|
|
1679
|
+
properties: {
|
|
1680
|
+
query: { type: "string", minLength: 1, maxLength: 2e4, description: "The GraphQL document: one query (and its fragments), no mutation." },
|
|
1681
|
+
variables: { type: "object", description: 'The variables, e.g. {"host": "yourname.hashnode.dev"}.' }
|
|
1682
|
+
},
|
|
1683
|
+
required: ["query"],
|
|
1684
|
+
additionalProperties: false
|
|
1685
|
+
},
|
|
1686
|
+
async run(args, h) {
|
|
1687
|
+
const { type } = oneOperation(args.query, "graphql_query");
|
|
1688
|
+
if (type === "mutation") throw new ToolFailure("graphql_query runs queries only: send a mutation with graphql_mutation. Nothing was sent.");
|
|
1689
|
+
if (type !== "query") throw new ToolFailure("The document has no query operation. Nothing was sent.");
|
|
1690
|
+
const result2 = await gql(h, args.query, args.variables);
|
|
1691
|
+
if (failedWhole(result2)) failFromErrors(result2.errors, false);
|
|
1692
|
+
return fitAnswer(compact({ data: result2.data, errors: warningsOf(result2) }));
|
|
1693
|
+
}
|
|
1694
|
+
},
|
|
1695
|
+
{
|
|
1696
|
+
name: "graphql_mutation",
|
|
1697
|
+
kind: "write",
|
|
1698
|
+
check: "graphql_query",
|
|
1699
|
+
title: "Run a Hashnode GraphQL mutation",
|
|
1700
|
+
description: "Any other change through Hashnode's GraphQL API, with the connected token, such as rejecting a submitted draft. One mutation per call, with any fragments it uses; sent once, never retried. Deleting posts and drafts (removePost, deleteDraft) is not offered: delete them in Hashnode.",
|
|
1701
|
+
inputSchema: {
|
|
1702
|
+
type: "object",
|
|
1703
|
+
properties: {
|
|
1704
|
+
query: { type: "string", minLength: 1, maxLength: 12e4, description: "The GraphQL document: one mutation (and its fragments)." },
|
|
1705
|
+
variables: { type: "object", description: 'The variables, e.g. {"input": {...}}.' }
|
|
1706
|
+
},
|
|
1707
|
+
required: ["query"],
|
|
1708
|
+
additionalProperties: false
|
|
1709
|
+
},
|
|
1710
|
+
async run(args, h) {
|
|
1711
|
+
const { document, type } = oneOperation(args.query, "graphql_mutation");
|
|
1712
|
+
if (type !== "mutation") throw new ToolFailure("The document has no mutation: run queries with graphql_query. Nothing was sent.");
|
|
1713
|
+
const deleting = DELETING_FIELDS.find((field) => document.names.has(field));
|
|
1714
|
+
if (deleting) throw new ToolFailure(`${deleting} is not offered here: Hashnode deletes for good, so delete it in Hashnode itself. Nothing was sent.`);
|
|
1715
|
+
const result2 = await gql(h, args.query, args.variables, { write: true });
|
|
1716
|
+
if (failedWhole(result2)) failFromErrors(result2.errors, true);
|
|
1717
|
+
return fitAnswer(compact({ data: result2.data, errors: warningsOf(result2) }));
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
]
|
|
1721
|
+
});
|
|
1722
|
+
module.exports = connector;
|