@telemai/sdk 0.7.0 → 0.8.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/README.md +37 -6
- package/dist/{chunk-TST6J3VA.js → chunk-274HRD4N.js} +34 -6
- package/dist/index.cjs +297 -90
- package/dist/index.d.cts +52 -2
- package/dist/index.d.ts +52 -2
- package/dist/index.js +272 -81
- package/dist/vercel/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -50,6 +50,7 @@ var TelemError = class extends Error {
|
|
|
50
50
|
this.status = options.status;
|
|
51
51
|
this.code = options.code;
|
|
52
52
|
this.details = options.details;
|
|
53
|
+
if (options.retryAfter !== void 0) this.retryAfter = options.retryAfter;
|
|
53
54
|
}
|
|
54
55
|
};
|
|
55
56
|
var TimeoutError = class extends TelemError {
|
|
@@ -60,7 +61,7 @@ var TimeoutError = class extends TelemError {
|
|
|
60
61
|
};
|
|
61
62
|
|
|
62
63
|
// src/version.ts
|
|
63
|
-
var VERSION = "0.
|
|
64
|
+
var VERSION = "0.8.0";
|
|
64
65
|
|
|
65
66
|
// src/config.ts
|
|
66
67
|
var DEFAULT_BASE_URL = "https://router.telem.ai";
|
|
@@ -195,6 +196,11 @@ function asObject(value) {
|
|
|
195
196
|
function asArray(value) {
|
|
196
197
|
return Array.isArray(value) ? value : [];
|
|
197
198
|
}
|
|
199
|
+
var optString = (v) => typeof v === "string" ? v : null;
|
|
200
|
+
var optStrings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string") ? v : null;
|
|
201
|
+
var optInt = (v) => Number.isInteger(v) ? v : null;
|
|
202
|
+
var optBool = (v) => typeof v === "boolean" ? v : null;
|
|
203
|
+
var optObject = (v) => isObject(v) ? v : null;
|
|
198
204
|
function invalidRequest(message) {
|
|
199
205
|
return new TelemError(message, { code: "invalid_request" });
|
|
200
206
|
}
|
|
@@ -245,12 +251,13 @@ function defaultMessage(status) {
|
|
|
245
251
|
return `Unexpected status code ${status}`;
|
|
246
252
|
}
|
|
247
253
|
var BLOCKED_MESSAGE = "The request was blocked by a firewall before it reached Telem; the text may have characters that are not allowed.";
|
|
248
|
-
function statusError(status, body) {
|
|
254
|
+
function statusError(status, body, retryAfter = null) {
|
|
249
255
|
const fallback = status === 403 && !isObject(body) ? BLOCKED_MESSAGE : defaultMessage(status);
|
|
250
256
|
return new TelemError(detailFromBody(body) ?? fallback, {
|
|
251
257
|
status,
|
|
252
258
|
code: codeFromBody(body),
|
|
253
|
-
details: body
|
|
259
|
+
details: body,
|
|
260
|
+
retryAfter: retryAfter !== null && /^\s*\d+\s*$/.test(retryAfter) ? Number(retryAfter) : void 0
|
|
254
261
|
});
|
|
255
262
|
}
|
|
256
263
|
function connectionError(url, cause) {
|
|
@@ -264,6 +271,16 @@ function connectionError(url, cause) {
|
|
|
264
271
|
function isRetryable(status) {
|
|
265
272
|
return status >= 500 || status === 429;
|
|
266
273
|
}
|
|
274
|
+
var NEVER_SENT = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN"]);
|
|
275
|
+
function neverSent(failure) {
|
|
276
|
+
const codes = (value) => {
|
|
277
|
+
if (typeof value !== "object" || value === null) return [];
|
|
278
|
+
const error = value;
|
|
279
|
+
return Array.isArray(error.errors) ? error.errors.flatMap(codes) : [error.code];
|
|
280
|
+
};
|
|
281
|
+
const found = codes(failure?.cause);
|
|
282
|
+
return found.length > 0 && found.every((code) => typeof code === "string" && NEVER_SENT.has(code));
|
|
283
|
+
}
|
|
267
284
|
function shouldRetry(mode, status, body) {
|
|
268
285
|
if (mode === "all") return isRetryable(status);
|
|
269
286
|
if (status === 429) return true;
|
|
@@ -282,7 +299,10 @@ function jittered(ms) {
|
|
|
282
299
|
return ms + Math.random() * Math.max(1e3, ms / 2);
|
|
283
300
|
}
|
|
284
301
|
function idempotentDelay(retryAfter, attempt) {
|
|
285
|
-
|
|
302
|
+
return idempotentWait(retryAfter !== null && /^\s*\d+\s*$/.test(retryAfter) ? Number(retryAfter) : null, attempt);
|
|
303
|
+
}
|
|
304
|
+
function idempotentWait(seconds, attempt) {
|
|
305
|
+
if (seconds !== null) return jittered(seconds * 1e3);
|
|
286
306
|
return Math.min(jittered(BASE_DELAY_MS * 2 ** attempt), MAX_IDEMPOTENT_BACKOFF_MS);
|
|
287
307
|
}
|
|
288
308
|
async function request(config, method, path, body, abort, retry = "all", extra = {}) {
|
|
@@ -310,7 +330,7 @@ async function request(config, method, path, body, abort, retry = "all", extra =
|
|
|
310
330
|
});
|
|
311
331
|
abortion?.catch(() => {
|
|
312
332
|
});
|
|
313
|
-
const
|
|
333
|
+
const pause2 = (ms) => abortion ? Promise.race([config.sleep(ms), abortion]) : config.sleep(ms);
|
|
314
334
|
try {
|
|
315
335
|
return await attempts();
|
|
316
336
|
} finally {
|
|
@@ -354,26 +374,28 @@ async function request(config, method, path, body, abort, retry = "all", extra =
|
|
|
354
374
|
const wait = delay(null, attempt);
|
|
355
375
|
if (signal?.aborted) {
|
|
356
376
|
if (retry === "idempotent" && attempt < maxRetries && fits(wait)) {
|
|
357
|
-
await
|
|
377
|
+
await pause2(wait);
|
|
358
378
|
continue;
|
|
359
379
|
}
|
|
360
380
|
throw new TimeoutError(`request to ${url} timed out after ${config.timeoutMs}ms`, cause);
|
|
361
381
|
}
|
|
362
|
-
if (retry === "rate_limit" ||
|
|
363
|
-
|
|
382
|
+
if (retry === "rate_limit" || retry === "metered" && !neverSent(cause)) throw connectionError(url, cause);
|
|
383
|
+
if (attempt >= maxRetries || !fits(wait)) throw connectionError(url, cause);
|
|
384
|
+
await pause2(wait);
|
|
364
385
|
continue;
|
|
365
386
|
} finally {
|
|
366
387
|
signal?.removeEventListener("abort", onAbort2);
|
|
367
388
|
}
|
|
368
389
|
if (received.status >= 200 && received.status < 300) return received.body;
|
|
369
|
-
|
|
390
|
+
const lostReply = retry === "idempotent" && extra.lostReplyStatuses?.includes(received.status) === true;
|
|
391
|
+
if ((lostReply || shouldRetry(retry, received.status, received.body)) && attempt < maxRetries) {
|
|
370
392
|
const wait = delay(received.retryAfter, attempt);
|
|
371
393
|
if (fits(wait)) {
|
|
372
|
-
await
|
|
394
|
+
await pause2(wait);
|
|
373
395
|
continue;
|
|
374
396
|
}
|
|
375
397
|
}
|
|
376
|
-
throw statusError(received.status, received.body);
|
|
398
|
+
throw statusError(received.status, received.body, received.retryAfter);
|
|
377
399
|
}
|
|
378
400
|
}
|
|
379
401
|
}
|
|
@@ -562,23 +584,24 @@ function fetchBody(url, options, defaults) {
|
|
|
562
584
|
function fetchResult(run) {
|
|
563
585
|
const row = asObject(asArray(asObject(run.output_payload).fetched_results)[0]);
|
|
564
586
|
return {
|
|
565
|
-
url: row.url || run.query || "",
|
|
566
|
-
canonicalUrl: row.canonical_url
|
|
567
|
-
title: row.title || "",
|
|
568
|
-
status: row.status || run.status || "",
|
|
569
|
-
content: row.content
|
|
570
|
-
contentTruncated: row.content_truncated
|
|
571
|
-
contentFormat: row.content_format
|
|
572
|
-
contentSha256: row.content_sha256
|
|
573
|
-
contentType: row.content_type
|
|
574
|
-
contentRef: row.content_ref
|
|
575
|
-
provider: row.provider || "",
|
|
576
|
-
httpStatus: row.http_status
|
|
577
|
-
fetchedAt: row.fetched_at
|
|
578
|
-
// Key presence, not truthiness: a row that really reported 0 ms keeps its 0.
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
587
|
+
url: optString(row.url) || optString(run.query) || "",
|
|
588
|
+
canonicalUrl: optString(row.canonical_url),
|
|
589
|
+
title: optString(row.title) || "",
|
|
590
|
+
status: optString(row.status) || optString(run.status) || "",
|
|
591
|
+
content: optString(row.content),
|
|
592
|
+
contentTruncated: optBool(row.content_truncated),
|
|
593
|
+
contentFormat: optString(row.content_format),
|
|
594
|
+
contentSha256: optString(row.content_sha256),
|
|
595
|
+
contentType: optString(row.content_type),
|
|
596
|
+
contentRef: optObject(row.content_ref),
|
|
597
|
+
provider: optString(row.provider) || "",
|
|
598
|
+
httpStatus: optInt(row.http_status),
|
|
599
|
+
fetchedAt: optString(row.fetched_at),
|
|
600
|
+
// Key presence, not truthiness: a row that really reported 0 ms keeps its 0. A
|
|
601
|
+
// malformed row value falls back to the run's, as a missing one does.
|
|
602
|
+
latencyMs: optInt(row.latency_ms) ?? optInt(run.latency_ms),
|
|
603
|
+
providerMetadata: optObject(row.provider_metadata),
|
|
604
|
+
error: optObject(row.error) || optObject(run.error) || null,
|
|
582
605
|
batchIndex: run.batch_index ?? 0,
|
|
583
606
|
raw: row
|
|
584
607
|
};
|
|
@@ -596,7 +619,7 @@ function buildFetchResponse(interaction) {
|
|
|
596
619
|
}
|
|
597
620
|
async function fetchUrls(config, url, options) {
|
|
598
621
|
const body = fetchBody(url, options, config.fetchDefaults);
|
|
599
|
-
return buildFetchResponse(await request(config, "POST", "/v1/fetch", body, options.signal));
|
|
622
|
+
return buildFetchResponse(await request(config, "POST", "/v1/fetch", body, options.signal, "metered"));
|
|
600
623
|
}
|
|
601
624
|
|
|
602
625
|
// src/methods/search.ts
|
|
@@ -698,21 +721,21 @@ function assertV2(data) {
|
|
|
698
721
|
}
|
|
699
722
|
function searchResults(envelope, provider) {
|
|
700
723
|
return asArray(envelope.results).filter(isObject).map((row) => ({
|
|
701
|
-
url: row.url || "",
|
|
702
|
-
title: row.title || "",
|
|
703
|
-
summary: row.summary
|
|
704
|
-
excerpt: row.excerpt
|
|
705
|
-
fullContent: row.full_content
|
|
706
|
-
publishDate: row.publish_date
|
|
707
|
-
rank: row.rank
|
|
708
|
-
thumbnail: row.thumbnail
|
|
709
|
-
favicon: row.favicon
|
|
710
|
-
source: row.source
|
|
711
|
-
enrichments: row.enrichments
|
|
712
|
-
fetchMeta: row.fetch_meta
|
|
713
|
-
imageUrl: row.image_url
|
|
714
|
-
imageWidth: row.image_width
|
|
715
|
-
imageHeight: row.image_height
|
|
724
|
+
url: optString(row.url) || "",
|
|
725
|
+
title: optString(row.title) || "",
|
|
726
|
+
summary: optString(row.summary),
|
|
727
|
+
excerpt: optStrings(row.excerpt),
|
|
728
|
+
fullContent: optObject(row.full_content),
|
|
729
|
+
publishDate: optString(row.publish_date),
|
|
730
|
+
rank: optInt(row.rank),
|
|
731
|
+
thumbnail: optString(row.thumbnail),
|
|
732
|
+
favicon: optString(row.favicon),
|
|
733
|
+
source: optObject(row.source),
|
|
734
|
+
enrichments: optObject(row.enrichments),
|
|
735
|
+
fetchMeta: optObject(row.fetch_meta),
|
|
736
|
+
imageUrl: optString(row.image_url),
|
|
737
|
+
imageWidth: optInt(row.image_width),
|
|
738
|
+
imageHeight: optInt(row.image_height),
|
|
716
739
|
provider,
|
|
717
740
|
raw: row
|
|
718
741
|
}));
|
|
@@ -759,7 +782,7 @@ function buildSearchResponse(interaction) {
|
|
|
759
782
|
}
|
|
760
783
|
async function search(config, query, options) {
|
|
761
784
|
const body = searchBody(config, query, options);
|
|
762
|
-
const data = await request(config, "POST", "/v1/interactions", body, options.signal);
|
|
785
|
+
const data = await request(config, "POST", "/v1/interactions", body, options.signal, "metered");
|
|
763
786
|
assertV2(data);
|
|
764
787
|
return buildSearchResponse(data);
|
|
765
788
|
}
|
|
@@ -782,7 +805,7 @@ function agentStateFrom(data) {
|
|
|
782
805
|
needsAttention: data.needs_attention === true,
|
|
783
806
|
planVersion: typeof data.plan_version === "number" ? data.plan_version : null,
|
|
784
807
|
nextRunAt: typeof data.next_run_at === "string" ? data.next_run_at : null,
|
|
785
|
-
watermark:
|
|
808
|
+
watermark: finite(data.watermark),
|
|
786
809
|
// No compile job yet is null, not an object of empty strings.
|
|
787
810
|
compile: isObject(data.compile) ? {
|
|
788
811
|
jobId: String(data.compile.job_id ?? ""),
|
|
@@ -824,10 +847,17 @@ function agentDocumentFrom(body) {
|
|
|
824
847
|
if (typeof data.spend_usd === "number") document.spendUsd = data.spend_usd;
|
|
825
848
|
return document;
|
|
826
849
|
}
|
|
850
|
+
function position(value, field) {
|
|
851
|
+
const n = typeof value === "number" ? value : typeof value === "string" && /^\d+$/.test(value) ? Number(value) : NaN;
|
|
852
|
+
if (Number.isSafeInteger(n) && n >= 0) return n;
|
|
853
|
+
const sent = value === void 0 ? "missing" : JSON.stringify(value) ?? String(value);
|
|
854
|
+
const shown = sent.length > 40 ? `${sent.slice(0, 40)}\u2026` : sent;
|
|
855
|
+
throw new TelemError(`${field} is not a stream position: ${shown}`, { code: "invalid_response", details: value });
|
|
856
|
+
}
|
|
827
857
|
function changeRecordFrom(entry) {
|
|
828
858
|
const subject = asObject(entry.subject);
|
|
829
859
|
return {
|
|
830
|
-
seq:
|
|
860
|
+
seq: position(entry.seq, "change seq"),
|
|
831
861
|
type: String(entry.type ?? ""),
|
|
832
862
|
kind: String(entry.kind ?? ""),
|
|
833
863
|
monitorId: String(entry.monitor_id ?? ""),
|
|
@@ -847,8 +877,8 @@ function changesPageFrom(body) {
|
|
|
847
877
|
const data = asObject(body);
|
|
848
878
|
return {
|
|
849
879
|
changes: asArray(data.changes).filter(isObject).map(changeRecordFrom),
|
|
850
|
-
nextCursor:
|
|
851
|
-
watermark:
|
|
880
|
+
nextCursor: position(data.next_cursor, "changes page next_cursor"),
|
|
881
|
+
watermark: position(data.watermark, "changes page watermark")
|
|
852
882
|
};
|
|
853
883
|
}
|
|
854
884
|
function monitorsChangesPageFrom(body) {
|
|
@@ -956,6 +986,10 @@ function dataMapFrom(body) {
|
|
|
956
986
|
raw: data
|
|
957
987
|
};
|
|
958
988
|
}
|
|
989
|
+
function finite(value) {
|
|
990
|
+
const n = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;
|
|
991
|
+
return Number.isFinite(n) ? n : 0;
|
|
992
|
+
}
|
|
959
993
|
function companyFrom(entry) {
|
|
960
994
|
return {
|
|
961
995
|
companyId: String(entry.company_id ?? ""),
|
|
@@ -968,17 +1002,17 @@ function companyFrom(entry) {
|
|
|
968
1002
|
newsroomUrl: String(entry.newsroom_url ?? ""),
|
|
969
1003
|
teamPage: String(entry.team_page ?? ""),
|
|
970
1004
|
tier: String(entry.tier ?? ""),
|
|
971
|
-
rank:
|
|
1005
|
+
rank: finite(entry.rank),
|
|
972
1006
|
raw: entry
|
|
973
1007
|
};
|
|
974
1008
|
}
|
|
975
1009
|
function companyListFrom(body) {
|
|
976
1010
|
const data = asObject(body);
|
|
977
1011
|
return {
|
|
978
|
-
total:
|
|
979
|
-
priorityCount:
|
|
980
|
-
offset:
|
|
981
|
-
limit:
|
|
1012
|
+
total: finite(data.total),
|
|
1013
|
+
priorityCount: finite(data.priority_count),
|
|
1014
|
+
offset: finite(data.offset),
|
|
1015
|
+
limit: finite(data.limit),
|
|
982
1016
|
nextOffset: typeof data.next_offset === "number" ? data.next_offset : null,
|
|
983
1017
|
companies: asArray(data.companies).filter(isObject).map(companyFrom),
|
|
984
1018
|
raw: data
|
|
@@ -1029,6 +1063,140 @@ function acrossQuery(scope, options) {
|
|
|
1029
1063
|
if (options.cursor !== void 0) params.set("cursor", options.cursor);
|
|
1030
1064
|
return readQuery(params, options);
|
|
1031
1065
|
}
|
|
1066
|
+
function createBody(config, query, options) {
|
|
1067
|
+
const given = options ?? {};
|
|
1068
|
+
const agent = given.agent == null ? true : Boolean(given.agent);
|
|
1069
|
+
if (agent && !given.ttl) throw invalidRequest(given.inputs == null ? NEEDS_TTL : NEEDS_TTL_INPUTS);
|
|
1070
|
+
const key = given.idempotencyKey ?? globalThis.crypto.randomUUID();
|
|
1071
|
+
if (typeof key !== "string" || !IDEMPOTENCY_KEY.test(key)) {
|
|
1072
|
+
throw invalidRequest("idempotencyKey must be 1 to 255 visible ASCII characters");
|
|
1073
|
+
}
|
|
1074
|
+
const monitorOptions = {};
|
|
1075
|
+
if (given.frequency !== void 0) monitorOptions.frequency = given.frequency;
|
|
1076
|
+
if (given.includeDomains !== void 0) {
|
|
1077
|
+
monitorOptions.include_domains = given.includeDomains;
|
|
1078
|
+
}
|
|
1079
|
+
if (given.search !== void 0) monitorOptions.search = searchBlock({}, given.search);
|
|
1080
|
+
const body = { query, options: monitorOptions };
|
|
1081
|
+
if (given.metadata !== void 0) body.metadata = given.metadata;
|
|
1082
|
+
if (given.webhookUrl !== void 0) body.webhook_url = given.webhookUrl;
|
|
1083
|
+
if (given.ttl !== void 0) body.ttl = given.ttl;
|
|
1084
|
+
if (given.inputs != null) {
|
|
1085
|
+
body.inputs = given.inputs;
|
|
1086
|
+
const vertical = config.defaults.vertical;
|
|
1087
|
+
if (vertical !== void 0 && !("vertical" in given.inputs)) {
|
|
1088
|
+
body.inputs = { ...given.inputs, vertical };
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
body.agent = agent;
|
|
1092
|
+
if (given.preset != null) body.preset = given.preset;
|
|
1093
|
+
if (given.tags != null) body.tags = given.tags;
|
|
1094
|
+
return { body, key };
|
|
1095
|
+
}
|
|
1096
|
+
var MAY_EXIST = "The monitor may exist: list monitors before you create it again.";
|
|
1097
|
+
var MAY_EXIST_MANY = "The monitors may exist: list monitors before you create them again.";
|
|
1098
|
+
function mayExist(note) {
|
|
1099
|
+
return (error) => {
|
|
1100
|
+
if (error instanceof TimeoutError) throw new TimeoutError(`${error.message}. ${note}`, error.cause);
|
|
1101
|
+
throw error;
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
var BATCH_SIZE = 10;
|
|
1105
|
+
var GATEWAY_TIMEOUTS = [502, 504];
|
|
1106
|
+
var ITEM_FIELDS = /* @__PURE__ */ new Set([
|
|
1107
|
+
"query",
|
|
1108
|
+
"frequency",
|
|
1109
|
+
"search",
|
|
1110
|
+
"includeDomains",
|
|
1111
|
+
"metadata",
|
|
1112
|
+
"webhookUrl",
|
|
1113
|
+
"tags",
|
|
1114
|
+
"idempotencyKey",
|
|
1115
|
+
"ttl",
|
|
1116
|
+
"agent",
|
|
1117
|
+
"inputs",
|
|
1118
|
+
"preset"
|
|
1119
|
+
]);
|
|
1120
|
+
function invalidBatch(message) {
|
|
1121
|
+
return new TelemError(message, { code: "invalid_response" });
|
|
1122
|
+
}
|
|
1123
|
+
function batchAnswer(data, sent, keys) {
|
|
1124
|
+
const answer = /* @__PURE__ */ new Map();
|
|
1125
|
+
const results = isObject(data) ? data.results : void 0;
|
|
1126
|
+
const count = `the batch answer does not have one result for each of the ${sent.length} monitors sent`;
|
|
1127
|
+
if (!Array.isArray(results)) return { answer, problem: invalidBatch(count) };
|
|
1128
|
+
let problem = results.length !== sent.length ? invalidBatch(count) : null;
|
|
1129
|
+
for (const entry of results) {
|
|
1130
|
+
try {
|
|
1131
|
+
const [position2, result] = batchEntry(entry, sent, keys, answer);
|
|
1132
|
+
answer.set(position2, result);
|
|
1133
|
+
} catch (error) {
|
|
1134
|
+
if (!(error instanceof TelemError)) throw error;
|
|
1135
|
+
problem ??= error;
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
return { answer, problem };
|
|
1139
|
+
}
|
|
1140
|
+
function batchEntry(entry, sent, keys, answer) {
|
|
1141
|
+
const index = isObject(entry) ? entry.index : void 0;
|
|
1142
|
+
if (!isObject(entry) || !Number.isInteger(index) || index < 0 || index >= sent.length) {
|
|
1143
|
+
throw invalidBatch("a batch result has no valid index");
|
|
1144
|
+
}
|
|
1145
|
+
if (!Number.isInteger(entry.status)) throw invalidBatch(`batch result ${index} has no status`);
|
|
1146
|
+
const position2 = sent[index];
|
|
1147
|
+
if (answer.has(position2)) throw invalidBatch(`two batch results have index ${index}`);
|
|
1148
|
+
return [
|
|
1149
|
+
position2,
|
|
1150
|
+
{
|
|
1151
|
+
index: position2,
|
|
1152
|
+
status: entry.status,
|
|
1153
|
+
monitor: isObject(entry.monitor) ? monitorFrom(entry.monitor) : null,
|
|
1154
|
+
replayed: entry.replayed === true,
|
|
1155
|
+
error: optObject(entry.error),
|
|
1156
|
+
retryAfter: optInt(entry.retry_after),
|
|
1157
|
+
idempotencyKey: keys[position2],
|
|
1158
|
+
raw: entry
|
|
1159
|
+
}
|
|
1160
|
+
];
|
|
1161
|
+
}
|
|
1162
|
+
function comesBack(result) {
|
|
1163
|
+
if (result === void 0 || result.status === 429) return true;
|
|
1164
|
+
return result.status === 409 && isObject(result.error) && result.error.code === "idempotency_in_progress";
|
|
1165
|
+
}
|
|
1166
|
+
function failed(error, results, keys) {
|
|
1167
|
+
const message = withNote(error.message);
|
|
1168
|
+
const { status, code, details, retryAfter } = error;
|
|
1169
|
+
const thrown = error instanceof TimeoutError ? new TimeoutError(message, error.cause) : new TelemError(message, { status, code, details, retryAfter, cause: error });
|
|
1170
|
+
return attach(thrown, results, keys);
|
|
1171
|
+
}
|
|
1172
|
+
function aborted(reason, results, keys) {
|
|
1173
|
+
const thrown = new TelemError(withNote("monitors.createMany() was aborted"), { code: "aborted", cause: reason });
|
|
1174
|
+
return attach(thrown, results, keys);
|
|
1175
|
+
}
|
|
1176
|
+
function withNote(message) {
|
|
1177
|
+
return `${message}${message.endsWith(".") ? "" : "."} ${MAY_EXIST_MANY}`;
|
|
1178
|
+
}
|
|
1179
|
+
function attach(thrown, results, keys) {
|
|
1180
|
+
const answered = results.filter((result) => result !== void 0);
|
|
1181
|
+
Object.defineProperty(thrown, "results", { value: answered, writable: true, configurable: true });
|
|
1182
|
+
Object.defineProperty(thrown, "idempotencyKeys", { value: [...keys], writable: true, configurable: true });
|
|
1183
|
+
return thrown;
|
|
1184
|
+
}
|
|
1185
|
+
async function pause(config, ms, signal) {
|
|
1186
|
+
if (!signal) return config.sleep(ms);
|
|
1187
|
+
if (signal.aborted) throw signal.reason ?? new Error("aborted");
|
|
1188
|
+
let onAbort = () => {
|
|
1189
|
+
};
|
|
1190
|
+
const aborted2 = new Promise((_, reject) => {
|
|
1191
|
+
onAbort = () => reject(signal.reason ?? new Error("aborted"));
|
|
1192
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1193
|
+
});
|
|
1194
|
+
try {
|
|
1195
|
+
await Promise.race([config.sleep(ms), aborted2]);
|
|
1196
|
+
} finally {
|
|
1197
|
+
signal.removeEventListener("abort", onAbort);
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1032
1200
|
function createMonitors(config) {
|
|
1033
1201
|
const path = (monitorId, suffix = "") => {
|
|
1034
1202
|
if (!monitorId || /^\.+$/.test(monitorId)) throw invalidRequest("a monitor id is required");
|
|
@@ -1056,50 +1224,89 @@ function createMonitors(config) {
|
|
|
1056
1224
|
return {
|
|
1057
1225
|
/** Create a monitor. Telem runs `query` on the schedule, and its agent keeps what matches. */
|
|
1058
1226
|
async create(query, options) {
|
|
1059
|
-
const
|
|
1060
|
-
const agent = given.agent == null ? true : Boolean(given.agent);
|
|
1061
|
-
if (agent && !given.ttl) throw invalidRequest(given.inputs == null ? NEEDS_TTL : NEEDS_TTL_INPUTS);
|
|
1062
|
-
const key = given.idempotencyKey ?? globalThis.crypto.randomUUID();
|
|
1063
|
-
if (typeof key !== "string" || !IDEMPOTENCY_KEY.test(key)) {
|
|
1064
|
-
throw invalidRequest("idempotencyKey must be 1 to 255 visible ASCII characters");
|
|
1065
|
-
}
|
|
1066
|
-
const monitorOptions = {};
|
|
1067
|
-
if (given.frequency !== void 0) monitorOptions.frequency = given.frequency;
|
|
1068
|
-
if (given.includeDomains !== void 0) {
|
|
1069
|
-
monitorOptions.include_domains = given.includeDomains;
|
|
1070
|
-
}
|
|
1071
|
-
if (given.search !== void 0) monitorOptions.search = searchBlock({}, given.search);
|
|
1072
|
-
const body = { query, options: monitorOptions };
|
|
1073
|
-
if (given.metadata !== void 0) body.metadata = given.metadata;
|
|
1074
|
-
if (given.webhookUrl !== void 0) body.webhook_url = given.webhookUrl;
|
|
1075
|
-
if (given.ttl !== void 0) body.ttl = given.ttl;
|
|
1076
|
-
if (given.inputs != null) {
|
|
1077
|
-
body.inputs = given.inputs;
|
|
1078
|
-
const vertical = config.defaults.vertical;
|
|
1079
|
-
if (vertical !== void 0 && !("vertical" in given.inputs)) {
|
|
1080
|
-
body.inputs = { ...given.inputs, vertical };
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
body.agent = agent;
|
|
1084
|
-
if (given.preset != null) body.preset = given.preset;
|
|
1085
|
-
if (given.tags != null) body.tags = given.tags;
|
|
1227
|
+
const { body, key } = createBody(config, query, options);
|
|
1086
1228
|
const extra = {
|
|
1087
1229
|
headers: { "Idempotency-Key": key },
|
|
1088
1230
|
maxRetries: config.createMaxRetries,
|
|
1089
1231
|
budgetMs: CREATE_RETRY_BUDGET_MS
|
|
1090
1232
|
};
|
|
1091
|
-
const data = await request(config, "POST", "/v1/monitors", body,
|
|
1092
|
-
(
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1233
|
+
const data = await request(config, "POST", "/v1/monitors", body, options?.signal, "idempotent", extra).catch(
|
|
1234
|
+
mayExist(MAY_EXIST)
|
|
1235
|
+
);
|
|
1236
|
+
return monitorFrom(data);
|
|
1237
|
+
},
|
|
1238
|
+
/** Create many monitors, ten per call, one call after another. */
|
|
1239
|
+
async createMany(items, options = {}) {
|
|
1240
|
+
if (!Array.isArray(items)) throw invalidRequest("createMany takes an array of monitors");
|
|
1241
|
+
const given = /* @__PURE__ */ new Map();
|
|
1242
|
+
const bodies = items.map((item, index) => {
|
|
1243
|
+
try {
|
|
1244
|
+
if (!isObject(item)) throw invalidRequest("a monitor must be an object of create's options");
|
|
1245
|
+
const unknown = Object.keys(item).find((key2) => !ITEM_FIELDS.has(key2));
|
|
1246
|
+
if (unknown !== void 0) throw invalidRequest(`unknown option ${JSON.stringify(unknown)}`);
|
|
1247
|
+
if (item.query == null) throw invalidRequest("query is required");
|
|
1248
|
+
const { body, key } = createBody(config, item.query, item);
|
|
1249
|
+
try {
|
|
1250
|
+
JSON.stringify(body);
|
|
1251
|
+
} catch (cause) {
|
|
1252
|
+
throw invalidRequest(`not JSON: ${cause?.message ?? String(cause)}`);
|
|
1098
1253
|
}
|
|
1254
|
+
return { ...body, idempotency_key: key };
|
|
1255
|
+
} catch (error) {
|
|
1256
|
+
if (error instanceof TelemError) throw invalidRequest(`monitor ${index}: ${error.message}`);
|
|
1099
1257
|
throw error;
|
|
1100
1258
|
}
|
|
1101
|
-
);
|
|
1102
|
-
|
|
1259
|
+
});
|
|
1260
|
+
items.forEach((item, index) => {
|
|
1261
|
+
if (item.idempotencyKey == null) return;
|
|
1262
|
+
const first = given.get(item.idempotencyKey) ?? index;
|
|
1263
|
+
given.set(item.idempotencyKey, first);
|
|
1264
|
+
if (first !== index) throw invalidRequest(`monitors ${first} and ${index} have the same idempotencyKey`);
|
|
1265
|
+
});
|
|
1266
|
+
const keys = bodies.map((body) => body.idempotency_key);
|
|
1267
|
+
const results = Array(bodies.length).fill(void 0);
|
|
1268
|
+
let sent = false;
|
|
1269
|
+
const fail = (error) => {
|
|
1270
|
+
if (!sent) return error;
|
|
1271
|
+
if (!(error instanceof TelemError)) {
|
|
1272
|
+
if (!options.signal?.aborted) return error;
|
|
1273
|
+
return aborted(error, results, keys);
|
|
1274
|
+
}
|
|
1275
|
+
return failed(error, results, keys);
|
|
1276
|
+
};
|
|
1277
|
+
for (let offset = 0; offset < bodies.length; offset += BATCH_SIZE) {
|
|
1278
|
+
let pending = keys.slice(offset, offset + BATCH_SIZE).map((_, i) => offset + i);
|
|
1279
|
+
const started = Date.now();
|
|
1280
|
+
for (let attempt = 0; ; attempt++) {
|
|
1281
|
+
const extra = {
|
|
1282
|
+
maxRetries: config.createMaxRetries,
|
|
1283
|
+
budgetMs: CREATE_RETRY_BUDGET_MS - (Date.now() - started),
|
|
1284
|
+
lostReplyStatuses: GATEWAY_TIMEOUTS
|
|
1285
|
+
};
|
|
1286
|
+
const body = { monitors: pending.map((i) => bodies[i]) };
|
|
1287
|
+
let data;
|
|
1288
|
+
try {
|
|
1289
|
+
sent ||= !options.signal?.aborted;
|
|
1290
|
+
data = await request(config, "POST", "/v1/monitors:batch", body, options.signal, "idempotent", extra);
|
|
1291
|
+
} catch (error) {
|
|
1292
|
+
throw fail(error);
|
|
1293
|
+
}
|
|
1294
|
+
const { answer, problem } = batchAnswer(data, pending, keys);
|
|
1295
|
+
for (const [position2, result] of answer) results[position2] = result;
|
|
1296
|
+
if (problem) throw fail(problem);
|
|
1297
|
+
pending = pending.filter((i) => comesBack(results[i]));
|
|
1298
|
+
if (!pending.length || attempt >= config.createMaxRetries) break;
|
|
1299
|
+
const known = pending.map((i) => results[i].retryAfter).filter((n) => n !== null && n >= 0);
|
|
1300
|
+
const wait = idempotentWait(known.length ? Math.max(...known) : null, attempt);
|
|
1301
|
+
if (Date.now() - started + wait > CREATE_RETRY_BUDGET_MS) break;
|
|
1302
|
+
try {
|
|
1303
|
+
await pause(config, wait, options.signal);
|
|
1304
|
+
} catch (error) {
|
|
1305
|
+
throw fail(error);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
return results;
|
|
1103
1310
|
},
|
|
1104
1311
|
/** List your monitors, newest first. `listPage` also gives the next cursor. */
|
|
1105
1312
|
async list(options = {}) {
|
package/dist/index.d.cts
CHANGED
|
@@ -323,6 +323,30 @@ type MonitorCreateOptions = MonitorCreateCommonOptions & ({
|
|
|
323
323
|
});
|
|
324
324
|
/** The `preset` of `monitors.create`. */
|
|
325
325
|
type MonitorPreset = "article" | "person" | "company" | "listing";
|
|
326
|
+
/** One monitor of `monitors.createMany`: its `query` and the options of `create`.
|
|
327
|
+
* `idempotencyKey` is this monitor's own key; the call takes the `signal`. */
|
|
328
|
+
type MonitorCreateManyItem = {
|
|
329
|
+
query: string;
|
|
330
|
+
} & WithoutSignal<MonitorCreateOptions>;
|
|
331
|
+
/** `Omit` for each member of a union, so the `agent`/`ttl` pairing holds. */
|
|
332
|
+
type WithoutSignal<T> = T extends unknown ? Omit<T, "signal"> : never;
|
|
333
|
+
/** One monitor's answer in `monitors.createMany`. */
|
|
334
|
+
type MonitorBatchResult = {
|
|
335
|
+
/** The monitor's position in the array you passed. */
|
|
336
|
+
index: number;
|
|
337
|
+
/** `201`: made. `200` with `replayed`: made before, under the same key. Any other
|
|
338
|
+
* status is this monitor's own error. */
|
|
339
|
+
status: number;
|
|
340
|
+
monitor: Monitor | null;
|
|
341
|
+
replayed: boolean;
|
|
342
|
+
/** `{ code, message }`, and `param` when a field is at fault. */
|
|
343
|
+
error: Json | null;
|
|
344
|
+
/** With a `429`: the seconds to wait before you send this monitor again. */
|
|
345
|
+
retryAfter: number | null;
|
|
346
|
+
/** The key this monitor was sent with: send it again with the same key. */
|
|
347
|
+
idempotencyKey: string;
|
|
348
|
+
raw: Json;
|
|
349
|
+
};
|
|
326
350
|
/** Options for `monitors.update`. Send at least one field. */
|
|
327
351
|
type MonitorUpdateOptions = {
|
|
328
352
|
/** `"paused"` or `"active"`. */
|
|
@@ -732,6 +756,18 @@ type MonitorsResource = {
|
|
|
732
756
|
* `ttl` is required: a create without it throws a `TelemError` (`invalid_request`)
|
|
733
757
|
* before anything is sent. */
|
|
734
758
|
create(query: string, options: MonitorCreateOptions): Promise<Monitor>;
|
|
759
|
+
/** Create many monitors, ten per call, one call after another. One result per monitor,
|
|
760
|
+
* in the order given; a monitor that fails does not stop the others. Each call retries
|
|
761
|
+
* as `create` does, and after a 502 or 504 too, then only the monitors answered with a 429 (or a 409
|
|
762
|
+
* `idempotency_in_progress`) are sent again, with their keys, for up to about 120 s per
|
|
763
|
+
* call. A bad monitor, an unknown option, a monitor that is not JSON or a key given
|
|
764
|
+
* twice throws a `TelemError` (`invalid_request`) naming the index, before anything is
|
|
765
|
+
* sent. Once a call was sent, any failure (a call refused whole, an abort as `aborted`)
|
|
766
|
+
* throws with `results` (each monitor's last answer so far) and `idempotencyKeys` (every
|
|
767
|
+
* monitor's key) on the error, and its message says the monitors may exist. */
|
|
768
|
+
createMany(items: MonitorCreateManyItem[], options?: {
|
|
769
|
+
signal?: AbortSignal;
|
|
770
|
+
}): Promise<MonitorBatchResult[]>;
|
|
735
771
|
list(options?: MonitorListOptions): Promise<Monitor[]>;
|
|
736
772
|
listPage(options?: MonitorListOptions): Promise<MonitorPage>;
|
|
737
773
|
get(monitorId: string, options?: {
|
|
@@ -803,7 +839,12 @@ type TelemClientErrorCode =
|
|
|
803
839
|
/** The request never produced a response (DNS, refused, reset, TLS). */
|
|
804
840
|
| "connection_error"
|
|
805
841
|
/** The request was still outstanding when the timeout fired. */
|
|
806
|
-
| "timeout"
|
|
842
|
+
| "timeout"
|
|
843
|
+
/** A 2xx body carried a value the client cannot use safely, such as a change-stream
|
|
844
|
+
* position (`seq`, `watermark`, `next_cursor`) that is not a whole number. */
|
|
845
|
+
| "invalid_response"
|
|
846
|
+
/** `monitors.createMany` was aborted after it sent a call: `cause` is the reason. */
|
|
847
|
+
| "aborted";
|
|
807
848
|
type TelemErrorOptions = {
|
|
808
849
|
/** HTTP status that produced this error; absent for transport failures. */
|
|
809
850
|
status?: number;
|
|
@@ -813,11 +854,20 @@ type TelemErrorOptions = {
|
|
|
813
854
|
/** Parsed response body (or raw text when it would not parse). */
|
|
814
855
|
details?: unknown;
|
|
815
856
|
cause?: unknown;
|
|
857
|
+
/** The response's `Retry-After`, in seconds, when it sent one as a number. */
|
|
858
|
+
retryAfter?: number;
|
|
816
859
|
};
|
|
817
860
|
declare class TelemError extends Error {
|
|
818
861
|
status?: number;
|
|
819
862
|
code?: TelemClientErrorCode | (string & {});
|
|
820
863
|
details?: unknown;
|
|
864
|
+
/** The response's `Retry-After`, in seconds, when it sent one as a number. */
|
|
865
|
+
retryAfter?: number;
|
|
866
|
+
/** From `monitors.createMany`: each monitor's last answer before it failed, in order.
|
|
867
|
+
* Not enumerable, so serialising the error does not write a `webhookSecret`. */
|
|
868
|
+
results?: MonitorBatchResult[];
|
|
869
|
+
/** From `monitors.createMany`: every monitor's key, in order. Not enumerable. */
|
|
870
|
+
idempotencyKeys?: string[];
|
|
821
871
|
constructor(message: string, options?: TelemErrorOptions);
|
|
822
872
|
}
|
|
823
873
|
/** The request never produced a response in time. Always `code: "timeout"`. */
|
|
@@ -967,4 +1017,4 @@ declare class Telem {
|
|
|
967
1017
|
providers(): Promise<ProviderInfo[]>;
|
|
968
1018
|
}
|
|
969
1019
|
|
|
970
|
-
export { type AgentCompileState, type AgentDocument, type AgentState, type ApplyResult, type ChangeRecord, type ChangeSubject, type ChangesPage, type CompanyList, type CompanyListRow, type CompanySheet, type DataMap, type ExpansionConfirmFields, type ExpansionRecord, type ExpansionsPage, type FeedbackResult, type FetchOptions, type FetchResponse, type FetchResult, type Json, type Monitor, type MonitorChangesAcrossOptions, type MonitorChangesAcrossScope, type MonitorChangesOptions, type MonitorCompaniesOptions, type MonitorCreateOptions, type MonitorExpansionsOptions, type MonitorFeedbackOptions, type MonitorInputs, type MonitorIterateChangesOptions, type MonitorListOptions, type MonitorPage, type MonitorPollOptions, type MonitorPreset, type MonitorUpdateOptions, type MonitorsChangesPage, type MonitorsResource, type OnboardingCandidate, type OnboardingCompany, type OnboardingExample, type OnboardingMarks, type OnboardingSheet, type ProviderInfo, type ProviderRun, RESERVED_METADATA, type SearchDefaults, type SearchOptions, type SearchResponse, type SearchResult, type SessionResults, type SessionSummary, type SessionsResource, type SnapshotArgs, Telem, type TelemClientErrorCode, TelemError, type TelemErrorOptions, type TelemOptions, TimeoutError, type TrajectoryArgs, type TrajectoryEnvelope, type TrajectorySnapshot, buildMetadata, buildSnapshot, contentAnchor, Telem as default, eventNodeKey, fingerprint, sessionKey, snapshotNodeKey, toolMarker, verifyWebhook, windowAnchor, withTrajectory };
|
|
1020
|
+
export { type AgentCompileState, type AgentDocument, type AgentState, type ApplyResult, type ChangeRecord, type ChangeSubject, type ChangesPage, type CompanyList, type CompanyListRow, type CompanySheet, type DataMap, type ExpansionConfirmFields, type ExpansionRecord, type ExpansionsPage, type FeedbackResult, type FetchOptions, type FetchResponse, type FetchResult, type Json, type Monitor, type MonitorBatchResult, type MonitorChangesAcrossOptions, type MonitorChangesAcrossScope, type MonitorChangesOptions, type MonitorCompaniesOptions, type MonitorCreateManyItem, type MonitorCreateOptions, type MonitorExpansionsOptions, type MonitorFeedbackOptions, type MonitorInputs, type MonitorIterateChangesOptions, type MonitorListOptions, type MonitorPage, type MonitorPollOptions, type MonitorPreset, type MonitorUpdateOptions, type MonitorsChangesPage, type MonitorsResource, type OnboardingCandidate, type OnboardingCompany, type OnboardingExample, type OnboardingMarks, type OnboardingSheet, type ProviderInfo, type ProviderRun, RESERVED_METADATA, type SearchDefaults, type SearchOptions, type SearchResponse, type SearchResult, type SessionResults, type SessionSummary, type SessionsResource, type SnapshotArgs, Telem, type TelemClientErrorCode, TelemError, type TelemErrorOptions, type TelemOptions, TimeoutError, type TrajectoryArgs, type TrajectoryEnvelope, type TrajectorySnapshot, buildMetadata, buildSnapshot, contentAnchor, Telem as default, eventNodeKey, fingerprint, sessionKey, snapshotNodeKey, toolMarker, verifyWebhook, windowAnchor, withTrajectory };
|