outbound-sdk 0.0.0-stage → 0.1.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 (271) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +121 -2
  3. package/dist/alerts/index.d.ts +2 -0
  4. package/dist/alerts/index.js +136 -0
  5. package/dist/alerts/plugin.d.ts +58 -0
  6. package/dist/audit/index.d.ts +33 -0
  7. package/dist/audit/index.js +60 -0
  8. package/dist/benchmarks/index.d.ts +29 -0
  9. package/dist/benchmarks/index.js +70 -0
  10. package/dist/budget/index.d.ts +21 -0
  11. package/dist/budget/index.js +50 -0
  12. package/dist/cache/index.d.ts +31 -0
  13. package/dist/cache/index.js +11 -0
  14. package/dist/cards/content.d.ts +43 -0
  15. package/dist/cards/copy-cards.d.ts +2 -0
  16. package/dist/cards/format.d.ts +39 -0
  17. package/dist/cards/index.d.ts +9 -0
  18. package/dist/cards/index.js +2070 -0
  19. package/dist/cards/notify-cards.d.ts +14 -0
  20. package/dist/cards/ops-cards.d.ts +2 -0
  21. package/dist/cards/parts.d.ts +22 -0
  22. package/dist/cards/people-cards.d.ts +2 -0
  23. package/dist/cards/render.d.ts +28 -0
  24. package/dist/cards/sender-cards.d.ts +2 -0
  25. package/dist/cards/slack-rich.d.ts +19 -0
  26. package/dist/cards/slack-text.d.ts +10 -0
  27. package/dist/cards/slack.d.ts +21 -0
  28. package/dist/cards/spec.d.ts +86 -0
  29. package/dist/cards/tool-cards.d.ts +4 -0
  30. package/dist/chunks/chunk-4O2HRTTI.js +75 -0
  31. package/dist/chunks/chunk-7BCYLIDG.js +483 -0
  32. package/dist/chunks/chunk-B7V6EOAC.js +2273 -0
  33. package/dist/chunks/chunk-CMQ5ZHLZ.js +25 -0
  34. package/dist/chunks/chunk-F7MKFVIG.js +43 -0
  35. package/dist/chunks/chunk-FZF6CLPX.js +232 -0
  36. package/dist/chunks/chunk-GPEJG34O.js +53 -0
  37. package/dist/chunks/chunk-HEC7XFFH.js +65 -0
  38. package/dist/chunks/chunk-IBC52BX3.js +24 -0
  39. package/dist/chunks/chunk-LNCOGBMI.js +144 -0
  40. package/dist/chunks/chunk-LOXBLQ3I.js +180 -0
  41. package/dist/chunks/chunk-NAWZ73QS.js +22 -0
  42. package/dist/chunks/chunk-OCV66TS2.js +705 -0
  43. package/dist/chunks/chunk-Q465X22Y.js +548 -0
  44. package/dist/chunks/chunk-QTB747K4.js +100 -0
  45. package/dist/chunks/chunk-QZNNCXXD.js +92 -0
  46. package/dist/chunks/chunk-R6AM4GJR.js +105 -0
  47. package/dist/chunks/chunk-TIJKJJDW.js +6 -0
  48. package/dist/chunks/chunk-VURTOVGI.js +61 -0
  49. package/dist/chunks/chunk-WAM6N4OF.js +269 -0
  50. package/dist/chunks/chunk-WW746NJF.js +94 -0
  51. package/dist/chunks/chunk-XC6CZP73.js +80 -0
  52. package/dist/chunks/chunk-ZGHQYZEH.js +45 -0
  53. package/dist/cli/bin.d.ts +2 -0
  54. package/dist/cli/bin.js +34 -0
  55. package/dist/cli/commands.d.ts +16 -0
  56. package/dist/cli/index.d.ts +13 -0
  57. package/dist/cli/index.js +25 -0
  58. package/dist/cli/mcp.d.ts +14 -0
  59. package/dist/clients/index.d.ts +2 -0
  60. package/dist/clients/index.js +107 -0
  61. package/dist/clients/plugin.d.ts +42 -0
  62. package/dist/combine/account.d.ts +4 -0
  63. package/dist/combine/adapter.d.ts +9 -0
  64. package/dist/combine/index.d.ts +2 -0
  65. package/dist/combine/index.js +345 -0
  66. package/dist/combine/route.d.ts +17 -0
  67. package/dist/exporter/index.d.ts +29 -0
  68. package/dist/exporter/index.js +77 -0
  69. package/dist/failover/index.d.ts +11 -0
  70. package/dist/failover/index.js +45 -0
  71. package/dist/fixtures/index.d.ts +27 -0
  72. package/dist/fixtures/index.js +241 -0
  73. package/dist/fixtures/scrub.d.ts +5 -0
  74. package/dist/heyreach/account.d.ts +11 -0
  75. package/dist/heyreach/adapter.d.ts +5 -0
  76. package/dist/heyreach/capabilities.d.ts +68 -0
  77. package/dist/heyreach/client.d.ts +20 -0
  78. package/dist/heyreach/inbox.d.ts +7 -0
  79. package/dist/heyreach/index.d.ts +18 -0
  80. package/dist/heyreach/index.js +1708 -0
  81. package/dist/heyreach/lookup.d.ts +15 -0
  82. package/dist/heyreach/map-account.d.ts +25 -0
  83. package/dist/heyreach/map-sequence.d.ts +5 -0
  84. package/dist/heyreach/map-stats.d.ts +10 -0
  85. package/dist/heyreach/map.d.ts +35 -0
  86. package/dist/heyreach/native-organization.d.ts +128 -0
  87. package/dist/heyreach/native-voice.d.ts +106 -0
  88. package/dist/heyreach/native.d.ts +496 -0
  89. package/dist/heyreach/paging.d.ts +7 -0
  90. package/dist/heyreach/webhooks.d.ts +2 -0
  91. package/dist/identity/index.d.ts +3 -0
  92. package/dist/identity/index.js +148 -0
  93. package/dist/identity/keys.d.ts +9 -0
  94. package/dist/identity/plugin.d.ts +34 -0
  95. package/dist/index.d.ts +36 -0
  96. package/dist/index.js +119 -0
  97. package/dist/insights/copy/copy-audit.d.ts +55 -0
  98. package/dist/insights/copy/copy-checks.d.ts +44 -0
  99. package/dist/insights/copy/copy-reuse.d.ts +59 -0
  100. package/dist/insights/copy/index.d.ts +67 -0
  101. package/dist/insights/copy/reply-timing.d.ts +63 -0
  102. package/dist/insights/copy/shared.d.ts +53 -0
  103. package/dist/insights/copy/step-funnel.d.ts +66 -0
  104. package/dist/insights/copy/variant-test.d.ts +64 -0
  105. package/dist/insights/define.d.ts +98 -0
  106. package/dist/insights/index.d.ts +10 -0
  107. package/dist/insights/index.js +4873 -0
  108. package/dist/insights/ops/anomalies.d.ts +80 -0
  109. package/dist/insights/ops/campaign-diagnosis.d.ts +39 -0
  110. package/dist/insights/ops/campaign-ranking.d.ts +56 -0
  111. package/dist/insights/ops/channel-mix.d.ts +44 -0
  112. package/dist/insights/ops/client-report.d.ts +76 -0
  113. package/dist/insights/ops/diagnosis-checks.d.ts +48 -0
  114. package/dist/insights/ops/index.d.ts +135 -0
  115. package/dist/insights/ops/period-comparison.d.ts +86 -0
  116. package/dist/insights/ops/pipeline-forecast.d.ts +44 -0
  117. package/dist/insights/ops/shared.d.ts +149 -0
  118. package/dist/insights/ops/tag-rollup.d.ts +32 -0
  119. package/dist/insights/people/account-summary.d.ts +68 -0
  120. package/dist/insights/people/dropped-replies.d.ts +51 -0
  121. package/dist/insights/people/find.d.ts +18 -0
  122. package/dist/insights/people/hot-leads.d.ts +67 -0
  123. package/dist/insights/people/index.d.ts +88 -0
  124. package/dist/insights/people/lead-collisions.d.ts +43 -0
  125. package/dist/insights/people/person-summary.d.ts +46 -0
  126. package/dist/insights/people/personalization-gaps.d.ts +60 -0
  127. package/dist/insights/people/read.d.ts +40 -0
  128. package/dist/insights/people/suppression-check.d.ts +53 -0
  129. package/dist/insights/plugin.d.ts +40 -0
  130. package/dist/insights/registry.d.ts +335 -0
  131. package/dist/insights/senders/bounce-watch.d.ts +70 -0
  132. package/dist/insights/senders/domain-health.d.ts +69 -0
  133. package/dist/insights/senders/index.d.ts +74 -0
  134. package/dist/insights/senders/read.d.ts +37 -0
  135. package/dist/insights/senders/sender-capacity.d.ts +67 -0
  136. package/dist/insights/senders/sender-load.d.ts +52 -0
  137. package/dist/insights/senders/settings-audit.d.ts +48 -0
  138. package/dist/insights/senders/warmup-readiness.d.ts +39 -0
  139. package/dist/insights/stats.d.ts +45 -0
  140. package/dist/insights/tools.d.ts +16 -0
  141. package/dist/insights/types.d.ts +4 -0
  142. package/dist/instantly/adapter-account.d.ts +5 -0
  143. package/dist/instantly/adapter-mail.d.ts +3 -0
  144. package/dist/instantly/adapter.d.ts +7 -0
  145. package/dist/instantly/capabilities.d.ts +83 -0
  146. package/dist/instantly/client.d.ts +29 -0
  147. package/dist/instantly/index.d.ts +20 -0
  148. package/dist/instantly/index.js +2372 -0
  149. package/dist/instantly/map-account.d.ts +23 -0
  150. package/dist/instantly/map-lead.d.ts +18 -0
  151. package/dist/instantly/map-stats.d.ts +22 -0
  152. package/dist/instantly/map.d.ts +24 -0
  153. package/dist/instantly/native-agents-sales.d.ts +161 -0
  154. package/dist/instantly/native-agents.d.ts +156 -0
  155. package/dist/instantly/native-campaigns.d.ts +101 -0
  156. package/dist/instantly/native-leads.d.ts +93 -0
  157. package/dist/instantly/native-params.d.ts +24 -0
  158. package/dist/instantly/native-search.d.ts +82 -0
  159. package/dist/instantly/native-senders.d.ts +182 -0
  160. package/dist/instantly/native-supersearch.d.ts +149 -0
  161. package/dist/instantly/native-workspace.d.ts +170 -0
  162. package/dist/instantly/native.d.ts +1081 -0
  163. package/dist/instantly/pages.d.ts +29 -0
  164. package/dist/instantly/stats.d.ts +5 -0
  165. package/dist/instantly/webhooks.d.ts +2 -0
  166. package/dist/internal/adapter.d.ts +189 -0
  167. package/dist/internal/capabilities.d.ts +86 -0
  168. package/dist/internal/cursor.d.ts +10 -0
  169. package/dist/internal/engine/budget.d.ts +44 -0
  170. package/dist/internal/engine/engine.d.ts +45 -0
  171. package/dist/internal/engine/rate-store.d.ts +25 -0
  172. package/dist/internal/engine/request.d.ts +27 -0
  173. package/dist/internal/engine/retry.d.ts +21 -0
  174. package/dist/internal/engine/runtime.d.ts +13 -0
  175. package/dist/internal/entities-account.d.ts +135 -0
  176. package/dist/internal/entities.d.ts +389 -0
  177. package/dist/internal/env.d.ts +4 -0
  178. package/dist/internal/errors.d.ts +57 -0
  179. package/dist/internal/hooks.d.ts +55 -0
  180. package/dist/internal/json.d.ts +40 -0
  181. package/dist/internal/limits.d.ts +34 -0
  182. package/dist/internal/metrics.d.ts +52 -0
  183. package/dist/internal/native.d.ts +66 -0
  184. package/dist/internal/outbound/api.d.ts +267 -0
  185. package/dist/internal/outbound/collections.d.ts +31 -0
  186. package/dist/internal/outbound/core.d.ts +36 -0
  187. package/dist/internal/outbound/create.d.ts +16 -0
  188. package/dist/internal/outbound/handles.d.ts +7 -0
  189. package/dist/internal/outbound/native.d.ts +4 -0
  190. package/dist/internal/outbound/operation-shared.d.ts +28 -0
  191. package/dist/internal/outbound/operations-account.d.ts +29 -0
  192. package/dist/internal/outbound/operations.d.ts +42 -0
  193. package/dist/internal/outbound/outbound.d.ts +64 -0
  194. package/dist/internal/outbound/plugins.d.ts +40 -0
  195. package/dist/internal/outbound/raw.d.ts +9 -0
  196. package/dist/internal/outbound/specs-account.d.ts +16 -0
  197. package/dist/internal/outbound/specs.d.ts +14 -0
  198. package/dist/internal/outbound/stats.d.ts +7 -0
  199. package/dist/internal/outbound/validate.d.ts +5 -0
  200. package/dist/internal/outbound/walker.d.ts +22 -0
  201. package/dist/internal/record.d.ts +19 -0
  202. package/dist/internal/redact.d.ts +18 -0
  203. package/dist/internal/ref.d.ts +16 -0
  204. package/dist/internal/sha256.d.ts +4 -0
  205. package/dist/internal/text.d.ts +11 -0
  206. package/dist/internal/url.d.ts +9 -0
  207. package/dist/loader/index.d.ts +12 -0
  208. package/dist/loader/index.js +12 -0
  209. package/dist/memory/account-reads.d.ts +5 -0
  210. package/dist/memory/account.d.ts +67 -0
  211. package/dist/memory/adapter.d.ts +16 -0
  212. package/dist/memory/data.d.ts +122 -0
  213. package/dist/memory/demo.d.ts +7 -0
  214. package/dist/memory/index.d.ts +5 -0
  215. package/dist/memory/index.js +792 -0
  216. package/dist/memory/stats.d.ts +6 -0
  217. package/dist/memory/store.d.ts +18 -0
  218. package/dist/providers/index.d.ts +22 -0
  219. package/dist/providers/index.js +10 -0
  220. package/dist/reconcile/index.d.ts +2 -0
  221. package/dist/reconcile/index.js +72 -0
  222. package/dist/reconcile/plugin.d.ts +55 -0
  223. package/dist/redact/index.d.ts +2 -0
  224. package/dist/redact/index.js +192 -0
  225. package/dist/redact/plugin.d.ts +22 -0
  226. package/dist/redis/index.d.ts +41 -0
  227. package/dist/redis/index.js +114 -0
  228. package/dist/smartlead/account.d.ts +5 -0
  229. package/dist/smartlead/adapter.d.ts +5 -0
  230. package/dist/smartlead/capabilities.d.ts +85 -0
  231. package/dist/smartlead/client.d.ts +23 -0
  232. package/dist/smartlead/hmac.d.ts +9 -0
  233. package/dist/smartlead/index.d.ts +17 -0
  234. package/dist/smartlead/index.js +2170 -0
  235. package/dist/smartlead/leads.d.ts +6 -0
  236. package/dist/smartlead/lookup.d.ts +8 -0
  237. package/dist/smartlead/mail.d.ts +5 -0
  238. package/dist/smartlead/map-account.d.ts +22 -0
  239. package/dist/smartlead/map-messages.d.ts +31 -0
  240. package/dist/smartlead/map-stats.d.ts +37 -0
  241. package/dist/smartlead/map.d.ts +52 -0
  242. package/dist/smartlead/native-analytics.d.ts +242 -0
  243. package/dist/smartlead/native-campaigns.d.ts +211 -0
  244. package/dist/smartlead/native-inbox.d.ts +141 -0
  245. package/dist/smartlead/native-params.d.ts +33 -0
  246. package/dist/smartlead/native-services.d.ts +204 -0
  247. package/dist/smartlead/native.d.ts +785 -0
  248. package/dist/smartlead/shared.d.ts +28 -0
  249. package/dist/smartlead/stats.d.ts +5 -0
  250. package/dist/smartlead/webhooks.d.ts +2 -0
  251. package/dist/sync/index.d.ts +2 -0
  252. package/dist/sync/index.js +158 -0
  253. package/dist/sync/plugin.d.ts +58 -0
  254. package/dist/tools/account-tools.d.ts +21 -0
  255. package/dist/tools/ai-sdk.d.ts +8 -0
  256. package/dist/tools/ai-sdk.js +26 -0
  257. package/dist/tools/campaign-tools.d.ts +59 -0
  258. package/dist/tools/claude-agent.d.ts +18 -0
  259. package/dist/tools/claude-agent.js +40 -0
  260. package/dist/tools/index.d.ts +28 -0
  261. package/dist/tools/index.js +20 -0
  262. package/dist/tools/people-tools.d.ts +19 -0
  263. package/dist/tools/registry.d.ts +34 -0
  264. package/dist/tools/shared.d.ts +75 -0
  265. package/dist/tracing/index.d.ts +25 -0
  266. package/dist/tracing/index.js +69 -0
  267. package/dist/webhooks/index.d.ts +3 -0
  268. package/dist/webhooks/index.js +226 -0
  269. package/dist/webhooks/parse.d.ts +41 -0
  270. package/dist/webhooks/secret.d.ts +4 -0
  271. package/package.json +181 -4
@@ -0,0 +1,2273 @@
1
+ import {
2
+ defaultRateLimitStore
3
+ } from "./chunk-4O2HRTTI.js";
4
+ import {
5
+ buildUrl
6
+ } from "./chunk-NAWZ73QS.js";
7
+ import {
8
+ sha256Hex
9
+ } from "./chunk-LNCOGBMI.js";
10
+ import {
11
+ CAPABILITY_KEYS,
12
+ intersectCapabilities,
13
+ requireCapability,
14
+ resolveCapabilities
15
+ } from "./chunk-QTB747K4.js";
16
+ import {
17
+ baseFields,
18
+ campaignSchema,
19
+ count as count2,
20
+ isoDateTime,
21
+ leadSchema,
22
+ messageSchema,
23
+ metricRowSchema,
24
+ replySchema,
25
+ senderSchema,
26
+ sequenceSchema,
27
+ workspaceSchema
28
+ } from "./chunk-WAM6N4OF.js";
29
+ import {
30
+ sourceIdFor
31
+ } from "./chunk-ZGHQYZEH.js";
32
+ import {
33
+ OutboundError,
34
+ redactUrl
35
+ } from "./chunk-LOXBLQ3I.js";
36
+ import {
37
+ count,
38
+ field,
39
+ isJsonObject,
40
+ isString,
41
+ parseJson
42
+ } from "./chunk-QZNNCXXD.js";
43
+
44
+ // src/internal/limits.ts
45
+ var DEFAULT_CONCURRENCY = 8;
46
+ var DEFAULT_SHARE = 0.5;
47
+ var scaleWindow = (window, share) => ({
48
+ perMs: window.perMs,
49
+ requests: Math.max(1, Math.floor(window.requests * share))
50
+ });
51
+
52
+ // src/internal/engine/retry.ts
53
+ var BASE_MS = 1e3;
54
+ var CAP_MS = 6e4;
55
+ var fullJitterBackoff = (attempt2, random) => Math.floor(random * Math.min(CAP_MS, BASE_MS * 2 ** (attempt2 - 1)));
56
+ var DEFAULT_RETRIES = 4;
57
+ var resolveRetryPolicy = (option) => {
58
+ if (option === void 0) {
59
+ return { backoff: fullJitterBackoff, max: DEFAULT_RETRIES };
60
+ }
61
+ if (isRetryCount(option)) {
62
+ return { backoff: fullJitterBackoff, max: Math.max(0, Math.floor(option)) };
63
+ }
64
+ return {
65
+ backoff: option.backoff ?? fullJitterBackoff,
66
+ max: Math.max(0, Math.floor(option.max))
67
+ };
68
+ };
69
+ var isRetryCount = (option) => typeof option === "number";
70
+ var secondsFromBody = (body) => {
71
+ if (!isJsonObject(body)) {
72
+ return void 0;
73
+ }
74
+ for (const key of ["retry_after", "retryAfter", "retry_after_seconds"]) {
75
+ const seconds = count(field(body, key));
76
+ if (seconds !== null) {
77
+ return seconds;
78
+ }
79
+ }
80
+ return void 0;
81
+ };
82
+ var parseRetryAfter = (headers, body, now) => {
83
+ const header = headers.get("retry-after");
84
+ if (header !== null && header.trim() !== "") {
85
+ const seconds2 = Number(header);
86
+ if (Number.isFinite(seconds2)) {
87
+ return Math.max(0, Math.ceil(seconds2 * 1e3));
88
+ }
89
+ const date = Date.parse(header);
90
+ if (!Number.isNaN(date)) {
91
+ return Math.max(0, date - now);
92
+ }
93
+ }
94
+ const seconds = secondsFromBody(body);
95
+ return seconds === void 0 ? void 0 : Math.max(0, Math.ceil(seconds * 1e3));
96
+ };
97
+ var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
98
+ 408,
99
+ 429,
100
+ 500,
101
+ 502,
102
+ 503,
103
+ 504
104
+ ]);
105
+ var isRetryableStatus = (status) => RETRYABLE_STATUSES.has(status);
106
+
107
+ // src/internal/entities-account.ts
108
+ import { z } from "zod";
109
+ var clock = z.string().regex(/^\d{2}:\d{2}$/u).nullable();
110
+ var flag = z.boolean().nullable();
111
+ var sendingWindowSchema = z.object({
112
+ /** Days of the week the window is open, 0 for Sunday to 6 for Saturday. */
113
+ days: z.array(z.number().int().min(0).max(6)),
114
+ /** `HH:MM` in `timezone`. */
115
+ from: clock,
116
+ name: z.string().nullable(),
117
+ /** An IANA name where the vendor gives one, otherwise the vendor's own label. */
118
+ timezone: z.string().nullable(),
119
+ /** `HH:MM` in `timezone`. */
120
+ to: clock
121
+ });
122
+ var campaignSettingsSchema = z.object({
123
+ ...baseFields,
124
+ campaignRef: z.string(),
125
+ /** The most messages (or LinkedIn actions) the campaign sends per day. */
126
+ dailyLimit: count2,
127
+ /** The most new leads the campaign contacts per day. */
128
+ dailyNewLeads: count2,
129
+ endDate: z.iso.date().nullable(),
130
+ /** The shortest wait between two sends, in minutes. */
131
+ gapMinutes: z.number().nonnegative().nullable(),
132
+ /** `true` when emails are sent without HTML. */
133
+ plainText: flag,
134
+ schedule: z.array(sendingWindowSchema),
135
+ startDate: z.iso.date().nullable(),
136
+ /** `true` when a lead who sends an automatic reply gets no more steps. */
137
+ stopOnAutoReply: flag,
138
+ /** `true` when a lead who replies gets no more steps. */
139
+ stopOnReply: flag,
140
+ tracking: z.object({ clicks: flag, opens: flag })
141
+ });
142
+ var senderHealthSchema = z.object({
143
+ ...baseFields,
144
+ /** `true` when the domain or address is on a block list the vendor checks. */
145
+ blacklisted: flag,
146
+ /** When the vendor last checked. */
147
+ checkedAt: isoDateTime,
148
+ /** `true` when the vendor can sign in to the mailbox or the LinkedIn seat. */
149
+ connected: flag,
150
+ /** Whether each DNS record is present and valid. */
151
+ dns: z.object({ dkim: flag, dmarc: flag, mx: flag, spf: flag }),
152
+ /** The mailbox's domain, lowercased. `null` for a LinkedIn seat. */
153
+ domain: z.string().nullable(),
154
+ /** Problems in the vendor's own words. */
155
+ issues: z.array(z.string()),
156
+ senderRef: z.string(),
157
+ /** Warmup traffic over the vendor's reporting window. `null` when there is none. */
158
+ warmup: z.object({
159
+ inbox: count2,
160
+ received: count2,
161
+ score: z.number().nullable(),
162
+ sent: count2,
163
+ spam: count2
164
+ }).nullable()
165
+ });
166
+ var leadListSchema = z.object({
167
+ ...baseFields,
168
+ createdAt: isoDateTime,
169
+ kind: z.enum(["companies", "leads"]),
170
+ name: z.string(),
171
+ /** How many records the list holds. */
172
+ size: count2
173
+ });
174
+ var blockEntrySchema = z.object({
175
+ ...baseFields,
176
+ createdAt: isoDateTime,
177
+ kind: z.enum(["company", "domain", "email", "linkedin", "other"]),
178
+ /** Lowercased for emails and domains. */
179
+ value: z.string()
180
+ });
181
+ var tagSchema = z.object({
182
+ ...baseFields,
183
+ description: z.string().nullable(),
184
+ name: z.string()
185
+ });
186
+ var webhookSubscriptionSchema = z.object({
187
+ ...baseFields,
188
+ active: flag,
189
+ /** The campaigns the webhook is limited to. Empty for every campaign. */
190
+ campaignRefs: z.array(z.string()),
191
+ createdAt: isoDateTime,
192
+ /** Event names in the vendor's own words. */
193
+ events: z.array(z.string()),
194
+ name: z.string().nullable(),
195
+ /** Where the vendor posts. It can hold a secret in its path or query. */
196
+ url: z.string()
197
+ });
198
+
199
+ // src/internal/hooks.ts
200
+ var ignore = () => {
201
+ };
202
+ var fire = (hook, event) => {
203
+ if (hook === void 0) {
204
+ return;
205
+ }
206
+ try {
207
+ Promise.resolve(hook(event)).catch(ignore);
208
+ } catch {
209
+ ignore();
210
+ }
211
+ };
212
+ var mergeHooks = (all) => {
213
+ const defined = all.filter((hooks) => hooks !== void 0);
214
+ return {
215
+ onAction: (event) => {
216
+ for (const hooks of defined) {
217
+ fire(hooks.onAction, event);
218
+ }
219
+ },
220
+ onError: (event) => {
221
+ for (const hooks of defined) {
222
+ fire(hooks.onError, event);
223
+ }
224
+ },
225
+ onRequest: (event) => {
226
+ for (const hooks of defined) {
227
+ fire(hooks.onRequest, event);
228
+ }
229
+ },
230
+ onRetry: (event) => {
231
+ for (const hooks of defined) {
232
+ fire(hooks.onRetry, event);
233
+ }
234
+ },
235
+ onThrottle: (event) => {
236
+ for (const hooks of defined) {
237
+ fire(hooks.onThrottle, event);
238
+ }
239
+ }
240
+ };
241
+ };
242
+
243
+ // src/internal/engine/runtime.ts
244
+ var defaultRuntime = {
245
+ fetch: (input, init) => fetch(input, init),
246
+ now: () => Date.now(),
247
+ random: () => Math.random(),
248
+ timer: (ms, onFire) => {
249
+ const handle = setTimeout(onFire, ms);
250
+ return () => {
251
+ clearTimeout(handle);
252
+ };
253
+ }
254
+ };
255
+ var abortedError = (provider) => new OutboundError("Provider", "The call was aborted", {
256
+ aborted: true,
257
+ provider
258
+ });
259
+ var sleep = (runtime, ms, provider, signal) => (
260
+ // oxlint-disable-next-line promise/avoid-new -- wraps a callback timer.
261
+ new Promise((resolve2, reject) => {
262
+ if (signal?.aborted) {
263
+ reject(abortedError(provider));
264
+ return;
265
+ }
266
+ const onAbort = () => {
267
+ cancel();
268
+ reject(abortedError(provider));
269
+ };
270
+ const cancel = runtime.timer(Math.max(0, ms), () => {
271
+ signal?.removeEventListener("abort", onAbort);
272
+ resolve2();
273
+ });
274
+ signal?.addEventListener("abort", onAbort, { once: true });
275
+ })
276
+ );
277
+
278
+ // src/internal/engine/budget.ts
279
+ var DEFAULT_LANE = "default";
280
+ var MIN_FACTOR = 0.1;
281
+ var RECOVERY_STEP = 0.05;
282
+ var Budget = class {
283
+ #options;
284
+ #waiting = [];
285
+ #inFlight = 0;
286
+ /** Drops to slow down after a 429, then recovers toward 1. */
287
+ #factor = 1;
288
+ constructor(options) {
289
+ this.#options = options;
290
+ }
291
+ #windows(lane) {
292
+ const { limits, share } = this.#options;
293
+ const declared = lane === DEFAULT_LANE ? limits.windows : limits.lanes?.[lane] ?? [];
294
+ return declared.map((window) => scaleWindow(window, share * this.#factor));
295
+ }
296
+ #storeKey(lane) {
297
+ return lane === DEFAULT_LANE ? this.#options.key : `${this.#options.key}#${lane}`;
298
+ }
299
+ async #reserve(lane, now) {
300
+ const { store } = this.#options;
301
+ if (lane !== DEFAULT_LANE) {
302
+ const laneWait = await store.reserve(
303
+ this.#storeKey(lane),
304
+ this.#windows(lane),
305
+ now
306
+ );
307
+ if (laneWait > 0) {
308
+ return laneWait;
309
+ }
310
+ }
311
+ return await store.reserve(
312
+ this.#options.key,
313
+ this.#windows(DEFAULT_LANE),
314
+ now
315
+ );
316
+ }
317
+ async #enter(options) {
318
+ const cap = this.#options.limits.concurrency ?? DEFAULT_CONCURRENCY;
319
+ if (this.#inFlight < cap) {
320
+ this.#inFlight += 1;
321
+ return;
322
+ }
323
+ await new Promise((resolve2, reject) => {
324
+ const onAbort = () => {
325
+ const index = this.#waiting.indexOf(enter);
326
+ if (index !== -1) {
327
+ this.#waiting.splice(index, 1);
328
+ }
329
+ reject(abortedError(this.#options.provider));
330
+ };
331
+ const enter = () => {
332
+ options.signal?.removeEventListener("abort", onAbort);
333
+ resolve2();
334
+ };
335
+ this.#waiting.push(enter);
336
+ options.signal?.addEventListener("abort", onAbort, { once: true });
337
+ });
338
+ }
339
+ /**
340
+ * Waits for a concurrency slot and for room in every window. Returns how
341
+ * long it waited. The caller must call `release()` afterwards.
342
+ */
343
+ async acquire(options) {
344
+ const { provider } = this.#options;
345
+ const { deadlineAt, hooks, lane, runtime, signal } = options;
346
+ if (signal?.aborted) {
347
+ throw abortedError(provider);
348
+ }
349
+ await this.#enter(options);
350
+ let waited = 0;
351
+ try {
352
+ for (; ; ) {
353
+ const now = runtime.now();
354
+ const waitMs = await this.#reserve(lane, now);
355
+ if (waitMs === 0) {
356
+ return waited;
357
+ }
358
+ if (deadlineAt !== void 0 && now + waitMs > deadlineAt) {
359
+ throw new OutboundError(
360
+ "RateLimited",
361
+ `${provider} rate budget is full and the deadline would pass before it frees up`,
362
+ { provider, retryAfterMs: waitMs, timedOut: true }
363
+ );
364
+ }
365
+ fire(hooks.onThrottle, { lane, provider, waitMs });
366
+ await sleep(runtime, waitMs, provider, signal);
367
+ waited += waitMs;
368
+ }
369
+ } catch (error) {
370
+ this.release();
371
+ throw error;
372
+ }
373
+ }
374
+ release() {
375
+ const resume = this.#waiting.shift();
376
+ if (resume === void 0) {
377
+ this.#inFlight = Math.max(0, this.#inFlight - 1);
378
+ } else {
379
+ resume();
380
+ }
381
+ }
382
+ /** Called on a 429: pause the lane and halve the rate. */
383
+ async rateLimited(lane, retryAfterMs, now) {
384
+ this.#factor = Math.max(MIN_FACTOR, this.#factor / 2);
385
+ await this.#options.store.pause(this.#storeKey(lane), now + retryAfterMs);
386
+ }
387
+ /** Called when the vendor's headers say the window is spent. */
388
+ async exhausted(resetInMs, now) {
389
+ await this.#options.store.pause(this.#options.key, now + resetInMs);
390
+ }
391
+ /** Called on a success: climb back toward the declared rate. */
392
+ succeeded() {
393
+ this.#factor = Math.min(1, this.#factor + RECOVERY_STEP);
394
+ }
395
+ async usage(now) {
396
+ const lanes = [
397
+ DEFAULT_LANE,
398
+ ...Object.keys(this.#options.limits.lanes ?? {})
399
+ ];
400
+ const perLane = await Promise.all(
401
+ lanes.map(async (lane) => {
402
+ const windows = this.#windows(lane);
403
+ const used = await this.#options.store.usage(
404
+ this.#storeKey(lane),
405
+ windows,
406
+ now
407
+ );
408
+ return windows.map((window, index) => ({
409
+ lane,
410
+ perMs: window.perMs,
411
+ requests: window.requests,
412
+ used: used[index] ?? 0
413
+ }));
414
+ })
415
+ );
416
+ return perLane.flat();
417
+ }
418
+ };
419
+
420
+ // src/internal/engine/request.ts
421
+ var DEFAULT_TIMEOUT_MS = 3e4;
422
+ var TIMED_OUT = /* @__PURE__ */ Symbol("timed-out");
423
+ var readBody = async (response) => {
424
+ const raw = await response.text();
425
+ if (raw === "") {
426
+ return null;
427
+ }
428
+ return parseJson(raw) ?? raw;
429
+ };
430
+ var fetchOnce = async (spec, environment) => {
431
+ const { runtime, state } = environment;
432
+ const controller = new AbortController();
433
+ const onCallerAbort = () => {
434
+ controller.abort();
435
+ };
436
+ let timedOut = false;
437
+ const cancelTimer = runtime.timer(state.timeoutMs, () => {
438
+ timedOut = true;
439
+ controller.abort();
440
+ });
441
+ state.signal?.addEventListener("abort", onCallerAbort, { once: true });
442
+ try {
443
+ return await runtime.fetch(spec.url, {
444
+ headers: {
445
+ accept: "application/json",
446
+ ...spec.body === void 0 ? void 0 : { "content-type": "application/json" },
447
+ ...spec.headers
448
+ },
449
+ method: spec.method,
450
+ signal: controller.signal,
451
+ ...spec.body === void 0 ? void 0 : { body: JSON.stringify(spec.body) }
452
+ });
453
+ } catch (error) {
454
+ throw timedOut ? TIMED_OUT : error;
455
+ } finally {
456
+ cancelTimer();
457
+ state.signal?.removeEventListener("abort", onCallerAbort);
458
+ }
459
+ };
460
+ var noteHeaders = async (response, environment) => {
461
+ const { adapter, budget, runtime } = environment;
462
+ const names = adapter.limits.headers;
463
+ if (names?.remaining === void 0 || names.reset === void 0) {
464
+ return;
465
+ }
466
+ const remaining = count(response.headers.get(names.remaining));
467
+ const reset = count(response.headers.get(names.reset));
468
+ if (remaining === null || reset === null || remaining > 0) {
469
+ return;
470
+ }
471
+ const now = runtime.now();
472
+ const resetInMs = names.resetUnit === "epoch-seconds" ? reset * 1e3 - now : reset * 1e3;
473
+ if (resetInMs > 0) {
474
+ await budget.exhausted(resetInMs, now);
475
+ }
476
+ };
477
+ var failureFor = async (response, body, spec, environment) => {
478
+ const { adapter, budget, runtime } = environment;
479
+ const now = runtime.now();
480
+ const retryAfterMs = parseRetryAfter(response.headers, body, now);
481
+ const failure = { body, retryAfterMs, status: response.status };
482
+ const error = adapter.mapError(failure);
483
+ if (response.status === 429) {
484
+ await budget.rateLimited(
485
+ spec.lane ?? DEFAULT_LANE,
486
+ retryAfterMs ?? 1e3,
487
+ now
488
+ );
489
+ }
490
+ if (!isRetryableStatus(response.status)) {
491
+ throw error;
492
+ }
493
+ return retryAfterMs === void 0 ? { error, kind: "retry" } : { error, kind: "retry", retryAfterMs };
494
+ };
495
+ var attempt = async (spec, environment, attemptNumber) => {
496
+ const { adapter, budget, hooks, runtime, state } = environment;
497
+ const lane = spec.lane ?? DEFAULT_LANE;
498
+ state.throttledMs += await budget.acquire({
499
+ deadlineAt: state.deadlineAt,
500
+ hooks,
501
+ lane,
502
+ runtime,
503
+ signal: state.signal
504
+ });
505
+ state.requests += 1;
506
+ const startedAt = runtime.now();
507
+ let status = null;
508
+ try {
509
+ const response = await fetchOnce(spec, environment);
510
+ ({ status } = response);
511
+ const body = await readBody(response);
512
+ await noteHeaders(response, environment);
513
+ if (response.ok) {
514
+ budget.succeeded();
515
+ return {
516
+ kind: "ok",
517
+ response: { body, headers: response.headers, status: response.status }
518
+ };
519
+ }
520
+ return await failureFor(response, body, spec, environment);
521
+ } catch (error) {
522
+ if (OutboundError.is(error)) {
523
+ throw error;
524
+ }
525
+ if (state.signal?.aborted) {
526
+ throw abortedError(adapter.name);
527
+ }
528
+ const timedOut = error === TIMED_OUT;
529
+ const message = timedOut ? `${adapter.name} did not answer within ${state.timeoutMs} ms` : `${adapter.name} request failed: ${error instanceof Error ? error.message : String(error)}`;
530
+ return {
531
+ error: new OutboundError("Provider", message, {
532
+ cause: timedOut ? void 0 : error,
533
+ provider: adapter.name,
534
+ secrets: adapter.secrets,
535
+ timedOut
536
+ }),
537
+ kind: "retry"
538
+ };
539
+ } finally {
540
+ budget.release();
541
+ fire(hooks.onRequest, {
542
+ attempt: attemptNumber,
543
+ durationMs: runtime.now() - startedAt,
544
+ lane,
545
+ method: spec.method,
546
+ provider: adapter.name,
547
+ status,
548
+ url: redactUrl(spec.url, adapter.secrets)
549
+ });
550
+ }
551
+ };
552
+ var assertRequestBudget = (environment) => {
553
+ const { adapter, state } = environment;
554
+ if (state.maxRequests !== void 0 && state.requests >= state.maxRequests) {
555
+ throw new OutboundError(
556
+ "RateLimited",
557
+ `The call used its budget of ${state.maxRequests} request(s) to ${adapter.name}`,
558
+ { provider: adapter.name }
559
+ );
560
+ }
561
+ };
562
+ var exhausted = (error, timedOut) => timedOut ? new OutboundError(error.code, error.message, {
563
+ cause: error.cause,
564
+ provider: error.provider,
565
+ retryAfterMs: error.retryAfterMs,
566
+ status: error.status,
567
+ timedOut: true
568
+ }) : error;
569
+ var execute = async (spec, environment) => {
570
+ const { adapter, hooks, runtime, state } = environment;
571
+ for (let attemptNumber = 1; ; attemptNumber += 1) {
572
+ assertRequestBudget(environment);
573
+ const result = await attempt(spec, environment, attemptNumber);
574
+ if (result.kind === "ok") {
575
+ return result.response;
576
+ }
577
+ if (attemptNumber > state.retry.max) {
578
+ throw result.error;
579
+ }
580
+ const backoff = state.retry.backoff(attemptNumber, runtime.random());
581
+ const delayMs = Math.max(result.retryAfterMs ?? 0, backoff);
582
+ if (state.deadlineAt !== void 0 && runtime.now() + delayMs > state.deadlineAt) {
583
+ throw exhausted(result.error, true);
584
+ }
585
+ fire(hooks.onRetry, {
586
+ attempt: attemptNumber,
587
+ delayMs,
588
+ provider: adapter.name,
589
+ reason: result.error.message,
590
+ url: redactUrl(spec.url, adapter.secrets)
591
+ });
592
+ await sleep(runtime, delayMs, adapter.name, state.signal);
593
+ }
594
+ };
595
+
596
+ // src/internal/engine/engine.ts
597
+ var BUDGETS = /* @__PURE__ */ Symbol.for("outbound-sdk.budgets");
598
+ var budgetsFor = (store) => {
599
+ const scope = globalThis;
600
+ scope[BUDGETS] ??= /* @__PURE__ */ new WeakMap();
601
+ let budgets = scope[BUDGETS].get(store);
602
+ if (budgets === void 0) {
603
+ budgets = /* @__PURE__ */ new Map();
604
+ scope[BUDGETS].set(store, budgets);
605
+ }
606
+ return budgets;
607
+ };
608
+ var credentialKey = (adapter) => adapter.secrets.length === 0 ? `${adapter.name}:${adapter.workspaceId}` : `${adapter.name}:${sha256Hex(adapter.secrets.join("")).slice(0, 24)}`;
609
+ var RequestEngine = class {
610
+ #runtime;
611
+ #store;
612
+ #hooks;
613
+ #share;
614
+ #defaults;
615
+ constructor(options = {}) {
616
+ this.#runtime = { ...defaultRuntime, ...options.runtime };
617
+ this.#store = options.store ?? defaultRateLimitStore();
618
+ this.#hooks = options.hooks ?? {};
619
+ this.#share = options.share ?? DEFAULT_SHARE;
620
+ this.#defaults = options.defaults ?? {};
621
+ if (!(this.#share > 0 && this.#share <= 1)) {
622
+ throw new OutboundError(
623
+ "Invalid",
624
+ "share must be greater than 0 and at most 1"
625
+ );
626
+ }
627
+ }
628
+ get hooks() {
629
+ return this.#hooks;
630
+ }
631
+ now() {
632
+ return this.#runtime.now();
633
+ }
634
+ #budget(adapter) {
635
+ const budgets = budgetsFor(this.#store);
636
+ const key = credentialKey(adapter);
637
+ let budget = budgets.get(key);
638
+ if (budget === void 0) {
639
+ budget = new Budget({
640
+ key,
641
+ limits: adapter.limits,
642
+ provider: adapter.name,
643
+ share: this.#share,
644
+ store: this.#store
645
+ });
646
+ budgets.set(key, budget);
647
+ }
648
+ return budget;
649
+ }
650
+ /** Starts the accounting for one SDK call. */
651
+ begin(options = {}) {
652
+ const merged = { ...this.#defaults, ...options };
653
+ return {
654
+ deadlineAt: merged.deadline === void 0 ? void 0 : this.now() + merged.deadline,
655
+ maxRequests: merged.maxRequests,
656
+ requests: 0,
657
+ retry: resolveRetryPolicy(merged.retries),
658
+ signal: merged.signal,
659
+ throttledMs: 0,
660
+ timeoutMs: merged.timeout ?? DEFAULT_TIMEOUT_MS
661
+ };
662
+ }
663
+ contextFor(adapter, state) {
664
+ return {
665
+ forAdapter: (other) => this.contextFor(other, state),
666
+ request: (spec) => execute(spec, {
667
+ adapter,
668
+ budget: this.#budget(adapter),
669
+ hooks: this.#hooks,
670
+ runtime: this.#runtime,
671
+ state
672
+ })
673
+ };
674
+ }
675
+ async limits(adapter) {
676
+ return {
677
+ provider: adapter.name,
678
+ share: this.#share,
679
+ source: adapter.limits.source,
680
+ windows: await this.#budget(adapter).usage(this.now()),
681
+ workspaceId: adapter.workspaceId
682
+ };
683
+ }
684
+ };
685
+
686
+ // src/internal/cursor.ts
687
+ var VERSION = 1;
688
+ var toBase64Url = (value) => {
689
+ const bytes = new TextEncoder().encode(value);
690
+ let binary = "";
691
+ for (const byte of bytes) {
692
+ binary += String.fromCodePoint(byte);
693
+ }
694
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/[=]+$/u, "");
695
+ };
696
+ var fromBase64Url = (value) => {
697
+ try {
698
+ const binary = atob(value.replaceAll("-", "+").replaceAll("_", "/"));
699
+ const bytes = Uint8Array.from(binary, (char) => char.codePointAt(0) ?? 0);
700
+ return new TextDecoder().decode(bytes);
701
+ } catch {
702
+ return void 0;
703
+ }
704
+ };
705
+ var encodeCursor = (scope, next) => toBase64Url(
706
+ JSON.stringify({
707
+ a: scope.action,
708
+ n: next,
709
+ p: scope.provider,
710
+ v: VERSION,
711
+ w: scope.workspaceId
712
+ })
713
+ );
714
+ var decodeCursor = (scope, cursor) => {
715
+ const decoded = fromBase64Url(cursor);
716
+ const parsed = decoded === void 0 ? void 0 : parseJson(decoded);
717
+ const next = field(parsed, "n");
718
+ const matches2 = field(parsed, "v") === VERSION && field(parsed, "p") === scope.provider && field(parsed, "w") === scope.workspaceId && field(parsed, "a") === scope.action;
719
+ if (!matches2 || next === void 0) {
720
+ const owner = isString(field(parsed, "a")) ? ` (it belongs to ${String(field(parsed, "a"))})` : "";
721
+ throw new OutboundError(
722
+ "Invalid",
723
+ `The cursor is not valid for ${scope.action}${owner}`,
724
+ {
725
+ provider: scope.provider
726
+ }
727
+ );
728
+ }
729
+ return next;
730
+ };
731
+
732
+ // src/internal/outbound/core.ts
733
+ var infoFor = (core, state) => ({
734
+ adapter: core.adapter,
735
+ provider: core.adapter.name,
736
+ state,
737
+ workspaceId: core.adapter.workspaceId
738
+ });
739
+ var toOutboundError = (core, cause) => OutboundError.is(cause) ? cause : core.adapter.mapError(cause);
740
+ var perform = async (core, action, options, body, shared, isAnswer) => {
741
+ const state = shared ?? core.engine.begin(options);
742
+ const startedAt = core.engine.now();
743
+ const { hooks } = core.engine;
744
+ const scope = {
745
+ action,
746
+ provider: core.adapter.name,
747
+ workspaceId: core.adapter.workspaceId
748
+ };
749
+ const done = () => {
750
+ fire(hooks.onAction, {
751
+ ...scope,
752
+ durationMs: core.engine.now() - startedAt,
753
+ requests: state.requests,
754
+ throttledMs: state.throttledMs
755
+ });
756
+ };
757
+ try {
758
+ const result = await body(state);
759
+ done();
760
+ return result;
761
+ } catch (error) {
762
+ const mapped = toOutboundError(core, error);
763
+ if (isAnswer?.(mapped) === true) {
764
+ done();
765
+ } else {
766
+ fire(hooks.onError, { ...scope, error: mapped });
767
+ }
768
+ throw mapped;
769
+ }
770
+ };
771
+ var metaFor = (core, state, input) => ({
772
+ complete: input.complete,
773
+ evidence: input.evidence,
774
+ fetchedAt: input.fetchedAt ?? new Date(core.engine.now()).toISOString(),
775
+ provider: core.adapter.name,
776
+ requests: state.requests,
777
+ stale: input.stale ?? false,
778
+ throttledMs: state.throttledMs,
779
+ workspaceId: core.adapter.workspaceId
780
+ });
781
+ var matches = (schema, record) => schema.safeParse(record).success;
782
+ var checked = (core, schema, records, action) => {
783
+ const items = [];
784
+ for (const record of records) {
785
+ if (!matches(schema, record)) {
786
+ const issue = schema.safeParse(record).error?.issues[0];
787
+ const where = issue === void 0 ? "" : ` at ${issue.path.join(".")}: ${issue.message}`;
788
+ throw new OutboundError(
789
+ "Provider",
790
+ `The ${core.adapter.name} adapter returned an invalid record for ${action}${where}`,
791
+ { provider: core.adapter.name }
792
+ );
793
+ }
794
+ items.push(record);
795
+ }
796
+ return items;
797
+ };
798
+
799
+ // src/internal/outbound/validate.ts
800
+ var DATE = /^\d{4}-\d{2}-\d{2}$/u;
801
+ var invalid = (message) => new OutboundError("Invalid", message);
802
+ var normalizeInstant = (value, name) => {
803
+ if (value === void 0) {
804
+ return void 0;
805
+ }
806
+ const time = Date.parse(value);
807
+ if (Number.isNaN(time)) {
808
+ throw invalid(
809
+ `${name} must be an ISO 8601 date or timestamp, got "${value}"`
810
+ );
811
+ }
812
+ return new Date(time).toISOString();
813
+ };
814
+ var normalizeRange = (range) => {
815
+ const since = normalizeInstant(range.since, "since");
816
+ const until = normalizeInstant(range.until, "until");
817
+ if (since !== void 0 && until !== void 0 && since > until) {
818
+ throw invalid("since must not be after until");
819
+ }
820
+ return { since, until };
821
+ };
822
+ var assertDay = (value, name) => {
823
+ if (value !== void 0 && (!DATE.test(value) || Number.isNaN(Date.parse(value)))) {
824
+ throw invalid(`${name} must be a date in YYYY-MM-DD form, got "${value}"`);
825
+ }
826
+ return value;
827
+ };
828
+ var assertLimit = (limit) => {
829
+ if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1)) {
830
+ throw invalid(`limit must be a positive integer, got ${limit}`);
831
+ }
832
+ return limit;
833
+ };
834
+ var assertId = (id, what) => {
835
+ if (id.trim() === "") {
836
+ throw invalid(`${what} id must not be empty`);
837
+ }
838
+ return id;
839
+ };
840
+
841
+ // src/internal/outbound/walker.ts
842
+ var PageWalker = class {
843
+ #options;
844
+ #cursor;
845
+ #meta;
846
+ #truncated = false;
847
+ constructor(options) {
848
+ this.#options = options;
849
+ this.#cursor = options.cursor;
850
+ }
851
+ get cursor() {
852
+ return this.#cursor;
853
+ }
854
+ get meta() {
855
+ return this.#meta;
856
+ }
857
+ get truncated() {
858
+ return this.#truncated;
859
+ }
860
+ async *[Symbol.asyncIterator]() {
861
+ const { fetchPage: fetchPage2, keyOf, max } = this.#options;
862
+ const seen = /* @__PURE__ */ new Set();
863
+ let state;
864
+ let yielded = 0;
865
+ for (; ; ) {
866
+ const fetched = await fetchPage2(this.#cursor, state);
867
+ ({ state } = fetched);
868
+ this.#meta = fetched.page.meta;
869
+ for (const item of fetched.page.items) {
870
+ const key = keyOf(item);
871
+ if (key === void 0 || !seen.has(key)) {
872
+ if (key !== void 0) {
873
+ seen.add(key);
874
+ }
875
+ if (max !== void 0 && yielded >= max) {
876
+ this.#truncated = true;
877
+ return;
878
+ }
879
+ yielded += 1;
880
+ yield item;
881
+ }
882
+ }
883
+ this.#cursor = fetched.page.cursor;
884
+ if (this.#cursor === void 0) {
885
+ return;
886
+ }
887
+ if (max !== void 0 && yielded >= max) {
888
+ this.#truncated = true;
889
+ return;
890
+ }
891
+ }
892
+ }
893
+ async toArray() {
894
+ const items = [];
895
+ for await (const item of this) {
896
+ items.push(item);
897
+ }
898
+ return items;
899
+ }
900
+ };
901
+
902
+ // src/internal/outbound/collections.ts
903
+ var DEFAULT_BULK_CONCURRENCY = 4;
904
+ var cursorScope = (core, action) => ({
905
+ action,
906
+ provider: core.adapter.name,
907
+ workspaceId: core.adapter.workspaceId
908
+ });
909
+ var fetchPage = (core, spec, request, options, shared) => perform(
910
+ core,
911
+ spec.action,
912
+ options,
913
+ async (state) => {
914
+ const scope = cursorScope(core, spec.action);
915
+ const next = request.cursor === void 0 ? void 0 : decodeCursor(scope, request.cursor);
916
+ const output2 = await core.run(
917
+ spec.toOperation(request.filters, { limit: request.limit, next }),
918
+ infoFor(core, state)
919
+ );
920
+ const complete = output2.next === void 0;
921
+ const page = {
922
+ complete,
923
+ cursor: output2.next === void 0 ? void 0 : encodeCursor(scope, output2.next),
924
+ items: checked(core, spec.schema, output2.items, spec.action),
925
+ meta: metaFor(core, state, {
926
+ complete,
927
+ evidence: output2.evidence,
928
+ fetchedAt: output2.fetchedAt,
929
+ stale: output2.stale
930
+ })
931
+ };
932
+ return { page, state };
933
+ },
934
+ shared
935
+ );
936
+ var makeReadCollection = (core, spec) => ({
937
+ list: async (options) => {
938
+ const filters = spec.prepare(options ?? {});
939
+ const limit = assertLimit(options?.limit);
940
+ const { page } = await fetchPage(
941
+ core,
942
+ spec,
943
+ { cursor: options?.cursor, filters, limit },
944
+ options
945
+ );
946
+ return page;
947
+ },
948
+ listAll: (options) => {
949
+ const filters = spec.prepare(options ?? {});
950
+ const limit = assertLimit(options?.limit);
951
+ const walkOptions = options;
952
+ return new PageWalker({
953
+ cursor: walkOptions?.cursor,
954
+ fetchPage: (cursor, state) => fetchPage(core, spec, { cursor, filters, limit }, options, state),
955
+ keyOf: (item) => spec.keyOf(item, filters),
956
+ max: walkOptions?.max
957
+ });
958
+ }
959
+ });
960
+ var isMissing = (error) => error.code === "NotFound";
961
+ var getOne = (core, spec, id, options, shared, missingIsAnswer = false) => perform(
962
+ core,
963
+ spec.action,
964
+ options,
965
+ async (state) => {
966
+ const output2 = await core.run(
967
+ spec.toOperation(assertId(id, spec.what)),
968
+ infoFor(core, state)
969
+ );
970
+ const [item] = checked(core, spec.schema, output2.items, spec.action);
971
+ if (item === void 0) {
972
+ throw new OutboundError(
973
+ "NotFound",
974
+ `${spec.what} ${id} was not found`,
975
+ {
976
+ provider: core.adapter.name
977
+ }
978
+ );
979
+ }
980
+ return {
981
+ ...item,
982
+ meta: metaFor(core, state, {
983
+ complete: true,
984
+ evidence: output2.evidence,
985
+ fetchedAt: output2.fetchedAt,
986
+ stale: output2.stale
987
+ })
988
+ };
989
+ },
990
+ shared,
991
+ missingIsAnswer ? isMissing : void 0
992
+ );
993
+ var makeGetter = (core, spec) => async (id, options) => {
994
+ spec.prepare();
995
+ return await getOne(core, spec, id, options);
996
+ };
997
+ var getMany = async (core, spec, ids, options) => {
998
+ spec.prepare();
999
+ const state = core.engine.begin(options);
1000
+ const results = [];
1001
+ const errors = [];
1002
+ const queue = [...ids];
1003
+ const worker = async () => {
1004
+ for (let id = queue.shift(); id !== void 0; id = queue.shift()) {
1005
+ try {
1006
+ const value = await getOne(core, spec, id, options, state, true);
1007
+ results.push({ id, value });
1008
+ } catch (error) {
1009
+ errors.push({ error: toOutboundError(core, error), id });
1010
+ }
1011
+ }
1012
+ };
1013
+ const workers = Math.max(
1014
+ 1,
1015
+ Math.min(options?.concurrency ?? DEFAULT_BULK_CONCURRENCY, ids.length)
1016
+ );
1017
+ await Promise.all(Array.from({ length: workers }, worker));
1018
+ const order = new Map(ids.map((id, index) => [id, index]));
1019
+ const byOrder = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
1020
+ return {
1021
+ errors: errors.toSorted(byOrder),
1022
+ results: results.toSorted(byOrder)
1023
+ };
1024
+ };
1025
+ var makeCollection = (core, listSpec, getSpec) => ({
1026
+ ...makeReadCollection(core, listSpec),
1027
+ exists: async (id, options) => {
1028
+ getSpec.prepare();
1029
+ try {
1030
+ await getOne(core, getSpec, id, options, void 0, true);
1031
+ return true;
1032
+ } catch (error) {
1033
+ if (OutboundError.is(error) && isMissing(error)) {
1034
+ return false;
1035
+ }
1036
+ throw error;
1037
+ }
1038
+ },
1039
+ get: makeGetter(core, getSpec),
1040
+ getMany: (ids, options) => getMany(core, getSpec, ids, options)
1041
+ });
1042
+
1043
+ // src/internal/outbound/specs-account.ts
1044
+ var refOf = (item) => item.ref;
1045
+ var settingsGet = (core) => ({
1046
+ action: "campaigns.settings",
1047
+ prepare: () => {
1048
+ requireCapability(
1049
+ core.gate,
1050
+ "campaigns.settings",
1051
+ "Reading a campaign's settings"
1052
+ );
1053
+ },
1054
+ schema: campaignSettingsSchema,
1055
+ toOperation: (id) => ({ id, kind: "campaigns.settings" }),
1056
+ what: "Settings for campaign"
1057
+ });
1058
+ var healthGet = (core) => ({
1059
+ action: "senders.health",
1060
+ prepare: () => {
1061
+ requireCapability(core.gate, "senders.health", "Reading a sender's health");
1062
+ },
1063
+ schema: senderHealthSchema,
1064
+ toOperation: (id) => ({ id, kind: "senders.health" }),
1065
+ what: "Health for sender"
1066
+ });
1067
+ var subsequenceList = (core) => ({
1068
+ action: "sequence.subsequences",
1069
+ keyOf: refOf,
1070
+ prepare: (filters) => {
1071
+ requireCapability(
1072
+ core.gate,
1073
+ "sequence.subsequences",
1074
+ "Listing a campaign's subsequences"
1075
+ );
1076
+ return { campaignId: filters.campaignId };
1077
+ },
1078
+ schema: sequenceSchema,
1079
+ toOperation: (filters, page) => {
1080
+ if (filters.campaignId === void 0) {
1081
+ throw new OutboundError("Invalid", "Subsequences need a campaign id");
1082
+ }
1083
+ return {
1084
+ kind: "sequence.subsequences",
1085
+ query: { campaignId: filters.campaignId, ...page }
1086
+ };
1087
+ }
1088
+ });
1089
+ var listList = (core) => ({
1090
+ action: "lists.list",
1091
+ keyOf: refOf,
1092
+ prepare: () => {
1093
+ requireCapability(core.gate, "lists.list", "Listing lead lists");
1094
+ return {};
1095
+ },
1096
+ schema: leadListSchema,
1097
+ toOperation: (_filters, page) => ({ kind: "lists.list", query: page })
1098
+ });
1099
+ var blocklistList = (core) => ({
1100
+ action: "blocklist.list",
1101
+ keyOf: refOf,
1102
+ prepare: () => {
1103
+ requireCapability(core.gate, "blocklist", "Listing the block list");
1104
+ return {};
1105
+ },
1106
+ schema: blockEntrySchema,
1107
+ toOperation: (_filters, page) => ({ kind: "blocklist.list", query: page })
1108
+ });
1109
+ var tagList = (core) => ({
1110
+ action: "tags.list",
1111
+ keyOf: refOf,
1112
+ prepare: () => {
1113
+ requireCapability(core.gate, "tags", "Listing tags");
1114
+ return {};
1115
+ },
1116
+ schema: tagSchema,
1117
+ toOperation: (_filters, page) => ({ kind: "tags.list", query: page })
1118
+ });
1119
+ var webhookList = (core) => ({
1120
+ action: "webhooks.list",
1121
+ keyOf: refOf,
1122
+ prepare: (filters) => {
1123
+ requireCapability(core.gate, "webhooks.list", "Listing webhooks");
1124
+ return { campaignId: filters.campaignId };
1125
+ },
1126
+ schema: webhookSubscriptionSchema,
1127
+ toOperation: (filters, page) => ({
1128
+ kind: "webhooks.list",
1129
+ query: { ...filters, ...page }
1130
+ })
1131
+ });
1132
+
1133
+ // src/internal/outbound/specs.ts
1134
+ var wantsBody = (include) => include?.includes("body") ?? false;
1135
+ var hasRange = (filters) => filters.since !== void 0 || filters.until !== void 0;
1136
+ var refOf2 = (item) => item.ref;
1137
+ var campaignList = (core) => ({
1138
+ action: "campaigns.list",
1139
+ keyOf: refOf2,
1140
+ prepare: (filters) => {
1141
+ if (filters.status !== void 0) {
1142
+ requireCapability(
1143
+ core.gate,
1144
+ "campaigns.status",
1145
+ "Filtering campaigns by status"
1146
+ );
1147
+ }
1148
+ return { status: filters.status };
1149
+ },
1150
+ schema: campaignSchema,
1151
+ toOperation: (filters, page) => ({
1152
+ kind: "campaigns.list",
1153
+ query: { ...filters, ...page }
1154
+ })
1155
+ });
1156
+ var campaignGet = () => ({
1157
+ action: "campaigns.get",
1158
+ prepare: () => {
1159
+ },
1160
+ schema: campaignSchema,
1161
+ toOperation: (id) => ({ id, kind: "campaigns.get" }),
1162
+ what: "Campaign"
1163
+ });
1164
+ var sequenceGet = (core) => ({
1165
+ action: "sequence.get",
1166
+ prepare: () => {
1167
+ requireCapability(core.gate, "sequence", "Reading a campaign's sequence");
1168
+ },
1169
+ schema: sequenceSchema,
1170
+ toOperation: (id) => ({ id, kind: "sequence.get" }),
1171
+ what: "Sequence for campaign"
1172
+ });
1173
+ var senderList = (core) => ({
1174
+ action: "senders.list",
1175
+ keyOf: refOf2,
1176
+ prepare: (filters) => {
1177
+ if (filters.campaignId === void 0) {
1178
+ requireCapability(core.gate, "senders.list", "Listing senders");
1179
+ } else {
1180
+ requireCapability(
1181
+ core.gate,
1182
+ "senders.byCampaign",
1183
+ "Listing a campaign's senders"
1184
+ );
1185
+ }
1186
+ return { campaignId: filters.campaignId };
1187
+ },
1188
+ schema: senderSchema,
1189
+ toOperation: (filters, page) => ({
1190
+ kind: "senders.list",
1191
+ query: { ...filters, ...page }
1192
+ })
1193
+ });
1194
+ var senderGet = (core) => ({
1195
+ action: "senders.get",
1196
+ prepare: () => {
1197
+ requireCapability(core.gate, "senders.get", "Reading one sender");
1198
+ },
1199
+ schema: senderSchema,
1200
+ toOperation: (id) => ({ id, kind: "senders.get" }),
1201
+ what: "Sender"
1202
+ });
1203
+ var leadList = (core) => ({
1204
+ action: "leads.list",
1205
+ // A lookup returns one record per campaign the person is in. On a vendor
1206
+ // whose lead id is the same in every campaign those records share a ref,
1207
+ // so the campaign is part of what tells them apart.
1208
+ keyOf: (lead, filters) => filters.email === void 0 && filters.linkedinUrl === void 0 ? lead.ref : `${lead.ref} ${lead.campaignRef ?? ""}`,
1209
+ prepare: (filters) => {
1210
+ if (filters.campaignId !== void 0 && filters.listId !== void 0) {
1211
+ throw new OutboundError(
1212
+ "Invalid",
1213
+ "Leads can be listed by campaign or by list, not both at once"
1214
+ );
1215
+ }
1216
+ const lookup2 = filters.email !== void 0 || filters.linkedinUrl !== void 0;
1217
+ if (lookup2) {
1218
+ requireCapability(
1219
+ core.gate,
1220
+ "leads.lookup",
1221
+ "Finding a lead by email or LinkedIn profile"
1222
+ );
1223
+ }
1224
+ if (filters.listId !== void 0) {
1225
+ requireCapability(core.gate, "lists.leads", "Listing a list's leads");
1226
+ } else if (filters.campaignId !== void 0) {
1227
+ requireCapability(
1228
+ core.gate,
1229
+ "leads.byCampaign",
1230
+ "Listing a campaign's leads"
1231
+ );
1232
+ } else if (!lookup2) {
1233
+ requireCapability(core.gate, "leads.list", "Listing leads");
1234
+ }
1235
+ if (hasRange(filters)) {
1236
+ requireCapability(core.gate, "leads.since", "Filtering leads by date");
1237
+ }
1238
+ return {
1239
+ campaignId: filters.campaignId,
1240
+ email: filters.email?.trim().toLowerCase(),
1241
+ linkedinUrl: filters.linkedinUrl?.trim(),
1242
+ listId: filters.listId,
1243
+ ...normalizeRange(filters)
1244
+ };
1245
+ },
1246
+ schema: leadSchema,
1247
+ toOperation: (filters, page) => ({
1248
+ kind: "leads.list",
1249
+ query: { ...filters, ...page }
1250
+ })
1251
+ });
1252
+ var leadGet = (core) => ({
1253
+ action: "leads.get",
1254
+ prepare: () => {
1255
+ requireCapability(core.gate, "leads.get", "Reading one lead");
1256
+ },
1257
+ schema: leadSchema,
1258
+ toOperation: (id) => ({ id, kind: "leads.get" }),
1259
+ what: "Lead"
1260
+ });
1261
+ var messageList = (core) => ({
1262
+ action: "messages.list",
1263
+ keyOf: refOf2,
1264
+ prepare: (filters) => {
1265
+ requireCapability(core.gate, "messages.list", "Listing messages");
1266
+ if (filters.threadId !== void 0) {
1267
+ requireCapability(
1268
+ core.gate,
1269
+ "messages.byThread",
1270
+ "Reading one conversation"
1271
+ );
1272
+ }
1273
+ if (wantsBody(filters.include)) {
1274
+ requireCapability(core.gate, "messages.body", "Reading message bodies");
1275
+ }
1276
+ if (hasRange(filters)) {
1277
+ requireCapability(
1278
+ core.gate,
1279
+ "messages.since",
1280
+ "Filtering messages by date"
1281
+ );
1282
+ }
1283
+ return {
1284
+ campaignId: filters.campaignId,
1285
+ include: filters.include,
1286
+ leadId: filters.leadId,
1287
+ threadId: filters.threadId,
1288
+ ...normalizeRange(filters)
1289
+ };
1290
+ },
1291
+ schema: messageSchema,
1292
+ toOperation: (filters, page) => ({
1293
+ kind: "messages.list",
1294
+ query: {
1295
+ campaignId: filters.campaignId,
1296
+ includeBody: wantsBody(filters.include),
1297
+ leadId: filters.leadId,
1298
+ since: filters.since,
1299
+ threadId: filters.threadId,
1300
+ until: filters.until,
1301
+ ...page
1302
+ }
1303
+ })
1304
+ });
1305
+ var replyList = (core) => ({
1306
+ action: "replies.list",
1307
+ keyOf: refOf2,
1308
+ prepare: (filters) => {
1309
+ requireCapability(core.gate, "replies.list", "Listing replies");
1310
+ if (filters.category !== void 0) {
1311
+ requireCapability(
1312
+ core.gate,
1313
+ "replies.category",
1314
+ "Filtering replies by category"
1315
+ );
1316
+ }
1317
+ if (wantsBody(filters.include)) {
1318
+ requireCapability(core.gate, "messages.body", "Reading reply bodies");
1319
+ }
1320
+ if (hasRange(filters)) {
1321
+ requireCapability(
1322
+ core.gate,
1323
+ "replies.since",
1324
+ "Filtering replies by date"
1325
+ );
1326
+ }
1327
+ return {
1328
+ campaignId: filters.campaignId,
1329
+ category: filters.category,
1330
+ include: filters.include,
1331
+ ...normalizeRange(filters)
1332
+ };
1333
+ },
1334
+ schema: replySchema,
1335
+ toOperation: (filters, page) => ({
1336
+ kind: "replies.list",
1337
+ query: {
1338
+ campaignId: filters.campaignId,
1339
+ category: filters.category,
1340
+ includeBody: wantsBody(filters.include),
1341
+ since: filters.since,
1342
+ until: filters.until,
1343
+ ...page
1344
+ }
1345
+ })
1346
+ });
1347
+ var workspaceList = (core) => ({
1348
+ action: "workspaces.list",
1349
+ keyOf: refOf2,
1350
+ prepare: () => {
1351
+ requireCapability(core.gate, "workspaces", "Listing workspaces");
1352
+ return {};
1353
+ },
1354
+ schema: workspaceSchema,
1355
+ toOperation: (_filters, page) => ({ kind: "workspaces.list", query: page })
1356
+ });
1357
+
1358
+ // src/internal/outbound/stats.ts
1359
+ var SCOPE_CAPABILITY = {
1360
+ campaign: "stats.campaign",
1361
+ sender: "stats.bySender",
1362
+ step: "stats.byStep",
1363
+ workspace: "stats.workspace"
1364
+ };
1365
+ var readStats = async (core, options = {}) => {
1366
+ const scope = options.scope ?? "workspace";
1367
+ const by = options.by ?? "total";
1368
+ const from = assertDay(options.from, "from");
1369
+ const to = assertDay(options.to, "to");
1370
+ if (from !== void 0 && to !== void 0 && from > to) {
1371
+ throw new OutboundError("Invalid", "from must not be after to");
1372
+ }
1373
+ if (scope !== "workspace" && options.scopeId === void 0) {
1374
+ throw new OutboundError(
1375
+ "Invalid",
1376
+ `stats for the ${scope} scope need a scopeId`
1377
+ );
1378
+ }
1379
+ requireCapability(
1380
+ core.gate,
1381
+ SCOPE_CAPABILITY[scope],
1382
+ `Reading stats for the ${scope} scope`
1383
+ );
1384
+ if (by === "day") {
1385
+ requireCapability(core.gate, "stats.byDay", "Reading stats by day");
1386
+ }
1387
+ return await perform(core, "stats", options, async (state) => {
1388
+ const output2 = await core.run(
1389
+ {
1390
+ kind: "stats",
1391
+ query: { by, from, scope, scopeId: options.scopeId, to }
1392
+ },
1393
+ infoFor(core, state)
1394
+ );
1395
+ return {
1396
+ meta: metaFor(core, state, {
1397
+ complete: true,
1398
+ evidence: output2.evidence,
1399
+ fetchedAt: output2.fetchedAt,
1400
+ stale: output2.stale
1401
+ }),
1402
+ rows: checked(core, metricRowSchema, output2.items, "stats")
1403
+ };
1404
+ });
1405
+ };
1406
+
1407
+ // src/internal/outbound/handles.ts
1408
+ var scoped = (core, spec, fixed) => {
1409
+ const collection = makeReadCollection(core, spec);
1410
+ const withCampaign = (options) => ({ ...options, ...fixed });
1411
+ return {
1412
+ list: (options) => collection.list(withCampaign(options)),
1413
+ listAll: (options) => collection.listAll(withCampaign(options))
1414
+ };
1415
+ };
1416
+ var makeCampaignHandle = (core, id) => {
1417
+ const campaignId = assertId(id, "Campaign");
1418
+ const get = makeGetter(core, campaignGet());
1419
+ const sequence = makeGetter(core, sequenceGet(core));
1420
+ const settings = makeGetter(core, settingsGet(core));
1421
+ const fixed = { campaignId };
1422
+ return {
1423
+ get: (options) => get(campaignId, options),
1424
+ id: campaignId,
1425
+ leads: scoped(core, leadList(core), fixed),
1426
+ messages: scoped(core, messageList(core), fixed),
1427
+ replies: scoped(core, replyList(core), fixed),
1428
+ senders: scoped(core, senderList(core), fixed),
1429
+ sequence: (options) => sequence(campaignId, options),
1430
+ settings: (options) => settings(campaignId, options),
1431
+ subsequences: scoped(core, subsequenceList(core), fixed),
1432
+ webhooks: scoped(core, webhookList(core), fixed),
1433
+ stats: (options) => readStats(core, {
1434
+ ...options,
1435
+ scope: options?.scope ?? "campaign",
1436
+ scopeId: campaignId
1437
+ })
1438
+ };
1439
+ };
1440
+ var makeSenderHandle = (core, id) => {
1441
+ const senderId = assertId(id, "Sender");
1442
+ const get = makeGetter(core, senderGet(core));
1443
+ const health = makeGetter(core, healthGet(core));
1444
+ return {
1445
+ get: (options) => get(senderId, options),
1446
+ health: (options) => health(senderId, options),
1447
+ id: senderId,
1448
+ stats: (options) => readStats(core, { ...options, scope: "sender", scopeId: senderId }),
1449
+ warmup: async (options) => {
1450
+ requireCapability(
1451
+ core.gate,
1452
+ "senders.warmup",
1453
+ "Reading a sender's warmup"
1454
+ );
1455
+ const sender = await get(senderId, options);
1456
+ if (sender.warmup === null) {
1457
+ throw new OutboundError(
1458
+ "NotFound",
1459
+ `Sender ${senderId} has no warmup data`,
1460
+ {
1461
+ provider: core.adapter.name
1462
+ }
1463
+ );
1464
+ }
1465
+ return sender.warmup;
1466
+ }
1467
+ };
1468
+ };
1469
+ var bySentAt = (left, right) => (left.sentAt ?? "").localeCompare(right.sentAt ?? "");
1470
+ var collect = async (core, walk, what) => {
1471
+ const items = await walk.toArray();
1472
+ if (walk.meta === void 0) {
1473
+ throw new OutboundError("Provider", `The ${what} returned no page`, {
1474
+ provider: core.adapter.name
1475
+ });
1476
+ }
1477
+ return { complete: true, items: items.toSorted(bySentAt), meta: walk.meta };
1478
+ };
1479
+ var makeLeadHandle = (core, id) => {
1480
+ const leadId = assertId(id, "Lead");
1481
+ const get = makeGetter(core, leadGet(core));
1482
+ const messages = makeReadCollection(core, messageList(core));
1483
+ return {
1484
+ get: (options) => get(leadId, options),
1485
+ id: leadId,
1486
+ // Async, so a refused read rejects like every other failure of the call.
1487
+ timeline: async (options) => {
1488
+ requireCapability(
1489
+ core.gate,
1490
+ "leads.timeline",
1491
+ "Reading a lead's timeline"
1492
+ );
1493
+ return await collect(
1494
+ core,
1495
+ messages.listAll({ ...options, leadId }),
1496
+ "timeline"
1497
+ );
1498
+ }
1499
+ };
1500
+ };
1501
+ var makeListHandle = (core, id) => {
1502
+ const listId = assertId(id, "List");
1503
+ return { id: listId, leads: scoped(core, leadList(core), { listId }) };
1504
+ };
1505
+ var makeThreadHandle = (core, id) => {
1506
+ const threadId = assertId(id, "Thread");
1507
+ const messages = makeReadCollection(core, messageList(core));
1508
+ return {
1509
+ id: threadId,
1510
+ // Async, so a refused read rejects like every other failure of the call.
1511
+ messages: async (options) => await collect(core, messages.listAll({ ...options, threadId }), "thread")
1512
+ };
1513
+ };
1514
+
1515
+ // src/internal/outbound/native.ts
1516
+ var invalid2 = (core, message) => new OutboundError("Invalid", message, { provider: core.adapter.name });
1517
+ var TYPE_CHECKS = {
1518
+ boolean: (value) => value === true || value === false,
1519
+ json: () => true,
1520
+ list: (value) => Array.isArray(value) && value.every((item) => !isJsonObject(item) && !Array.isArray(item)),
1521
+ number: (value) => Number.isFinite(value),
1522
+ string: (value) => String(value) === value
1523
+ };
1524
+ var scalar = (value) => isJsonObject(value) || Array.isArray(value) ? JSON.stringify(value) : value;
1525
+ var place = (built, name, param, value) => {
1526
+ if (param.in === "path") {
1527
+ return {
1528
+ ...built,
1529
+ path: built.path.replace(`{${name}}`, encodeURIComponent(String(value)))
1530
+ };
1531
+ }
1532
+ if (param.in === "query" && param.type === "list" && Array.isArray(value)) {
1533
+ return {
1534
+ ...built,
1535
+ repeated: [
1536
+ ...built.repeated,
1537
+ ...value.map((item) => [name, String(item)])
1538
+ ]
1539
+ };
1540
+ }
1541
+ return param.in === "query" ? { ...built, query: { ...built.query, [name]: scalar(value) } } : { ...built, body: { ...built.body, [name]: value } };
1542
+ };
1543
+ var withRepeated = (url, repeated) => {
1544
+ if (repeated.length === 0) {
1545
+ return url;
1546
+ }
1547
+ const parsed = new URL(url);
1548
+ for (const [name, value] of repeated) {
1549
+ parsed.searchParams.append(name, value);
1550
+ }
1551
+ return parsed.toString();
1552
+ };
1553
+ var build = (core, { name, read }, params) => {
1554
+ const declared = Object.entries(read.params ?? {});
1555
+ const known = new Set(declared.map(([param]) => param));
1556
+ const unknown = Object.keys(params).find((param) => !known.has(param));
1557
+ if (unknown !== void 0) {
1558
+ throw invalid2(
1559
+ core,
1560
+ `${name} has no parameter "${unknown}". It takes: ${[...known].join(", ") || "nothing"}`
1561
+ );
1562
+ }
1563
+ let built = {
1564
+ body: read.method === "POST" ? {} : void 0,
1565
+ path: read.path,
1566
+ query: {},
1567
+ repeated: []
1568
+ };
1569
+ for (const [param, spec] of declared) {
1570
+ const value = params[param];
1571
+ if (value === void 0 || value === null) {
1572
+ if (spec.required === true || spec.in === "path") {
1573
+ throw invalid2(core, `${name} needs "${param}"`);
1574
+ }
1575
+ continue;
1576
+ }
1577
+ if (!TYPE_CHECKS[spec.type](value)) {
1578
+ throw invalid2(core, `${name}: "${param}" must be a ${spec.type}`);
1579
+ }
1580
+ built = place(built, param, spec, value);
1581
+ }
1582
+ return built;
1583
+ };
1584
+ var makeNativeClient = (core) => {
1585
+ const { adapter } = core;
1586
+ const catalog = adapter.native ?? {};
1587
+ const read = async (name, params = {}, options = {}) => {
1588
+ if (adapter.members !== void 0) {
1589
+ throw new OutboundError(
1590
+ "Unsupported",
1591
+ `native is not available on a combined instance: it belongs to one vendor. Use outbound.workspace("provider:workspace").native, for example ${adapter.members.map((member) => `"${member.name}:${member.workspaceId}"`).join(" or ")}`,
1592
+ { provider: adapter.name }
1593
+ );
1594
+ }
1595
+ requireCapability(core.gate, "native", "Reading the vendor's own data");
1596
+ const entry = Object.hasOwn(catalog, name) ? catalog[name] : void 0;
1597
+ if (entry === void 0) {
1598
+ throw invalid2(
1599
+ core,
1600
+ `${adapter.name} has no native read "${name}". See outbound.native.catalog`
1601
+ );
1602
+ }
1603
+ const built = build(core, { name, read: entry }, params);
1604
+ return await perform(core, `native.${name}`, options, async (state) => {
1605
+ const spec = adapter.raw.authorize({
1606
+ body: built.body,
1607
+ lane: entry.lane,
1608
+ method: entry.method,
1609
+ url: withRepeated(
1610
+ buildUrl(
1611
+ entry.baseUrl ?? adapter.raw.baseUrl,
1612
+ built.path,
1613
+ built.query
1614
+ ),
1615
+ built.repeated
1616
+ )
1617
+ });
1618
+ const response = await core.engine.contextFor(adapter, state).request(spec);
1619
+ return {
1620
+ data: response.body,
1621
+ meta: metaFor(core, state, { complete: true, evidence: "exact" })
1622
+ };
1623
+ });
1624
+ };
1625
+ const reads = {};
1626
+ for (const name of Object.keys(catalog)) {
1627
+ reads[name] = (params, options) => read(name, params, options);
1628
+ }
1629
+ return {
1630
+ // SAFETY: the catalog is the adapter's own, typed by the caller as Native.
1631
+ catalog,
1632
+ provider: adapter.name,
1633
+ read,
1634
+ // SAFETY: one function per catalog name, each taking that read's parameters.
1635
+ reads
1636
+ };
1637
+ };
1638
+
1639
+ // src/internal/outbound/operation-shared.ts
1640
+ var unsupported = (adapter, kind) => new OutboundError(
1641
+ "Unsupported",
1642
+ `The ${adapter.name} adapter does not implement ${kind}`,
1643
+ {
1644
+ provider: adapter.name
1645
+ }
1646
+ );
1647
+ var idFor = (adapter, id) => (
1648
+ // A combined adapter routes by ref, so it needs the id untouched.
1649
+ adapter.members === void 0 ? sourceIdFor(id, adapter.name, adapter.workspaceId) : id
1650
+ );
1651
+ var optionalId = (adapter, id) => id === void 0 ? void 0 : idFor(adapter, id);
1652
+ var output = (page, derived = false) => ({
1653
+ evidence: derived ? "derived" : "exact",
1654
+ items: page.items,
1655
+ next: page.next
1656
+ });
1657
+ var single = (item) => ({
1658
+ evidence: "exact",
1659
+ items: [item]
1660
+ });
1661
+
1662
+ // src/internal/outbound/operations-account.ts
1663
+ var ACCOUNT_KINDS = /* @__PURE__ */ new Set([
1664
+ "blocklist.list",
1665
+ "campaigns.settings",
1666
+ "lists.list",
1667
+ "senders.health",
1668
+ "sequence.subsequences",
1669
+ "tags.list",
1670
+ "webhooks.list"
1671
+ ]);
1672
+ var isAccountOperation = (operation) => ACCOUNT_KINDS.has(operation.kind);
1673
+ var lookup = async (target, operation) => {
1674
+ const { adapter, ctx } = target;
1675
+ const id = idFor(adapter, operation.id);
1676
+ if (operation.kind === "campaigns.settings") {
1677
+ if (adapter.getCampaignSettings === void 0) {
1678
+ throw unsupported(adapter, operation.kind);
1679
+ }
1680
+ return single(await adapter.getCampaignSettings(id, ctx));
1681
+ }
1682
+ if (adapter.getSenderHealth === void 0) {
1683
+ throw unsupported(adapter, operation.kind);
1684
+ }
1685
+ return single(await adapter.getSenderHealth(id, ctx));
1686
+ };
1687
+ var scopedList = async (target, operation) => {
1688
+ const { adapter, ctx } = target;
1689
+ if (operation.kind === "sequence.subsequences") {
1690
+ if (adapter.listSubsequences === void 0) {
1691
+ throw unsupported(adapter, operation.kind);
1692
+ }
1693
+ return output(
1694
+ await adapter.listSubsequences(
1695
+ {
1696
+ ...operation.query,
1697
+ campaignId: idFor(adapter, operation.query.campaignId)
1698
+ },
1699
+ ctx
1700
+ )
1701
+ );
1702
+ }
1703
+ if (adapter.listWebhooks === void 0) {
1704
+ throw unsupported(adapter, operation.kind);
1705
+ }
1706
+ return output(
1707
+ await adapter.listWebhooks(
1708
+ {
1709
+ ...operation.query,
1710
+ campaignId: optionalId(adapter, operation.query.campaignId)
1711
+ },
1712
+ ctx
1713
+ )
1714
+ );
1715
+ };
1716
+ var dispatchAccount = async (target, operation) => {
1717
+ const { adapter, ctx } = target;
1718
+ switch (operation.kind) {
1719
+ case "campaigns.settings":
1720
+ case "senders.health": {
1721
+ return await lookup(target, operation);
1722
+ }
1723
+ case "sequence.subsequences":
1724
+ case "webhooks.list": {
1725
+ return await scopedList(target, operation);
1726
+ }
1727
+ case "blocklist.list": {
1728
+ if (adapter.listBlocklist === void 0) {
1729
+ throw unsupported(adapter, operation.kind);
1730
+ }
1731
+ return output(await adapter.listBlocklist(operation.query, ctx));
1732
+ }
1733
+ case "lists.list": {
1734
+ if (adapter.listLists === void 0) {
1735
+ throw unsupported(adapter, operation.kind);
1736
+ }
1737
+ return output(await adapter.listLists(operation.query, ctx));
1738
+ }
1739
+ case "tags.list": {
1740
+ if (adapter.listTags === void 0) {
1741
+ throw unsupported(adapter, operation.kind);
1742
+ }
1743
+ return output(await adapter.listTags(operation.query, ctx));
1744
+ }
1745
+ default: {
1746
+ const unreachable = operation;
1747
+ return unreachable;
1748
+ }
1749
+ }
1750
+ };
1751
+
1752
+ // src/internal/outbound/operations.ts
1753
+ var inRange = (value, range) => {
1754
+ if (range.since === void 0 && range.until === void 0) {
1755
+ return true;
1756
+ }
1757
+ if (value === null) {
1758
+ return false;
1759
+ }
1760
+ const time = Date.parse(value);
1761
+ return (range.since === void 0 || time >= Date.parse(range.since)) && (range.until === void 0 || time <= Date.parse(range.until));
1762
+ };
1763
+ var hasRange2 = (range) => range.since !== void 0 || range.until !== void 0;
1764
+ var filterByTime = (page, range, grade, timeOf) => {
1765
+ if (grade !== "client" || !hasRange2(range)) {
1766
+ return { derived: false, page };
1767
+ }
1768
+ return {
1769
+ derived: true,
1770
+ page: {
1771
+ items: page.items.filter((item) => inRange(timeOf(item), range)),
1772
+ next: page.next
1773
+ }
1774
+ };
1775
+ };
1776
+ var listCampaigns = async (target, query) => {
1777
+ const page = await target.adapter.listCampaigns(query, target.ctx);
1778
+ if (target.capabilities["campaigns.status"] !== "client" || query.status === void 0) {
1779
+ return output(page);
1780
+ }
1781
+ return output(
1782
+ {
1783
+ items: page.items.filter((campaign) => campaign.status === query.status),
1784
+ next: page.next
1785
+ },
1786
+ true
1787
+ );
1788
+ };
1789
+ var listLeads = async (target, query) => {
1790
+ const { adapter, capabilities, ctx } = target;
1791
+ if (adapter.listLeads === void 0) {
1792
+ throw unsupported(adapter, "leads.list");
1793
+ }
1794
+ const page = await adapter.listLeads(
1795
+ {
1796
+ ...query,
1797
+ campaignId: optionalId(adapter, query.campaignId),
1798
+ listId: optionalId(adapter, query.listId)
1799
+ },
1800
+ ctx
1801
+ );
1802
+ const filtered = filterByTime(
1803
+ page,
1804
+ query,
1805
+ capabilities["leads.since"],
1806
+ (lead) => lead.createdAt
1807
+ );
1808
+ return output(filtered.page, filtered.derived);
1809
+ };
1810
+ var listMessages = async (target, query) => {
1811
+ const { adapter, capabilities, ctx } = target;
1812
+ if (adapter.listMessages === void 0) {
1813
+ throw unsupported(adapter, "messages.list");
1814
+ }
1815
+ const page = await adapter.listMessages(
1816
+ {
1817
+ ...query,
1818
+ campaignId: optionalId(adapter, query.campaignId),
1819
+ leadId: optionalId(adapter, query.leadId)
1820
+ },
1821
+ ctx
1822
+ );
1823
+ const filtered = filterByTime(
1824
+ page,
1825
+ query,
1826
+ capabilities["messages.since"],
1827
+ (message) => message.sentAt
1828
+ );
1829
+ return output(filtered.page, filtered.derived);
1830
+ };
1831
+ var listReplies = async (target, query) => {
1832
+ const { adapter, capabilities, ctx } = target;
1833
+ if (adapter.listReplies === void 0) {
1834
+ throw unsupported(adapter, "replies.list");
1835
+ }
1836
+ const page = await adapter.listReplies(
1837
+ { ...query, campaignId: optionalId(adapter, query.campaignId) },
1838
+ ctx
1839
+ );
1840
+ const filtered = filterByTime(
1841
+ page,
1842
+ query,
1843
+ capabilities["replies.since"],
1844
+ (reply) => reply.sentAt
1845
+ );
1846
+ return output(filtered.page, filtered.derived);
1847
+ };
1848
+ var listSenders = async (target, query) => {
1849
+ const { adapter, ctx } = target;
1850
+ if (adapter.listSenders === void 0) {
1851
+ throw unsupported(adapter, "senders.list");
1852
+ }
1853
+ return output(
1854
+ await adapter.listSenders(
1855
+ { ...query, campaignId: optionalId(adapter, query.campaignId) },
1856
+ ctx
1857
+ )
1858
+ );
1859
+ };
1860
+ var stats = async (target, query) => {
1861
+ const { adapter, ctx } = target;
1862
+ if (adapter.stats === void 0) {
1863
+ throw unsupported(adapter, "stats");
1864
+ }
1865
+ const rows = await adapter.stats(
1866
+ { ...query, scopeId: optionalId(adapter, query.scopeId) },
1867
+ ctx
1868
+ );
1869
+ const derived = rows.some((row) => row.evidence !== "exact");
1870
+ return { evidence: derived ? "derived" : "exact", items: rows };
1871
+ };
1872
+ var getOne2 = async (target, operation) => {
1873
+ const { adapter, ctx } = target;
1874
+ const id = idFor(adapter, operation.id);
1875
+ switch (operation.kind) {
1876
+ case "campaigns.get": {
1877
+ return single(await adapter.getCampaign(id, ctx));
1878
+ }
1879
+ case "leads.get": {
1880
+ if (adapter.getLead === void 0) {
1881
+ throw unsupported(adapter, operation.kind);
1882
+ }
1883
+ return single(await adapter.getLead(id, ctx));
1884
+ }
1885
+ case "senders.get": {
1886
+ if (adapter.getSender === void 0) {
1887
+ throw unsupported(adapter, operation.kind);
1888
+ }
1889
+ return single(await adapter.getSender(id, ctx));
1890
+ }
1891
+ case "sequence.get": {
1892
+ if (adapter.getSequence === void 0) {
1893
+ throw unsupported(adapter, operation.kind);
1894
+ }
1895
+ return single(await adapter.getSequence(id, ctx));
1896
+ }
1897
+ default: {
1898
+ const unreachable = operation;
1899
+ return unreachable;
1900
+ }
1901
+ }
1902
+ };
1903
+ var dispatch = async (target, operation) => {
1904
+ if (isAccountOperation(operation)) {
1905
+ return await dispatchAccount(target, operation);
1906
+ }
1907
+ switch (operation.kind) {
1908
+ case "campaigns.list": {
1909
+ return await listCampaigns(target, operation.query);
1910
+ }
1911
+ case "leads.list": {
1912
+ return await listLeads(target, operation.query);
1913
+ }
1914
+ case "messages.list": {
1915
+ return await listMessages(target, operation.query);
1916
+ }
1917
+ case "replies.list": {
1918
+ return await listReplies(target, operation.query);
1919
+ }
1920
+ case "senders.list": {
1921
+ return await listSenders(target, operation.query);
1922
+ }
1923
+ case "stats": {
1924
+ return await stats(target, operation.query);
1925
+ }
1926
+ case "workspaces.list": {
1927
+ if (target.adapter.listWorkspaces === void 0) {
1928
+ throw unsupported(target.adapter, operation.kind);
1929
+ }
1930
+ return output(
1931
+ await target.adapter.listWorkspaces(operation.query, target.ctx)
1932
+ );
1933
+ }
1934
+ default: {
1935
+ return await getOne2(target, operation);
1936
+ }
1937
+ }
1938
+ };
1939
+
1940
+ // src/internal/outbound/plugins.ts
1941
+ var narrowCapabilities = (declared, plugins) => {
1942
+ const narrowedBy = /* @__PURE__ */ new Map();
1943
+ let current = declared;
1944
+ for (const plugin of plugins) {
1945
+ if (plugin.capabilities !== void 0) {
1946
+ const next = intersectCapabilities(
1947
+ current,
1948
+ plugin.capabilities({ ...current })
1949
+ );
1950
+ for (const key of CAPABILITY_KEYS) {
1951
+ if (next[key] === false && current[key] !== false) {
1952
+ narrowedBy.set(key, plugin.name);
1953
+ }
1954
+ }
1955
+ current = next;
1956
+ }
1957
+ }
1958
+ return { capabilities: current, narrowedBy };
1959
+ };
1960
+ var composeOperations = (plugins, innermost) => {
1961
+ const wraps = plugins.flatMap(
1962
+ (plugin) => plugin.wrap === void 0 ? [] : [plugin.wrap]
1963
+ );
1964
+ return (operation, info) => {
1965
+ const run = (index, current) => {
1966
+ const wrap = wraps[index];
1967
+ return wrap === void 0 ? innermost(current, info) : wrap(current, (inner) => run(index + 1, inner), info);
1968
+ };
1969
+ return run(0, operation);
1970
+ };
1971
+ };
1972
+ var assertUniquePluginNames = (plugins) => {
1973
+ const seen = /* @__PURE__ */ new Set();
1974
+ for (const plugin of plugins) {
1975
+ if (seen.has(plugin.name)) {
1976
+ throw new OutboundError(
1977
+ "Invalid",
1978
+ `The ${plugin.name} plugin is listed twice`
1979
+ );
1980
+ }
1981
+ seen.add(plugin.name);
1982
+ }
1983
+ };
1984
+ var isExtension = (value) => typeof value === "object" && value !== null;
1985
+ var installExtensions = (outbound, plugins) => {
1986
+ for (const plugin of plugins) {
1987
+ const extension = plugin.extend?.(outbound);
1988
+ for (const [name, value] of Object.entries(
1989
+ isExtension(extension) ? extension : {}
1990
+ )) {
1991
+ if (name in outbound) {
1992
+ throw new OutboundError(
1993
+ "Invalid",
1994
+ `The ${plugin.name} plugin adds "${name}", which already exists on the instance`
1995
+ );
1996
+ }
1997
+ Object.defineProperty(outbound, name, { enumerable: true, value });
1998
+ }
1999
+ }
2000
+ };
2001
+
2002
+ // src/internal/outbound/raw.ts
2003
+ var ENCODED_SEPARATOR = /%(?:2f|5c|2e)|\\/iu;
2004
+ var refuse = (core, message) => new OutboundError("Unsupported", message, {
2005
+ provider: core.adapter.name
2006
+ });
2007
+ var resolve = (core, path, query) => {
2008
+ const { baseUrl } = core.adapter.raw;
2009
+ if (ENCODED_SEPARATOR.test(path)) {
2010
+ throw new OutboundError(
2011
+ "Invalid",
2012
+ "A raw path may not contain a backslash or an encoded slash, backslash or dot",
2013
+ { provider: core.adapter.name }
2014
+ );
2015
+ }
2016
+ const base = new URL(baseUrl);
2017
+ const url = new URL(buildUrl(baseUrl, path, query));
2018
+ const root = base.pathname.replace(/\/+$/u, "");
2019
+ if (url.origin !== base.origin || !(url.pathname === root || url.pathname.startsWith(`${root}/`))) {
2020
+ throw refuse(
2021
+ core,
2022
+ `${path} leaves the ${core.adapter.name} API, so raw will not send it`
2023
+ );
2024
+ }
2025
+ const relative = `/${url.pathname.slice(root.length).split("/").filter((part) => part !== "").join("/")}`;
2026
+ url.pathname = `${root}${relative}`;
2027
+ return { path: relative, query: url.searchParams, url: url.toString() };
2028
+ };
2029
+ var makeRawClient = (core, nativeOffBy) => {
2030
+ const { adapter } = core;
2031
+ const request = async (method, path, options = {}) => {
2032
+ if (adapter.members !== void 0) {
2033
+ throw refuse(
2034
+ core,
2035
+ `raw is not available on a combined instance: it belongs to one vendor. Use outbound.workspace("provider:workspace").raw, for example ${adapter.members.map((member) => `"${member.name}:${member.workspaceId}"`).join(" or ")}`
2036
+ );
2037
+ }
2038
+ if (nativeOffBy !== void 0) {
2039
+ throw refuse(
2040
+ core,
2041
+ `raw is not available: the ${nativeOffBy} plugin turned the vendor's own reads off (native), and raw returns the same untouched payload`
2042
+ );
2043
+ }
2044
+ const target = resolve(core, path, options.query);
2045
+ if (adapter.raw.isSecret?.(target.path, target.query) === true) {
2046
+ throw refuse(
2047
+ core,
2048
+ `${method} ${target.path} returns secrets (keys or passwords) on ${adapter.name}, so raw never reads it`
2049
+ );
2050
+ }
2051
+ const isRead = adapter.raw.isRead(method, target.path);
2052
+ if (!core.allowWrites && !isRead) {
2053
+ throw refuse(
2054
+ core,
2055
+ `${method} ${target.path} is not a known read on ${adapter.name}. The SDK is read-only; pass allowWrites: true to createOutbound to permit it`
2056
+ );
2057
+ }
2058
+ const settings = isRead || options.retries !== void 0 ? options : { ...options, retries: 0 };
2059
+ return await perform(core, "raw", settings, async (state) => {
2060
+ const spec = adapter.raw.authorize({
2061
+ body: options.body,
2062
+ lane: options.lane,
2063
+ method,
2064
+ url: target.url
2065
+ });
2066
+ const response = await core.engine.contextFor(adapter, state).request(spec);
2067
+ return response.body;
2068
+ });
2069
+ };
2070
+ return {
2071
+ get: (path, options) => request("GET", path, options),
2072
+ provider: adapter.name,
2073
+ request
2074
+ };
2075
+ };
2076
+
2077
+ // src/internal/outbound/outbound.ts
2078
+ var engineFor = (options) => new RequestEngine({
2079
+ defaults: {
2080
+ deadline: options.deadline,
2081
+ maxRequests: options.maxRequests,
2082
+ retries: options.retries,
2083
+ signal: options.signal,
2084
+ timeout: options.timeout
2085
+ },
2086
+ hooks: mergeHooks([
2087
+ options.hooks,
2088
+ ...(options.plugins ?? []).map((plugin) => plugin.hooks)
2089
+ ]),
2090
+ runtime: options.fetch === void 0 ? options.runtime : { ...options.runtime, fetch: options.fetch },
2091
+ share: options.share,
2092
+ store: options.rateLimitStore
2093
+ });
2094
+ var Outbound = class _Outbound {
2095
+ #core;
2096
+ #options;
2097
+ #plugins;
2098
+ campaigns;
2099
+ senders;
2100
+ leads;
2101
+ messages;
2102
+ replies;
2103
+ workspaces;
2104
+ lists;
2105
+ blocklist;
2106
+ tags;
2107
+ webhooks;
2108
+ raw;
2109
+ native;
2110
+ constructor(options, engine = engineFor(options)) {
2111
+ const { adapter } = options;
2112
+ const plugins = options.plugins ?? [];
2113
+ assertUniquePluginNames(plugins);
2114
+ const declared = resolveCapabilities(adapter.capabilities);
2115
+ const narrowed = narrowCapabilities(declared, plugins);
2116
+ const run = composeOperations(
2117
+ plugins,
2118
+ (operation, info) => dispatch(
2119
+ {
2120
+ adapter,
2121
+ capabilities: declared,
2122
+ ctx: engine.contextFor(adapter, info.state)
2123
+ },
2124
+ operation
2125
+ )
2126
+ );
2127
+ this.#options = options;
2128
+ this.#plugins = plugins;
2129
+ this.#core = {
2130
+ adapter,
2131
+ allowWrites: options.allowWrites ?? false,
2132
+ engine,
2133
+ gate: { ...narrowed, provider: adapter.name },
2134
+ run
2135
+ };
2136
+ this.campaigns = makeCollection(
2137
+ this.#core,
2138
+ campaignList(this.#core),
2139
+ campaignGet()
2140
+ );
2141
+ this.senders = makeCollection(
2142
+ this.#core,
2143
+ senderList(this.#core),
2144
+ senderGet(this.#core)
2145
+ );
2146
+ this.leads = makeCollection(
2147
+ this.#core,
2148
+ leadList(this.#core),
2149
+ leadGet(this.#core)
2150
+ );
2151
+ this.messages = makeReadCollection(this.#core, messageList(this.#core));
2152
+ this.replies = makeReadCollection(this.#core, replyList(this.#core));
2153
+ this.workspaces = makeReadCollection(this.#core, workspaceList(this.#core));
2154
+ this.lists = makeReadCollection(this.#core, listList(this.#core));
2155
+ this.blocklist = makeReadCollection(this.#core, blocklistList(this.#core));
2156
+ this.tags = makeReadCollection(this.#core, tagList(this.#core));
2157
+ this.webhooks = makeReadCollection(this.#core, webhookList(this.#core));
2158
+ this.raw = makeRawClient(
2159
+ this.#core,
2160
+ // Asked as if the adapter had native reads: a plugin that would turn
2161
+ // them off must stop raw on an adapter that has none, too.
2162
+ narrowCapabilities({ ...declared, native: true }, plugins).narrowedBy.get(
2163
+ "native"
2164
+ )
2165
+ );
2166
+ this.native = makeNativeClient(this.#core);
2167
+ }
2168
+ get provider() {
2169
+ return this.#core.adapter.name;
2170
+ }
2171
+ get workspaceId() {
2172
+ return this.#core.adapter.workspaceId;
2173
+ }
2174
+ get capabilities() {
2175
+ return { ...this.#core.gate.capabilities };
2176
+ }
2177
+ get maturity() {
2178
+ return this.#core.adapter.maturity;
2179
+ }
2180
+ get caveats() {
2181
+ return this.#core.adapter.caveats ?? [];
2182
+ }
2183
+ /** The plugins on this instance, outermost first. */
2184
+ get plugins() {
2185
+ return this.#plugins;
2186
+ }
2187
+ campaign(id) {
2188
+ return makeCampaignHandle(this.#core, id);
2189
+ }
2190
+ sender(id) {
2191
+ return makeSenderHandle(this.#core, id);
2192
+ }
2193
+ lead(id) {
2194
+ return makeLeadHandle(this.#core, id);
2195
+ }
2196
+ list(id) {
2197
+ return makeListHandle(this.#core, id);
2198
+ }
2199
+ thread(id) {
2200
+ return makeThreadHandle(this.#core, id);
2201
+ }
2202
+ /**
2203
+ * The same instance scoped to one client or workspace. It keeps the
2204
+ * plugins and what they add, so `outbound.workspace(id).insights` works.
2205
+ */
2206
+ workspace(id) {
2207
+ const { adapter, engine } = this.#core;
2208
+ if (adapter.members === void 0 && adapter.workspaceId === id) {
2209
+ return this;
2210
+ }
2211
+ const member = adapter.scope?.(id);
2212
+ if (member === void 0) {
2213
+ throw new OutboundError(
2214
+ "NotFound",
2215
+ `Workspace ${id} is not on this instance`,
2216
+ {
2217
+ provider: adapter.name
2218
+ }
2219
+ );
2220
+ }
2221
+ const scoped2 = new _Outbound({ ...this.#options, adapter: member }, engine);
2222
+ installExtensions(scoped2, this.#plugins);
2223
+ return scoped2;
2224
+ }
2225
+ stats(options) {
2226
+ return readStats(this.#core, options);
2227
+ }
2228
+ limits() {
2229
+ const { adapter, engine } = this.#core;
2230
+ return Promise.all(
2231
+ (adapter.members ?? [adapter]).map((member) => engine.limits(member))
2232
+ );
2233
+ }
2234
+ estimate(query) {
2235
+ const cost = this.#core.adapter.costs?.[query.action];
2236
+ if (cost === void 0) {
2237
+ return {
2238
+ basis: `${this.provider} declares no cost for ${query.action}`,
2239
+ requests: null
2240
+ };
2241
+ }
2242
+ const pageSize = query.limit ?? cost.pageSize;
2243
+ if (query.records === void 0 || pageSize === void 0) {
2244
+ return { basis: `${cost.perPage} request(s) per page`, requests: null };
2245
+ }
2246
+ const pages = Math.max(1, Math.ceil(query.records / pageSize));
2247
+ const requests = pages * cost.perPage + query.records * (cost.perRecord ?? 0);
2248
+ return {
2249
+ basis: `${pages} page(s) of ${pageSize} at ${cost.perPage} request(s) each, plus ${cost.perRecord ?? 0} per record`,
2250
+ requests
2251
+ };
2252
+ }
2253
+ };
2254
+
2255
+ // src/internal/outbound/create.ts
2256
+ var createOutbound = (options) => {
2257
+ const outbound = new Outbound(options);
2258
+ installExtensions(outbound, options.plugins ?? []);
2259
+ return outbound;
2260
+ };
2261
+
2262
+ export {
2263
+ DEFAULT_SHARE,
2264
+ fullJitterBackoff,
2265
+ campaignSettingsSchema,
2266
+ senderHealthSchema,
2267
+ leadListSchema,
2268
+ blockEntrySchema,
2269
+ tagSchema,
2270
+ webhookSubscriptionSchema,
2271
+ Outbound,
2272
+ createOutbound
2273
+ };