outbound-sdk 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +2 -2
  2. package/dist/alerts/check-evaluate.d.ts +53 -0
  3. package/dist/alerts/check-measure.d.ts +100 -0
  4. package/dist/alerts/check-schema.d.ts +184 -0
  5. package/dist/alerts/check-validate.d.ts +18 -0
  6. package/dist/alerts/index.d.ts +7 -0
  7. package/dist/alerts/index.js +635 -2
  8. package/dist/budget/index.d.ts +2 -0
  9. package/dist/budget/index.js +1 -0
  10. package/dist/cards/format.d.ts +1 -1
  11. package/dist/cards/index.js +49 -19
  12. package/dist/cards/parts.d.ts +1 -6
  13. package/dist/chunks/{chunk-7LNJJ2RO.js → chunk-3JOC5DGD.js} +127 -17
  14. package/dist/chunks/chunk-53DCVFUB.js +55 -0
  15. package/dist/chunks/{chunk-E6DSDCPI.js → chunk-BK5SLY32.js} +92 -101
  16. package/dist/chunks/chunk-HPNGSG5E.js +51 -0
  17. package/dist/chunks/chunk-HWHI4LFY.js +102 -0
  18. package/dist/chunks/chunk-MGR6HREO.js +91 -0
  19. package/dist/chunks/{chunk-Y5RAJ6PZ.js → chunk-OLPMBRXM.js} +3 -2
  20. package/dist/chunks/{chunk-IZFTTMJP.js → chunk-PHNQ3WC2.js} +5 -5
  21. package/dist/chunks/chunk-SXGCKCAR.js +678 -0
  22. package/dist/chunks/chunk-TFICTGM2.js +18 -0
  23. package/dist/chunks/{chunk-ZFVHM5JI.js → chunk-UWUPUMM2.js} +11 -4
  24. package/dist/chunks/{chunk-A6WVOCA4.js → chunk-W22SDX6S.js} +4 -4
  25. package/dist/chunks/{chunk-7ZDS6SZD.js → chunk-WH6V3YNN.js} +25 -0
  26. package/dist/chunks/chunk-XL6LJVHJ.js +71 -0
  27. package/dist/chunks/{chunk-5FVKRIEJ.js → chunk-YYCT3NGV.js} +35 -11
  28. package/dist/cli/bin.js +13 -28
  29. package/dist/cli/index.d.ts +3 -0
  30. package/dist/cli/index.js +12 -11
  31. package/dist/cli/output.d.ts +9 -0
  32. package/dist/cli/update.d.ts +15 -0
  33. package/dist/emailbison/account.d.ts +7 -0
  34. package/dist/emailbison/adapter.d.ts +5 -0
  35. package/dist/emailbison/capabilities.d.ts +78 -0
  36. package/dist/emailbison/client.d.ts +29 -0
  37. package/dist/emailbison/index.d.ts +30 -0
  38. package/dist/emailbison/index.js +1018 -0
  39. package/dist/emailbison/mail.d.ts +5 -0
  40. package/dist/emailbison/map-mail.d.ts +13 -0
  41. package/dist/emailbison/map-sequence.d.ts +12 -0
  42. package/dist/emailbison/map-stats.d.ts +47 -0
  43. package/dist/emailbison/map.d.ts +24 -0
  44. package/dist/emailbison/native-params.d.ts +5 -0
  45. package/dist/emailbison/native-workspace.d.ts +167 -0
  46. package/dist/emailbison/native.d.ts +327 -0
  47. package/dist/emailbison/stats.d.ts +4 -0
  48. package/dist/emailbison/webhooks.d.ts +2 -0
  49. package/dist/fixtures/index.js +6 -6
  50. package/dist/heyreach/capabilities.d.ts +3 -0
  51. package/dist/heyreach/index.js +22 -20
  52. package/dist/index.js +19 -18
  53. package/dist/insights/copy/copy-preview.d.ts +58 -0
  54. package/dist/insights/copy/copy-reuse.d.ts +0 -13
  55. package/dist/insights/copy/index.d.ts +9 -0
  56. package/dist/insights/copy/reuse-base.d.ts +0 -2
  57. package/dist/insights/copy/shared.d.ts +3 -8
  58. package/dist/insights/copy/step-funnel.d.ts +1 -12
  59. package/dist/insights/copy/variant-test.d.ts +0 -5
  60. package/dist/insights/cost.d.ts +91 -0
  61. package/dist/insights/define.d.ts +22 -1
  62. package/dist/insights/index.d.ts +4 -3
  63. package/dist/insights/index.js +810 -415
  64. package/dist/insights/inputs.generated.d.ts +21 -24
  65. package/dist/insights/ops/campaign-diagnosis.d.ts +0 -2
  66. package/dist/insights/ops/campaign-ranking.d.ts +3 -3
  67. package/dist/insights/ops/client-report.d.ts +0 -2
  68. package/dist/insights/ops/index.d.ts +2 -6
  69. package/dist/insights/ops/shared.d.ts +10 -2
  70. package/dist/insights/plugin.d.ts +19 -0
  71. package/dist/insights/registry.d.ts +10 -10
  72. package/dist/insights/run-cap.d.ts +35 -0
  73. package/dist/insights/senders/bounce-watch.d.ts +0 -11
  74. package/dist/insights/senders/domain-health.d.ts +0 -7
  75. package/dist/insights/senders/index.d.ts +0 -4
  76. package/dist/insights/senders/sender-load.d.ts +0 -2
  77. package/dist/insights/tools.d.ts +10 -0
  78. package/dist/insights/types.d.ts +1 -1
  79. package/dist/insights/variables.d.ts +33 -0
  80. package/dist/instantly/capabilities.d.ts +13 -0
  81. package/dist/instantly/index.js +43 -28
  82. package/dist/internal/adapter.d.ts +12 -0
  83. package/dist/internal/outbound/outbound.d.ts +5 -1
  84. package/dist/internal/request-cap.d.ts +35 -0
  85. package/dist/loader/index.js +2 -2
  86. package/dist/memory/index.js +10 -10
  87. package/dist/providers/index.d.ts +21 -1
  88. package/dist/providers/index.js +1 -1
  89. package/dist/redact/index.js +4 -4
  90. package/dist/smartlead/capabilities.d.ts +5 -0
  91. package/dist/smartlead/index.js +26 -24
  92. package/dist/tools/ai-sdk.js +5 -3
  93. package/dist/tools/claude-agent.js +5 -3
  94. package/dist/tools/index.d.ts +2 -2
  95. package/dist/tools/index.js +11 -6
  96. package/dist/tools/registry.d.ts +20 -1
  97. package/dist/tools/shared.d.ts +20 -1
  98. package/dist/webhooks/index.js +17 -7
  99. package/package.json +8 -2
  100. package/dist/chunks/chunk-5CFO3CXG.js +0 -176
  101. package/dist/chunks/chunk-K4USHN4C.js +0 -40
  102. package/dist/chunks/chunk-LVQUSKEX.js +0 -17
  103. package/dist/internal/renamed.d.ts +0 -28
  104. package/dist/chunks/{chunk-C4LS2HNV.js → chunk-JWGSB7PT.js} +3 -3
@@ -2,12 +2,19 @@ import {
2
2
  percentOf
3
3
  } from "../chunks/chunk-4PA526S7.js";
4
4
  import "../chunks/chunk-PTZO4QXR.js";
5
+ import {
6
+ metricRowSchema,
7
+ senderSchema,
8
+ senderStatusSchema
9
+ } from "../chunks/chunk-BOWXGMN3.js";
5
10
  import {
6
11
  computeRates
7
12
  } from "../chunks/chunk-PQSTQKRD.js";
8
13
  import "../chunks/chunk-QGRZDTX4.js";
9
14
  import "../chunks/chunk-QAKJ76HB.js";
10
- import "../chunks/chunk-J7DDZ4C2.js";
15
+ import {
16
+ OutboundError
17
+ } from "../chunks/chunk-J7DDZ4C2.js";
11
18
  import "../chunks/chunk-BLCJHP5H.js";
12
19
 
13
20
  // src/alerts/plugin.ts
@@ -161,11 +168,637 @@ var alerts = (options) => {
161
168
  }
162
169
  };
163
170
  };
171
+
172
+ // src/alerts/check-schema.ts
173
+ import { z } from "zod";
174
+ var STATS_SCOPE = ["client", "campaign", "sender"];
175
+ var CHECK_METRICS = {
176
+ blocked_leads: {
177
+ description: "Leads in a campaign that are on a block list, per campaign. Read with `suppressionCheck`.",
178
+ reads: "suppressionCheck",
179
+ scope: ["client", "campaign"],
180
+ unit: "count"
181
+ },
182
+ bounce_rate: {
183
+ description: "Bounced divided by sent, per stats row. Rows with fewer than `min_sent` sends are skipped.",
184
+ reads: "stats",
185
+ scope: STATS_SCOPE,
186
+ unit: "rate"
187
+ },
188
+ broken_variable_leads: {
189
+ description: "Leads who get broken copy from one merge variable with no value and no fallback, per variable. Read with `personalizationGaps`.",
190
+ reads: "personalizationGaps",
191
+ scope: ["client", "campaign"],
192
+ unit: "count"
193
+ },
194
+ lead_runway_days: {
195
+ description: "Days until a campaign runs out of leads at its recent contact rate. Read with `pipelineForecast`.",
196
+ reads: "pipelineForecast",
197
+ scope: ["client", "campaign"],
198
+ unit: "days"
199
+ },
200
+ positive_reply_waiting_hours: {
201
+ description: "Hours a positive reply has waited with no answer, per reply. Read with `droppedReplies`.",
202
+ reads: "droppedReplies",
203
+ scope: ["client", "campaign", "person"],
204
+ unit: "hours"
205
+ },
206
+ reply_rate: {
207
+ description: "Replies divided by leads contacted (or sent), per stats row. Rows with fewer than `min_sent` sends are skipped.",
208
+ reads: "stats",
209
+ scope: STATS_SCOPE,
210
+ unit: "rate"
211
+ },
212
+ sender_status: {
213
+ description: "A sender's status: active, paused, disconnected or error. A sender whose status is unknown is skipped.",
214
+ reads: "senders",
215
+ scope: ["client", "sender"],
216
+ unit: "status"
217
+ },
218
+ sent: {
219
+ description: "Messages sent, per stats row. With `window`, daily rows older than the window are skipped.",
220
+ reads: "stats",
221
+ scope: STATS_SCOPE,
222
+ unit: "count"
223
+ }
224
+ };
225
+ var METRIC_NAMES = Object.keys(CHECK_METRICS);
226
+ var NUMBER_OPS = [">", ">=", "<", "<=", "==", "!="];
227
+ var OP_ALIASES = /* @__PURE__ */ new Map([
228
+ ["!==", "!="],
229
+ ["<>", "!="],
230
+ ["=", "=="],
231
+ ["===", "=="],
232
+ ["eq", "=="],
233
+ ["gt", ">"],
234
+ ["gte", ">="],
235
+ ["lt", "<"],
236
+ ["lte", "<="],
237
+ ["ne", "!="],
238
+ ["neq", "!="]
239
+ ]);
240
+ var STATUSES = new Set(senderStatusSchema.options);
241
+ var REF = /^[^:\s]+:[^:\s]+:\S+$/u;
242
+ var ref = (what) => z.string({ error: `must be the ${what}'s ref, a string` }).regex(REF, {
243
+ error: `must be the ${what}'s ref, like "instantly:ws_1:abc123" (provider:workspaceId:id), not its name or address`
244
+ });
245
+ var scopeSchema = z.strictObject({
246
+ campaign: ref("campaign").optional(),
247
+ client: z.string({
248
+ error: "must be the client's name as your clients rules give it"
249
+ }).min(1, { error: "must not be empty" }).optional(),
250
+ person: ref("lead").optional(),
251
+ sender: ref("sender").optional()
252
+ });
253
+ var windowSchema = z.strictObject({
254
+ days: z.number({ error: "must be a whole number of days" }).int({ error: "must be a whole number of days" }).min(1, { error: "must be at least 1" }).max(366, { error: "must be at most 366" })
255
+ });
256
+ var needs = (missing, wrong) => (issue) => issue.input === void 0 ? `is required: ${missing}` : wrong;
257
+ var baseSchema = z.strictObject({
258
+ metric: z.enum(METRIC_NAMES, {
259
+ error: needs(
260
+ `the number to check, one of ${METRIC_NAMES.join(", ")}`,
261
+ `must be one of ${METRIC_NAMES.join(", ")}`
262
+ )
263
+ }),
264
+ min_sent: z.number({ error: "must be a whole number of sends" }).int({ error: "must be a whole number of sends" }).min(0, { error: "must be 0 or more" }).optional(),
265
+ name: z.string({ error: "must be a string" }).min(1, { error: "must not be empty" }).optional(),
266
+ op: z.enum(NUMBER_OPS, {
267
+ error: needs(
268
+ `how to compare, one of ${NUMBER_OPS.join(" ")}`,
269
+ `must be one of ${NUMBER_OPS.join(" ")}`
270
+ )
271
+ }),
272
+ scope: scopeSchema.optional(),
273
+ value: z.union([z.number(), z.string()], {
274
+ error: needs(
275
+ "what to compare with, such as 0.03 for a 3% rate",
276
+ "must be a number, or a sender status for sender_status"
277
+ )
278
+ }),
279
+ window: windowSchema.optional()
280
+ });
281
+ var looseCheck = z.object({
282
+ metric: z.enum(METRIC_NAMES),
283
+ min_sent: z.unknown().optional().transform((value) => value !== void 0),
284
+ op: z.string().optional().catch(void 0),
285
+ scope: z.record(z.string(), z.unknown()).optional().catch(void 0),
286
+ value: z.union([
287
+ z.number().transform((value) => ({ kind: "number", value })),
288
+ z.string().transform((value) => ({ kind: "string", value }))
289
+ ]).catch({ kind: "none" }),
290
+ window: z.unknown().optional().transform((value) => value !== void 0)
291
+ });
292
+ var statusFits = (given) => given.kind === "none" || given.kind === "string" && STATUSES.has(given.value) ? null : `sender_status compares a status: one of ${senderStatusSchema.options.join(", ")}`;
293
+ var numberFits = (metric, unit, given) => {
294
+ if (given.kind === "string") {
295
+ return `${metric} compares a number, not ${JSON.stringify(given.value)}`;
296
+ }
297
+ if (given.kind === "none") {
298
+ return null;
299
+ }
300
+ const { value } = given;
301
+ if (unit === "rate" && (value < 0 || value > 1)) {
302
+ return value > 1 && value <= 100 ? `${metric} is a fraction from 0 to 1: write ${value / 100} for ${value}%` : `${metric} is a fraction from 0 to 1`;
303
+ }
304
+ return value < 0 ? `${metric} is never below 0` : null;
305
+ };
306
+ var optionIssues = (check, metric) => [
307
+ ...check.window && metric.reads !== "stats" ? [
308
+ {
309
+ message: `${check.metric} takes no window: the ${metric.reads} read you pass sets its period`,
310
+ path: ["window"]
311
+ }
312
+ ] : [],
313
+ ...check.min_sent && metric.unit !== "rate" ? [
314
+ {
315
+ message: "min_sent applies only to bounce_rate and reply_rate",
316
+ path: ["min_sent"]
317
+ }
318
+ ] : []
319
+ ];
320
+ var fitIssues = (check) => {
321
+ const metric = CHECK_METRICS[check.metric];
322
+ const issues = [];
323
+ const valueIssue = metric.unit === "status" ? statusFits(check.value) : numberFits(check.metric, metric.unit, check.value);
324
+ if (valueIssue !== null) {
325
+ issues.push({ message: valueIssue, path: ["value"] });
326
+ }
327
+ if (metric.unit === "status" && check.op !== void 0 && check.op !== "==" && check.op !== "!=") {
328
+ issues.push({
329
+ message: `sender_status takes == or !=, not ${check.op}`,
330
+ path: ["op"]
331
+ });
332
+ }
333
+ for (const key of Object.keys(check.scope ?? {})) {
334
+ if (key in scopeSchema.shape && !metric.scope.some((each) => each === key)) {
335
+ issues.push({
336
+ message: `${check.metric} cannot be narrowed by ${key}. It takes ${metric.scope.join(", ")}`,
337
+ path: ["scope", key]
338
+ });
339
+ }
340
+ }
341
+ return [...issues, ...optionIssues(check, metric)];
342
+ };
343
+ var checkSchema = baseSchema.superRefine((check, ctx) => {
344
+ for (const issue of fitIssues(looseCheck.parse(check))) {
345
+ ctx.addIssue({
346
+ code: "custom",
347
+ message: issue.message,
348
+ path: [...issue.path]
349
+ });
350
+ }
351
+ });
352
+
353
+ // src/alerts/check-validate.ts
354
+ import { z as z2 } from "zod";
355
+ var KEY_HINTS = /* @__PURE__ */ new Map([
356
+ [
357
+ "",
358
+ /* @__PURE__ */ new Map([
359
+ ["days", "window: { days }"],
360
+ ["minSent", "min_sent"],
361
+ ["operator", "op"],
362
+ ["threshold", "value"]
363
+ ])
364
+ ],
365
+ [
366
+ "scope",
367
+ /* @__PURE__ */ new Map([
368
+ ["campaignId", "campaign"],
369
+ ["lead", "person"],
370
+ ["senderId", "sender"]
371
+ ])
372
+ ]
373
+ ]);
374
+ var unknownKey = (key, where) => {
375
+ const hint = KEY_HINTS.get(where)?.get(key);
376
+ return hint === void 0 ? `${key} is not a check field` : `${key} is not a check field: write ${hint}`;
377
+ };
378
+ var snake = (text) => text.replaceAll(/(?<lower>[a-z])(?<upper>[A-Z])/gu, "$<lower>_$<upper>").replaceAll(/[\s-]+/gu, "_").toLowerCase();
379
+ var written = z2.object({
380
+ metric: z2.string().optional().catch(void 0),
381
+ op: z2.string().optional().catch(void 0)
382
+ }).catch({ metric: void 0, op: void 0 });
383
+ var hintFor = (path, given, message) => {
384
+ const close = given.metric === void 0 ? void 0 : snake(given.metric);
385
+ if (path === "metric" && close !== void 0 && close in CHECK_METRICS) {
386
+ return `${message}. Did you mean ${close}?`;
387
+ }
388
+ const alias = given.op === void 0 ? void 0 : OP_ALIASES.get(given.op);
389
+ return path === "op" && alias !== void 0 ? `${message}. Write ${alias} for ${given.op}` : message;
390
+ };
391
+ var toIssues = (error, given) => error.issues.flatMap((issue) => {
392
+ const where = issue.path.join(".");
393
+ if (issue.code === "unrecognized_keys") {
394
+ return issue.keys.map((key) => ({
395
+ message: unknownKey(key, where),
396
+ path: where === "" ? key : `${where}.${key}`
397
+ }));
398
+ }
399
+ if (where === "" && issue.code === "invalid_type") {
400
+ return [{ message: "a check is a JSON object", path: "" }];
401
+ }
402
+ return [{ message: hintFor(where, given, issue.message), path: where }];
403
+ });
404
+ var validateCheck = (input) => {
405
+ const parsed = baseSchema.safeParse(input);
406
+ const loose = looseCheck.safeParse(input);
407
+ const issues = [
408
+ ...parsed.success ? [] : toIssues(parsed.error, written.parse(input)),
409
+ ...(loose.success ? fitIssues(loose.data) : []).map((issue) => ({
410
+ message: issue.message,
411
+ path: issue.path.join(".")
412
+ }))
413
+ ];
414
+ return parsed.success && issues.length === 0 ? { check: parsed.data, ok: true } : { issues, ok: false };
415
+ };
416
+ var describeIssues = (issues) => issues.map(
417
+ (issue) => issue.path === "" ? issue.message : `${issue.path}: ${issue.message}`
418
+ ).join("\n");
419
+
420
+ // src/alerts/check-measure.ts
421
+ import { z as z3 } from "zod";
422
+ var blank = {
423
+ campaign: null,
424
+ day: null,
425
+ person: null,
426
+ sender: null,
427
+ subjectName: null
428
+ };
429
+ var rowReading = (metric, row) => {
430
+ if (metric === "bounce_rate") {
431
+ return {
432
+ numbers: { bounced: row.bounced, sent: row.sent },
433
+ value: computeRates(row).bounceRate.value
434
+ };
435
+ }
436
+ if (metric === "reply_rate") {
437
+ return {
438
+ numbers: {
439
+ contacted: row.contacted,
440
+ replied: row.replied,
441
+ sent: row.sent
442
+ },
443
+ value: computeRates(row).replyRate.value
444
+ };
445
+ }
446
+ return { numbers: { sent: row.sent }, value: row.sent };
447
+ };
448
+ var fromRows = (metric, rows, options) => {
449
+ const inWindow = rows.filter(
450
+ (row) => options.fromDay === null || row.date === null || row.date >= options.fromDay
451
+ );
452
+ const rate = metric !== "sent";
453
+ const measured = inWindow.flatMap((row) => {
454
+ const { numbers, value } = rowReading(metric, row);
455
+ if (value === null || rate && (row.sent ?? 0) < options.minSent) {
456
+ return [];
457
+ }
458
+ return [
459
+ {
460
+ ...blank,
461
+ campaign: row.scope === "campaign" ? row.scopeRef : null,
462
+ day: row.date,
463
+ numbers,
464
+ sender: row.scope === "sender" ? row.scopeRef : null,
465
+ subject: row.scopeRef,
466
+ value
467
+ }
468
+ ];
469
+ });
470
+ return { measured, skipped: rows.length - measured.length };
471
+ };
472
+ var fromSenders = (senders) => {
473
+ const known = senders.filter((sender) => sender.status !== "unknown");
474
+ return {
475
+ measured: known.map((sender) => ({
476
+ ...blank,
477
+ numbers: { status: sender.status },
478
+ sender: sender.ref,
479
+ subject: sender.ref,
480
+ subjectName: sender.address ?? sender.name,
481
+ value: sender.status
482
+ })),
483
+ skipped: senders.length - known.length
484
+ };
485
+ };
486
+ var ref2 = z3.string();
487
+ var maybe = z3.string().nullable();
488
+ var droppedAnswer = z3.object({
489
+ dropped: z3.array(
490
+ z3.object({
491
+ campaign: maybe,
492
+ category: z3.string(),
493
+ email: maybe,
494
+ hoursWaiting: z3.number(),
495
+ lead: maybe,
496
+ linkedinUrl: maybe,
497
+ name: maybe,
498
+ receivedAt: z3.string(),
499
+ reply: ref2,
500
+ unansweredReplies: z3.number()
501
+ })
502
+ ),
503
+ olderThanHours: z3.number()
504
+ });
505
+ var forecastAnswer = z3.object({
506
+ campaign: ref2,
507
+ campaignName: z3.string(),
508
+ dailyContactRate: z3.number().nullable(),
509
+ daysLeft: z3.number().nullable(),
510
+ estimate: z3.literal(true),
511
+ remaining: z3.number()
512
+ });
513
+ var suppressionAnswer = z3.object({
514
+ byCampaign: z3.array(
515
+ z3.object({
516
+ campaign: ref2,
517
+ campaignName: z3.string(),
518
+ leadsRead: z3.number(),
519
+ violations: z3.number()
520
+ })
521
+ ),
522
+ violations: z3.array(z3.unknown())
523
+ });
524
+ var gapsAnswer = z3.object({
525
+ campaign: ref2,
526
+ totals: z3.object({ leadsRead: z3.number() }),
527
+ unknownVariables: z3.array(z3.string()),
528
+ variables: z3.array(
529
+ z3.object({
530
+ gap: z3.boolean(),
531
+ leadsAffected: z3.number().nullable(),
532
+ leadsWithoutValue: z3.number().nullable(),
533
+ name: z3.string()
534
+ })
535
+ )
536
+ });
537
+ var fromDropped = (data) => ({
538
+ measured: data.dropped.filter((reply) => reply.category === "positive").map((reply) => ({
539
+ ...blank,
540
+ campaign: reply.campaign,
541
+ numbers: {
542
+ hoursWaiting: reply.hoursWaiting,
543
+ receivedAt: reply.receivedAt,
544
+ unansweredReplies: reply.unansweredReplies
545
+ },
546
+ person: reply.lead,
547
+ subject: reply.reply,
548
+ subjectName: reply.name ?? reply.email ?? reply.linkedinUrl,
549
+ value: reply.hoursWaiting
550
+ })),
551
+ skipped: 0
552
+ });
553
+ var fromForecast = (data) => data.daysLeft === null ? { measured: [], skipped: 1 } : {
554
+ measured: [
555
+ {
556
+ ...blank,
557
+ campaign: data.campaign,
558
+ numbers: {
559
+ dailyContactRate: data.dailyContactRate,
560
+ daysLeft: data.daysLeft,
561
+ remaining: data.remaining
562
+ },
563
+ subject: data.campaign,
564
+ subjectName: data.campaignName,
565
+ value: data.daysLeft
566
+ }
567
+ ],
568
+ skipped: 0
569
+ };
570
+ var fromSuppression = (data) => ({
571
+ measured: data.byCampaign.map((each) => ({
572
+ ...blank,
573
+ campaign: each.campaign,
574
+ numbers: { leadsRead: each.leadsRead, violations: each.violations },
575
+ subject: each.campaign,
576
+ subjectName: each.campaignName,
577
+ value: each.violations
578
+ })),
579
+ skipped: 0
580
+ });
581
+ var fromGaps = (data) => {
582
+ const broken = data.variables.filter((each) => each.gap);
583
+ const measured = broken.flatMap(
584
+ (each) => each.leadsAffected === null ? [] : [
585
+ {
586
+ ...blank,
587
+ campaign: data.campaign,
588
+ numbers: {
589
+ leadsAffected: each.leadsAffected,
590
+ leadsRead: data.totals.leadsRead,
591
+ leadsWithoutValue: each.leadsWithoutValue
592
+ },
593
+ subject: data.campaign,
594
+ subjectName: each.name,
595
+ value: each.leadsAffected
596
+ }
597
+ ]
598
+ );
599
+ return { measured, skipped: broken.length - measured.length };
600
+ };
601
+ var insightResult = z3.object({ data: z3.unknown(), insight: z3.string() });
602
+ var measureAnswer = (schema, read, input) => {
603
+ const result = insightResult.safeParse(input);
604
+ const parsed = schema.safeParse(result.success ? result.data.data : input);
605
+ return parsed.success ? read(parsed.data) : null;
606
+ };
607
+ var ANSWERS = {
608
+ droppedReplies: (input) => measureAnswer(droppedAnswer, fromDropped, input),
609
+ personalizationGaps: (input) => measureAnswer(gapsAnswer, fromGaps, input),
610
+ pipelineForecast: (input) => measureAnswer(forecastAnswer, fromForecast, input),
611
+ suppressionCheck: (input) => measureAnswer(suppressionAnswer, fromSuppression, input)
612
+ };
613
+ var listed = z3.union([
614
+ z3.array(z3.unknown()),
615
+ z3.object({ rows: z3.array(z3.unknown()) }).transform((result) => result.rows),
616
+ z3.object({ items: z3.array(z3.unknown()) }).transform((page) => page.items)
617
+ ]);
618
+ var parsedAll = (schema, records) => records.flatMap((record) => {
619
+ const parsed = schema.safeParse(record);
620
+ return parsed.success ? [parsed.data] : [];
621
+ });
622
+ var fromRecords = (metric, source, input, options) => {
623
+ const list = listed.safeParse(input);
624
+ const records = list.success ? list.data : [input];
625
+ const rows = source === "stats" ? parsedAll(metricRowSchema, records) : [];
626
+ const senders = source === "senders" ? parsedAll(senderSchema, records) : [];
627
+ if (records.length > 0 && rows.length + senders.length === 0) {
628
+ return {
629
+ ok: false,
630
+ reason: source === "stats" ? `${metric} reads stats rows. Pass the rows a stats() read returned` : `${metric} reads senders. Pass what outbound.senders.list() returned`
631
+ };
632
+ }
633
+ return {
634
+ ok: true,
635
+ readings: source === "stats" ? fromRows(metric, rows, options) : fromSenders(senders)
636
+ };
637
+ };
638
+ var measure = (metric, source, input, options) => {
639
+ if (source === "stats" || source === "senders") {
640
+ return fromRecords(metric, source, input, options);
641
+ }
642
+ const readings = ANSWERS[source](input);
643
+ return readings === null ? {
644
+ ok: false,
645
+ reason: `${metric} reads a ${source} answer. Pass what outbound.insights.${source}() returned`
646
+ } : { ok: true, readings };
647
+ };
648
+
649
+ // src/alerts/check-evaluate.ts
650
+ var DAY_MS = 864e5;
651
+ var DEFAULT_MIN_SENT = 50;
652
+ var OP_WORDS = {
653
+ "!=": "not",
654
+ "<": "below",
655
+ "<=": "at or below",
656
+ "==": "equal to",
657
+ ">": "above",
658
+ ">=": "at or above"
659
+ };
660
+ var parseCheck = (input) => {
661
+ const validation = validateCheck(input);
662
+ if (!validation.ok) {
663
+ throw new OutboundError(
664
+ "Invalid",
665
+ `The check is not valid:
666
+ ${describeIssues(validation.issues)}`
667
+ );
668
+ }
669
+ return validation.check;
670
+ };
671
+ var breaks = (op, value, limit) => {
672
+ switch (op) {
673
+ case "==": {
674
+ return value === limit;
675
+ }
676
+ case "!=": {
677
+ return value !== limit;
678
+ }
679
+ case ">": {
680
+ return value > limit;
681
+ }
682
+ case ">=": {
683
+ return value >= limit;
684
+ }
685
+ case "<": {
686
+ return value < limit;
687
+ }
688
+ default: {
689
+ return value <= limit;
690
+ }
691
+ }
692
+ };
693
+ var shown = (metric, value) => {
694
+ if (metric.unit === "status") {
695
+ return String(value);
696
+ }
697
+ const amount = Number(value);
698
+ if (metric.unit === "rate") {
699
+ return percentOf(amount);
700
+ }
701
+ const rounded = String(Math.round(amount * 10) / 10);
702
+ return metric.unit === "count" ? rounded : `${rounded} ${metric.unit}`;
703
+ };
704
+ var inScope = (check, reading) => {
705
+ const { campaign, person, sender } = check.scope ?? {};
706
+ return (campaign === void 0 || reading.campaign === campaign) && (sender === void 0 || reading.sender === sender) && (person === void 0 || reading.person === person);
707
+ };
708
+ var fromDayOf = (check, now) => {
709
+ if (check.window === void 0) {
710
+ return null;
711
+ }
712
+ const end = new Date(now ?? Date.now()).getTime();
713
+ if (Number.isNaN(end)) {
714
+ throw new OutboundError(
715
+ "Invalid",
716
+ `now is not a date: ${String(now)}. Pass a Date, milliseconds or an ISO 8601 string`
717
+ );
718
+ }
719
+ return new Date(end - (check.window.days - 1) * DAY_MS).toISOString().slice(0, 10);
720
+ };
721
+ var notChecked = (name, reason) => ({
722
+ breaches: [],
723
+ check: name,
724
+ checked: 0,
725
+ reason,
726
+ skipped: 0,
727
+ status: "not_checked"
728
+ });
729
+ var clientMismatch = (check, client) => {
730
+ const wanted = check.scope?.client;
731
+ if (wanted === void 0 || wanted === client) {
732
+ return null;
733
+ }
734
+ return client === void 0 ? `The check is scoped to client "${wanted}". Pass { client: "${wanted}" } with that client's read` : `The check is scoped to client "${wanted}", and this read is "${client}"'s`;
735
+ };
736
+ var evaluateCheck = (input, read, options = {}) => {
737
+ const check = parseCheck(input);
738
+ const name = check.name ?? check.metric;
739
+ const metric = CHECK_METRICS[check.metric];
740
+ const mismatch = clientMismatch(check, options.client);
741
+ if (mismatch !== null) {
742
+ return notChecked(name, mismatch);
743
+ }
744
+ const readings = measure(check.metric, metric.reads, read, {
745
+ fromDay: fromDayOf(check, options.now),
746
+ minSent: check.min_sent ?? DEFAULT_MIN_SENT
747
+ });
748
+ if (!readings.ok) {
749
+ return notChecked(name, readings.reason);
750
+ }
751
+ const measured = readings.readings.measured.filter(
752
+ (reading) => inScope(check, reading)
753
+ );
754
+ const breaches = measured.filter((reading) => breaks(check.op, reading.value, check.value)).map((reading) => ({
755
+ day: reading.day,
756
+ message: `${check.metric} is ${shown(metric, reading.value)}, ${OP_WORDS[check.op]} ${shown(metric, check.value)}`,
757
+ metric: check.metric,
758
+ numbers: reading.numbers,
759
+ op: check.op,
760
+ rule: name,
761
+ subject: reading.subject,
762
+ subjectName: reading.subjectName,
763
+ threshold: check.value,
764
+ value: reading.value
765
+ }));
766
+ return {
767
+ breaches,
768
+ check: name,
769
+ checked: measured.length,
770
+ reason: null,
771
+ skipped: readings.readings.skipped,
772
+ status: breaches.length > 0 ? "fail" : "pass"
773
+ };
774
+ };
775
+ var checkRule = (input, options = {}) => {
776
+ const check = parseCheck(input);
777
+ const { reads } = CHECK_METRICS[check.metric];
778
+ if (reads !== "stats" && reads !== "senders") {
779
+ throw new OutboundError(
780
+ "Invalid",
781
+ `${check.metric} reads a ${reads} answer, not records, so it cannot be an alert rule. Call evaluateCheck(check, await outbound.insights.${reads}(...)) instead`
782
+ );
783
+ }
784
+ return {
785
+ check: (record) => evaluateCheck(check, record, options).breaches[0] ?? null,
786
+ name: check.name ?? check.metric,
787
+ state: reads === "senders"
788
+ };
789
+ };
164
790
  export {
791
+ CHECK_METRICS,
165
792
  alerts,
166
793
  bounceRateAbove,
794
+ checkRule,
795
+ checkSchema,
796
+ describeIssues,
797
+ evaluateCheck,
167
798
  memoryAlertDedupe,
168
799
  noSends,
800
+ parseCheck,
169
801
  replyRateBelow,
170
- senderNotActive
802
+ senderNotActive,
803
+ validateCheck
171
804
  };
@@ -11,6 +11,8 @@ export interface BudgetOptions {
11
11
  }
12
12
  export interface BudgetExtension {
13
13
  readonly requestBudget: {
14
+ /** What the budget counts against: each call, or the whole run. */
15
+ readonly per: "call" | "run";
14
16
  /** Requests counted against a `run` budget so far. */
15
17
  readonly used: () => number;
16
18
  readonly remaining: () => number;
@@ -26,6 +26,7 @@ var budget = (options) => {
26
26
  return {
27
27
  extend: () => ({
28
28
  requestBudget: {
29
+ per: perRun ? "run" : "call",
29
30
  remaining,
30
31
  reset: () => {
31
32
  used = 0;
@@ -15,7 +15,7 @@ export declare const clip: (value: string, max: number) => string;
15
15
  export declare const str: (value: Json | undefined, key: string) => string | null;
16
16
  /** A string field for display: made inert, or a dash. */
17
17
  export declare const show: (value: Json | undefined, key: string) => string;
18
- /** A campaign's name: `campaignName`, or `name` in a result stored before it. */
18
+ /** A campaign's name, as an insight's campaign row carries it. */
19
19
  export declare const campaignNameOf: (value: Json | undefined) => string;
20
20
  export declare const num: (value: Json | undefined, key: string) => number | null;
21
21
  export declare const bool: (value: Json | undefined, key: string) => boolean | null;