@adport/provider-reddit 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,179 @@
1
+ // src/catalog-access.ts
2
+ import { createHash, randomUUID } from "crypto";
3
+ import { constants, promises as fs } from "fs";
4
+ import path from "path";
5
+ import { AdportError, adportHome } from "@adport/core";
6
+ import { z as z2 } from "zod";
7
+
8
+ // src/schemas.ts
9
+ import { z } from "zod";
10
+ var redditId = z.string().regex(/^[A-Za-z0-9_-]+$/);
11
+ var micros = z.number().int().nonnegative().safe();
12
+ var status = z.enum(["ACTIVE", "PAUSED"]);
13
+ var objective = z.enum(["APP_INSTALLS", "BRAND_AWARENESS", "CATALOG_SALES", "CLICKS", "CONVERSIONS", "IMPRESSIONS", "LEAD_GENERATION", "SALES", "VIDEO_VIEWABLE_IMPRESSIONS"]);
14
+ var createCampaign = z.object({
15
+ name: z.string().trim().min(1),
16
+ objective: objective.default("CLICKS"),
17
+ funding_instrument_id: redditId,
18
+ configured_status: status.default("PAUSED"),
19
+ budget_micros: micros.positive().optional(),
20
+ budget_type: z.enum(["DAILY_SPEND", "LIFETIME_SPEND"]).default("DAILY_SPEND"),
21
+ conversion_pixel_id: redditId.optional(),
22
+ spend_cap_micros: micros.positive().optional()
23
+ }).refine((v) => !v.budget_micros || Boolean(v.conversion_pixel_id), "conversion_pixel_id is required for CBO campaigns");
24
+ var setCampaignStatus = z.object({ campaign_id: redditId, configured_status: status });
25
+ var setCampaignBudget = z.object({ campaign_id: redditId, budget_micros: micros.positive(), budget_type: z.enum(["DAILY_SPEND", "LIFETIME_SPEND"]).optional() });
26
+
27
+ // src/catalog-access.ts
28
+ var redditBusinessId = z2.string().regex(/^[a-fA-F0-9]{8}-(?:[a-fA-F0-9]{4}-){3}[a-fA-F0-9]{12}$/).toLowerCase();
29
+ var redditCatalogId = redditId.min(1).max(256);
30
+ var accountId = redditCatalogId;
31
+ var catalogScope = z2.object({ accountId, businessId: redditBusinessId, resourceId: redditCatalogId, kind: z2.enum(["catalog", "catalog_creation"]) }).strict();
32
+ var catalogAccessMode = z2.enum(["none", "read", "write", "create"]);
33
+ function catalogGrant(scope3, mode = "none", revision = 0) {
34
+ const parsed = catalogScope.parse(scope3);
35
+ catalogAccessMode.parse(mode);
36
+ if (!Number.isSafeInteger(revision) || revision < 0 || parsed.kind === "catalog_creation" && (parsed.resourceId !== parsed.businessId || !["none", "create"].includes(mode)) || parsed.kind === "catalog" && mode === "create") throw new AdportError("INVALID_INPUT", "Invalid Reddit catalog access configuration.");
37
+ return { scope: parsed, mode, revision, hash: createHash("sha256").update(JSON.stringify(["reddit", parsed.accountId, parsed.businessId, parsed.kind, parsed.resourceId, mode, revision])).digest("hex") };
38
+ }
39
+ function catalogScopeKey(scope3) {
40
+ return catalogGrant(scope3).hash;
41
+ }
42
+ async function requireCatalogAccess(store, scope3, write2 = false) {
43
+ if (!store) throw new AdportError("POLICY_VIOLATION", "Catalog access has not been selected for this project. An owner or admin must grant the exact Business/catalog in Accounts.");
44
+ if (write2 && !store.canWrite) throw new AdportError("POLICY_VIOLATION", "This connection cannot modify Reddit catalogs.");
45
+ const grant = await store.authorize(scope3, write2);
46
+ if (catalogScopeKey(grant.scope) !== catalogScopeKey(scope3)) throw new AdportError("POLICY_VIOLATION", "Catalog grant scope does not match the requested resource.");
47
+ if (!(write2 ? grant.mode === "write" : grant.mode === "read" || grant.mode === "write")) throw new AdportError("POLICY_VIOLATION", `This project does not have ${write2 ? "write" : "read"} access to the selected Reddit catalog. Ask an owner or admin to review catalog access in Accounts.`);
48
+ return grant;
49
+ }
50
+ var creationScope = (accountId2, businessId) => {
51
+ const normalized2 = redditBusinessId.parse(businessId);
52
+ return catalogScope.parse({ accountId: accountId2, businessId: normalized2, resourceId: normalized2, kind: "catalog_creation" });
53
+ };
54
+ async function requireCatalogCreationAccess(store, scope3, write2 = false) {
55
+ if (!store || scope3.kind !== "catalog_creation" || scope3.resourceId !== scope3.businessId || write2 && !store.canWrite) throw new AdportError("POLICY_VIOLATION", "Catalog creation requires owner-delegated creation access and a writable connection.");
56
+ const grant = await store.authorize(scope3, write2);
57
+ if (catalogScopeKey(grant.scope) !== catalogScopeKey(scope3) || grant.mode !== "create") throw new AdportError("POLICY_VIOLATION", "An owner must delegate catalog creation for this exact advertiser and Business. Existing catalog grants do not grant creation access.");
58
+ return grant;
59
+ }
60
+ var FileRedditCatalogAccessStore = class {
61
+ constructor(dir = path.join(adportHome(), "catalog-access", "reddit")) {
62
+ this.dir = dir;
63
+ }
64
+ dir;
65
+ canManage = true;
66
+ canWrite = true;
67
+ file(scope3) {
68
+ return path.join(this.dir, catalogScopeKey(scope3) + ".json");
69
+ }
70
+ async authorize(scope3, _write) {
71
+ return this.get(scope3);
72
+ }
73
+ async get(scope3) {
74
+ const absent = catalogGrant(scope3);
75
+ let handle;
76
+ try {
77
+ handle = await fs.open(this.file(scope3), constants.O_RDONLY | constants.O_NOFOLLOW);
78
+ await handle.chmod(384);
79
+ if ((await handle.stat()).size > 65536) throw new Error("size");
80
+ const value = JSON.parse(await handle.readFile("utf8"));
81
+ const grant = catalogGrant(value.scope, value.mode, value.revision);
82
+ if (catalogScopeKey(grant.scope) !== catalogScopeKey(scope3)) throw new Error("scope");
83
+ return grant;
84
+ } catch (error) {
85
+ if (error.code === "ENOENT") return absent;
86
+ throw new AdportError("POLICY_VIOLATION", "Local Reddit catalog access could not be verified.");
87
+ } finally {
88
+ await handle?.close();
89
+ }
90
+ }
91
+ async list(accountId2) {
92
+ if (!redditCatalogId.safeParse(accountId2).success) throw new AdportError("INVALID_INPUT", "Invalid advertiser ID.");
93
+ let files;
94
+ try {
95
+ files = await fs.readdir(this.dir);
96
+ } catch (error) {
97
+ if (error.code === "ENOENT") return [];
98
+ throw error;
99
+ }
100
+ const names = files.filter((value) => /^[a-f0-9]{64}\.json$/.test(value));
101
+ if (names.length > 5e3) throw new AdportError("POLICY_VIOLATION", "Local catalog access inventory exceeds its verification bound.");
102
+ const rows = [];
103
+ for (const name4 of names) {
104
+ let handle;
105
+ try {
106
+ handle = await fs.open(path.join(this.dir, name4), constants.O_RDONLY | constants.O_NOFOLLOW);
107
+ await handle.chmod(384);
108
+ if ((await handle.stat()).size > 65536) throw new Error("size");
109
+ const value = JSON.parse(await handle.readFile("utf8"));
110
+ const grant = catalogGrant(value.scope, value.mode, value.revision);
111
+ if (catalogScopeKey(grant.scope) + ".json" !== name4) throw new Error("scope");
112
+ if (grant.scope.accountId === accountId2 && grant.mode !== "none") rows.push(grant);
113
+ } catch {
114
+ throw new AdportError("POLICY_VIOLATION", "Local Reddit catalog access inventory could not be verified.");
115
+ } finally {
116
+ await handle?.close();
117
+ }
118
+ }
119
+ return rows;
120
+ }
121
+ async adoptCreated(value, expectedCreationHash) {
122
+ const scope3 = catalogScope.parse(value);
123
+ if (scope3.kind !== "catalog") throw new AdportError("POLICY_VIOLATION", "Only a new exact catalog can be adopted.");
124
+ const parent = creationScope(scope3.accountId, scope3.businessId);
125
+ await fs.mkdir(this.dir, { recursive: true, mode: 448 });
126
+ await fs.chmod(this.dir, 448);
127
+ const lock = path.join(this.dir, catalogScopeKey(parent) + ".lock");
128
+ try {
129
+ await fs.mkdir(lock, { mode: 448 });
130
+ } catch {
131
+ throw new AdportError("POLICY_VIOLATION", "Catalog creation access is changing. Reconcile the known catalog before retrying.");
132
+ }
133
+ try {
134
+ const grant = await requireCatalogCreationAccess(this, parent, true);
135
+ if (grant.hash !== expectedCreationHash) throw new AdportError("POLICY_VIOLATION", "Creation delegation changed. The created catalog was not adopted.");
136
+ return await this.compareAndSet(scope3, catalogGrant(scope3).hash, "write");
137
+ } finally {
138
+ await fs.rmdir(lock);
139
+ }
140
+ }
141
+ async compareAndSet(scope3, expectedHash, mode) {
142
+ catalogGrant(scope3, mode);
143
+ if (!/^[a-f0-9]{64}$/.test(expectedHash)) throw new AdportError("INVALID_INPUT", "Read the current catalog access hash first.");
144
+ await fs.mkdir(this.dir, { recursive: true, mode: 448 });
145
+ await fs.chmod(this.dir, 448);
146
+ const lock = path.join(this.dir, catalogScopeKey(scope3) + ".lock");
147
+ try {
148
+ await fs.mkdir(lock, { mode: 448 });
149
+ } catch {
150
+ throw new AdportError("POLICY_VIOLATION", "Catalog access is being changed by another local operation. Inspect it before retrying.");
151
+ }
152
+ const temporary = path.join(this.dir, randomUUID() + ".tmp");
153
+ try {
154
+ const current = await this.get(scope3);
155
+ if (current.hash !== expectedHash) throw new AdportError("POLICY_VIOLATION", "Catalog access changed. Read and review it again.");
156
+ const next = catalogGrant(scope3, mode, current.revision + 1), handle = await fs.open(temporary, "wx", 384);
157
+ try {
158
+ await handle.writeFile(JSON.stringify(next) + "\n");
159
+ await handle.sync();
160
+ } finally {
161
+ await handle.close();
162
+ }
163
+ await fs.rename(temporary, this.file(scope3));
164
+ return next;
165
+ } finally {
166
+ await fs.unlink(temporary).catch((error) => {
167
+ if (error.code !== "ENOENT") throw error;
168
+ });
169
+ await fs.rmdir(lock);
170
+ }
171
+ }
172
+ };
173
+
1
174
  // src/client.ts
2
- import { AdportError } from "@adport/core";
175
+ import { AdportError as AdportError2 } from "@adport/core";
176
+ import { createHmac, timingSafeEqual } from "crypto";
3
177
  var REDDIT_API_VERSION = "v3";
4
178
  var REDDIT_API_BASE = `https://ads-api.reddit.com/api/${REDDIT_API_VERSION}`;
5
179
  var REDDIT_TOKEN_URL = "https://www.reddit.com/api/v1/access_token";
@@ -13,9 +187,37 @@ var RedditAdsClient = class {
13
187
  fetchImpl;
14
188
  token;
15
189
  refreshToken;
190
+ refreshing;
191
+ /** Bind account-less native async job IDs to their approved create request. */
192
+ resourceReceipt(kind, accountId2, profileId, resourceId) {
193
+ for (const value of [accountId2, profileId, resourceId]) if (!/^[A-Za-z0-9_-]{1,256}$/.test(value)) throw new AdportError2("PROVIDER_ERROR", "reddit: invalid resource ID in create receipt");
194
+ const payload = Buffer.from(JSON.stringify({ kind, account_id: accountId2, profile_id: profileId, resource_id: resourceId, expires_at: Math.floor(Date.now() / 1e3) + 86400 })).toString("base64url");
195
+ return `${payload}.${this.receiptMac(payload).toString("base64url")}`;
196
+ }
197
+ verifyResourceReceipt(receipt, kind, accountId2, resourceId) {
198
+ const invalid5 = () => new AdportError2("INVALID_INPUT", "reddit: invalid or expired resource receipt; use the receipt returned by the approved create operation");
199
+ if (receipt.length > 2048 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/.test(receipt)) throw invalid5();
200
+ const [payload, signature] = receipt.split("."), expected = this.receiptMac(payload), supplied = Buffer.from(signature, "base64url");
201
+ if (supplied.toString("base64url") !== signature || supplied.byteLength !== expected.byteLength || !timingSafeEqual(supplied, expected)) throw invalid5();
202
+ let value;
203
+ try {
204
+ value = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
205
+ } catch {
206
+ throw invalid5();
207
+ }
208
+ const data = value && typeof value === "object" && !Array.isArray(value) ? value : {};
209
+ if (data.kind !== kind || data.account_id !== accountId2 || data.resource_id !== resourceId || typeof data.profile_id !== "string" || !/^[A-Za-z0-9_-]{1,256}$/.test(data.profile_id) || typeof data.expires_at !== "number" || !Number.isSafeInteger(data.expires_at) || data.expires_at <= Math.floor(Date.now() / 1e3) || data.expires_at > Math.floor(Date.now() / 1e3) + 86400) throw invalid5();
210
+ return { profile_id: data.profile_id };
211
+ }
212
+ receiptMac(payload) {
213
+ return createHmac("sha256", this.credentials.clientSecret).update(`adport.reddit.resource.v1.${payload}`).digest();
214
+ }
215
+ diagnostic(value) {
216
+ return typeof value === "string" ? this.redact(value) : void 0;
217
+ }
16
218
  async get(pathOrUrl, params = {}) {
17
- const url = this.url(pathOrUrl, params);
18
- return this.send(url, { method: "GET" });
219
+ const url3 = this.url(pathOrUrl, params);
220
+ return this.send(url3, { method: "GET" });
19
221
  }
20
222
  async post(pathOrUrl, body) {
21
223
  return this.send(this.url(pathOrUrl), { method: "POST", body: JSON.stringify(body) });
@@ -26,30 +228,41 @@ var RedditAdsClient = class {
26
228
  async delete(pathOrUrl) {
27
229
  return this.send(this.url(pathOrUrl), { method: "DELETE" });
28
230
  }
29
- async getPaged(path, params = {}, limit = 1e3) {
231
+ async getPaged(path2, params = {}, limit = 1e3) {
232
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError2("INVALID_INPUT", "reddit: list limit must be a positive safe integer");
30
233
  const rows = [];
31
- let page = await this.get(path, params);
234
+ let url3 = this.url(path2, params);
235
+ const seen = /* @__PURE__ */ new Set();
32
236
  while (true) {
33
- rows.push(...page.data.slice(0, Math.max(0, limit - rows.length)));
34
- if (rows.length >= limit || !page.pagination?.next_url) return rows;
35
- page = await this.get(page.pagination.next_url);
237
+ if (seen.has(url3) || seen.size >= 1e3) throw new AdportError2("PROVIDER_ERROR", "reddit: pagination did not terminate");
238
+ seen.add(url3);
239
+ const page2 = await this.get(url3);
240
+ if (!Array.isArray(page2.data)) throw new AdportError2("PROVIDER_ERROR", "reddit: expected a native list response");
241
+ rows.push(...page2.data.slice(0, Math.max(0, limit - rows.length)));
242
+ if (rows.length >= limit || !page2.pagination?.next_url) return rows;
243
+ url3 = this.nextUrl(page2.pagination.next_url, url3);
36
244
  }
37
245
  }
246
+ nextUrl(next, current) {
247
+ const target = this.url(next), previous = this.url(current);
248
+ if (new URL(target).pathname !== new URL(previous).pathname) throw new AdportError2("PROVIDER_ERROR", "reddit: pagination changed resource scope");
249
+ return target;
250
+ }
38
251
  url(pathOrUrl, params = {}) {
39
- const normalized = pathOrUrl.trim();
40
- const url = normalized.startsWith("https://") ? new URL(normalized) : new URL(`${REDDIT_API_BASE}/${normalized.replace(/^\/+/, "")}`);
41
- if (url.origin !== "https://ads-api.reddit.com" || !url.pathname.startsWith("/api/v3/")) {
42
- throw new AdportError("INVALID_INPUT", "reddit: pagination or API URL must stay within https://ads-api.reddit.com/api/v3/");
252
+ const normalized2 = pathOrUrl.trim();
253
+ const url3 = normalized2.startsWith("https://") ? new URL(normalized2) : new URL(`${REDDIT_API_BASE}/${normalized2.replace(/^\/+/, "")}`);
254
+ if (url3.origin !== "https://ads-api.reddit.com" || !url3.pathname.startsWith("/api/v3/") || url3.username || url3.password || url3.hash) {
255
+ throw new AdportError2("INVALID_INPUT", "reddit: pagination or API URL must stay within https://ads-api.reddit.com/api/v3/");
43
256
  }
44
257
  for (const [key, value] of Object.entries(params)) {
45
258
  if (value === void 0) continue;
46
- url.searchParams.set(key, Array.isArray(value) ? value.join(",") : String(value));
259
+ url3.searchParams.set(key, Array.isArray(value) ? value.join(",") : String(value));
47
260
  }
48
- return url.toString();
261
+ return url3.toString();
49
262
  }
50
- async send(url, init) {
263
+ async send(url3, init) {
51
264
  const accessToken = await this.accessToken();
52
- const response = await this.fetchImpl(url, {
265
+ const response = await this.fetchImpl(url3, {
53
266
  method: init.method,
54
267
  headers: {
55
268
  authorization: `Bearer ${accessToken}`,
@@ -57,21 +270,34 @@ var RedditAdsClient = class {
57
270
  accept: "application/json",
58
271
  ...init.body ? { "content-type": "application/json" } : {}
59
272
  },
60
- body: init.body
273
+ body: init.body,
274
+ redirect: "error",
275
+ signal: AbortSignal.timeout(3e4)
61
276
  });
62
277
  const raw = await response.text();
63
- const parsed = raw ? safeJson(raw) : { data: {} };
278
+ const parsed = raw ? safeJson(raw) : response.status === 204 ? { data: {} } : void 0;
64
279
  if (!response.ok) {
65
- throw new AdportError(
280
+ const message = this.redact(redditErrorMessage(parsed));
281
+ throw new AdportError2(
66
282
  "PROVIDER_ERROR",
67
- `Reddit Ads API ${response.status} ${init.method} ${new URL(url).pathname}: ${redditErrorMessage(parsed)}`,
68
- parsed
283
+ `Reddit Ads API ${response.status} ${init.method} ${new URL(url3).pathname}: ${message}`,
284
+ { http_status: response.status, api_message: message }
69
285
  );
70
286
  }
287
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Object.hasOwn(parsed, "data")) throw new AdportError2("PROVIDER_ERROR", "reddit: malformed API response");
71
288
  return parsed;
72
289
  }
73
290
  async accessToken() {
74
291
  if (this.token && this.token.expiresAt > Date.now() + 6e4) return this.token.accessToken;
292
+ if (!this.refreshing) this.refreshing = this.refresh().finally(() => {
293
+ this.refreshing = void 0;
294
+ });
295
+ return this.refreshing;
296
+ }
297
+ redact(value) {
298
+ return [this.credentials.clientId, this.credentials.clientSecret, this.credentials.refreshToken, this.refreshToken, this.token?.accessToken, Buffer.from(`${this.credentials.clientId}:${this.credentials.clientSecret}`).toString("base64")].reduce((text3, secret) => secret ? text3.replaceAll(secret, "[redacted]") : text3, value).replace(/Bearer\s+\S+/gi, "Bearer [redacted]").replace(/\b[a-f0-9]{64}\b/gi, "[redacted hash]").replace(/([?&](?:token|sig|signature|access_token|x-amz-signature|x-goog-signature)=)[^&\s"'<>]+/gi, "$1[redacted]").slice(0, 2e3);
299
+ }
300
+ async refresh() {
75
301
  const response = await this.fetchImpl(REDDIT_TOKEN_URL, {
76
302
  method: "POST",
77
303
  headers: {
@@ -79,17 +305,19 @@ var RedditAdsClient = class {
79
305
  "content-type": "application/x-www-form-urlencoded",
80
306
  "user-agent": this.credentials.userAgent
81
307
  },
82
- body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: this.refreshToken })
308
+ body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: this.refreshToken }),
309
+ redirect: "error",
310
+ signal: AbortSignal.timeout(3e4)
83
311
  });
84
- const data = await response.json();
85
- if (!response.ok || !data.access_token) {
86
- throw new AdportError(
312
+ const raw = await response.json().catch(() => void 0);
313
+ const data = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
314
+ if (!response.ok || typeof data.access_token !== "string" || !data.access_token || data.expires_in !== void 0 && (!Number.isFinite(data.expires_in) || data.expires_in <= 0)) {
315
+ throw new AdportError2(
87
316
  "PROVIDER_ERROR",
88
- `Reddit OAuth refresh failed${data.error ? ` (${data.error})` : ""}: ${data.message ?? "no access token returned"}`,
89
- data
317
+ `Reddit OAuth refresh failed (HTTP ${response.status}); re-authorize if the existing grant was revoked or expired`
90
318
  );
91
319
  }
92
- if (data.refresh_token && data.refresh_token !== this.refreshToken) {
320
+ if (typeof data.refresh_token === "string" && data.refresh_token && data.refresh_token !== this.refreshToken) {
93
321
  this.refreshToken = data.refresh_token;
94
322
  await this.credentials.onRefreshToken?.(data.refresh_token);
95
323
  }
@@ -104,36 +332,2268 @@ function safeJson(raw) {
104
332
  try {
105
333
  return JSON.parse(raw);
106
334
  } catch {
107
- return { message: raw };
335
+ return void 0;
108
336
  }
109
337
  }
110
338
  function redditErrorMessage(value) {
111
- if (!value || typeof value !== "object") return String(value);
112
- const record = value;
113
- return String(record.message ?? record.error ?? record.detail ?? "unknown provider error");
339
+ if (!value || typeof value !== "object" || Array.isArray(value)) return "provider returned an invalid error response";
340
+ const record2 = value;
341
+ for (const key of ["message", "error", "detail"]) if (typeof record2[key] === "string") return record2[key];
342
+ const error = record2.error;
343
+ if (error && typeof error === "object" && !Array.isArray(error) && typeof error.message === "string") return error.message;
344
+ return "provider request failed";
114
345
  }
115
346
 
116
347
  // src/provider.ts
117
348
  import {
118
- AdportError as AdportError2,
349
+ AdportError as AdportError10,
119
350
  resolveDateRange
120
351
  } from "@adport/core";
352
+
353
+ // src/creatives.ts
354
+ import { AdportError as AdportError3, LocalMediaResolver, creativeStatusAction } from "@adport/core";
355
+ import { z as z4 } from "zod";
356
+
357
+ // src/creative-tools.ts
358
+ import { creativesOutput, defineTool, guardedWriteTool, mediaSourceFields } from "@adport/core";
359
+ import { z as z3 } from "zod";
360
+ var strings = z3.array(z3.string().min(1)).max(500);
361
+ var ids = z3.array(redditId).min(1).max(200);
362
+ var url = z3.string().url().max(4096).refine((value) => {
363
+ const u = new URL(value);
364
+ return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password;
365
+ }, "Use an HTTP(S) URL without embedded credentials");
366
+ var mediaUrl = url.refine((value) => {
367
+ const u = new URL(value), host = u.hostname.toLowerCase().replace(/\.$/, "");
368
+ return u.protocol === "https:" && !u.hash && host.includes(".") && !host.endsWith(".local") && !host.endsWith(".localhost") && !/^[\d.]+$/.test(host) && !host.includes(":");
369
+ }, "Use an externally accessible HTTPS media hostname");
370
+ var name = z3.string().trim().min(1);
371
+ var headline = z3.string().min(1).max(300);
372
+ var copy = z3.string().max(4e4);
373
+ var cta = z3.string().regex(/^[A-Z_]+$/);
374
+ var targeting = z3.object({ carriers: strings.nullable().optional(), communities: strings.optional(), custom_audience_ids: strings.optional(), excluded_communities: strings.optional(), excluded_custom_audience_ids: strings.optional(), excluded_geolocations: strings.optional(), excluded_interests: strings.optional(), excluded_keywords: strings.optional(), expand_targeting: z3.boolean().nullable().optional(), gender: z3.enum(["FEMALE", "MALE"]).nullable().optional(), geolocations: strings.optional(), interests: strings.optional(), keywords: strings.optional(), locations: z3.array(z3.enum(["FEED", "COMMENTS_PAGE"])).optional(), platforms: z3.array(z3.enum(["ALL", "DESKTOP", "MOBILE_NATIVE", "MOBILE_WEB", "MOBILE_WEB_3X", "SHREDTOP"])).optional(), suppression_event_types: z3.array(z3.literal("ALL_FEATURES")).optional(), view_modes: z3.array(z3.enum(["ALL", "CARD", "CLASSIC", "COMPACT", "IMMERSIVE"])).optional(), languages: strings.nullable().optional(), devices: z3.array(z3.object({ type: z3.enum(["DESKTOP", "MOBILE"]), os: z3.enum(["ANDROID", "IOS"]).nullable().optional(), min_version: z3.string().nullable().optional(), max_version: z3.string().nullable().optional(), label_map: z3.record(z3.string(), strings).nullable().optional() }).strict()).optional() }).strict();
375
+ var dates = { start_time: z3.iso.datetime({ offset: true }).nullable().optional(), end_time: z3.iso.datetime({ offset: true }).nullable().optional() };
376
+ var bidStrategy = z3.enum(["BIDLESS", "MANUAL_BIDDING", "MAXIMIZE_VOLUME", "TARGET_CPX"]);
377
+ var bidType = z3.enum(["CPC", "CPM", "CPV", "CPV6", "CPV15"]);
378
+ var createGroup = z3.object({ campaign_id: redditId, name, configured_status: status.default("PAUSED"), targeting, bid_strategy: bidStrategy.nullable(), bid_type: bidType.nullable(), bid_micros: micros.positive().optional(), budget_micros: micros.positive().optional(), budget_type: z3.enum(["DAILY_SPEND", "LIFETIME_SPEND"]).optional(), ...dates, optimization_goal: z3.string().regex(/^[A-Z0-9_]+$/).nullable().optional(), conversion_pixel_id: redditId.optional(), app_id: redditId.optional(), saved_audience_id: redditId.optional() });
379
+ var updateGroup = z3.object({ ad_group_id: redditId, name: name.optional(), ...dates }).refine((v) => Object.keys(v).length > 1, "Provide an ad-group field");
380
+ var createAd = z3.object({ ad_group_id: redditId, post_id: z3.string().regex(/^t3_[A-Za-z0-9]+$/), name, configured_status: status.default("PAUSED"), click_url: url.optional(), click_url_query_parameters: z3.string().optional() });
381
+ var updateAd = z3.object({ ad_id: redditId, name: name.optional(), post_id: z3.string().regex(/^t3_[A-Za-z0-9]+$/).optional(), click_url: url.optional(), click_url_query_parameters: z3.string().optional() }).refine((v) => Object.keys(v).length > 1, "Provide an ad field");
382
+ var source = { ...mediaSourceFields };
383
+ var uploadAsset = z3.object({ profile_id: redditId, type: z3.enum(["IMAGE", "VIDEO"]), name, ...source, poster_media_id: z3.string().uuid().optional(), poster_expected_sha256: z3.string().regex(/^[a-fA-F0-9]{64}$/).optional() }).refine((v) => Boolean(v.media_id) !== Boolean(v.file_path), "Choose a project media_id or local file_path").refine((v) => v.type !== "VIDEO" || Boolean(v.poster_media_id && v.poster_expected_sha256), "Video requires an approved project poster image");
384
+ var importAsset = z3.object({ profile_id: redditId, type: z3.enum(["IMAGE", "VIDEO"]), name, media_url: mediaUrl, poster_url: mediaUrl.optional() }).refine((v) => v.type !== "VIDEO" || Boolean(v.poster_url), "Video requires poster_url");
385
+ var textAsset = z3.object({ profile_id: redditId, type: z3.enum(["HEADLINE", "CTA"]), text: headline.optional(), call_to_action: cta.optional() }).refine((v) => v.type === "HEADLINE" ? Boolean(v.text) && !v.call_to_action : Boolean(v.call_to_action) && !v.text, "Provide text for HEADLINE or call_to_action for CTA");
386
+ var createPost = z3.object({ profile_id: redditId, type: z3.enum(["TEXT", "IMAGE", "VIDEO", "CAROUSEL"]), headline, body: copy.optional(), allow_comments: z3.boolean().default(false), destination_url: url.optional(), call_to_action: cta.optional(), image_asset_id: redditId.optional(), video_asset_id: redditId.optional(), thumbnail_asset_id: redditId.optional(), carousel: z3.array(z3.object({ image_asset_id: redditId, destination_url: url, call_to_action: cta.optional(), caption: z3.string().max(180).optional() }).strict()).min(1).max(40).optional() }).refine((v) => v.type !== "TEXT" || Boolean(v.body), "TEXT requires body").refine((v) => v.type !== "IMAGE" || Boolean(v.image_asset_id && v.destination_url), "IMAGE requires an owned image and destination").refine((v) => v.type !== "VIDEO" || Boolean(v.video_asset_id && v.thumbnail_asset_id), "VIDEO requires an owned video and thumbnail").refine((v) => v.type !== "CAROUSEL" || Boolean(v.carousel?.length), "CAROUSEL requires cards");
387
+ var stageCopy = z3.object({ ad_id: redditId, source_post_id: z3.string().regex(/^t3_[A-Za-z0-9]+$/), profile_id: redditId, headline: headline.optional(), body: copy.optional() }).refine((v) => v.headline !== void 0 || v.body !== void 0, "Provide headline or body edits");
388
+ function redditCreativeTools(provider) {
389
+ const account = { account_id: redditId }, page2 = { page_size: z3.number().int().min(1).max(1e3).default(50), cursor: z3.string().url().optional().describe("Native next_url returned as next_cursor; followed exactly within the same resource") };
390
+ const read = (name4, description, input, handler) => defineTool({ name: name4, namespace: "reddit", description, input, annotations: { readOnly: true }, handler });
391
+ const write2 = (name4, description, payload, kind = "update") => guardedWriteTool({ name: name4, namespace: "reddit", provider: "reddit", description, payload, kind });
392
+ return [
393
+ read("reddit_get_entity", "Read a native campaign, ad group or ad by ID and verify the selected account and parent hierarchy.", z3.object({ ...account, entity: z3.enum(["campaigns", "ad_groups", "ads"]), resource_id: redditId }), (v) => provider.creatives.owned(v.account_id, v.entity, v.resource_id)),
394
+ read("reddit_ad_groups", "Read account ad-group configuration, targeting, bids and budgets with native pagination.", z3.object({ ...account, campaign_id: redditId.optional(), ad_group_ids: ids.optional(), ...page2 }), (v) => provider.creatives.groups(v)),
395
+ defineTool({ name: "reddit_ads", namespace: "reddit", description: "View account ad settings and referenced structured-post copy/media. Creative edit actions stage a separate copy; original posts remain unchanged.", input: z3.object({ ...account, ad_ids: ids.optional(), ad_group_ids: ids.optional(), campaign_ids: ids.optional(), include_post_details: z3.boolean().default(true), ...page2, page_size: z3.number().int().min(1).max(50).default(20) }), output: creativesOutput.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations: { readOnly: true }, handler: (v) => provider.creatives.ads(v) }),
396
+ read("reddit_profiles", "List profiles already associated with this ad account, including native profile IDs and Reddit user IDs.", z3.object(account), (v) => provider.creatives.profiles(v.account_id)),
397
+ defineTool({ name: "reddit_posts", namespace: "reddit", description: "View structured-post copy/media belonging to an account-associated profile, including unattached posts staged for review.", input: z3.object({ ...account, profile_id: redditId, ...page2, page_size: z3.number().int().min(1).max(50).default(20) }), output: creativesOutput.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations: { readOnly: true }, handler: (v) => provider.creatives.posts(v) }),
398
+ defineTool({ name: "reddit_assets", namespace: "reddit", description: "View an associated profile\u2019s native image/video/headline/CTA asset library and processing readiness.", input: z3.object({ ...account, profile_id: redditId, ...page2, page_size: z3.number().int().min(1).max(50).default(20) }), output: creativesOutput.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations: { readOnly: true }, handler: (v) => provider.creatives.assets(v) }),
399
+ read("reddit_post_job", "Read a created post job using its account-bound resource_receipt. Rechecks current profile association; arbitrary global job IDs are rejected.", z3.object({ ...account, job_id: redditId, resource_receipt: z3.string().max(2048) }), (v) => provider.creatives.postJob(v)),
400
+ read("reddit_asset_upload_status", "Read native asset-processing status using the account-bound resource_receipt from its approved upload.", z3.object({ ...account, upload_id: redditId, resource_receipt: z3.string().max(2048) }), (v) => provider.creatives.uploadStatus(v)),
401
+ read("reddit_targeting_options", "Read native carriers, communities/search, devices, geolocations, interests, languages and third-party audience choices.", z3.object({ ...account, dimension: z3.enum(["carriers", "communities", "communities_search", "devices", "geolocations", "interests", "languages", "third_party_audiences"]), query: z3.string().optional(), country: z3.string().optional(), postal_code: z3.string().optional(), cities_search: z3.string().optional(), ...page2 }), (v) => provider.creatives.targetingOptions(v)),
402
+ write2("reddit_create_ad_group", "Create a MANUAL ad group, paused by policy. Non-CBO groups require an explicit budget and bid settings; pass null bid fields only to inherit CBO settings.", createGroup, "create"),
403
+ write2("reddit_update_ad_group", "Patch an owned ad group\u2019s supplied name/start/end fields while preserving omitted settings.", updateGroup),
404
+ write2("reddit_update_targeting", "Edit supplied targeting dimensions, preserving omitted dimensions and replacing supplied arrays. Explicit expansion settings are retained.", z3.object({ ad_group_id: redditId, targeting }).refine((v) => Object.keys(v.targeting).length > 0, "Provide targeting dimensions")),
405
+ write2("reddit_set_ad_group_budget", "Change a non-CBO ad-group budget in integer micros using the current value; preserves its daily/lifetime type.", z3.object({ ad_group_id: redditId, budget_micros: micros.positive() })),
406
+ write2("reddit_set_ad_group_bidding", "Change a non-CBO strategy/monetary bid in integer micros. Removing an existing monetary cap is rejected until policy can represent an unbounded change.", z3.object({ ad_group_id: redditId, bid_strategy: bidStrategy.optional(), bid_micros: micros.positive().optional() }).refine((v) => Boolean(v.bid_strategy || v.bid_micros), "Provide a bidding field")),
407
+ write2("reddit_create_ad", "Create a paused ad from an account-owned ad group and an eligible post; verifies referenced profile/content before creation.", createAd, "create"),
408
+ write2("reddit_update_ad", "Patch name, destination or post reference on one verified ad. A post replacement preserves configured status and can trigger review.", updateAd),
409
+ ...["ad_group", "ad"].map((entity) => write2(`reddit_set_${entity}_status`, "Pause or activate a child after verifying its entire account/parent hierarchy.", z3.object({ [entity === "ad" ? "ad_id" : "ad_group_id"]: redditId, configured_status: status }))),
410
+ write2("reddit_archive_entity", "Archive a verified campaign/ad group/ad using native PATCH; this changes delivery without inventing an unsupported DELETE endpoint.", z3.object({ entity: z3.enum(["campaigns", "ad_groups", "ads"]), resource_id: redditId })),
411
+ write2("reddit_upload_asset", "Stage checksum-bound project image/video bytes for Reddit\u2019s URL-pull asset processor. Requires a hosted immutable media resolver; private source URLs are omitted from previews.", uploadAsset, "create"),
412
+ write2("reddit_import_asset_url", "Ask Reddit to import an existing HTTPS image/video URL. Approval binds the URL, not mutable remote bytes; prefer reddit_upload_asset for exact project files. No file is fetched by Adport.", importAsset, "create"),
413
+ write2("reddit_create_text_asset", "Create a headline or CTA asset through the native asset-processing API. Does not create or activate an ad.", textAsset, "create"),
414
+ write2("reddit_rename_asset", "Rename an asset in an account-associated profile library; the name is shared by users of that profile.", z3.object({ profile_id: redditId, creative_asset_id: redditId, name })),
415
+ write2("reddit_delete_asset", "Permanently remove an asset from an account-associated profile library. Review shared profile usage before approval.", z3.object({ profile_id: redditId, creative_asset_id: redditId }), "remove"),
416
+ write2("reddit_create_post", "Create an async structured advertising-post job from owned ready assets. Comments default off. Ad creation and activation remain separate approvals.", createPost, "create"),
417
+ write2("reddit_stage_post_copy", "Stage a new structured-post copy for one verified ad with supplied headline/body edits. Does not mutate the original post or attach the result to the ad.", stageCopy, "create")
418
+ ];
419
+ }
420
+
421
+ // src/creatives.ts
422
+ var rowSchema = z4.looseObject({ id: redditId });
423
+ var record = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
424
+ var string = (v) => typeof v === "string" && Boolean(v);
425
+ var safeUrl = (v) => {
426
+ if (!string(v)) return void 0;
427
+ try {
428
+ const u = new URL(v);
429
+ return u.protocol === "https:" && !u.username && !u.password ? v : void 0;
430
+ } catch {
431
+ return void 0;
432
+ }
433
+ };
434
+ var landing = (v) => {
435
+ if (!string(v)) return [];
436
+ try {
437
+ const u = new URL(v);
438
+ return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password ? [v] : [];
439
+ } catch {
440
+ return [];
441
+ }
442
+ };
443
+ var RedditCreativeService = class {
444
+ constructor(client, media = new LocalMediaResolver()) {
445
+ this.client = client;
446
+ this.media = media;
447
+ }
448
+ client;
449
+ media;
450
+ async one(path2) {
451
+ const result = await this.client.get(path2), parsed = rowSchema.safeParse(result.data);
452
+ if (!parsed.success) throw new AdportError3("PROVIDER_ERROR", "reddit: malformed entity response");
453
+ return parsed.data;
454
+ }
455
+ async owned(account, entity, resource2) {
456
+ redditId.parse(account);
457
+ redditId.parse(resource2);
458
+ const row2 = await this.one(`${entity}/${resource2}`);
459
+ if (row2.id !== resource2 || row2.ad_account_id !== void 0 && row2.ad_account_id !== account) throw new AdportError3("INVALID_INPUT", "reddit: entity ID/account ownership mismatch");
460
+ if (entity === "campaigns") {
461
+ if (row2.ad_account_id !== account) throw new AdportError3("INVALID_INPUT", "reddit: campaign is not owned by this account");
462
+ } else if (entity === "ad_groups") await this.owned(account, "campaigns", redditId.parse(row2.campaign_id));
463
+ else {
464
+ const parent = await this.owned(account, "ad_groups", redditId.parse(row2.ad_group_id));
465
+ if (row2.campaign_id !== void 0 && row2.campaign_id !== parent.campaign_id) throw new AdportError3("PROVIDER_ERROR", "reddit: ad parent hierarchy mismatch");
466
+ }
467
+ return row2;
468
+ }
469
+ async page(path2, input, params = {}) {
470
+ const url3 = input.cursor ? this.client.nextUrl(input.cursor, path2) : path2;
471
+ const data = await this.client.get(url3, input.cursor ? {} : { ...params, "page.size": input.page_size });
472
+ if (!Array.isArray(data.data) || data.data.some((row2) => !row2 || typeof row2 !== "object" || Array.isArray(row2))) throw new AdportError3("PROVIDER_ERROR", "reddit: malformed collection response");
473
+ const next = data.pagination?.next_url ? this.client.nextUrl(data.pagination.next_url, path2) : void 0;
474
+ if (next === this.client.nextUrl(url3, path2)) throw new AdportError3("PROVIDER_ERROR", "reddit: pagination repeated the current page");
475
+ return { items: data.data, truncated: Boolean(next), ...next ? { next_cursor: next } : {} };
476
+ }
477
+ async profiles(account) {
478
+ const rows = await this.client.getPaged(`ad_accounts/${redditId.parse(account)}/profiles`, { "page.size": 100 }, 5e3);
479
+ return rows.map((row2) => rowSchema.parse(row2));
480
+ }
481
+ async profile(account, profileId) {
482
+ const rows = (await this.profiles(account)).filter((row2) => row2.id === profileId || row2.reddit_user_id === profileId);
483
+ if (rows.length !== 1) throw new AdportError3("INVALID_INPUT", "reddit: profile is not unambiguously associated with the selected account");
484
+ return rows[0];
485
+ }
486
+ profileMatch(value, profile) {
487
+ return value === profile.id || value === profile.reddit_user_id;
488
+ }
489
+ async groups(input) {
490
+ if (input.campaign_id) await this.owned(input.account_id, "campaigns", input.campaign_id);
491
+ const data = await this.page(`ad_accounts/${redditId.parse(input.account_id)}/ad_groups`, input, { campaign_id: input.campaign_id, id: input.ad_group_ids });
492
+ data.items.forEach((row2) => rowSchema.parse(row2));
493
+ if (data.items.some((row2) => row2.ad_account_id !== void 0 && row2.ad_account_id !== input.account_id || input.campaign_id && row2.campaign_id !== input.campaign_id)) throw new AdportError3("PROVIDER_ERROR", "reddit: ad-group collection account/parent mismatch");
494
+ return data;
495
+ }
496
+ async post(postId) {
497
+ if (!/^t3_[A-Za-z0-9]+$/.test(postId)) throw new AdportError3("INVALID_INPUT", "reddit: invalid post ID");
498
+ let row2;
499
+ try {
500
+ row2 = await this.one(`structured_posts/${postId}`);
501
+ } catch (error) {
502
+ if (!(error instanceof AdportError3) || record(error.details).http_status !== 404) throw error;
503
+ row2 = await this.one(`posts/${postId}`);
504
+ }
505
+ if (row2.id !== postId) throw new AdportError3("PROVIDER_ERROR", "reddit: post ID mismatch");
506
+ return row2;
507
+ }
508
+ async ownedPost(account, postId) {
509
+ const profiles = await this.profiles(account), row2 = await this.post(postId);
510
+ if (!profiles.some((profile) => this.profileMatch(row2.profile_id, profile))) throw new AdportError3("INVALID_INPUT", "reddit: post author is not associated with this account");
511
+ return row2;
512
+ }
513
+ async assertPostOwned(account, postId) {
514
+ await this.ownedPost(account, postId);
515
+ }
516
+ async assertProfileAvailable(account, profileId) {
517
+ await this.profile(account, profileId);
518
+ }
519
+ async assertTargetingAvailable(account, value) {
520
+ await this.verifyTargeting(account, targeting.parse(value));
521
+ }
522
+ async posts(input) {
523
+ const profile = await this.profile(input.account_id, input.profile_id), data = await this.page(`profiles/${profile.id}/structured_posts`, input);
524
+ if (data.items.some((row2) => !rowSchema.safeParse(row2).success || !this.profileMatch(row2.profile_id, profile))) throw new AdportError3("PROVIDER_ERROR", "reddit: post collection profile mismatch");
525
+ const creatives = data.items.map((row2) => {
526
+ const content = record(row2.creative), title = string(content.headline) ? content.headline : String(row2.id);
527
+ return { id: String(row2.id), provider: "reddit", account_id: input.account_id, name: title, type: String(content.type ?? "POST"), headlines: [title], descriptions: string(content.body) ? [content.body] : [], landing_urls: landing(record(content.destination).url), media: postMedia(content, row2), actions: [] };
528
+ });
529
+ return { ...data, creatives };
530
+ }
531
+ async asset(account, profileId, assetId) {
532
+ const profile = await this.profile(account, profileId);
533
+ const rows = await this.client.getPaged(`profiles/${profile.id}/creative_assets`, { "page.size": 1e3 }, 5e3);
534
+ const asset = rows.map((row2) => record(row2.result)).find((row2) => row2.id === assetId);
535
+ if (!asset) throw new AdportError3("INVALID_INPUT", "reddit: asset is not in the associated profile\u2019s first5000library entries");
536
+ return { profile, asset };
537
+ }
538
+ async readyAsset(account, profile, assetId, type) {
539
+ const { asset } = await this.asset(account, profile, assetId);
540
+ if (asset.type !== type || !["ACTIVE", "DUPLICATE_ASSET"].includes(String(asset.status))) throw new AdportError3("INVALID_INPUT", "reddit: asset is not ready or has the wrong type");
541
+ const url3 = safeUrl(record(asset.media).permanent_url) ?? safeUrl(record(asset.media).url);
542
+ if (!url3) throw new AdportError3("INVALID_INPUT", "reddit: asset has no usable HTTPS media URL");
543
+ return { media: { type: "URL", url: url3 } };
544
+ }
545
+ async assets(input) {
546
+ const profile = await this.profile(input.account_id, input.profile_id), data = await this.page(`profiles/${profile.id}/creative_assets`, input);
547
+ const items = data.items.map((row2) => rowSchema.parse(row2.result));
548
+ const creatives = items.map((row2) => {
549
+ const url3 = safeUrl(record(row2.media).permanent_url) ?? safeUrl(record(row2.media).url);
550
+ return { id: row2.id, provider: "reddit", account_id: input.account_id, name: String(row2.name ?? row2.text ?? row2.call_to_action ?? row2.id), type: `${row2.type}_ASSET`, ...string(row2.status) ? { status: row2.status } : {}, headlines: string(row2.text) ? [row2.text] : [], descriptions: [`Library readiness: ${row2.status ?? "unknown"}`, ...string(row2.call_to_action) ? [row2.call_to_action] : []], landing_urls: [], media: url3 && ["IMAGE", "VIDEO"].includes(String(row2.type)) ? [{ type: row2.type === "VIDEO" ? "video" : "image", url: url3 }] : [], actions: row2.status === "DELETED" ? [] : [{ label: "Rename shared profile asset", tool: "reddit_rename_asset", arguments: { account_id: input.account_id, profile_id: profile.id, creative_asset_id: row2.id }, fields: [{ key: "name", label: "Asset name", type: "text", value: String(row2.name ?? "") }] }] };
551
+ });
552
+ return { ...data, items, creatives };
553
+ }
554
+ async ads(input) {
555
+ const data = await this.page(`ad_accounts/${redditId.parse(input.account_id)}/ads`, input, { id: input.ad_ids, ad_group_id: input.ad_group_ids, campaign_id: input.campaign_ids });
556
+ data.items.forEach((row2) => rowSchema.parse(row2));
557
+ if (data.items.some((row2) => row2.ad_account_id !== input.account_id)) throw new AdportError3("PROVIDER_ERROR", "reddit: ad collection returned another account");
558
+ const posts = /* @__PURE__ */ new Map(), warnings = [], profiles = input.include_post_details ? await this.profiles(input.account_id) : [];
559
+ const postIds = [...new Set(data.items.map((row2) => row2.post_id).filter(string))];
560
+ let cursor = 0;
561
+ if (input.include_post_details) await Promise.all(Array.from({ length: Math.min(4, postIds.length) }, async () => {
562
+ while (cursor < postIds.length) {
563
+ const postId = postIds[cursor++];
564
+ try {
565
+ posts.set(postId, await this.post(postId));
566
+ } catch (error) {
567
+ warnings.push({ provider: "reddit", message: `Referenced post ${postId} unavailable: ${error instanceof Error ? error.message : "provider read failed"}` });
568
+ }
569
+ }
570
+ }));
571
+ const creatives = data.items.map((row2) => {
572
+ const post = posts.get(String(row2.post_id)), content = record(post?.creative), profile = profiles.find((profile2) => this.profileMatch(post?.profile_id, profile2)), args = { account_id: input.account_id, ad_id: row2.id };
573
+ const status2 = String(row2.configured_status ?? ""), body = string(content.body) ? content.body : string(post?.body) ? post.body : void 0;
574
+ const title = string(content.headline) ? content.headline : string(post?.headline) ? post.headline : void 0;
575
+ const actions = ["ACTIVE", "PAUSED"].includes(status2) ? [creativeStatusAction("reddit_set_ad_status", args, status2, ["ACTIVE", "PAUSED"]), { label: "Edit ad name", tool: "reddit_update_ad", arguments: args, fields: [{ key: "name", label: "Ad name", type: "text", value: String(row2.name ?? "") }] }] : [];
576
+ if (profile && ["TEXT", "IMAGE", "VIDEO", "CAROUSEL"].includes(String(content.type)) && !["ARCHIVED", "DELETED"].includes(status2)) actions.push({ label: "Stage a creative copy", tool: "reddit_stage_post_copy", arguments: { ...args, source_post_id: row2.post_id, profile_id: profile.id }, fields: [{ key: "headline", label: "Headline", type: "text", value: title ?? "", max_length: 300 }, ...body ? [{ key: "body", label: "Body", type: "text", value: body, max_length: 4e4 }] : []] });
577
+ return { id: String(row2.id), provider: "reddit", account_id: input.account_id, name: String(row2.name ?? row2.id), type: String(content.type ?? "POST_AD"), status: status2, ...string(row2.campaign_id) ? { campaign_id: row2.campaign_id } : {}, ...string(row2.ad_group_id) ? { ad_group_id: row2.ad_group_id } : {}, headlines: title ? [title] : [], descriptions: body ? [body] : [], landing_urls: landing(row2.click_url).length ? landing(row2.click_url) : landing(record(content.destination).url), media: postMedia(content, post), actions };
578
+ });
579
+ return { ...data, creatives, warnings };
580
+ }
581
+ async postJob(input) {
582
+ const bound = this.client.verifyResourceReceipt(input.resource_receipt, "post_job", input.account_id, input.job_id), profile = await this.profile(input.account_id, bound.profile_id), row2 = await this.one(`structured_posts/jobs/${redditId.parse(input.job_id)}`);
583
+ if (row2.id !== input.job_id || !["PROCESSING", "SUCCESS", "CLIENT_ERROR", "SERVER_ERROR", "QUEUED"].includes(String(row2.status))) throw new AdportError3("PROVIDER_ERROR", "reddit: post job receipt ID/status mismatch");
584
+ if (row2.status === "SUCCESS") {
585
+ const post = await this.post(String(row2.post_id));
586
+ if (!this.profileMatch(post.profile_id, profile)) throw new AdportError3("PROVIDER_ERROR", "reddit: created post belongs to a different profile");
587
+ }
588
+ return { job_id: row2.id, status: row2.status, post_id: row2.post_id ?? null, ...this.client.diagnostic(row2.error_message) ? { error_message: this.client.diagnostic(row2.error_message) } : {} };
589
+ }
590
+ async uploadStatus(input) {
591
+ const bound = this.client.verifyResourceReceipt(input.resource_receipt, "asset_upload", input.account_id, input.upload_id);
592
+ await this.profile(input.account_id, bound.profile_id);
593
+ const row2 = await this.one(`creative_assets/uploads/${redditId.parse(input.upload_id)}`);
594
+ if (row2.id !== input.upload_id || !["PROCESSING_MEDIA", "ACTIVE", "INVALID_MEDIA"].includes(String(row2.status))) throw new AdportError3("PROVIDER_ERROR", "reddit: asset upload receipt ID/status mismatch");
595
+ if (row2.status !== "PROCESSING_MEDIA" && (!rowSchema.safeParse(row2.result).success || !["IMAGE", "VIDEO", "HEADLINE", "CTA"].includes(String(record(row2.result).type)))) throw new AdportError3("PROVIDER_ERROR", "reddit: completed asset upload is missing a valid stored asset");
596
+ return { upload_id: row2.id, status: row2.status, ...row2.result ? { result: row2.result } : {}, ...record(row2.result).status === "DUPLICATE_ASSET" ? { warning: "Reddit reused an existing asset. This is not proof that the asset was newly created." } : {} };
597
+ }
598
+ async targetingOptions(input) {
599
+ redditId.parse(input.account_id);
600
+ const dimensions = ["carriers", "communities", "communities_search", "devices", "geolocations", "interests", "languages", "third_party_audiences"];
601
+ if (!dimensions.includes(input.dimension)) throw new AdportError3("INVALID_INPUT", "reddit: unsupported targeting dimension");
602
+ const path2 = `targeting/${input.dimension === "communities_search" ? "communities/search" : input.dimension}`;
603
+ if (["geolocations", "interests"].includes(input.dimension)) {
604
+ if (input.cursor) throw new AdportError3("INVALID_INPUT", "reddit: this native dimension is not paginated; narrow its query instead");
605
+ const data = await this.client.get(path2, input.dimension === "geolocations" ? { country: input.country, postal_code: input.postal_code, cities_search: input.cities_search } : {});
606
+ if (!Array.isArray(data.data) || data.data.some((row2) => !row2 || typeof row2 !== "object" || Array.isArray(row2))) throw new AdportError3("PROVIDER_ERROR", "reddit: malformed targeting choices");
607
+ return { items: data.data.slice(0, input.page_size), truncated: data.data.length > input.page_size, ...data.data.length > input.page_size ? { warning: "Native endpoint has no pagination. Narrow the filter or increase page_size to inspect more choices." } : {} };
608
+ }
609
+ return this.page(path2, input, { ...input.dimension === "communities_search" ? { query: input.query } : {}, ...input.dimension === "geolocations" ? { country: input.country, postal_code: input.postal_code, cities_search: input.cities_search } : {} });
610
+ }
611
+ async verifyTargeting(account, value) {
612
+ const references = [...Array.isArray(value.custom_audience_ids) ? value.custom_audience_ids : [], ...Array.isArray(value.excluded_custom_audience_ids) ? value.excluded_custom_audience_ids : []];
613
+ if (references.length) {
614
+ const audiences = await this.client.getPaged(`ad_accounts/${account}/custom_audiences`, { "page.size": 1e3 }, 5e3), known = new Set(audiences.map((row2) => row2.id));
615
+ if (references.some((value2) => !known.has(value2))) throw new AdportError3("INVALID_INPUT", "reddit: targeting audience is not available to this account");
616
+ }
617
+ }
618
+ async mutation(account, path2, method, fields, expected) {
619
+ const response = method === "POST" ? await this.client.post(path2, { data: fields }) : await this.client.patch(path2, { data: fields }), row2 = record(response.data), ids2 = string(row2.id) ? [row2.id] : [];
620
+ if (ids2.length !== 1 || row2.ad_account_id !== account || Object.entries(expected).some(([key, value]) => value !== void 0 && (key === "targeting" ? !targetingMatches(row2[key], value) : ["start_time", "end_time"].includes(key) && value !== null ? Date.parse(String(row2[key])) !== Date.parse(String(value)) : row2[key] !== value))) throw new AdportError3("PROVIDER_ERROR", "reddit: child receipt ID/account/status/money mismatch; reconcile before retrying", { resource_ids: ids2 });
621
+ return { applied: true, resourceIds: ids2 };
622
+ }
623
+ async assetUpload(account, profile, payload) {
624
+ const data = await this.client.post(`profiles/${profile.id}/creative_assets/uploads`, { data: [payload] });
625
+ const rows = Array.isArray(data.data) ? data.data : [], ids2 = rows.map((row2) => record(row2).id).filter(string);
626
+ if (rows.length !== 1 || ids2.length !== 1 || !redditId.safeParse(ids2[0]).success) throw new AdportError3("PROVIDER_ERROR", "reddit: asset upload did not return one native handle; reconcile before retrying", { resource_ids: ids2 });
627
+ return { applied: true, resourceIds: ids2, details: { upload_id: ids2[0], resource_receipt: this.client.resourceReceipt("asset_upload", account, String(profile.id), ids2[0]), next_tool: "reddit_asset_upload_status" } };
628
+ }
629
+ async postCreate(account, profile, payload) {
630
+ const data = await this.client.post(`profiles/${profile.id}/structured_posts/jobs`, { data: payload }), row2 = record(data.data), ids2 = string(row2.id) ? [row2.id] : [];
631
+ if (ids2.length !== 1 || !["PROCESSING", "QUEUED", "SUCCESS"].includes(String(row2.status))) throw new AdportError3("PROVIDER_ERROR", "reddit: post job was not accepted; reconcile before retrying", { resource_ids: ids2, job_status: row2.status });
632
+ return { applied: true, resourceIds: ids2, details: { job_id: row2.id, status: row2.status, resource_receipt: this.client.resourceReceipt("post_job", account, String(profile.id), ids2[0]), next_tool: "reddit_post_job" } };
633
+ }
634
+ async plan(op, guard) {
635
+ const account = redditId.parse(op.accountId), p = op.payload, expectedKind = /^reddit_(?:create_|stage_|upload_|import_)/.test(op.tool) ? "create" : op.tool === "reddit_delete_asset" ? "remove" : "update";
636
+ if (op.provider !== "reddit" || op.kind !== expectedKind) throw new AdportError3("INVALID_INPUT", "reddit: provider or write kind mismatch");
637
+ const coercions = [], budgetDeltas = [], notes3 = [];
638
+ let fields = {}, current = {}, expected = {}, path2 = "", method = "PATCH";
639
+ const paused = (value) => {
640
+ if (guard.forcePausedCreation && value !== "PAUSED") coercions.push("configured_status coerced to PAUSED by policy (paused_creation)");
641
+ return guard.forcePausedCreation ? "PAUSED" : value;
642
+ };
643
+ switch (op.tool) {
644
+ case "reddit_create_ad_group": {
645
+ const input = createGroup.parse(p), parent = await this.owned(account, "campaigns", input.campaign_id);
646
+ if (parent.type === "AUTOMATED" || parent.is_max === true) throw new AdportError3("INVALID_INPUT", "reddit: this tool creates MANUAL ad groups; Reddit Max requires its own authoring flow");
647
+ await this.verifyTargeting(account, input.targeting);
648
+ const cbo = parent.is_campaign_budget_optimization === true;
649
+ if (cbo && (input.budget_micros !== void 0 || input.bid_micros !== void 0 || input.bid_type !== null || input.bid_strategy !== null)) throw new AdportError3("INVALID_INPUT", "reddit: CBO ad groups inherit budget/bidding; use null bid settings and omit child money");
650
+ if (!cbo && (!input.budget_micros || !input.budget_type || !input.bid_type || !input.bid_strategy || input.bid_strategy !== "BIDLESS" && !input.bid_micros)) throw new AdportError3("INVALID_INPUT", "reddit: non-CBO ad groups require explicit budget, budget type, bid type and bidding settings");
651
+ if (input.bid_strategy === "BIDLESS" && input.bid_micros) throw new AdportError3("INVALID_INPUT", "reddit: BIDLESS requires no monetary bid");
652
+ if (input.conversion_pixel_id) {
653
+ const pixels = await this.client.getPaged(`ad_accounts/${account}/pixels`, {}, 1e3);
654
+ if (!pixels.some((row2) => row2.id === input.conversion_pixel_id)) throw new AdportError3("INVALID_INPUT", "reddit: Pixel is not available to this account");
655
+ }
656
+ if (input.app_id) {
657
+ const apps = await this.client.getPaged(`ad_accounts/${account}/apps`, {}, 1e3);
658
+ if (!apps.some((row2) => row2.id === input.app_id)) throw new AdportError3("INVALID_INPUT", "reddit: app is not available to this account");
659
+ }
660
+ if (input.saved_audience_id) {
661
+ const audience = await this.one(`saved_audiences/${input.saved_audience_id}`);
662
+ if (audience.ad_account_id !== account) throw new AdportError3("INVALID_INPUT", "reddit: saved audience is not owned by this account");
663
+ }
664
+ const { budget_micros, budget_type, bid_micros, ...native } = input;
665
+ fields = { ...native, type: "MANUAL", configured_status: paused(input.configured_status), targeting: { expand_targeting: false, ...input.targeting }, goal_value: cbo ? null : budget_micros, goal_type: cbo ? null : budget_type, bid_value: cbo || input.bid_strategy === "BIDLESS" ? null : bid_micros };
666
+ path2 = `ad_accounts/${account}/ad_groups`;
667
+ method = "POST";
668
+ expected = { campaign_id: input.campaign_id, type: "MANUAL" };
669
+ break;
670
+ }
671
+ case "reddit_update_ad_group": {
672
+ const { ad_group_id, ...input } = updateGroup.parse(p);
673
+ current = await this.owned(account, "ad_groups", ad_group_id);
674
+ path2 = `ad_groups/${ad_group_id}`;
675
+ fields = input;
676
+ expected = { id: ad_group_id, campaign_id: current.campaign_id };
677
+ break;
678
+ }
679
+ case "reddit_update_targeting": {
680
+ const nativeId = redditId.parse(p.ad_group_id), input = targeting.parse(p.targeting);
681
+ current = await this.owned(account, "ad_groups", nativeId);
682
+ const previous = record(current.targeting);
683
+ if (!targeting.safeParse(previous).success) throw new AdportError3("INVALID_INPUT", "reddit: current targeting contains unsupported fields; refusing a partial update that could reset them");
684
+ const merged = { ...previous, ...input };
685
+ await this.verifyTargeting(account, merged);
686
+ path2 = `ad_groups/${nativeId}`;
687
+ fields = { targeting: merged };
688
+ expected = { id: nativeId, campaign_id: current.campaign_id };
689
+ break;
690
+ }
691
+ case "reddit_set_ad_group_budget":
692
+ case "reddit_set_ad_group_bidding": {
693
+ const nativeId = redditId.parse(p.ad_group_id);
694
+ current = await this.owned(account, "ad_groups", nativeId);
695
+ const parent = await this.owned(account, "campaigns", String(current.campaign_id));
696
+ if (parent.is_campaign_budget_optimization === true) throw new AdportError3("INVALID_INPUT", "reddit: CBO budgets and bidding belong to the parent campaign");
697
+ path2 = `ad_groups/${nativeId}`;
698
+ expected = { id: nativeId, campaign_id: current.campaign_id };
699
+ if (op.tool.endsWith("_budget")) {
700
+ if (!["DAILY_SPEND", "LIFETIME_SPEND"].includes(String(current.goal_type)) || !Number.isSafeInteger(current.goal_value)) throw new AdportError3("INVALID_INPUT", "reddit: current ad-group budget/type is unavailable");
701
+ fields = { goal_value: micros.positive().parse(p.budget_micros) };
702
+ } else {
703
+ const strategy = p.bid_strategy !== void 0 ? bidStrategy.parse(p.bid_strategy) : current.bid_strategy;
704
+ if (current.bid_strategy !== "BIDLESS" && (current.bid_value === void 0 || current.bid_value === null)) throw new AdportError3("INVALID_INPUT", "reddit: current monetary bid is unavailable");
705
+ if (strategy === "BIDLESS" && (p.bid_micros !== void 0 || Number(current.bid_value) > 0)) throw new AdportError3("INVALID_INPUT", "reddit: removing an existing monetary bid cap cannot be represented by the current policy; preserve a bounded bid");
706
+ if (strategy !== "BIDLESS" && !(p.bid_micros ?? current.bid_value)) throw new AdportError3("INVALID_INPUT", "reddit: the strategy requires a monetary bid");
707
+ fields = { ...p.bid_strategy !== void 0 ? { bid_strategy: strategy } : {}, ...p.bid_micros !== void 0 ? { bid_value: micros.positive().parse(p.bid_micros) } : {} };
708
+ }
709
+ break;
710
+ }
711
+ case "reddit_create_ad": {
712
+ const input = createAd.parse(p);
713
+ await this.owned(account, "ad_groups", input.ad_group_id);
714
+ await this.ownedPost(account, input.post_id);
715
+ fields = { ...input, type: "UNSPECIFIED", configured_status: paused(input.configured_status) };
716
+ path2 = `ad_accounts/${account}/ads`;
717
+ method = "POST";
718
+ expected = { ad_group_id: input.ad_group_id, post_id: input.post_id };
719
+ break;
720
+ }
721
+ case "reddit_update_ad": {
722
+ const { ad_id, ...input } = updateAd.parse(p);
723
+ current = await this.owned(account, "ads", ad_id);
724
+ if (input.post_id) {
725
+ if (!["ACTIVE", "PAUSED"].includes(String(current.configured_status))) throw new AdportError3("INVALID_INPUT", "reddit: creative replacement requires a readable ACTIVE/PAUSED configured status");
726
+ await this.ownedPost(account, input.post_id);
727
+ expected.configured_status = current.configured_status;
728
+ notes3.push(`Post replacement preserves configured status ${current.configured_status} and can trigger review.`);
729
+ }
730
+ fields = input;
731
+ path2 = `ads/${ad_id}`;
732
+ expected = { ...expected, id: ad_id, ad_group_id: current.ad_group_id };
733
+ break;
734
+ }
735
+ case "reddit_set_ad_status":
736
+ case "reddit_set_ad_group_status": {
737
+ const entity = op.tool === "reddit_set_ad_status" ? "ads" : "ad_groups", nativeId = redditId.parse(p[entity === "ads" ? "ad_id" : "ad_group_id"]);
738
+ current = await this.owned(account, entity, nativeId);
739
+ path2 = `${entity}/${nativeId}`;
740
+ fields = { configured_status: z4.enum(["ACTIVE", "PAUSED"]).parse(p.configured_status) };
741
+ expected = { id: nativeId };
742
+ break;
743
+ }
744
+ case "reddit_archive_entity": {
745
+ const entity = z4.enum(["campaigns", "ad_groups", "ads"]).parse(p.entity), nativeId = redditId.parse(p.resource_id);
746
+ current = await this.owned(account, entity, nativeId);
747
+ path2 = `${entity}/${nativeId}`;
748
+ fields = { configured_status: "ARCHIVED" };
749
+ expected = { id: nativeId };
750
+ break;
751
+ }
752
+ case "reddit_upload_asset": {
753
+ const input = uploadAsset.parse(p), profile = await this.profile(account, input.profile_id);
754
+ if (!this.media.providerUrl) throw new AdportError3("INVALID_INPUT", "reddit: exact-file uploads require a hosted immutable media source. Local CLI can use reddit_import_asset_url for an existing HTTPS asset.");
755
+ const options = { maxBytes: 100 * 1024 * 1024, contentTypes: input.type === "IMAGE" ? ["image/png", "image/jpeg", "image/webp"] : ["video/mp4", "video/quicktime"] };
756
+ const file = await this.media.read(input, options), poster = input.type === "VIDEO" ? { media_id: input.poster_media_id, expected_sha256: input.poster_expected_sha256 } : void 0;
757
+ if (poster) await this.media.read(poster, { contentTypes: ["image/png", "image/jpeg", "image/webp"] });
758
+ return { summary: `Import approved Reddit ${input.type} asset`, changes: [`Profile ${profile.id}; ${file.name}, ${file.bytes.byteLength}bytes, SHA-256 ${file.sha256}. Reddit downloads a temporary immutable project source after approval; no ad is created.`], coercions, budgetDeltas, execute: async () => {
759
+ const source2 = await this.media.providerUrl(input, options), payload = { type: input.type, name: input.name, media: { type: "URL", url: source2.url } };
760
+ if (source2.sha256 !== file.sha256 || !safeUrl(source2.url) || !Number.isFinite(Date.parse(source2.expires_at)) || Date.parse(source2.expires_at) <= Date.now()) throw new AdportError3("INVALID_INPUT", "reddit: invalid or changed immutable provider media source");
761
+ if (poster) {
762
+ const image = await this.media.providerUrl(poster, { contentTypes: ["image/png", "image/jpeg", "image/webp"] });
763
+ if (image.sha256 !== poster.expected_sha256.toLowerCase() || !safeUrl(image.url) || !Number.isFinite(Date.parse(image.expires_at)) || Date.parse(image.expires_at) <= Date.now()) throw new AdportError3("INVALID_INPUT", "reddit: invalid poster source");
764
+ payload.poster = { type: "URL", url: image.url };
765
+ }
766
+ return this.assetUpload(account, profile, payload);
767
+ } };
768
+ }
769
+ case "reddit_import_asset_url": {
770
+ const input = importAsset.parse(p), profile = await this.profile(account, input.profile_id), payload = { name: input.name, type: input.type, media: { type: "URL", url: input.media_url }, ...input.poster_url ? { poster: { type: "URL", url: input.poster_url } } : {} };
771
+ return { summary: "Import a Reddit media URL", changes: [`Reddit fetches the supplied URL; approval binds this URL rather than remote bytes: ${JSON.stringify(payload)}`], coercions, budgetDeltas, execute: () => this.assetUpload(account, profile, payload) };
772
+ }
773
+ case "reddit_create_text_asset": {
774
+ const { profile_id, ...input } = textAsset.parse(p), profile = await this.profile(account, profile_id);
775
+ return { summary: `Create Reddit ${input.type} asset`, changes: [JSON.stringify(input)], coercions, budgetDeltas, execute: () => this.assetUpload(account, profile, input) };
776
+ }
777
+ case "reddit_rename_asset":
778
+ case "reddit_delete_asset": {
779
+ const assetId = redditId.parse(p.creative_asset_id), { profile, asset } = await this.asset(account, redditId.parse(p.profile_id), assetId), remove = op.tool === "reddit_delete_asset", name4 = remove ? void 0 : z4.string().trim().min(1).parse(p.name);
780
+ return { summary: `${remove ? "Delete" : "Rename"} shared Reddit profile asset ${assetId}`, changes: [`Profile ${profile.id}; current ${asset.name ?? asset.id}. ${remove ? "Permanently delete from the shared profile library." : `Rename to ${name4}.`}`], coercions, budgetDeltas, execute: async () => {
781
+ if (remove) {
782
+ const result2 = await this.client.delete(`creative_assets/${assetId}`);
783
+ if (result2.data !== null && (!result2.data || typeof result2.data !== "object" || Object.keys(result2.data).length)) throw new AdportError3("PROVIDER_ERROR", "reddit: unexpected asset deletion receipt; reconcile before retrying", { resource_ids: [assetId] });
784
+ return { applied: true, resourceIds: [assetId] };
785
+ }
786
+ const result = await this.client.patch(`creative_assets/${assetId}`, { data: { name: name4 } });
787
+ if (result.data.id !== assetId || result.data.name !== name4) throw new AdportError3("PROVIDER_ERROR", "reddit: asset rename receipt mismatch", { resource_ids: [assetId] });
788
+ return { applied: true, resourceIds: [assetId] };
789
+ } };
790
+ }
791
+ case "reddit_create_post": {
792
+ const input = createPost.parse(p), profile = await this.profile(account, input.profile_id), creative = { type: input.type, headline: input.headline, ...input.body !== void 0 ? { body: input.body, text_format: "PLAIN_TEXT" } : {} };
793
+ if (input.destination_url) creative.destination = { type: "URL", url: input.destination_url, ...input.call_to_action ? { call_to_action: input.call_to_action } : {} };
794
+ if (input.type === "IMAGE") creative.image = await this.readyAsset(account, String(profile.id), input.image_asset_id, "IMAGE");
795
+ if (input.type === "VIDEO") creative.video = await this.readyAsset(account, String(profile.id), input.video_asset_id, "VIDEO");
796
+ if (input.thumbnail_asset_id) creative.thumbnail = await this.readyAsset(account, String(profile.id), input.thumbnail_asset_id, "IMAGE");
797
+ if (input.type === "CAROUSEL") creative.carousel = await Promise.all(input.carousel.map(async (card) => ({ image: await this.readyAsset(account, String(profile.id), card.image_asset_id, "IMAGE"), destination: { type: "URL", url: card.destination_url, ...card.call_to_action ? { call_to_action: card.call_to_action } : {} }, ...card.caption !== void 0 ? { caption: card.caption } : {} })));
798
+ const payload = { allow_comments: input.allow_comments, creative };
799
+ return { summary: "Create a Reddit structured-post job", changes: [`Create a new post under profile ${profile.id}; ad attachment requires a separate approval. ${JSON.stringify(payload)}`], coercions, budgetDeltas, execute: () => this.postCreate(account, profile, payload) };
800
+ }
801
+ case "reddit_stage_post_copy": {
802
+ const input = stageCopy.parse(p), ad = await this.owned(account, "ads", input.ad_id), profile = await this.profile(account, input.profile_id);
803
+ if (ad.post_id !== input.source_post_id) throw new AdportError3("INVALID_INPUT", "reddit: source post no longer matches the selected ad");
804
+ const post = await this.post(input.source_post_id);
805
+ if (!this.profileMatch(post.profile_id, profile)) throw new AdportError3("INVALID_INPUT", "reddit: source post belongs to a different associated profile");
806
+ const creative = writableCopy(record(post.creative));
807
+ if (input.headline !== void 0) creative.headline = input.headline;
808
+ if (input.body !== void 0) {
809
+ creative.body = input.body;
810
+ creative.text_format = "PLAIN_TEXT";
811
+ }
812
+ const payload = { allow_comments: post.allow_comments === true, creative };
813
+ return { summary: `Stage a new creative copy for Reddit ad ${input.ad_id}`, changes: [`Create a new post under profile ${profile.id}. The original ${input.source_post_id} and ad reference remain unchanged until a separate reddit_update_ad approval. ${JSON.stringify(payload)}`], coercions, budgetDeltas, execute: () => this.postCreate(account, profile, payload) };
814
+ }
815
+ default:
816
+ throw new AdportError3("INVALID_INPUT", `reddit: unsupported creative write ${op.tool}`);
817
+ }
818
+ const effective = { ...current, ...fields };
819
+ if (effective.end_time && (!effective.start_time || Date.parse(String(effective.end_time)) <= Date.parse(String(effective.start_time)))) throw new AdportError3("INVALID_INPUT", "reddit: end_time requires a preceding start_time");
820
+ for (const key of ["goal_value", "bid_value"]) if (fields[key] !== void 0 && fields[key] !== null) budgetDeltas.push({ target: `${path2} ${key}`, ...current[key] !== void 0 && current[key] !== null ? { fromMicros: micros.parse(current[key]) } : {}, toMicros: micros.parse(fields[key]) });
821
+ for (const key of ["name", "configured_status", "goal_value", "bid_value", "bid_strategy", "post_id", "start_time", "end_time", "targeting"]) if (fields[key] !== void 0) expected[key] = fields[key];
822
+ return { summary: `Reddit ${op.tool.replace("reddit_", "").replaceAll("_", " ")}`, changes: [...notes3, `${method} ${path2}: ${JSON.stringify({ data: fields })}`], coercions, budgetDeltas, execute: () => this.mutation(account, path2, method, fields, expected) };
823
+ }
824
+ };
825
+ function postMedia(creative, legacy) {
826
+ const result = [];
827
+ for (const [key, type] of [["image", "image"], ["video", "video"], ["thumbnail", "image"]]) {
828
+ const asset = record(creative[key]), media = record(asset.media), url3 = safeUrl(media.url) ?? safeUrl(media.permanent_url);
829
+ if (url3) result.push({ type, url: url3 });
830
+ }
831
+ if (Array.isArray(creative.carousel)) for (const card of creative.carousel) {
832
+ const url3 = safeUrl(record(record(record(card).image).media).url);
833
+ if (url3) result.push({ type: "image", url: url3 });
834
+ }
835
+ if (!result.length && Array.isArray(legacy?.content)) for (const card of legacy.content) {
836
+ const url3 = safeUrl(record(card).media_url);
837
+ if (url3 && ["IMAGE", "VIDEO", "CAROUSEL"].includes(String(legacy?.type))) result.push({ type: legacy?.type === "VIDEO" ? "video" : "image", url: url3 });
838
+ }
839
+ return result.slice(0, 40);
840
+ }
841
+ function writableCopy(source2) {
842
+ if (!["TEXT", "IMAGE", "VIDEO", "CAROUSEL"].includes(String(source2.type))) throw new AdportError3("INVALID_INPUT", "reddit: this post format requires a dedicated authoring flow");
843
+ const allowed = ["type", "headline", "body", "text_format", "destination", "image", "video", "thumbnail", "carousel", "supplementary_text", "event", "enhancements"];
844
+ if (Object.keys(source2).some((key) => !allowed.includes(key))) throw new AdportError3("INVALID_INPUT", "reddit: source creative contains unsupported fields; refusing a copy that could omit them");
845
+ const result = structuredClone(source2);
846
+ const cleanMedia = (value) => {
847
+ const asset = record(value), media = record(asset.media), url3 = safeUrl(media.url) ?? safeUrl(media.permanent_url);
848
+ if (!url3) throw new AdportError3("INVALID_INPUT", "reddit: source creative media has no safe HTTPS URL");
849
+ return { ...Object.fromEntries(Object.entries(asset).filter(([key]) => ["crop", "name", "gifify"].includes(key))), media: { type: "URL", url: url3 } };
850
+ };
851
+ for (const key of ["image", "video", "thumbnail"]) if (result[key] !== void 0 && result[key] !== null) result[key] = cleanMedia(result[key]);
852
+ if (Array.isArray(result.carousel)) result.carousel = result.carousel.map((value) => {
853
+ const card = record(value);
854
+ return { ...card, image: cleanMedia(card.image) };
855
+ });
856
+ return result;
857
+ }
858
+ function targetingMatches(actual, expected) {
859
+ const canonical5 = (value) => Array.isArray(value) ? value.map(canonical5).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, canonical5(child)])) : value;
860
+ if (Array.isArray(expected)) return JSON.stringify(canonical5(actual)) === JSON.stringify(canonical5(expected));
861
+ if (expected && typeof expected === "object") return actual !== null && typeof actual === "object" && !Array.isArray(actual) && Object.entries(expected).every(([key, value]) => targetingMatches(actual[key], value));
862
+ return actual === expected;
863
+ }
864
+
865
+ // src/catalogs.ts
866
+ import { createHash as createHash2 } from "crypto";
867
+ import { AdportError as AdportError4 } from "@adport/core";
868
+ import { z as z6 } from "zod";
869
+
870
+ // src/catalog-schemas.ts
871
+ import { z as z5 } from "zod";
872
+ var hash = z5.string().regex(/^[a-f0-9]{64}$/);
873
+ var catalogInput = z5.object({ account_id: redditCatalogId, business_id: redditBusinessId, catalog_id: redditCatalogId }).strict();
874
+ var creationInput = catalogInput.omit({ catalog_id: true });
875
+ var sourceIds = z5.array(redditCatalogId.max(50)).max(100).refine((ids2) => new Set(ids2).size === ids2.length, "Pixel IDs must be unique");
876
+ var sourceContext = catalogInput.extend({ event_sources: sourceIds }).strict();
877
+ var creationContext = creationInput.extend({ event_sources: sourceIds.default([]) }).strict();
878
+ var catalogCreate = z5.object({ business_id: redditBusinessId, name: z5.string().min(1).max(200), default_language: z5.enum(["en", "de", "es", "fr", "it", "pt"]), default_currency: z5.enum(["USD", "GBP", "CAD", "EUR", "AUD", "JPY", "CHF", "NZD", "SEK", "NOK", "BRL"]), event_sources: sourceIds.default([]), expected_creation_access_hash: hash, expected_event_sources_hash: hash, acknowledge_new_catalog_management: z5.literal(true) }).strict();
879
+ var catalogRename = catalogInput.omit({ account_id: true }).extend({ name: z5.string().min(1).max(200), expected_configuration_hash: hash, acknowledge_shared_effects: z5.literal(true) }).strict();
880
+ var catalogSources = catalogInput.omit({ account_id: true }).extend({ event_sources: sourceIds, expected_configuration_hash: hash, expected_event_sources_hash: hash, acknowledge_shared_effects: z5.literal(true), acknowledge_measurement_effects: z5.literal(true) }).strict();
881
+ var catalogDelete = catalogInput.omit({ account_id: true }).extend({ expected_configuration_hash: hash, confirm_catalog_name: z5.string().min(1).max(200), acknowledge_shared_effects: z5.literal(true), acknowledge_delete_contents: z5.literal(true) }).strict();
882
+ var permissionSelection = z5.object({ account_id: redditCatalogId, business_id: redditBusinessId, catalog_id: redditCatalogId.optional(), resource_kind: z5.enum(["catalog", "catalog_creation"]).optional() }).strict();
883
+ var validPermission = (input) => input.resource_kind === "catalog_creation" ? !input.catalog_id && (!input.mode || ["none", "create"].includes(input.mode)) : !!input.catalog_id && input.mode !== "create";
884
+ var permissionSnapshot = permissionSelection.refine(validPermission, "Choose an exact catalog or creation delegation without a catalog ID");
885
+ var permissionChange = permissionSelection.omit({ account_id: true }).extend({ mode: z5.enum(["none", "read", "write", "create"]), expected_access_hash: hash }).strict().refine(validPermission, "Choose catalog read/write/none or new-catalog create/none access");
886
+
887
+ // src/catalogs.ts
888
+ var count = z6.number().int().nonnegative().safe();
889
+ var eventSources = z6.array(redditCatalogId.max(50)).max(5e3).refine((ids2) => new Set(ids2).size === ids2.length);
890
+ var nativeCatalog = z6.object({ id: redditCatalogId, business_id: redditBusinessId, name: z6.string().min(1).max(200), default_language: z6.string().min(1).max(32), default_currency: z6.string().regex(/^[A-Z]{3}$/), event_sources: eventSources.optional(), data_sources: z6.array(z6.string()).max(100).optional(), summary: z6.object({ products_count: count.optional(), approved_products_count: count.optional(), rejected_products_count: count.optional(), invalid_products_count: count.optional() }).optional() });
891
+ var canonical = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
892
+ var digest = (value) => createHash2("sha256").update(canonical(value)).digest("hex");
893
+ var config = (row2) => ({ id: row2.id, business_id: row2.business_id, name: row2.name, default_language: row2.default_language, default_currency: row2.default_currency, event_sources: row2.event_sources ? [...row2.event_sources].sort() : void 0 });
894
+ var configurationHash = (scope3, row2) => digest({ account_id: scope3.account_id, business_id: scope3.business_id, catalog_id: scope3.catalog_id, configuration: config(row2) });
895
+ var resource = (input) => ({ accountId: input.account_id, businessId: input.business_id, resourceId: input.catalog_id, kind: "catalog" });
896
+ var permissionResource = (input) => input.resource_kind === "catalog_creation" ? creationScope(input.account_id, input.business_id) : resource({ ...input, catalog_id: input.catalog_id });
897
+ var failure = (error, message, ids2) => {
898
+ const details = error instanceof AdportError4 && error.details && typeof error.details === "object" ? error.details : {};
899
+ return new AdportError4("PROVIDER_ERROR", message + " Provider bodies stay hidden; no native write was retried.", { ...Number.isInteger(details.http_status) ? { http_status: details.http_status } : {}, ...ids2 ? { resourceIds: ids2 } : {} });
900
+ };
901
+ var invalid = () => new AdportError4("PROVIDER_ERROR", "Reddit catalog/Business scope or native response shape could not be verified.");
902
+ var RedditCatalogService = class {
903
+ constructor(client, store) {
904
+ this.client = client;
905
+ this.store = store;
906
+ }
907
+ client;
908
+ store;
909
+ manager() {
910
+ if (!this.store?.canManage) throw new AdportError4("POLICY_VIOLATION", "Only the local owner or a signed-in project owner/admin can administer catalog access.");
911
+ return this.store;
912
+ }
913
+ async read(path2, absent = false) {
914
+ try {
915
+ return (await this.client.get(path2)).data;
916
+ } catch (error) {
917
+ if (error instanceof AdportError4 && ["POLICY_VIOLATION", "NOT_CONNECTED"].includes(error.code)) throw error;
918
+ if (absent && error instanceof AdportError4 && error.details?.http_status === 404) return void 0;
919
+ throw failure(error, "Reddit catalog read failed. Check native Business/catalog access.");
920
+ }
921
+ }
922
+ async native(scope3, absent = false) {
923
+ const value = await this.read(`product_catalogs/${encodeURIComponent(scope3.catalog_id)}`, absent);
924
+ if (value === void 0 && absent) return;
925
+ const parsed = nativeCatalog.safeParse(value);
926
+ if (!parsed.success || parsed.data.id !== scope3.catalog_id || parsed.data.business_id !== scope3.business_id) throw invalid();
927
+ return parsed.data;
928
+ }
929
+ async parent(scope3, write2 = false) {
930
+ await requireCatalogAccess(this.store, resource(scope3), write2);
931
+ return await this.native(scope3);
932
+ }
933
+ async authorize(value, write2 = false) {
934
+ const input = catalogInput.parse(value), row2 = await this.parent(input, write2);
935
+ return { ...row2, configuration_hash: configurationHash(input, row2) };
936
+ }
937
+ async business(id) {
938
+ const parsed = z6.object({ id: redditBusinessId, name: z6.string().max(4e3) }).safeParse(await this.read(`businesses/${encodeURIComponent(id)}`));
939
+ if (!parsed.success || parsed.data.id !== id) throw invalid();
940
+ return parsed.data;
941
+ }
942
+ async selectedSources(input, ids2) {
943
+ const selected2 = [...ids2].sort();
944
+ if (selected2.length) {
945
+ let raw;
946
+ try {
947
+ raw = await this.client.getPaged(`ad_accounts/${encodeURIComponent(input.account_id)}/pixels`, { "page.size": 1e3 }, 5e3);
948
+ } catch (error) {
949
+ throw failure(error, "Selected-account Pixel lookup failed.");
950
+ }
951
+ const parsed = z6.array(z6.object({ id: redditCatalogId, ad_account_id: redditCatalogId.optional() })).max(5e3).safeParse(raw);
952
+ if (!parsed.success || parsed.data.some((row2) => row2.ad_account_id !== void 0 && row2.ad_account_id !== input.account_id) || new Set(parsed.data.map((row2) => row2.id)).size !== parsed.data.length) throw invalid();
953
+ if (selected2.some((id) => !parsed.data.some((row2) => row2.id === id))) throw new AdportError4("INVALID_INPUT", "Every selected event-source Pixel must be available to the selected ad account within the bounded native lookup.");
954
+ }
955
+ return digest({ account_id: input.account_id, business_id: input.business_id, catalog_id: input.catalog_id ?? null, event_sources: selected2 });
956
+ }
957
+ async access(account) {
958
+ redditCatalogId.parse(account);
959
+ const grants = await this.store?.list(account) ?? [];
960
+ if (grants.some((grant) => grant.scope.accountId !== account)) throw new AdportError4("POLICY_VIOLATION", "Catalog access does not match this advertiser.");
961
+ return { grants, records: grants.map((grant) => ({ id: grant.scope.resourceId, name: grant.scope.kind === "catalog_creation" ? "New catalogs" : "Catalog " + grant.scope.resourceId, business_id: grant.scope.businessId, access: grant.mode })), notes: ["Only explicit project grants are listed. Enabled ad-account access does not authorize Business catalogs."] };
962
+ }
963
+ async snapshot(value) {
964
+ const input = permissionSnapshot.parse(value), scope3 = permissionResource(input), grant = await this.manager().get(scope3);
965
+ return { grant, records: [{ id: scope3.resourceId, name: "Catalog access", business_id: scope3.businessId, access: grant.mode }] };
966
+ }
967
+ async get(value) {
968
+ const input = catalogInput.parse(value), current = await this.parent(input);
969
+ return { catalog: { ...current, configuration_hash: configurationHash(input, current) }, records: [{ id: current.id, name: current.name, business_id: current.business_id, currency: current.default_currency, language: current.default_language, products: current.summary?.products_count, event_source_count: current.event_sources?.length }], notes: ["Native counts/fields that are absent stay unavailable. This is configuration, not full product or dependent-ad inventory."] };
970
+ }
971
+ async creationContext(value) {
972
+ const input = creationContext.parse(value), grant = await requireCatalogCreationAccess(this.store, creationScope(input.account_id, input.business_id)), business = await this.business(input.business_id), sourcesHash = await this.selectedSources(input, input.event_sources);
973
+ return { expected_creation_access_hash: grant.hash, expected_event_sources_hash: sourcesHash, event_sources: input.event_sources, business, records: [{ id: business.id, name: business.name, access: "Create and manage verified new catalogs", selected_event_sources: input.event_sources.length }], complete: true, truncated: false, notes: ["Delegation authorizes creation and management of verified new IDs only. Existing Business catalogs are not enumerated or granted.", "Selected event-source Pixel IDs are checked under the selected ad account; empty selection installs no binding. No events, products, ads or spend are created by this context."] };
974
+ }
975
+ async sourceContext(value) {
976
+ const input = sourceContext.parse(value), current = await this.parent(input), sourcesHash = await this.selectedSources(input, input.event_sources);
977
+ if (!current.event_sources) throw new AdportError4("PROVIDER_ERROR", "Current catalog event sources are unavailable. No replacement preview was prepared.");
978
+ return { expected_configuration_hash: configurationHash(input, current), expected_event_sources_hash: sourcesHash, current_event_sources: current.event_sources, event_sources: input.event_sources, records: [{ id: current.id, name: current.name, previous_sources: current.event_sources.length, selected_sources: input.event_sources.length }], complete: true, truncated: false, notes: ["This replaces the entire event-source list. Empty explicitly clears it. Shared matching and existing ads may be affected; no events are sent."] };
979
+ }
980
+ async plan(op) {
981
+ if (op.provider !== "reddit") throw new AdportError4("INVALID_INPUT", "Reddit catalog provider differs.");
982
+ if (op.tool === "reddit_set_catalog_access" && op.kind === "update") {
983
+ const store = this.manager(), input2 = permissionChange.parse(op.payload), scope4 = permissionResource({ ...input2, account_id: op.accountId }), before = await store.get(scope4);
984
+ if (before.hash !== input2.expected_access_hash) throw new AdportError4("PENDING_MISMATCH", "Catalog access changed. Read and review it again.");
985
+ const creation = scope4.kind === "catalog_creation";
986
+ let subject = creation ? "New catalogs" : input2.catalog_id;
987
+ if (input2.mode !== "none") {
988
+ const business = await this.business(input2.business_id);
989
+ subject = creation ? business.name : (await this.native({ account_id: op.accountId, business_id: input2.business_id, catalog_id: input2.catalog_id })).name;
990
+ }
991
+ const notes4 = ["Changes Adport project access, not Reddit native user permissions. Native Business/catalog eligibility remains authoritative.", "Creation delegates management of verified new catalog IDs only. Existing catalogs require separate grants. Revoking creation leaves existing catalog grants independent."];
992
+ return {
993
+ summary: `${input2.mode === "none" ? "Revoke" : "Grant"} Reddit catalog access \xB7 ${subject}`,
994
+ changes: [`~ Project access ${before.mode} \u2192 ${input2.mode} for Business ${input2.business_id}, ${creation ? "new catalogs only" : "catalog " + input2.catalog_id}`],
995
+ coercions: [],
996
+ budgetDeltas: [],
997
+ notes: notes4,
998
+ review: { provider: "reddit", accountId: op.accountId, kind: "update", title: input2.mode === "none" ? "Revoke catalog access" : creation ? "Delegate catalog creation" : "Grant catalog access", subject, fields: [{ label: "Business", after: input2.business_id }, { label: "Resource", after: creation ? "Verified new catalogs only" : input2.catalog_id }, { label: "Project access", before: before.mode, after: input2.mode === "create" ? "Create and manage new catalogs" : input2.mode }], notices: notes4 },
999
+ execute: async () => {
1000
+ const result = await store.compareAndSet(scope4, input2.expected_access_hash, input2.mode), actual = await store.get(scope4);
1001
+ if (catalogScopeKey(result.scope) !== catalogScopeKey(scope4) || result.mode !== input2.mode || actual.hash !== result.hash) throw new AdportError4("POLICY_VIOLATION", "Catalog access receipt could not be confirmed.");
1002
+ return [scope4.resourceId];
1003
+ }
1004
+ };
1005
+ }
1006
+ if (op.tool === "reddit_create_catalog" && op.kind === "create") {
1007
+ const input2 = catalogCreate.parse(op.payload), selection = { account_id: op.accountId, business_id: input2.business_id }, store = this.store;
1008
+ if (!store?.adoptCreated) throw new AdportError4("NOT_CONNECTED", "This runtime cannot adopt independently verified new catalogs.");
1009
+ const prepare2 = async () => {
1010
+ await requireCatalogCreationAccess(store, creationScope(op.accountId, input2.business_id), true);
1011
+ const context = await this.creationContext({ ...selection, event_sources: input2.event_sources });
1012
+ if (context.expected_creation_access_hash !== input2.expected_creation_access_hash || context.expected_event_sources_hash !== input2.expected_event_sources_hash) throw new AdportError4("PENDING_MISMATCH", "Creation delegation or selected sources changed. Read context and request a new preview.");
1013
+ };
1014
+ await prepare2();
1015
+ const data2 = { name: input2.name, default_currency: input2.default_currency, default_language: input2.default_language, event_sources: input2.event_sources }, notes4 = ["Creates an empty Business catalog. No products, ads, spend or conversion events are submitted.", "Default currency/language are not patchable through the current catalog endpoint. Project write access is adopted only for this verified new native ID.", "Native creation and project access are not atomic. Reconcile a known ID after uncertain creation/readback/adoption; never replay automatically."];
1016
+ return {
1017
+ summary: `Create Reddit catalog "${input2.name}"`,
1018
+ changes: ["+ Catalog " + canonical(data2), "+ Project read/write access for the verified new ID only"],
1019
+ coercions: [],
1020
+ budgetDeltas: [],
1021
+ notes: notes4,
1022
+ review: { provider: "reddit", accountId: op.accountId, kind: "create", title: "Create catalog", subject: input2.name, fields: [{ label: "Business", after: input2.business_id }, { label: "Default currency", after: input2.default_currency }, { label: "Default language", after: input2.default_language }, { label: "Event-source Pixels", after: input2.event_sources.join(", ") || "None" }, { label: "New catalog project access", after: "Read and write" }], notices: notes4 },
1023
+ execute: async () => {
1024
+ await prepare2();
1025
+ let id;
1026
+ try {
1027
+ const raw = (await this.client.post(`businesses/${encodeURIComponent(input2.business_id)}/product_catalogs`, { data: data2 })).data, knownId = z6.object({ id: redditCatalogId }).safeParse(raw);
1028
+ if (knownId.success) id = knownId.data.id;
1029
+ const receipt = nativeCatalog.parse(raw);
1030
+ id = receipt.id;
1031
+ if (receipt.business_id !== input2.business_id) throw invalid();
1032
+ await requireCatalogCreationAccess(store, creationScope(op.accountId, input2.business_id), true);
1033
+ const actual = await this.native({ ...selection, catalog_id: id });
1034
+ if (!actual || canonical(config(actual)) !== canonical({ id, business_id: input2.business_id, ...data2, event_sources: [...data2.event_sources].sort() })) throw new Error("Creation readback differs");
1035
+ const adopted = await store.adoptCreated({ accountId: op.accountId, businessId: input2.business_id, resourceId: id, kind: "catalog" }, input2.expected_creation_access_hash);
1036
+ if (adopted.mode !== "write" || adopted.scope.resourceId !== id || adopted.scope.businessId !== input2.business_id || adopted.scope.accountId !== op.accountId || adopted.scope.kind !== "catalog") throw new Error("Adoption receipt differs");
1037
+ return [id];
1038
+ } catch (error) {
1039
+ throw failure(error, "Reddit catalog creation or project adoption is unconfirmed. Reconcile known IDs before another create.", id ? [id] : void 0);
1040
+ }
1041
+ }
1042
+ };
1043
+ }
1044
+ const rename = op.tool === "reddit_rename_catalog", sources = op.tool === "reddit_set_catalog_event_sources", remove = op.tool === "reddit_delete_catalog";
1045
+ if (!(rename && op.kind === "update" || sources && op.kind === "update" || remove && op.kind === "remove")) throw new AdportError4("INVALID_INPUT", "Unsupported Reddit catalog operation or kind.");
1046
+ const input = rename ? catalogRename.parse(op.payload) : sources ? catalogSources.parse(op.payload) : catalogDelete.parse(op.payload), scope3 = { account_id: op.accountId, business_id: input.business_id, catalog_id: input.catalog_id };
1047
+ const prepare = async () => {
1048
+ const current2 = await this.parent(scope3, true);
1049
+ if (configurationHash(scope3, current2) !== input.expected_configuration_hash || "confirm_catalog_name" in input && current2.name !== input.confirm_catalog_name) throw new AdportError4("PENDING_MISMATCH", "Catalog configuration/name changed. Read and preview again.");
1050
+ if (!remove && !current2.event_sources) throw new AdportError4("PROVIDER_ERROR", "Current event sources are unavailable; preservation cannot be verified.");
1051
+ if ("expected_event_sources_hash" in input && await this.selectedSources(scope3, input.event_sources) !== input.expected_event_sources_hash) throw new AdportError4("PENDING_MISMATCH", "Selected event sources changed. Request a fresh preview.");
1052
+ return current2;
1053
+ };
1054
+ const current = await prepare(), data = "name" in input ? { name: input.name } : "event_sources" in input ? { event_sources: input.event_sources } : {}, title = rename ? "Rename catalog" : sources ? "Replace catalog event sources" : "Delete catalog permanently", notes3 = remove ? ["Permanently removes the entire shared catalog and affects its current contents/consumers. Contents are not enumerated or frozen by this configuration snapshot.", "Checks native acknowledgement and exact lookup absence. Other errors are not absence; no restore/global usage guarantee or automatic replay. Project grants remain separate owner settings."] : ["Changes a shared Business catalog; other accounts/ads may be affected. Unselected configuration is checked after the write.", ...sources ? ["Replaces the entire event-source list, including clearing it when explicitly empty. Selected Pixel IDs are checked under this ad account. No conversion events are sent."] : [], "No automatic write replay; reconcile the known catalog after any uncertain result."];
1055
+ return {
1056
+ summary: `${title} "${current.name}"`,
1057
+ changes: [remove ? "- Entire catalog " + current.id + " and its current contents" : "~ Catalog configuration " + canonical(data)],
1058
+ coercions: [],
1059
+ budgetDeltas: [],
1060
+ notes: notes3,
1061
+ review: { provider: "reddit", accountId: op.accountId, kind: remove ? "remove" : "update", title, subject: current.name, fields: [{ label: "Catalog", after: current.id }, { label: "Business", after: current.business_id }, ...rename ? [{ label: "Name", before: current.name, after: input.name }] : sources ? [{ label: "Event-source Pixels", before: current.event_sources.join(", ") || "None", after: input.event_sources.join(", ") || "None" }] : [{ label: "Contents affected", after: "Entire catalog; contents not enumerated or frozen" }]], notices: notes3 },
1062
+ execute: async () => {
1063
+ const fresh = await prepare();
1064
+ try {
1065
+ if (remove) {
1066
+ const receipt = await this.client.delete(`product_catalogs/${encodeURIComponent(current.id)}`);
1067
+ if (receipt.data === null || typeof receipt.data !== "object" || Array.isArray(receipt.data)) throw new Error("Unexpected deletion acknowledgement");
1068
+ await requireCatalogAccess(this.store, resource(scope3), true);
1069
+ if (await this.native(scope3, true)) throw new Error("Catalog remains visible");
1070
+ } else {
1071
+ const receipt = nativeCatalog.parse((await this.client.patch(`product_catalogs/${encodeURIComponent(current.id)}`, { data })).data);
1072
+ if (receipt.id !== current.id || receipt.business_id !== scope3.business_id) throw invalid();
1073
+ await requireCatalogAccess(this.store, resource(scope3), true);
1074
+ const actual = await this.native(scope3), expected = config({ ...fresh, ...data });
1075
+ if (!actual || canonical(config(actual)) !== canonical(expected)) throw new Error("Catalog preservation readback differs");
1076
+ }
1077
+ return [current.id];
1078
+ } catch (error) {
1079
+ throw failure(error, "Reddit catalog mutation or independent preservation/absence readback is unconfirmed. Inspect the known catalog before another write.", [current.id]);
1080
+ }
1081
+ }
1082
+ };
1083
+ }
1084
+ };
1085
+
1086
+ // src/catalog-content.ts
1087
+ import { createHash as createHash3 } from "crypto";
1088
+ import { AdportError as AdportError5 } from "@adport/core";
1089
+ import { z as z8 } from "zod";
1090
+
1091
+ // src/catalog-content-schemas.ts
1092
+ import { z as z7 } from "zod";
1093
+ var productId = z7.string().min(1).max(128).regex(/^[^\x00-\x1f\x7f]+$/);
1094
+ var page = { page_size: z7.number().int().positive().max(1e3).default(20), cursor: z7.string().url().max(8192).optional() };
1095
+ var setInput = catalogInput.extend({ product_set_id: redditCatalogId }).strict();
1096
+ var setList = catalogInput.extend(page).strict();
1097
+ var productFilters = { ids: z7.array(productId).min(1).max(100).refine((ids2) => new Set(ids2).size === ids2.length).optional(), approval_decision: z7.enum(["PENDING", "APPROVED", "REJECTED"]).optional(), search: z7.string().min(1).max(100).optional() };
1098
+ var productList = catalogInput.extend({ ...page, ...productFilters }).strict();
1099
+ var setProductList = setInput.extend({ ...page, ...productFilters, issue_code: z7.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/).optional() }).strict();
1100
+ var attributes = /* @__PURE__ */ new Set(["id", "title", "description", "price", "currency", "sale_price", "availability", "brand", "color", "gender", "product_type", "item_group_id", "condition", "age_group", "size", "pattern", "material", "custom_label_0", "custom_label_1", "custom_label_2", "custom_label_3", "custom_label_4"]);
1101
+ var operators = /* @__PURE__ */ new Set(["contains", "not_contains", "i_contains", "i_not_contains", "starts_with", "i_starts_with", "eq", "neq", "lt", "lte", "gt", "gte"]);
1102
+ var arrayOperators = /* @__PURE__ */ new Set(["is_any", "is_not_any", "i_is_any", "i_is_not_any"]);
1103
+ function validFilter(value) {
1104
+ let nodes = 0;
1105
+ const visit = (item, depth) => {
1106
+ if (++nodes > 500 || depth > 8 || !item || typeof item !== "object" || Array.isArray(item)) return false;
1107
+ const entries = Object.entries(item);
1108
+ if (entries.length !== 1) return false;
1109
+ const [key, condition] = entries[0];
1110
+ if (key === "and" || key === "or") return Array.isArray(condition) && condition.length > 0 && condition.length <= 100 && condition.every((child) => visit(child, depth + 1));
1111
+ if (!attributes.has(key) || !condition || typeof condition !== "object" || Array.isArray(condition)) return false;
1112
+ const checks = Object.entries(condition);
1113
+ if (checks.length !== 1) return false;
1114
+ const [operator, operand] = checks[0];
1115
+ return operators.has(operator) ? typeof operand === "string" && operand.length > 0 && operand.length <= 4e3 : arrayOperators.has(operator) && Array.isArray(operand) && operand.length > 0 && operand.length <= 100 && operand.every((v) => typeof v === "string" && v.length > 0 && v.length <= 4e3);
1116
+ };
1117
+ try {
1118
+ return visit(JSON.parse(value), 0);
1119
+ } catch {
1120
+ return false;
1121
+ }
1122
+ }
1123
+ var setFilter = z7.string().min(2).max(65536).refine((value) => Buffer.byteLength(value, "utf8") <= 65536, "Filter JSON must not exceed 64 KiB in UTF-8").refine(validFilter, "Use the documented Reddit product-filter JSON grammar");
1124
+ var setCreate = catalogInput.omit({ account_id: true }).extend({ name: z7.string().min(1).max(100), filter: setFilter, expected_catalog_configuration_hash: hash, acknowledge_shared_effects: z7.literal(true) }).strict();
1125
+ var setUpdate = setInput.omit({ account_id: true }).extend({ name: z7.string().min(1).max(100).optional(), filter: setFilter.optional(), expected_configuration_hash: hash, acknowledge_shared_effects: z7.literal(true) }).strict().refine((input) => input.name !== void 0 || input.filter !== void 0, "Provide a name or filter");
1126
+ var setDelete = setInput.omit({ account_id: true }).extend({ expected_configuration_hash: hash, confirm_name: z7.string().min(1).max(100), acknowledge_shared_effects: z7.literal(true), acknowledge_remove_set: z7.literal(true) }).strict();
1127
+ var importInput = catalogInput.extend({ import_id: redditCatalogId }).strict();
1128
+ var importList = catalogInput.extend({ ...page, feed_ids: z7.array(redditCatalogId).min(1).max(100).refine((ids2) => new Set(ids2).size === ids2.length).optional(), statuses: z7.array(z7.enum(["PENDING", "PROCESSING", "COMPLETED", "FAILED", "SKIPPED"])).min(1).max(5).refine((values) => new Set(values).size === values.length).optional() }).strict();
1129
+ var importIssues = importInput.extend({ ...page, code: z7.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/).optional() }).strict();
1130
+
1131
+ // src/catalog-content.ts
1132
+ var scope = (input) => ({ account_id: input.account_id, business_id: input.business_id, catalog_id: input.catalog_id });
1133
+ var canonical2 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
1134
+ var digest2 = (value) => createHash3("sha256").update(canonical2(value)).digest("hex");
1135
+ var filterValue = (value) => {
1136
+ try {
1137
+ return JSON.parse(value);
1138
+ } catch {
1139
+ return value;
1140
+ }
1141
+ };
1142
+ function filterText(value) {
1143
+ if (!validFilter(value)) return value;
1144
+ const labels = { contains: "contains", not_contains: "does not contain", i_contains: "contains (case insensitive)", i_not_contains: "does not contain (case insensitive)", starts_with: "starts with", i_starts_with: "starts with (case insensitive)", is_any: "matches any of", is_not_any: "matches none of", i_is_any: "matches any of (case insensitive)", i_is_not_any: "matches none of (case insensitive)", eq: "equals", neq: "does not equal", lt: "is less than", lte: "is at most", gt: "is greater than", gte: "is at least" };
1145
+ const text3 = (item) => {
1146
+ const [key, condition] = Object.entries(item)[0];
1147
+ if (key === "and" || key === "or") return (key === "and" ? "All conditions" : "Any condition") + ": (" + condition.map(text3).join("; ") + ")";
1148
+ const [operator, operand] = Object.entries(condition)[0];
1149
+ return key.replaceAll("_", " ").replace(/^./, (c) => c.toUpperCase()) + " " + labels[operator] + " " + (Array.isArray(operand) ? operand.join(", ") : String(operand));
1150
+ };
1151
+ return text3(JSON.parse(value));
1152
+ }
1153
+ var count2 = z8.number().int().nonnegative().safe();
1154
+ var setRow = z8.object({ id: redditCatalogId, catalog_id: redditCatalogId, name: z8.string().min(1).max(100), filter: z8.string().max(65536), summary: z8.object({ products_count: count2.optional(), approved_products_count: count2.nullable().optional(), rejected_products_count: count2.nullable().optional(), invalid_products_count: count2.nullable().optional() }).optional() });
1155
+ var setConfig = (row2) => ({ id: row2.id, catalog_id: row2.catalog_id, name: row2.name, filter: filterValue(row2.filter) });
1156
+ var setHash = (input, row2) => digest2({ ...scope(input), configuration: setConfig(row2) });
1157
+ var issueRow = z8.object({ field: z8.string().max(1e3).nullable().optional(), severity: z8.enum(["WARNING", "CRITICAL"]), code: z8.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/), message: z8.string().max(4e4).optional() });
1158
+ var productRow = z8.object({ id: productId, title: z8.string().max(4e4).nullable().optional(), description: z8.string().max(4e4).nullable().optional(), price: z8.string().max(256).optional(), link: z8.string().max(8192).optional(), image_link: z8.string().max(8192).optional(), item_group_id: z8.string().max(1e3).nullable().optional(), brand: z8.string().max(4e3).nullable().optional(), availability: z8.enum(["BACKORDER", "IN_STOCK", "OUT_OF_STOCK", "PREORDER"]).nullable().optional(), reddit: z8.object({ id: redditCatalogId.optional(), catalog_id: redditCatalogId, image_link: z8.string().max(8192).nullable().optional(), approval_decision: z8.enum(["PENDING", "APPROVED", "REJECTED"]).optional(), issues: z8.array(issueRow).max(1e3).nullable().optional() }) });
1159
+ var importRow = z8.object({ id: redditCatalogId, catalog_id: redditCatalogId, feed_id: redditCatalogId.optional(), filename: z8.string().max(4e3).optional(), status: z8.enum(["PENDING", "PROCESSING", "COMPLETED", "FAILED", "SKIPPED"]), summary: z8.object({ added_products_count: count2.nullable().optional(), modified_products_count: count2.nullable().optional(), deleted_products_count: count2.nullable().optional(), invalid_products_count: count2.nullable().optional() }).nullable().optional() });
1160
+ var nativePage = z8.object({ next_url: z8.string().url().max(8192).nullable().optional() });
1161
+ function failure2(error, message, ids2) {
1162
+ const details = error instanceof AdportError5 && error.details && typeof error.details === "object" ? error.details : {};
1163
+ return new AdportError5("PROVIDER_ERROR", message + " No native mutation was retried; provider bodies stay hidden.", { ...Number.isInteger(details.http_status) ? { http_status: details.http_status } : {}, ...ids2 ? { resourceIds: ids2 } : {} });
1164
+ }
1165
+ var invalid2 = () => new AdportError5("PROVIDER_ERROR", "Reddit catalog child scope or response shape could not be verified.");
1166
+ function safeUrl2(value, image = false) {
1167
+ try {
1168
+ const url3 = new URL(value);
1169
+ if (!(image ? url3.protocol === "https:" && /\.(redd\.it|redditmedia\.com|redditstatic\.com)$/.test(url3.hostname) : ["https:", "http:"].includes(url3.protocol)) || url3.username || url3.password) return;
1170
+ return url3.href;
1171
+ } catch {
1172
+ return;
1173
+ }
1174
+ }
1175
+ var RedditCatalogContentService = class {
1176
+ constructor(client, catalogs) {
1177
+ this.client = client;
1178
+ this.catalogs = catalogs;
1179
+ }
1180
+ client;
1181
+ catalogs;
1182
+ async request(path2, absent = false) {
1183
+ try {
1184
+ return await this.client.get(path2);
1185
+ } catch (error) {
1186
+ if (absent && error instanceof AdportError5 && error.details?.http_status === 404) return;
1187
+ throw failure2(error, "Reddit catalog content read failed.");
1188
+ }
1189
+ }
1190
+ url(path2, params = {}) {
1191
+ const url3 = new URL("https://ads-api.reddit.com/api/v3/" + path2);
1192
+ for (const [key, value] of Object.entries(params)) if (Array.isArray(value)) value.forEach((item) => url3.searchParams.append(key, item));
1193
+ else if (value !== void 0) url3.searchParams.set(key, String(value));
1194
+ return url3.href;
1195
+ }
1196
+ async page(path2, params, schema, cursor) {
1197
+ const first = this.url(path2, params), current = cursor ? this.client.nextUrl(cursor, first) : first, response = await this.request(current), parsed = z8.array(schema).max(1e3).safeParse(response.data), pagination = nativePage.safeParse(response.pagination);
1198
+ if (!parsed.success || !pagination.success || parsed.data.length > Number(params["page.size"])) throw invalid2();
1199
+ const next = pagination.data.next_url ? this.client.nextUrl(pagination.data.next_url, first) : void 0;
1200
+ if (next === current) throw new AdportError5("PROVIDER_ERROR", "Reddit catalog pagination did not advance.");
1201
+ return { rows: parsed.data, next_cursor: next, truncated: !!next, complete: !next };
1202
+ }
1203
+ async set(input, absent = false) {
1204
+ const response = await this.request("product_sets/" + encodeURIComponent(input.product_set_id), absent);
1205
+ if (!response && absent) return;
1206
+ const parsed = setRow.safeParse(response?.data);
1207
+ if (!parsed.success || parsed.data.id !== input.product_set_id || parsed.data.catalog_id !== input.catalog_id) throw invalid2();
1208
+ return parsed.data;
1209
+ }
1210
+ async sets(value) {
1211
+ const input = setList.parse(value);
1212
+ await this.catalogs.authorize(scope(input));
1213
+ const result = await this.page("product_catalogs/" + encodeURIComponent(input.catalog_id) + "/product_sets", { "page.size": input.page_size }, setRow, input.cursor);
1214
+ if (result.rows.some((row2) => row2.catalog_id !== input.catalog_id) || new Set(result.rows.map((row2) => row2.id)).size !== result.rows.length) throw invalid2();
1215
+ return { product_sets: result.rows.map((row2) => ({ ...row2, configuration_hash: setHash(input, row2) })), records: result.rows.map((row2) => ({ id: row2.id, name: row2.name, filter: filterText(row2.filter), products: row2.summary?.products_count })), next_cursor: result.next_cursor, truncated: result.truncated, complete: result.complete };
1216
+ }
1217
+ async getSet(value) {
1218
+ const input = setInput.parse(value);
1219
+ await this.catalogs.authorize(scope(input));
1220
+ const row2 = await this.set(input);
1221
+ return { product_set: { ...row2, configuration_hash: setHash(input, row2) }, records: [{ id: row2.id, name: row2.name, filter: filterText(row2.filter), products: row2.summary?.products_count }], complete: true, truncated: false, notes: ["The hash binds the exact account/Business/catalog/set configuration, excluding volatile product counts. Project access is checked separately. Set membership can change independently."] };
1222
+ }
1223
+ async products(value, inSet = false) {
1224
+ const selectedSet = inSet ? setProductList.parse(value) : void 0, input = selectedSet ?? productList.parse(value);
1225
+ await this.catalogs.authorize(scope(input));
1226
+ if (selectedSet) await this.set(selectedSet);
1227
+ const path2 = selectedSet ? "product_sets/" + encodeURIComponent(selectedSet.product_set_id) + "/products" : "product_catalogs/" + encodeURIComponent(input.catalog_id) + "/products", result = await this.page(path2, { "page.size": input.page_size, ids: input.ids, approval_decision: input.approval_decision, search: input.search, issue_code: selectedSet?.issue_code }, productRow, input.cursor);
1228
+ if (result.rows.some((row2) => row2.reddit.catalog_id !== input.catalog_id || input.ids && !input.ids.includes(row2.id)) || new Set(result.rows.map((row2) => row2.id)).size !== result.rows.length) throw invalid2();
1229
+ const products = result.rows.map((row2) => ({ ...row2, link: safeUrl2(row2.link), image_link: safeUrl2(row2.image_link), reddit: { ...row2.reddit, image_link: safeUrl2(row2.reddit.image_link), issues: row2.reddit.issues?.map((issue) => ({ ...issue, message: this.client.diagnostic(issue.message) })) } }));
1230
+ const creatives = products.map((row2) => {
1231
+ const image = safeUrl2(row2.reddit.image_link, true), landing2 = safeUrl2(row2.link);
1232
+ return { id: row2.id, provider: "reddit", account_id: input.account_id, name: row2.title ?? row2.id, type: "CATALOG_PRODUCT", status: row2.reddit.approval_decision, headlines: row2.title ? [row2.title] : [], descriptions: [row2.description, row2.price, row2.brand, row2.availability].filter((v) => typeof v === "string"), landing_urls: landing2 ? [landing2] : [], media: image ? [{ type: "image", url: image, alt: row2.id }] : [], actions: [] };
1233
+ });
1234
+ return { products, creatives, next_cursor: result.next_cursor, truncated: result.truncated, complete: result.complete, notes: ["Native product IDs and supplied filters are preserved. Missing titles/descriptions or approval/count fields remain unavailable. Only Reddit-hosted native preview images are embedded; merchant hosts are not added to widget CSP."] };
1235
+ }
1236
+ async imports(value) {
1237
+ const input = importList.parse(value);
1238
+ await this.catalogs.authorize(scope(input));
1239
+ const result = await this.page("product_catalogs/" + encodeURIComponent(input.catalog_id) + "/catalog_imports", { "page.size": input.page_size, feed_ids: input.feed_ids, statuses: input.statuses?.join(",") }, importRow, input.cursor);
1240
+ if (result.rows.some((row2) => row2.catalog_id !== input.catalog_id || input.feed_ids && (!row2.feed_id || !input.feed_ids.includes(row2.feed_id)) || input.statuses && !input.statuses.includes(row2.status)) || new Set(result.rows.map((row2) => row2.id)).size !== result.rows.length) throw invalid2();
1241
+ return { imports: result.rows, records: result.rows.map((row2) => ({ id: row2.id, name: row2.filename ?? "Catalog import", status: row2.status, feed_id: row2.feed_id, ...row2.summary })), next_cursor: result.next_cursor, truncated: result.truncated, complete: result.complete };
1242
+ }
1243
+ async selectedImport(input) {
1244
+ await this.catalogs.authorize(scope(input));
1245
+ let cursor;
1246
+ const seen = /* @__PURE__ */ new Set(), ids2 = /* @__PURE__ */ new Set();
1247
+ for (let pages = 0; pages < 10; pages++) {
1248
+ const result = await this.page("product_catalogs/" + encodeURIComponent(input.catalog_id) + "/catalog_imports", { "page.size": 1e3 }, importRow, cursor);
1249
+ if (result.rows.some((row2) => row2.catalog_id !== input.catalog_id || ids2.has(row2.id)) || new Set(result.rows.map((row2) => row2.id)).size !== result.rows.length) throw invalid2();
1250
+ result.rows.forEach((row2) => ids2.add(row2.id));
1251
+ const selected2 = result.rows.find((row2) => row2.id === input.import_id);
1252
+ if (selected2) return selected2;
1253
+ if (!result.next_cursor) throw new AdportError5("INVALID_INPUT", "The import is not in this catalog.");
1254
+ if (seen.has(result.next_cursor)) throw invalid2();
1255
+ seen.add(result.next_cursor);
1256
+ cursor = result.next_cursor;
1257
+ }
1258
+ throw new AdportError5("PROVIDER_ERROR", "Selected import membership was not established within the 10,000-row verification bound. Narrow catalog access or inspect native import history.");
1259
+ }
1260
+ async issues(value) {
1261
+ const input = importIssues.parse(value);
1262
+ await this.selectedImport(input);
1263
+ const schema = issueRow.extend({ id: redditCatalogId, import_id: redditCatalogId, line: count2.nullable().optional(), product_id: productId.nullable().optional() }), result = await this.page("catalog_imports/" + encodeURIComponent(input.import_id) + "/issues", { "page.size": input.page_size, code: input.code }, schema, input.cursor);
1264
+ if (result.rows.some((row2) => row2.import_id !== input.import_id || input.code && row2.code !== input.code) || new Set(result.rows.map((row2) => row2.id)).size !== result.rows.length) throw invalid2();
1265
+ const issues = result.rows.map((row2) => ({ ...row2, message: this.client.diagnostic(row2.message) }));
1266
+ return { issues, records: issues.map((row2) => ({ ...row2, name: row2.code })), next_cursor: result.next_cursor, truncated: result.truncated, complete: result.complete };
1267
+ }
1268
+ async report(value) {
1269
+ const input = importInput.parse(value);
1270
+ await this.selectedImport(input);
1271
+ const result = await this.request("catalog_imports/" + encodeURIComponent(input.import_id) + "/report"), raw = result.data;
1272
+ if (raw && typeof raw === "object" && !Array.isArray(raw) && Object.keys(raw).length === 0) return { report_available: false, records: [{ id: input.import_id, name: "Import report unavailable" }], notes: ["The native response supplied no report. This is not evidence that the import has no issues."] };
1273
+ const parsed = z8.object({ url: z8.string().url().max(8192), expires_at: z8.iso.datetime({ offset: true }) }).safeParse(raw);
1274
+ if (!parsed.success || !safeUrl2(parsed.data.url) || new URL(parsed.data.url).protocol !== "https:" || Date.parse(parsed.data.expires_at) <= Date.now()) throw invalid2();
1275
+ return { report_available: true, import_id: input.import_id, download_url: parsed.data.url, expires_at: parsed.data.expires_at, records: [{ id: input.import_id, name: "Catalog import report", expires_at: parsed.data.expires_at }], notes: ["Temporary native download URL for this verified catalog/import only. Adport does not fetch it or forward Reddit credentials to its host."] };
1276
+ }
1277
+ async plan(op) {
1278
+ const create = op.tool === "reddit_create_catalog_product_set", update = op.tool === "reddit_update_catalog_product_set", remove = op.tool === "reddit_delete_catalog_product_set";
1279
+ if (op.provider !== "reddit" || !(create && op.kind === "create" || update && op.kind === "update" || remove && op.kind === "remove")) throw new AdportError5("INVALID_INPUT", "Unsupported catalog product-set operation/kind.");
1280
+ const input = create ? setCreate.parse(op.payload) : update ? setUpdate.parse(op.payload) : setDelete.parse(op.payload), selected2 = { account_id: op.accountId, business_id: input.business_id, catalog_id: input.catalog_id };
1281
+ const prepare = async () => {
1282
+ const parent = await this.catalogs.authorize(selected2, true);
1283
+ if ("expected_catalog_configuration_hash" in input) {
1284
+ if (parent.configuration_hash !== input.expected_catalog_configuration_hash) throw new AdportError5("PENDING_MISMATCH", "Catalog configuration changed; read it and preview again.");
1285
+ return;
1286
+ }
1287
+ const current2 = await this.set({ ...selected2, product_set_id: input.product_set_id });
1288
+ if (setHash(selected2, current2) !== input.expected_configuration_hash || "confirm_name" in input && current2.name !== input.confirm_name) throw new AdportError5("PENDING_MISMATCH", "Product-set configuration/name changed; read and preview again.");
1289
+ return current2;
1290
+ };
1291
+ const current = await prepare(), data = { ..."name" in input && input.name !== void 0 ? { name: input.name } : {}, ..."filter" in input && input.filter !== void 0 ? { filter: input.filter } : {} }, title = create ? "Create product set" : update ? "Update product set" : "Delete product set permanently", notes3 = ["This is a shared Business catalog; set membership and ads using it may be affected. No ads, spend or conversion events are submitted.", ...remove ? ["Deletes the set definition, not a snapshot of products. Dependent ads and current matching membership are not enumerated or frozen. No native restore/global usage guarantee."] : ["Filter JSON is sent once as the native string. Omitted set configuration is preserved and independently checked after updates."], "Native results are never replayed automatically. Reconcile known IDs after uncertain mutation or readback."];
1292
+ return {
1293
+ summary: `${title} \xB7 ${"name" in input && input.name !== void 0 ? input.name : current.name}`,
1294
+ changes: [remove ? "- Product set " + current.id : (create ? "+ " : "~ ") + "Product set " + canonical2(data)],
1295
+ coercions: [],
1296
+ budgetDeltas: [],
1297
+ notes: notes3,
1298
+ review: { provider: "reddit", accountId: op.accountId, kind: op.kind, title, subject: "name" in input && input.name !== void 0 ? input.name : current.name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Business", after: input.business_id }, ...!create ? [{ label: "Product set", after: current.id }] : [], ..."name" in data ? [{ label: "Name", before: current?.name, after: data.name }] : [], ..."filter" in data ? [{ label: "Filter", before: current ? filterText(current.filter) : void 0, after: filterText(data.filter) }] : [], ...remove ? [{ label: "Definition removed", after: filterText(current.filter) }] : []], notices: notes3 },
1299
+ execute: async () => {
1300
+ const fresh = await prepare();
1301
+ let id = current?.id;
1302
+ try {
1303
+ if (remove) {
1304
+ const response = await this.client.delete("product_sets/" + encodeURIComponent(id));
1305
+ if (!response.data || typeof response.data !== "object" || Array.isArray(response.data)) throw invalid2();
1306
+ await this.catalogs.authorize(selected2, true);
1307
+ if (await this.set({ ...selected2, product_set_id: id }, true)) throw invalid2();
1308
+ } else {
1309
+ const raw = create ? (await this.client.post("product_catalogs/" + encodeURIComponent(input.catalog_id) + "/product_sets", { data })).data : (await this.client.patch("product_sets/" + encodeURIComponent(id), { data })).data, known = z8.object({ id: redditCatalogId }).safeParse(raw);
1310
+ if (create && known.success) id = known.data.id;
1311
+ const receipt = setRow.safeParse(raw);
1312
+ if (!receipt.success || receipt.data.id !== id || receipt.data.catalog_id !== input.catalog_id) throw invalid2();
1313
+ await this.catalogs.authorize(selected2, true);
1314
+ const actual = await this.set({ ...selected2, product_set_id: id }), expected = create ? { id, catalog_id: input.catalog_id, name: input.name, filter: input.filter } : { ...fresh, ...data };
1315
+ if (canonical2(setConfig(actual)) !== canonical2(setConfig(expected))) throw invalid2();
1316
+ }
1317
+ return [id];
1318
+ } catch (error) {
1319
+ throw failure2(error, "Product-set mutation or independent preservation/absence readback is unconfirmed.", id ? [id] : void 0);
1320
+ }
1321
+ }
1322
+ };
1323
+ }
1324
+ };
1325
+
1326
+ // src/catalog-feeds.ts
1327
+ import { createHash as createHash4 } from "crypto";
1328
+ import { AdportError as AdportError6 } from "@adport/core";
1329
+ import { z as z10 } from "zod";
1330
+
1331
+ // src/catalog-feed-schemas.ts
1332
+ import { z as z9 } from "zod";
1333
+ import { hostedFeedUrl } from "@adport/core";
1334
+
1335
+ // src/catalog-feed-timezones.ts
1336
+ var REDDIT_CATALOG_TIMEZONES = /* @__PURE__ */ new Set([
1337
+ "Africa/Abidjan",
1338
+ "Africa/Accra",
1339
+ "Africa/Addis_Ababa",
1340
+ "Africa/Algiers",
1341
+ "Africa/Asmara",
1342
+ "Africa/Asmera",
1343
+ "Africa/Bamako",
1344
+ "Africa/Bangui",
1345
+ "Africa/Banjul",
1346
+ "Africa/Bissau",
1347
+ "Africa/Blantyre",
1348
+ "Africa/Brazzaville",
1349
+ "Africa/Bujumbura",
1350
+ "Africa/Cairo",
1351
+ "Africa/Casablanca",
1352
+ "Africa/Ceuta",
1353
+ "Africa/Conakry",
1354
+ "Africa/Dakar",
1355
+ "Africa/Dar_es_Salaam",
1356
+ "Africa/Djibouti",
1357
+ "Africa/Douala",
1358
+ "Africa/El_Aaiun",
1359
+ "Africa/Freetown",
1360
+ "Africa/Gaborone",
1361
+ "Africa/Harare",
1362
+ "Africa/Johannesburg",
1363
+ "Africa/Juba",
1364
+ "Africa/Kampala",
1365
+ "Africa/Khartoum",
1366
+ "Africa/Kigali",
1367
+ "Africa/Kinshasa",
1368
+ "Africa/Lagos",
1369
+ "Africa/Libreville",
1370
+ "Africa/Lome",
1371
+ "Africa/Luanda",
1372
+ "Africa/Lubumbashi",
1373
+ "Africa/Lusaka",
1374
+ "Africa/Malabo",
1375
+ "Africa/Maputo",
1376
+ "Africa/Maseru",
1377
+ "Africa/Mbabane",
1378
+ "Africa/Mogadishu",
1379
+ "Africa/Monrovia",
1380
+ "Africa/Nairobi",
1381
+ "Africa/Ndjamena",
1382
+ "Africa/Niamey",
1383
+ "Africa/Nouakchott",
1384
+ "Africa/Ouagadougou",
1385
+ "Africa/Porto-Novo",
1386
+ "Africa/Sao_Tome",
1387
+ "Africa/Timbuktu",
1388
+ "Africa/Tripoli",
1389
+ "Africa/Tunis",
1390
+ "Africa/Windhoek",
1391
+ "America/Adak",
1392
+ "America/Anchorage",
1393
+ "America/Anguilla",
1394
+ "America/Antigua",
1395
+ "America/Araguaina",
1396
+ "America/Argentina/Buenos_Aires",
1397
+ "America/Argentina/Catamarca",
1398
+ "America/Argentina/ComodRivadavia",
1399
+ "America/Argentina/Cordoba",
1400
+ "America/Argentina/Jujuy",
1401
+ "America/Argentina/La_Rioja",
1402
+ "America/Argentina/Mendoza",
1403
+ "America/Argentina/Rio_Gallegos",
1404
+ "America/Argentina/Salta",
1405
+ "America/Argentina/San_Juan",
1406
+ "America/Argentina/San_Luis",
1407
+ "America/Argentina/Tucuman",
1408
+ "America/Argentina/Ushuaia",
1409
+ "America/Aruba",
1410
+ "America/Asuncion",
1411
+ "America/Atikokan",
1412
+ "America/Atka",
1413
+ "America/Bahia",
1414
+ "America/Bahia_Banderas",
1415
+ "America/Barbados",
1416
+ "America/Belem",
1417
+ "America/Belize",
1418
+ "America/Blanc-Sablon",
1419
+ "America/Boa_Vista",
1420
+ "America/Bogota",
1421
+ "America/Boise",
1422
+ "America/Buenos_Aires",
1423
+ "America/Cambridge_Bay",
1424
+ "America/Campo_Grande",
1425
+ "America/Cancun",
1426
+ "America/Caracas",
1427
+ "America/Catamarca",
1428
+ "America/Cayenne",
1429
+ "America/Cayman",
1430
+ "America/Chicago",
1431
+ "America/Chihuahua",
1432
+ "America/Ciudad_Juarez",
1433
+ "America/Coral_Harbour",
1434
+ "America/Cordoba",
1435
+ "America/Costa_Rica",
1436
+ "America/Creston",
1437
+ "America/Cuiaba",
1438
+ "America/Curacao",
1439
+ "America/Danmarkshavn",
1440
+ "America/Dawson",
1441
+ "America/Dawson_Creek",
1442
+ "America/Denver",
1443
+ "America/Detroit",
1444
+ "America/Dominica",
1445
+ "America/Edmonton",
1446
+ "America/Eirunepe",
1447
+ "America/El_Salvador",
1448
+ "America/Ensenada",
1449
+ "America/Fort_Nelson",
1450
+ "America/Fort_Wayne",
1451
+ "America/Fortaleza",
1452
+ "America/Glace_Bay",
1453
+ "America/Godthab",
1454
+ "America/Goose_Bay",
1455
+ "America/Grand_Turk",
1456
+ "America/Grenada",
1457
+ "America/Guadeloupe",
1458
+ "America/Guatemala",
1459
+ "America/Guayaquil",
1460
+ "America/Guyana",
1461
+ "America/Halifax",
1462
+ "America/Havana",
1463
+ "America/Hermosillo",
1464
+ "America/Indiana/Indianapolis",
1465
+ "America/Indiana/Knox",
1466
+ "America/Indiana/Marengo",
1467
+ "America/Indiana/Petersburg",
1468
+ "America/Indiana/Tell_City",
1469
+ "America/Indiana/Vevay",
1470
+ "America/Indiana/Vincennes",
1471
+ "America/Indiana/Winamac",
1472
+ "America/Indianapolis",
1473
+ "America/Inuvik",
1474
+ "America/Iqaluit",
1475
+ "America/Jamaica",
1476
+ "America/Jujuy",
1477
+ "America/Juneau",
1478
+ "America/Kentucky/Louisville",
1479
+ "America/Kentucky/Monticello",
1480
+ "America/Knox_IN",
1481
+ "America/Kralendijk",
1482
+ "America/La_Paz",
1483
+ "America/Lima",
1484
+ "America/Los_Angeles",
1485
+ "America/Louisville",
1486
+ "America/Lower_Princes",
1487
+ "America/Maceio",
1488
+ "America/Managua",
1489
+ "America/Manaus",
1490
+ "America/Marigot",
1491
+ "America/Martinique",
1492
+ "America/Matamoros",
1493
+ "America/Mazatlan",
1494
+ "America/Mendoza",
1495
+ "America/Menominee",
1496
+ "America/Merida",
1497
+ "America/Metlakatla",
1498
+ "America/Mexico_City",
1499
+ "America/Miquelon",
1500
+ "America/Moncton",
1501
+ "America/Monterrey",
1502
+ "America/Montevideo",
1503
+ "America/Montreal",
1504
+ "America/Montserrat",
1505
+ "America/Nassau",
1506
+ "America/New_York",
1507
+ "America/Nipigon",
1508
+ "America/Nome",
1509
+ "America/Noronha",
1510
+ "America/North_Dakota/Beulah",
1511
+ "America/North_Dakota/Center",
1512
+ "America/North_Dakota/New_Salem",
1513
+ "America/Nuuk",
1514
+ "America/Ojinaga",
1515
+ "America/Panama",
1516
+ "America/Pangnirtung",
1517
+ "America/Paramaribo",
1518
+ "America/Phoenix",
1519
+ "America/Port-au-Prince",
1520
+ "America/Port_of_Spain",
1521
+ "America/Porto_Acre",
1522
+ "America/Porto_Velho",
1523
+ "America/Puerto_Rico",
1524
+ "America/Punta_Arenas",
1525
+ "America/Rainy_River",
1526
+ "America/Rankin_Inlet",
1527
+ "America/Recife",
1528
+ "America/Regina",
1529
+ "America/Resolute",
1530
+ "America/Rio_Branco",
1531
+ "America/Rosario",
1532
+ "America/Santa_Isabel",
1533
+ "America/Santarem",
1534
+ "America/Santiago",
1535
+ "America/Santo_Domingo",
1536
+ "America/Sao_Paulo",
1537
+ "America/Scoresbysund",
1538
+ "America/Shiprock",
1539
+ "America/Sitka",
1540
+ "America/St_Barthelemy",
1541
+ "America/St_Johns",
1542
+ "America/St_Kitts",
1543
+ "America/St_Lucia",
1544
+ "America/St_Thomas",
1545
+ "America/St_Vincent",
1546
+ "America/Swift_Current",
1547
+ "America/Tegucigalpa",
1548
+ "America/Thule",
1549
+ "America/Thunder_Bay",
1550
+ "America/Tijuana",
1551
+ "America/Toronto",
1552
+ "America/Tortola",
1553
+ "America/Vancouver",
1554
+ "America/Virgin",
1555
+ "America/Whitehorse",
1556
+ "America/Winnipeg",
1557
+ "America/Yakutat",
1558
+ "America/Yellowknife",
1559
+ "Antarctica/Casey",
1560
+ "Antarctica/Davis",
1561
+ "Antarctica/DumontDUrville",
1562
+ "Antarctica/Macquarie",
1563
+ "Antarctica/Mawson",
1564
+ "Antarctica/McMurdo",
1565
+ "Antarctica/Palmer",
1566
+ "Antarctica/Rothera",
1567
+ "Antarctica/South_Pole",
1568
+ "Antarctica/Syowa",
1569
+ "Antarctica/Troll",
1570
+ "Antarctica/Vostok",
1571
+ "Arctic/Longyearbyen",
1572
+ "Asia/Aden",
1573
+ "Asia/Almaty",
1574
+ "Asia/Amman",
1575
+ "Asia/Anadyr",
1576
+ "Asia/Aqtau",
1577
+ "Asia/Aqtobe",
1578
+ "Asia/Ashgabat",
1579
+ "Asia/Ashkhabad",
1580
+ "Asia/Atyrau",
1581
+ "Asia/Baghdad",
1582
+ "Asia/Bahrain",
1583
+ "Asia/Baku",
1584
+ "Asia/Bangkok",
1585
+ "Asia/Barnaul",
1586
+ "Asia/Beirut",
1587
+ "Asia/Bishkek",
1588
+ "Asia/Brunei",
1589
+ "Asia/Calcutta",
1590
+ "Asia/Chita",
1591
+ "Asia/Choibalsan",
1592
+ "Asia/Chongqing",
1593
+ "Asia/Chungking",
1594
+ "Asia/Colombo",
1595
+ "Asia/Dacca",
1596
+ "Asia/Damascus",
1597
+ "Asia/Dhaka",
1598
+ "Asia/Dili",
1599
+ "Asia/Dubai",
1600
+ "Asia/Dushanbe",
1601
+ "Asia/Famagusta",
1602
+ "Asia/Gaza",
1603
+ "Asia/Harbin",
1604
+ "Asia/Hebron",
1605
+ "Asia/Ho_Chi_Minh",
1606
+ "Asia/Hong_Kong",
1607
+ "Asia/Hovd",
1608
+ "Asia/Irkutsk",
1609
+ "Asia/Istanbul",
1610
+ "Asia/Jakarta",
1611
+ "Asia/Jayapura",
1612
+ "Asia/Jerusalem",
1613
+ "Asia/Kabul",
1614
+ "Asia/Kamchatka",
1615
+ "Asia/Karachi",
1616
+ "Asia/Kashgar",
1617
+ "Asia/Kathmandu",
1618
+ "Asia/Katmandu",
1619
+ "Asia/Khandyga",
1620
+ "Asia/Kolkata",
1621
+ "Asia/Krasnoyarsk",
1622
+ "Asia/Kuala_Lumpur",
1623
+ "Asia/Kuching",
1624
+ "Asia/Kuwait",
1625
+ "Asia/Macao",
1626
+ "Asia/Macau",
1627
+ "Asia/Magadan",
1628
+ "Asia/Makassar",
1629
+ "Asia/Manila",
1630
+ "Asia/Muscat",
1631
+ "Asia/Nicosia",
1632
+ "Asia/Novokuznetsk",
1633
+ "Asia/Novosibirsk",
1634
+ "Asia/Omsk",
1635
+ "Asia/Oral",
1636
+ "Asia/Phnom_Penh",
1637
+ "Asia/Pontianak",
1638
+ "Asia/Pyongyang",
1639
+ "Asia/Qatar",
1640
+ "Asia/Qostanay",
1641
+ "Asia/Qyzylorda",
1642
+ "Asia/Rangoon",
1643
+ "Asia/Riyadh",
1644
+ "Asia/Saigon",
1645
+ "Asia/Sakhalin",
1646
+ "Asia/Samarkand",
1647
+ "Asia/Seoul",
1648
+ "Asia/Shanghai",
1649
+ "Asia/Singapore",
1650
+ "Asia/Srednekolymsk",
1651
+ "Asia/Taipei",
1652
+ "Asia/Tashkent",
1653
+ "Asia/Tbilisi",
1654
+ "Asia/Tehran",
1655
+ "Asia/Tel_Aviv",
1656
+ "Asia/Thimbu",
1657
+ "Asia/Thimphu",
1658
+ "Asia/Tokyo",
1659
+ "Asia/Tomsk",
1660
+ "Asia/Ujung_Pandang",
1661
+ "Asia/Ulaanbaatar",
1662
+ "Asia/Ulan_Bator",
1663
+ "Asia/Urumqi",
1664
+ "Asia/Ust-Nera",
1665
+ "Asia/Vientiane",
1666
+ "Asia/Vladivostok",
1667
+ "Asia/Yakutsk",
1668
+ "Asia/Yangon",
1669
+ "Asia/Yekaterinburg",
1670
+ "Asia/Yerevan",
1671
+ "Atlantic/Azores",
1672
+ "Atlantic/Bermuda",
1673
+ "Atlantic/Canary",
1674
+ "Atlantic/Cape_Verde",
1675
+ "Atlantic/Faeroe",
1676
+ "Atlantic/Faroe",
1677
+ "Atlantic/Jan_Mayen",
1678
+ "Atlantic/Madeira",
1679
+ "Atlantic/Reykjavik",
1680
+ "Atlantic/South_Georgia",
1681
+ "Atlantic/St_Helena",
1682
+ "Atlantic/Stanley",
1683
+ "Australia/ACT",
1684
+ "Australia/Adelaide",
1685
+ "Australia/Brisbane",
1686
+ "Australia/Broken_Hill",
1687
+ "Australia/Canberra",
1688
+ "Australia/Currie",
1689
+ "Australia/Darwin",
1690
+ "Australia/Eucla",
1691
+ "Australia/Hobart",
1692
+ "Australia/LHI",
1693
+ "Australia/Lindeman",
1694
+ "Australia/Lord_Howe",
1695
+ "Australia/Melbourne",
1696
+ "Australia/NSW",
1697
+ "Australia/North",
1698
+ "Australia/Perth",
1699
+ "Australia/Queensland",
1700
+ "Australia/South",
1701
+ "Australia/Sydney",
1702
+ "Australia/Tasmania",
1703
+ "Australia/Victoria",
1704
+ "Australia/West",
1705
+ "Australia/Yancowinna",
1706
+ "Brazil/Acre",
1707
+ "Brazil/DeNoronha",
1708
+ "Brazil/East",
1709
+ "Brazil/West",
1710
+ "CET",
1711
+ "CST6CDT",
1712
+ "Canada/Atlantic",
1713
+ "Canada/Central",
1714
+ "Canada/Eastern",
1715
+ "Canada/Mountain",
1716
+ "Canada/Newfoundland",
1717
+ "Canada/Pacific",
1718
+ "Canada/Saskatchewan",
1719
+ "Canada/Yukon",
1720
+ "Chile/Continental",
1721
+ "Chile/EasterIsland",
1722
+ "Cuba",
1723
+ "EET",
1724
+ "EST",
1725
+ "EST5EDT",
1726
+ "Egypt",
1727
+ "Eire",
1728
+ "Etc/GMT",
1729
+ "Etc/GMT+0",
1730
+ "Etc/GMT+1",
1731
+ "Etc/GMT+10",
1732
+ "Etc/GMT+11",
1733
+ "Etc/GMT+12",
1734
+ "Etc/GMT+2",
1735
+ "Etc/GMT+3",
1736
+ "Etc/GMT+4",
1737
+ "Etc/GMT+5",
1738
+ "Etc/GMT+6",
1739
+ "Etc/GMT+7",
1740
+ "Etc/GMT+8",
1741
+ "Etc/GMT+9",
1742
+ "Etc/GMT-0",
1743
+ "Etc/GMT-1",
1744
+ "Etc/GMT-10",
1745
+ "Etc/GMT-11",
1746
+ "Etc/GMT-12",
1747
+ "Etc/GMT-13",
1748
+ "Etc/GMT-14",
1749
+ "Etc/GMT-2",
1750
+ "Etc/GMT-3",
1751
+ "Etc/GMT-4",
1752
+ "Etc/GMT-5",
1753
+ "Etc/GMT-6",
1754
+ "Etc/GMT-7",
1755
+ "Etc/GMT-8",
1756
+ "Etc/GMT-9",
1757
+ "Etc/GMT0",
1758
+ "Etc/Greenwich",
1759
+ "Etc/UCT",
1760
+ "Etc/UTC",
1761
+ "Etc/Universal",
1762
+ "Etc/Zulu",
1763
+ "Europe/Amsterdam",
1764
+ "Europe/Andorra",
1765
+ "Europe/Astrakhan",
1766
+ "Europe/Athens",
1767
+ "Europe/Belfast",
1768
+ "Europe/Belgrade",
1769
+ "Europe/Berlin",
1770
+ "Europe/Bratislava",
1771
+ "Europe/Brussels",
1772
+ "Europe/Bucharest",
1773
+ "Europe/Budapest",
1774
+ "Europe/Busingen",
1775
+ "Europe/Chisinau",
1776
+ "Europe/Copenhagen",
1777
+ "Europe/Dublin",
1778
+ "Europe/Gibraltar",
1779
+ "Europe/Guernsey",
1780
+ "Europe/Helsinki",
1781
+ "Europe/Isle_of_Man",
1782
+ "Europe/Istanbul",
1783
+ "Europe/Jersey",
1784
+ "Europe/Kaliningrad",
1785
+ "Europe/Kiev",
1786
+ "Europe/Kirov",
1787
+ "Europe/Kyiv",
1788
+ "Europe/Lisbon",
1789
+ "Europe/Ljubljana",
1790
+ "Europe/London",
1791
+ "Europe/Luxembourg",
1792
+ "Europe/Madrid",
1793
+ "Europe/Malta",
1794
+ "Europe/Mariehamn",
1795
+ "Europe/Minsk",
1796
+ "Europe/Monaco",
1797
+ "Europe/Moscow",
1798
+ "Europe/Nicosia",
1799
+ "Europe/Oslo",
1800
+ "Europe/Paris",
1801
+ "Europe/Podgorica",
1802
+ "Europe/Prague",
1803
+ "Europe/Riga",
1804
+ "Europe/Rome",
1805
+ "Europe/Samara",
1806
+ "Europe/San_Marino",
1807
+ "Europe/Sarajevo",
1808
+ "Europe/Saratov",
1809
+ "Europe/Simferopol",
1810
+ "Europe/Skopje",
1811
+ "Europe/Sofia",
1812
+ "Europe/Stockholm",
1813
+ "Europe/Tallinn",
1814
+ "Europe/Tirane",
1815
+ "Europe/Tiraspol",
1816
+ "Europe/Ulyanovsk",
1817
+ "Europe/Uzhgorod",
1818
+ "Europe/Vaduz",
1819
+ "Europe/Vatican",
1820
+ "Europe/Vienna",
1821
+ "Europe/Vilnius",
1822
+ "Europe/Volgograd",
1823
+ "Europe/Warsaw",
1824
+ "Europe/Zagreb",
1825
+ "Europe/Zaporozhye",
1826
+ "Europe/Zurich",
1827
+ "GB",
1828
+ "GB-Eire",
1829
+ "GMT",
1830
+ "GMT+0",
1831
+ "GMT-0",
1832
+ "GMT0",
1833
+ "Greenwich",
1834
+ "HST",
1835
+ "Hongkong",
1836
+ "Iceland",
1837
+ "Indian/Antananarivo",
1838
+ "Indian/Chagos",
1839
+ "Indian/Christmas",
1840
+ "Indian/Cocos",
1841
+ "Indian/Comoro",
1842
+ "Indian/Kerguelen",
1843
+ "Indian/Mahe",
1844
+ "Indian/Maldives",
1845
+ "Indian/Mauritius",
1846
+ "Indian/Mayotte",
1847
+ "Indian/Reunion",
1848
+ "Iran",
1849
+ "Israel",
1850
+ "Jamaica",
1851
+ "Japan",
1852
+ "Kwajalein",
1853
+ "Libya",
1854
+ "MET",
1855
+ "MST",
1856
+ "MST7MDT",
1857
+ "Mexico/BajaNorte",
1858
+ "Mexico/BajaSur",
1859
+ "Mexico/General",
1860
+ "NZ",
1861
+ "NZ-CHAT",
1862
+ "Navajo",
1863
+ "PRC",
1864
+ "PST8PDT",
1865
+ "Pacific/Apia",
1866
+ "Pacific/Auckland",
1867
+ "Pacific/Bougainville",
1868
+ "Pacific/Chatham",
1869
+ "Pacific/Chuuk",
1870
+ "Pacific/Easter",
1871
+ "Pacific/Efate",
1872
+ "Pacific/Enderbury",
1873
+ "Pacific/Fakaofo",
1874
+ "Pacific/Fiji",
1875
+ "Pacific/Funafuti",
1876
+ "Pacific/Galapagos",
1877
+ "Pacific/Gambier",
1878
+ "Pacific/Guadalcanal",
1879
+ "Pacific/Guam",
1880
+ "Pacific/Honolulu",
1881
+ "Pacific/Johnston",
1882
+ "Pacific/Kanton",
1883
+ "Pacific/Kiritimati",
1884
+ "Pacific/Kosrae",
1885
+ "Pacific/Kwajalein",
1886
+ "Pacific/Majuro",
1887
+ "Pacific/Marquesas",
1888
+ "Pacific/Midway",
1889
+ "Pacific/Nauru",
1890
+ "Pacific/Niue",
1891
+ "Pacific/Norfolk",
1892
+ "Pacific/Noumea",
1893
+ "Pacific/Pago_Pago",
1894
+ "Pacific/Palau",
1895
+ "Pacific/Pitcairn",
1896
+ "Pacific/Pohnpei",
1897
+ "Pacific/Ponape",
1898
+ "Pacific/Port_Moresby",
1899
+ "Pacific/Rarotonga",
1900
+ "Pacific/Saipan",
1901
+ "Pacific/Samoa",
1902
+ "Pacific/Tahiti",
1903
+ "Pacific/Tarawa",
1904
+ "Pacific/Tongatapu",
1905
+ "Pacific/Truk",
1906
+ "Pacific/Wake",
1907
+ "Pacific/Wallis",
1908
+ "Pacific/Yap",
1909
+ "Poland",
1910
+ "Portugal",
1911
+ "ROC",
1912
+ "ROK",
1913
+ "Singapore",
1914
+ "Turkey",
1915
+ "UCT",
1916
+ "US/Alaska",
1917
+ "US/Aleutian",
1918
+ "US/Arizona",
1919
+ "US/Central",
1920
+ "US/East-Indiana",
1921
+ "US/Eastern",
1922
+ "US/Hawaii",
1923
+ "US/Indiana-Starke",
1924
+ "US/Michigan",
1925
+ "US/Mountain",
1926
+ "US/Pacific",
1927
+ "US/Samoa",
1928
+ "UTC",
1929
+ "Universal",
1930
+ "W-SU",
1931
+ "WET",
1932
+ "Zulu"
1933
+ ]);
1934
+
1935
+ // src/catalog-feed-schemas.ts
1936
+ var timezone = z9.string().min(1).max(128).refine((value) => REDDIT_CATALOG_TIMEZONES.has(value), "Use a time zone from Reddit\u2019s published IANA list");
1937
+ var sourceUrl = z9.string().min(1).max(8192).refine((value) => {
1938
+ try {
1939
+ const url3 = new URL(value), host = url3.hostname.toLowerCase().replace(/\.$/, "");
1940
+ return ["https:", "ftp:", "sftp:"].includes(url3.protocol) && !url3.username && !url3.password && !url3.hash && !/[\x00-\x20\x7f]/.test(value) && host.includes(".") && !/[^\w.-]/.test(host) && !/^[\d.]+$/.test(host) && ![".local", ".localhost", ".internal"].some((suffix) => host.endsWith(suffix));
1941
+ } catch {
1942
+ return false;
1943
+ }
1944
+ }, "Use an externally hosted HTTPS, FTP or SFTP URL without embedded credentials, whitespace or a fragment");
1945
+ var feedMode = z9.enum(["REPLACE", "UPDATE"]);
1946
+ var feedSchedule = z9.object({
1947
+ is_paused: z9.boolean(),
1948
+ interval: z9.enum(["HOURLY", "DAILY", "WEEKLY", "MONTHLY"]),
1949
+ interval_count: z9.number().int().positive().safe(),
1950
+ hour: z9.number().int().min(0).max(23),
1951
+ minute: z9.number().int().min(0).max(59),
1952
+ timezone,
1953
+ day_of_month: z9.number().int().min(1).max(31).nullable().optional(),
1954
+ day_of_week: z9.enum(["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]).nullable().optional()
1955
+ }).strict().superRefine((input, ctx) => {
1956
+ if (input.interval === "MONTHLY" ? input.day_of_month == null : input.day_of_month != null) ctx.addIssue({ code: "custom", path: ["day_of_month"], message: "Choose a day_of_month only for a monthly schedule" });
1957
+ if (input.interval === "WEEKLY" ? input.day_of_week == null : input.day_of_week != null) ctx.addIssue({ code: "custom", path: ["day_of_week"], message: "Choose a day_of_week only for a weekly schedule" });
1958
+ });
1959
+ var feedInput = catalogInput.extend({ feed_id: redditCatalogId }).strict();
1960
+ var feedList = catalogInput.extend({ page_size: z9.number().int().min(1).max(100).default(20), cursor: z9.string().min(1).max(512).optional() }).strict();
1961
+ var name2 = z9.string().min(1).max(4e3).nullable();
1962
+ var authentication = { username: z9.string().max(100).nullable().optional(), password: z9.string().max(100).nullable().optional() };
1963
+ var selected = feedInput.omit({ account_id: true });
1964
+ var feedCreate = catalogInput.omit({ account_id: true }).extend({
1965
+ name: name2.optional(),
1966
+ url: sourceUrl,
1967
+ mode: feedMode,
1968
+ schedule: feedSchedule.nullable(),
1969
+ ...authentication,
1970
+ expected_catalog_configuration_hash: hash,
1971
+ acknowledge_shared_effects: z9.literal(true),
1972
+ acknowledge_automatic_processing: z9.literal(true)
1973
+ }).strict();
1974
+ var feedUpdateFields = selected.extend({
1975
+ name: name2.optional(),
1976
+ url: sourceUrl.optional(),
1977
+ mode: feedMode.optional(),
1978
+ schedule: feedSchedule.nullable().optional(),
1979
+ ...authentication,
1980
+ expected_configuration_hash: hash,
1981
+ acknowledge_shared_effects: z9.literal(true),
1982
+ acknowledge_automatic_processing: z9.literal(true).optional()
1983
+ }).strict();
1984
+ var feedUpdate = feedUpdateFields.refine((input) => ["name", "url", "mode", "schedule", "username", "password"].some((key) => Object.hasOwn(input, key)), "Provide a feed field").refine((input) => !["url", "mode", "schedule", "username", "password"].some((key) => Object.hasOwn(input, key)) || input.acknowledge_automatic_processing === true, "Source/mode/schedule/authentication changes require automatic-processing acknowledgement");
1985
+ var hostedFeedCreate = feedCreate.omit({ username: true, password: true }).extend({ url: hostedFeedUrl });
1986
+ var hostedFeedUpdate = feedUpdateFields.omit({ username: true, password: true }).extend({ url: hostedFeedUrl.optional() });
1987
+ var feedStatus = selected.extend({ is_paused: z9.boolean(), expected_configuration_hash: hash, acknowledge_shared_effects: z9.literal(true), acknowledge_automatic_processing: z9.literal(true) }).strict();
1988
+ var feedDelete = selected.extend({ expected_configuration_hash: hash, acknowledge_shared_effects: z9.literal(true), acknowledge_delete_feed: z9.literal(true) }).strict();
1989
+
1990
+ // src/catalog-feeds.ts
1991
+ var nativeSchedule = z10.object({ is_paused: z10.boolean().nullable().optional(), interval: z10.enum(["HOURLY", "DAILY", "WEEKLY", "MONTHLY"]).nullable().optional(), interval_count: z10.number().int().positive().safe().nullable().optional(), day_of_month: z10.number().int().min(1).max(31).nullable().optional(), day_of_week: z10.enum(["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]).nullable().optional(), hour: z10.number().int().min(0).max(23).nullable().optional(), minute: z10.number().int().min(0).max(59).nullable().optional(), timezone: z10.string().max(128).nullable().optional(), next_import_at: z10.iso.datetime({ offset: true }).nullable().optional() }).strict();
1992
+ var feedRow = z10.object({ id: redditCatalogId, catalog_id: redditCatalogId, name: z10.string().min(1).max(4e3).nullable().optional(), url: z10.string().min(1).max(8192), mode: feedMode, schedule: nativeSchedule.nullable().optional(), username: z10.string().max(100).nullable().optional(), password: z10.string().max(100).nullable().optional() });
1993
+ var scope2 = (input) => ({ account_id: input.account_id, business_id: input.business_id, catalog_id: input.catalog_id });
1994
+ var canonical3 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
1995
+ var digest3 = (value) => createHash4("sha256").update(canonical3(value)).digest("hex");
1996
+ function scheduleConfig(value) {
1997
+ if (value === null || value === void 0) return value;
1998
+ const { next_import_at: _volatile, ...config4 } = value;
1999
+ return { ...config4, day_of_month: config4.day_of_month ?? null, day_of_week: config4.day_of_week ?? null };
2000
+ }
2001
+ var config2 = (row2) => ({ id: row2.id, catalog_id: row2.catalog_id, name: row2.name, url: row2.url, mode: row2.mode, schedule: scheduleConfig(row2.schedule) });
2002
+ var configurationHash2 = (input, row2) => digest3({ ...scope2(input), configuration: config2(row2) });
2003
+ var origin = (value) => {
2004
+ try {
2005
+ const url3 = new URL(value);
2006
+ return url3.protocol + "//" + url3.host;
2007
+ } catch {
2008
+ return "Unavailable";
2009
+ }
2010
+ };
2011
+ function secrets(row2) {
2012
+ if (!row2) return [];
2013
+ const values = [row2.url, row2.username, row2.password].filter((value) => typeof value === "string" && value.length > 0);
2014
+ try {
2015
+ const url3 = new URL(row2.url);
2016
+ for (const value of url3.searchParams.values()) if (value) values.push(value);
2017
+ for (const entry of url3.search.slice(1).split("&")) {
2018
+ const value = entry.slice(entry.indexOf("=") + 1);
2019
+ if (entry.includes("=") && value) values.push(value);
2020
+ }
2021
+ } catch {
2022
+ }
2023
+ return values;
2024
+ }
2025
+ function redact(text3, values) {
2026
+ const alternatives = [...new Set(values)].filter(Boolean).sort((a, b) => b.length - a.length).map((value) => value.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"));
2027
+ return alternatives.length ? text3.replace(new RegExp(alternatives.join("|"), "g"), "[redacted]") : text3;
2028
+ }
2029
+ function publicValue(value, privateValues) {
2030
+ if (typeof value === "string") return redact(value, privateValues);
2031
+ if (Array.isArray(value)) return value.map((item) => publicValue(item, privateValues));
2032
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, publicValue(item, privateValues)]));
2033
+ return value;
2034
+ }
2035
+ function publicFeed(input, row2) {
2036
+ const privateValues = secrets(row2);
2037
+ return { feed_id: row2.id, catalog_id: row2.catalog_id, name: row2.name == null ? row2.name : redact(row2.name, privateValues), mode: row2.mode, source_origin: redact(origin(row2.url), privateValues), source_fingerprint: digest3(row2.url), schedule: row2.schedule === void 0 ? void 0 : row2.schedule === null ? null : { ...scheduleConfig(row2.schedule), timezone: row2.schedule.timezone == null ? row2.schedule.timezone : redact(row2.schedule.timezone, privateValues), next_import_at: row2.schedule.next_import_at }, configuration_hash: configurationHash2(input, row2), authentication_values_reported: false };
2038
+ }
2039
+ var notes = ["This shared feed can change products used by existing ads. No ads, spend or conversion events are submitted by this operation.", "Choose native REPLACE or UPDATE explicitly. Feed processing can change shared catalog products; native import results and downstream effects require separate inspection.", "Source URLs/authentication are private in tool results and widget approval metadata. Source, authentication and name changes must be applied by the agent with the identical arguments.", "Authentication values are not independently verified by native reads. Configuration hashes exclude them and cannot detect authentication-only changes.", "Source lifetime and successful ingestion are not established by configuration readback. A short-lived private upload URL is unsuitable for an ongoing recurring feed.", "Source fingerprints identify the URL, not immutable feed bytes. Approval binds the URL/configuration; remote source contents can change between imports.", "Never replay a native write automatically. Reconcile known IDs after uncertain mutation or readback."];
2040
+ var invalid3 = () => new AdportError6("PROVIDER_ERROR", "Reddit feed identifier, catalog scope or native configuration could not be verified.");
2041
+ function failure3(error, message, ids2) {
2042
+ const details = error instanceof AdportError6 && error.details && typeof error.details === "object" ? error.details : {};
2043
+ return new AdportError6("PROVIDER_ERROR", message + " Provider bodies and source credentials stay hidden; no mutation was retried.", { ...Number.isInteger(details.http_status) ? { http_status: details.http_status } : {}, ...ids2 ? { resourceIds: ids2 } : {} });
2044
+ }
2045
+ function knownSchedule(value) {
2046
+ if (value === null) return null;
2047
+ if (value === void 0) throw new AdportError6("PROVIDER_ERROR", "Current feed schedule is unavailable; preservation cannot be verified.");
2048
+ const parsed = feedSchedule.safeParse(scheduleConfig(value));
2049
+ if (!parsed.success) throw new AdportError6("PROVIDER_ERROR", "Current feed schedule is incomplete or unsupported; read native configuration before changing it.");
2050
+ return parsed.data;
2051
+ }
2052
+ var RedditCatalogFeeds = class {
2053
+ constructor(client, catalogs) {
2054
+ this.client = client;
2055
+ this.catalogs = catalogs;
2056
+ }
2057
+ client;
2058
+ catalogs;
2059
+ async native(input, id, absent = false) {
2060
+ const path2 = id ? "product_feeds/" + encodeURIComponent(id) : "product_catalogs/" + encodeURIComponent(input.catalog_id) + "/product_feeds";
2061
+ let response;
2062
+ try {
2063
+ response = await this.client.get(path2);
2064
+ } catch (error) {
2065
+ if (absent && error instanceof AdportError6 && error.details?.http_status === 404) return [];
2066
+ throw failure3(error, "Reddit catalog feed read failed.");
2067
+ }
2068
+ const parsed = (id ? feedRow.transform((value) => [value]) : z10.array(feedRow).max(5e3)).safeParse(response.data);
2069
+ if (!parsed.success || response.pagination?.next_url || parsed.data.some((row2) => row2.catalog_id !== input.catalog_id || id && row2.id !== id) || new Set(parsed.data.map((row2) => row2.id)).size !== parsed.data.length) throw invalid3();
2070
+ return parsed.data;
2071
+ }
2072
+ async list(value) {
2073
+ const input = feedList.parse(value);
2074
+ await this.catalogs.authorize(scope2(input));
2075
+ const rows = (await this.native(input)).sort((a, b) => a.id.localeCompare(b.id)), snapshot2 = digest3({ ...scope2(input), page_size: input.page_size, feeds: rows.map(config2) });
2076
+ let offset = 0;
2077
+ if (input.cursor) {
2078
+ let parsed;
2079
+ try {
2080
+ parsed = z10.object({ offset: z10.number().int().positive().max(4999), snapshot: z10.string().regex(/^[a-f0-9]{64}$/) }).strict().parse(JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")));
2081
+ } catch {
2082
+ throw new AdportError6("INVALID_INPUT", "Invalid feed cursor; refresh the first page.");
2083
+ }
2084
+ if (parsed.snapshot !== snapshot2 || parsed.offset >= rows.length || parsed.offset % input.page_size !== 0) throw new AdportError6("PENDING_MISMATCH", "Feed configuration or selection changed; refresh the first page.");
2085
+ offset = parsed.offset;
2086
+ }
2087
+ const feeds = rows.slice(offset, offset + input.page_size).map((row2) => publicFeed(input, row2)), more = offset + feeds.length < rows.length;
2088
+ return { feeds, records: feeds.map((row2) => ({ id: row2.feed_id, name: row2.name ?? "Feed " + row2.feed_id, mode: row2.mode, source: row2.source_origin, schedule: row2.schedule === void 0 ? "Unavailable" : row2.schedule === null ? "No recurring schedule" : row2.schedule.is_paused === true ? "Paused" : row2.schedule.is_paused === false ? "Running" : "Unavailable" })), complete: !more, truncated: more, ...more ? { next_cursor: Buffer.from(JSON.stringify({ offset: offset + feeds.length, snapshot: snapshot2 })).toString("base64url") } : {}, notes: ["Native feed lists are unpaged. Adport bounds them to 5,000 and pages a configuration snapshot locally; this is not a product inventory.", ...notes.slice(2, 5)] };
2089
+ }
2090
+ async get(value) {
2091
+ const input = feedInput.parse(value);
2092
+ await this.catalogs.authorize(scope2(input));
2093
+ const feed = publicFeed(input, (await this.native(input, input.feed_id))[0]);
2094
+ return { feed, records: [{ id: feed.feed_id, name: feed.name ?? "Feed " + feed.feed_id, mode: feed.mode, source: feed.source_origin }], complete: true, truncated: false, notes: notes.slice(2, 5) };
2095
+ }
2096
+ async plan(op) {
2097
+ const create = op.tool === "reddit_create_catalog_feed", update = op.tool === "reddit_update_catalog_feed", toggle = op.tool === "reddit_set_catalog_feed_schedule_status", remove = op.tool === "reddit_delete_catalog_feed";
2098
+ if (op.provider !== "reddit" || !(create && op.kind === "create" || (update || toggle) && op.kind === "update" || remove && op.kind === "remove")) throw new AdportError6("INVALID_INPUT", "Reddit feed operation/provider kind mismatch.");
2099
+ const input = create ? feedCreate.parse(op.payload) : update ? feedUpdate.parse(op.payload) : toggle ? feedStatus.parse(op.payload) : feedDelete.parse(op.payload), selected2 = { account_id: op.accountId, business_id: input.business_id, catalog_id: input.catalog_id };
2100
+ const prepare = async () => {
2101
+ const parent = await this.catalogs.authorize(selected2, true);
2102
+ if ("expected_catalog_configuration_hash" in input) {
2103
+ if (parent.configuration_hash !== input.expected_catalog_configuration_hash) throw new AdportError6("PENDING_MISMATCH", "Catalog configuration changed; read and preview again.");
2104
+ return;
2105
+ }
2106
+ const current = (await this.native(selected2, input.feed_id))[0];
2107
+ if (configurationHash2(selected2, current) !== input.expected_configuration_hash) throw new AdportError6("PENDING_MISMATCH", "Feed configuration changed; read and preview again.");
2108
+ if (!remove) {
2109
+ const schedule = knownSchedule(current.schedule);
2110
+ if ("is_paused" in input && (schedule === null || schedule.is_paused === input.is_paused)) throw new AdportError6("INVALID_INPUT", "A configured schedule must change to its opposite pause state.");
2111
+ }
2112
+ return current;
2113
+ };
2114
+ const before = await prepare(), data = {};
2115
+ const writable = /* @__PURE__ */ new Set(["name", "url", "mode", "schedule", "username", "password"]);
2116
+ for (const [key, value] of Object.entries(input)) if (writable.has(key) && value !== void 0) data[key] = value;
2117
+ if ("is_paused" in input) data.schedule = { ...knownSchedule(before.schedule), is_paused: input.is_paused };
2118
+ const privateValues = [...secrets(before), ...secrets({ url: "url" in input ? input.url ?? "" : "", username: "username" in input ? input.username : void 0, password: "password" in input ? input.password : void 0 })], display = (value) => redact(value, privateValues), fields = [{ label: "Catalog", after: input.catalog_id }, { label: "Business", after: input.business_id }];
2119
+ if (before) fields.push({ label: "Feed", after: before.id });
2120
+ if ("name" in data) fields.push({ label: "Name", before: before?.name == null ? before?.name : display(before.name), after: data.name === null ? "Cleared" : display(String(data.name)) });
2121
+ if ("url" in data) fields.push({ label: "Source", ...before ? { before: { origin: display(origin(before.url)), fingerprint: digest3(before.url) } } : {}, after: { origin: display(origin(String(data.url))), fingerprint: digest3(String(data.url)) } });
2122
+ if ("mode" in data) fields.push({ label: "Product processing", ...before ? { before: before.mode } : {}, after: data.mode });
2123
+ if ("username" in data || "password" in data) fields.push({ label: "Source authentication", after: { username: "username" in data ? data.username === null ? "Cleared" : "Supplied; hidden" : "Preserved", password: "password" in data ? data.password === null ? "Cleared" : "Supplied; hidden" : "Preserved" } });
2124
+ if ("schedule" in data) fields.push({ label: "Schedule", ...before ? { before: scheduleConfig(before.schedule) } : {}, after: data.schedule === null ? "No recurring schedule" : data.schedule });
2125
+ if (remove) fields.push({ label: "Feed removed", before: before.name == null ? "Feed " + before.id : display(before.name), after: "Permanently deleted" });
2126
+ const title = create ? "Create catalog feed" : remove ? "Delete catalog feed permanently" : toggle ? "Change feed schedule status" : "Update catalog feed", subject = "name" in input && typeof input.name === "string" ? display(input.name) : before?.name == null ? create ? "New catalog feed" : "Feed " + before.id : display(before.name), safeFields = publicValue(fields, privateValues);
2127
+ const notices = [notes[0]];
2128
+ if (remove) notices.push("Permanently removes the shared feed definition. Imported products and dependent ads are not enumerated or frozen; their effects require separate inspection.", "No restore or automatic write replay is available. Reconcile the known feed after an uncertain result.");
2129
+ else if (toggle) notices.push("Pausing controls future scheduling; this does not certify cancellation or reversal of an existing import.");
2130
+ else {
2131
+ if (["url", "mode", "schedule", "username", "password"].some((key) => key in data)) notices.push("The selected changes may start native product processing immediately. Configuration readback does not certify source authentication, successful ingestion or product retention.");
2132
+ if (["url", "name", "username", "password"].some((key) => key in data)) notices.push("Private source/name arguments stay with the agent. Review in chat, then ask it to apply the identical arguments.");
2133
+ if ("url" in data) notices.push("The fingerprint identifies the URL, not immutable feed bytes. The source can change between imports and must remain available for its intended schedule.");
2134
+ }
2135
+ return {
2136
+ summary: title + " \xB7 " + subject,
2137
+ changes: safeFields.map((field) => (remove ? "- " : create ? "+ " : "~ ") + field.label + ": " + canonical3(field.after)),
2138
+ coercions: [],
2139
+ budgetDeltas: [],
2140
+ notes: notices,
2141
+ review: { provider: "reddit", accountId: op.accountId, kind: op.kind, title, subject, fields: safeFields, notices },
2142
+ execute: async () => {
2143
+ const fresh = await prepare();
2144
+ let id = before?.id;
2145
+ try {
2146
+ if (remove) {
2147
+ const receipt = await this.client.delete("product_feeds/" + encodeURIComponent(id));
2148
+ if (!receipt.data || typeof receipt.data !== "object" || Array.isArray(receipt.data)) throw invalid3();
2149
+ await this.catalogs.authorize(selected2, true);
2150
+ if ((await this.native(selected2, id, true)).length) throw invalid3();
2151
+ } else {
2152
+ const raw = create ? (await this.client.post("product_catalogs/" + encodeURIComponent(input.catalog_id) + "/product_feeds", { data })).data : (await this.client.patch("product_feeds/" + encodeURIComponent(id), { data })).data, known = z10.object({ id: redditCatalogId }).safeParse(raw);
2153
+ if (create && known.success) id = known.data.id;
2154
+ const receipt = feedRow.safeParse(raw);
2155
+ if (!receipt.success || receipt.data.id !== id || receipt.data.catalog_id !== input.catalog_id) throw invalid3();
2156
+ await this.catalogs.authorize(selected2, true);
2157
+ const actual = (await this.native(selected2, id))[0];
2158
+ const expected = create ? { id, catalog_id: input.catalog_id, name: "name" in data ? data.name : actual.name, url: data.url, mode: data.mode, schedule: data.schedule } : { ...fresh, ...data };
2159
+ if (canonical3(config2(actual)) !== canonical3(config2(feedRow.parse(expected)))) throw invalid3();
2160
+ }
2161
+ return { applied: true, resourceIds: [id], ..."username" in data || "password" in data ? { details: { authentication_readback_verified: false }, warnings: ["Native configuration was read back; source authentication and ingestion success were not independently verified."] } : {} };
2162
+ } catch (error) {
2163
+ throw failure3(error, "Reddit feed mutation or independent configuration/absence readback is unconfirmed. Reconcile known IDs before another write.", id ? [id] : void 0);
2164
+ }
2165
+ }
2166
+ };
2167
+ }
2168
+ };
2169
+
2170
+ // src/catalog-products.ts
2171
+ import { createHash as createHash5 } from "crypto";
2172
+ import { z as z12 } from "zod";
2173
+ import { AdportError as AdportError7 } from "@adport/core";
2174
+
2175
+ // src/catalog-product-schemas.ts
2176
+ import { z as z11 } from "zod";
2177
+ var text = z11.string().max(4e4);
2178
+ var optionalText = text.nullable().optional();
2179
+ var url2 = z11.string().max(8192).url().refine((value) => {
2180
+ const parsed = new URL(value);
2181
+ return ["http:", "https:"].includes(parsed.protocol) && !parsed.username && !parsed.password;
2182
+ }, "Use an HTTP(S) URL without credentials");
2183
+ var money = z11.string().regex(/^\d+(?:\.\d+)? [A-Z]{3}$/).max(256);
2184
+ var number = z11.number().int().safe().nullable().optional();
2185
+ var period = z11.string().max(256).refine((value) => {
2186
+ const parts = value.split("/");
2187
+ return parts.length === 2 && parts.every((v) => /T.*(?:Z|[+-]\d{2}:?\d{2})$/.test(v) && Number.isFinite(Date.parse(v))) && Date.parse(parts[0]) < Date.parse(parts[1]);
2188
+ }, "Use an ordered ISO datetime interval with timezones");
2189
+ var catalogProduct = z11.object({
2190
+ id: productId,
2191
+ title: optionalText,
2192
+ description: optionalText,
2193
+ price: money.nullable().optional(),
2194
+ link: url2.nullable().optional(),
2195
+ image_link: url2.nullable().optional(),
2196
+ item_group_id: optionalText,
2197
+ sale_price: money.nullable().optional(),
2198
+ sale_price_effective_date: period.nullable().optional(),
2199
+ cost_of_goods_sold: money.nullable().optional(),
2200
+ mobile_link: url2.nullable().optional(),
2201
+ platform_specific_link: z11.object({ android: url2.nullable().optional(), ios: url2.nullable().optional() }).strict().nullable().optional(),
2202
+ lifestyle_image_link: url2.nullable().optional(),
2203
+ additional_image_links: z11.array(url2).max(10).refine((values) => new Set(values).size === values.length).nullable().optional(),
2204
+ product_type: optionalText,
2205
+ product_detail: optionalText,
2206
+ product_highlight: optionalText,
2207
+ google_product_category: optionalText,
2208
+ brand: optionalText,
2209
+ gtin: optionalText,
2210
+ mpn: optionalText,
2211
+ size: optionalText,
2212
+ size_type: optionalText,
2213
+ condition: optionalText,
2214
+ color: optionalText,
2215
+ gender: optionalText,
2216
+ material: optionalText,
2217
+ pattern: optionalText,
2218
+ age_group: optionalText,
2219
+ adult: z11.boolean().nullable().optional(),
2220
+ is_bundle: z11.boolean().nullable().optional(),
2221
+ custom_label_0: optionalText,
2222
+ custom_label_1: optionalText,
2223
+ custom_label_2: optionalText,
2224
+ custom_label_3: optionalText,
2225
+ custom_label_4: optionalText,
2226
+ custom_number_0: number,
2227
+ custom_number_1: number,
2228
+ custom_number_2: number,
2229
+ custom_number_3: number,
2230
+ custom_number_4: number,
2231
+ expiration_date: z11.iso.datetime({ offset: true }).nullable().optional(),
2232
+ average_review_rating: optionalText,
2233
+ number_of_ratings: z11.number().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable().optional(),
2234
+ availability: z11.enum(["BACKORDER", "IN_STOCK", "OUT_OF_STOCK", "PREORDER"]).optional()
2235
+ }).strict();
2236
+ var completeCatalogProduct = catalogProduct.extend({ title: text.min(1), description: text.min(1), price: money, link: url2, image_link: url2, availability: z11.enum(["BACKORDER", "IN_STOCK", "OUT_OF_STOCK", "PREORDER"]) });
2237
+ var productIds = z11.array(productId).min(1).max(100).refine((ids2) => new Set(ids2).size === ids2.length, "Select unique external product SKUs");
2238
+ var productContext = catalogInput.extend({ product_ids: productIds }).strict();
2239
+ var write = catalogInput.omit({ account_id: true }).extend({ expected_selection_hash: hash, acknowledge_shared_effects: z11.literal(true) });
2240
+ var batch = (schema) => z11.array(schema).min(1).max(100).refine((rows) => new Set(rows.map((row2) => row2.id)).size === rows.length, "Select unique external product SKUs");
2241
+ var productsCreate = write.extend({ products: batch(completeCatalogProduct) }).strict();
2242
+ var productsUpdate = write.extend({ products: batch(catalogProduct.refine((row2) => Object.keys(row2).some((key) => key !== "id"), "Provide a product field to change")) }).strict();
2243
+ var productsDelete = write.extend({ product_ids: productIds, acknowledge_permanent_deletion: z11.literal(true) }).strict();
2244
+
2245
+ // src/catalog-products.ts
2246
+ var nativeProduct = z12.object({ id: productId, reddit: z12.object({ id: redditCatalogId.optional(), catalog_id: redditCatalogId }).passthrough() }).catchall(z12.json());
2247
+ var keys = new Set(Object.keys(catalogProduct.shape));
2248
+ var canonical4 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
2249
+ var digest4 = (value) => createHash5("sha256").update(canonical4(value)).digest("hex");
2250
+ var config3 = (row2) => Object.fromEntries(Object.entries(row2).filter(([key]) => keys.has(key)));
2251
+ var snapshot = (row2) => ({ ...config3(row2), reddit_id: row2.reddit.id, created_at: row2.created_at, modified_at: row2.modified_at, unknown: Object.fromEntries(Object.entries(row2).filter(([key]) => !keys.has(key) && !["reddit", "created_at", "modified_at"].includes(key))) });
2252
+ var normalized = (row2) => Object.fromEntries(Object.entries(row2).filter(([, value]) => value != null));
2253
+ var invalid4 = () => new AdportError7("PROVIDER_ERROR", "Reddit product selection scope, pagination or native receipt could not be verified.");
2254
+ var notes2 = ["Products belong to a shared Business catalog. These changes can affect existing product sets and ads; no ads, spend or conversion events are submitted.", "Native batch upsert has no conditional-write guarantee. Concurrent feed/product writers can race the final preflight; scheduled feeds can overwrite these changes or recreate deleted products.", "Updates send all currently known writable fields, merged with the selected changes. Readback checks the complete known configuration. Unknown fields refuse an update; absent optional fields and null are equivalent only for verification.", "There is no native server dry run or atomic batch guarantee. Partial or uncertain outcomes consume approval and are never replayed automatically. Reconcile each selected SKU before another preview."];
2255
+ var RedditCatalogProducts = class {
2256
+ constructor(client, catalogs) {
2257
+ this.client = client;
2258
+ this.catalogs = catalogs;
2259
+ }
2260
+ client;
2261
+ catalogs;
2262
+ async selected(input, ids2) {
2263
+ const url3 = new URL("https://ads-api.reddit.com/api/v3/product_catalogs/" + encodeURIComponent(input.catalog_id) + "/products");
2264
+ url3.searchParams.set("page.size", "1000");
2265
+ for (const id of ids2) url3.searchParams.append("ids", id);
2266
+ const first = url3.href, seen = /* @__PURE__ */ new Set(), rows = [];
2267
+ let current = first;
2268
+ for (let page2 = 0; page2 < 10; page2++) {
2269
+ if (seen.has(current)) throw invalid4();
2270
+ seen.add(current);
2271
+ const response = await this.client.get(current), parsed = z12.array(nativeProduct).max(1e3).safeParse(response.data), pagination = z12.object({ next_url: z12.string().url().max(8192).nullable().optional() }).safeParse(response.pagination);
2272
+ if (!parsed.success || !pagination.success) throw invalid4();
2273
+ for (const row2 of parsed.data) {
2274
+ if (row2.reddit.catalog_id !== input.catalog_id || !ids2.includes(row2.id) || rows.some((previous) => previous.id === row2.id)) throw invalid4();
2275
+ rows.push(row2);
2276
+ }
2277
+ if (!pagination.data.next_url) return rows.sort((a, b) => a.id.localeCompare(b.id));
2278
+ const next = new URL(this.client.nextUrl(pagination.data.next_url, first)), nextIds = next.searchParams.getAll("ids");
2279
+ if ([...next.searchParams.keys()].some((key) => !["ids", "page.token", "page.size"].includes(key)) || !next.searchParams.get("page.token") || nextIds.length && canonical4([...nextIds].sort()) !== canonical4([...ids2].sort())) throw invalid4();
2280
+ next.searchParams.delete("ids");
2281
+ for (const id of ids2) next.searchParams.append("ids", id);
2282
+ next.searchParams.set("page.size", "1000");
2283
+ current = next.href;
2284
+ }
2285
+ throw new AdportError7("PROVIDER_ERROR", "Reddit selected-product verification exceeded ten pages; missing SKUs cannot be inferred.");
2286
+ }
2287
+ async selection(input, ids2, write2 = false) {
2288
+ const parent = await this.catalogs.authorize(input, write2), products = await this.selected(input, ids2);
2289
+ return { products, selection_hash: digest4({ ...input, catalog_configuration_hash: parent.configuration_hash, product_ids: [...ids2].sort(), products: products.map(snapshot) }) };
2290
+ }
2291
+ async context(value) {
2292
+ const input = productContext.parse(value), selected2 = { account_id: input.account_id, business_id: input.business_id, catalog_id: input.catalog_id }, result = await this.selection(selected2, input.product_ids);
2293
+ return { selection_hash: result.selection_hash, records: input.product_ids.map((id) => {
2294
+ const row2 = result.products.find((row3) => row3.id === id);
2295
+ return { id, name: typeof row2?.title === "string" ? row2.title : id, state: row2 ? "Present" : "Absent" };
2296
+ }), products: result.products.map((row2) => ({ ...config3(row2), reddit_id: row2.reddit.id })), missing_product_ids: input.product_ids.filter((id) => !result.products.some((row2) => row2.id === id)), complete: true, truncated: false, notes: ["External product SKUs are distinct from Reddit-assigned internal product IDs. The hash binds this exact account/Business/catalog and exhausted selected-product snapshot; it is not a frozen global inventory.", ...notes2] };
2297
+ }
2298
+ async plan(op) {
2299
+ const create = op.tool === "reddit_create_catalog_products", update = op.tool === "reddit_update_catalog_products", remove = op.tool === "reddit_delete_catalog_products";
2300
+ if (op.provider !== "reddit" || !(create && op.kind === "create" || update && op.kind === "update" || remove && op.kind === "remove")) throw new AdportError7("INVALID_INPUT", "Reddit product operation/provider kind mismatch.");
2301
+ const input = create ? productsCreate.parse(op.payload) : update ? productsUpdate.parse(op.payload) : productsDelete.parse(op.payload), scope3 = { account_id: op.accountId, business_id: input.business_id, catalog_id: input.catalog_id }, ids2 = "products" in input ? input.products.map((row2) => row2.id) : input.product_ids;
2302
+ const prepare = async () => {
2303
+ const result = await this.selection(scope3, ids2, true);
2304
+ if (result.selection_hash !== input.expected_selection_hash) throw new AdportError7("PENDING_MISMATCH", "Catalog or selected products changed; read the product context and preview again.");
2305
+ if (create ? result.products.length !== 0 : result.products.length !== ids2.length) throw new AdportError7("INVALID_INPUT", create ? "Create requires every selected SKU to be absent." : "Update/delete requires every selected external SKU to be present.");
2306
+ const products = "products" in input ? input.products.map((row2) => {
2307
+ const before = result.products.find((previous) => previous.id === row2.id);
2308
+ if (before && Object.keys(before).some((key) => !keys.has(key) && !["reddit", "created_at", "modified_at"].includes(key))) throw new AdportError7("INVALID_INPUT", "A selected product has unknown fields; its configuration cannot be preserved by this update.");
2309
+ return completeCatalogProduct.parse({ ...before ? config3(before) : {}, ...row2 });
2310
+ }) : [];
2311
+ if (Buffer.byteLength(JSON.stringify({ data: remove ? ids2 : products }), "utf8") > 1e6) throw new AdportError7("INVALID_INPUT", "Product batch exceeds the 1 MB Adport bound; use a smaller selection.");
2312
+ return { before: result.products, products };
2313
+ };
2314
+ const initial = await prepare(), title = create ? "Create catalog products" : update ? "Update catalog products" : "Delete catalog products permanently";
2315
+ return {
2316
+ summary: `${title} \xB7 ${ids2.length} selected`,
2317
+ changes: ids2.map((id) => `${create ? "+" : remove ? "-" : "~"} Product ${id}`),
2318
+ coercions: [],
2319
+ budgetDeltas: [],
2320
+ notes: notes2,
2321
+ review: { provider: "reddit", accountId: op.accountId, kind: op.kind, title, subject: `${ids2.length} selected products`, fields: [{ label: "Business", after: scope3.business_id }, { label: "Catalog", after: scope3.catalog_id }, ...ids2.map((id) => ({ label: id, ...create ? {} : { before: config3(initial.before.find((row2) => row2.id === id)) }, after: remove ? "Permanently deleted" : initial.products.find((row2) => row2.id === id) }))], notices: notes2 },
2322
+ execute: async () => {
2323
+ const fresh = await prepare();
2324
+ let outcomes = [];
2325
+ try {
2326
+ const response = await this.client.post("product_catalogs/" + encodeURIComponent(scope3.catalog_id) + "/products/" + (remove ? "batch_delete" : "batch_upsert"), { data: remove ? ids2 : fresh.products });
2327
+ let receiptValid = false;
2328
+ if (remove) {
2329
+ const parsed = z12.record(z12.string(), z12.enum(["DELETED", "NOT_FOUND"])).safeParse(response.data);
2330
+ if (parsed.success) {
2331
+ outcomes = Object.entries(parsed.data).filter(([id]) => ids2.includes(id)).map(([id, status2]) => ({ id, status: status2 }));
2332
+ receiptValid = Object.keys(parsed.data).length === ids2.length && ids2.every((id) => Object.hasOwn(parsed.data, id));
2333
+ }
2334
+ } else {
2335
+ const parsed = z12.array(z12.object({ status: z12.enum(["CREATED", "UPDATED", "INVALID", "UNCHANGED"]), product: nativeProduct.nullable().optional() })).max(100).safeParse(response.data);
2336
+ if (parsed.success) {
2337
+ outcomes = parsed.data.map((row2) => ({ ...row2.product && ids2.includes(row2.product.id) ? { id: row2.product.id } : {}, status: row2.status }));
2338
+ receiptValid = parsed.data.length === ids2.length && parsed.data.every((row2) => (create ? row2.status === "CREATED" : ["UPDATED", "UNCHANGED"].includes(row2.status)) && row2.product && row2.product.reddit.catalog_id === scope3.catalog_id && ids2.includes(row2.product.id)) && new Set(outcomes.map((row2) => row2.id)).size === ids2.length;
2339
+ }
2340
+ }
2341
+ await this.catalogs.authorize(scope3, true);
2342
+ const actual = await this.selected(scope3, ids2);
2343
+ const verified = remove ? ids2.filter((id) => !actual.some((row2) => row2.id === id)) : fresh.products.filter((expected) => {
2344
+ const row2 = actual.find((row3) => row3.id === expected.id);
2345
+ return row2 && canonical4(normalized(config3(row2))) === canonical4(normalized(expected));
2346
+ }).map((row2) => row2.id);
2347
+ if (!receiptValid || verified.length !== ids2.length) throw new AdportError7("PROVIDER_ERROR", "Native batch receipt or independent product configuration/absence readback is unconfirmed.", { verified_product_ids: verified });
2348
+ return { applied: true, resourceIds: ids2, details: { outcomes, independently_verified: true }, warnings: [...notes2.slice(0, 2), ...outcomes.some((row2) => row2.status === "NOT_FOUND") ? ["Some SKUs were already absent at native deletion; they are not reported as deleted by this request."] : []] };
2349
+ } catch (error) {
2350
+ const details = error instanceof AdportError7 && error.details && typeof error.details === "object" ? error.details : {};
2351
+ throw new AdportError7("PROVIDER_ERROR", "Reddit product batch outcome may be partial or unknown. No mutation was retried; reconcile selected SKUs before another preview.", { resourceIds: ids2, outcomes, ...Number.isInteger(details.http_status) ? { http_status: details.http_status } : {}, ...Array.isArray(details.verified_product_ids) ? { verified_product_ids: details.verified_product_ids } : {} });
2352
+ }
2353
+ }
2354
+ };
2355
+ }
2356
+ };
2357
+
2358
+ // src/management.ts
2359
+ import { createHash as createHash6 } from "crypto";
2360
+ import { AdportError as AdportError8 } from "@adport/core";
2361
+
2362
+ // src/management-tools.ts
2363
+ import { defineTool as defineTool2, guardedWriteTool as guardedWriteTool2 } from "@adport/core";
2364
+ import { z as z13 } from "zod";
2365
+ var name3 = z13.string().trim().min(1).max(200);
2366
+ var hash2 = z13.string().regex(/^[a-f0-9]{64}$/);
2367
+ var unique = (values) => new Set(values).size === values.length;
2368
+ var trackingType = z13.enum(["PAGE_VISIT", "VIEW_CONTENT", "SEARCH", "ADD_TO_CART", "ADD_TO_WISHLIST", "PURCHASE", "LEAD", "SIGN_UP", "CUSTOM"]);
2369
+ var customerAudience = z13.object({ name: name3, type: z13.literal("CUSTOMER_LIST") }).strict();
2370
+ var pixelAudience = z13.object({ name: name3, type: z13.literal("PIXEL_RETARGETING"), pixel_audience_config: z13.object({ pixel_ids: z13.array(redditId).length(1), targetings: z13.array(trackingType).min(1).refine(unique, "Use unique tracking types"), lookback_window_days: z13.number().int().min(1).max(90), custom_targetings: z13.array(z13.string().min(1)).max(50).optional() }).strict() }).strict();
2371
+ var engagementAudience = z13.object({ name: name3, type: z13.literal("ENGAGEMENT_RETARGETING"), engagement_audience_config: z13.object({ campaign_ids: z13.array(redditId).min(1).max(500).refine(unique, "Use unique campaign IDs"), tracking_types: z13.array(z13.enum(["IMPRESSIONS", "CLICKS", "UPVOTES", "COMMENT_SUBMISSIONS", "VIDEO_WATCHED_50_PERCENT", "VIDEO_WATCHED_100_PERCENT", "VIDEO_STARTED"])).min(1).refine(unique, "Use unique tracking types"), lookback_window_days: z13.number().int().min(1).max(180) }).strict() }).strict();
2372
+ var customAudience = z13.discriminatedUnion("type", [customerAudience, pixelAudience, engagementAudience]);
2373
+ var audienceUsers = z13.object({ audience_id: redditId, action_type: z13.enum(["ADD", "REMOVE"]), column_order: z13.array(z13.enum(["EMAIL_SHA256", "MAID_SHA256"])).min(1).max(2).refine(unique, "Use unique columns"), user_data: z13.array(z13.array(hash2).min(1).max(2)).min(1).max(2500) }).refine((v) => v.user_data.every((row2) => row2.length === v.column_order.length), "Each row must match column_order").refine((v) => new Set(v.user_data.map((row2) => JSON.stringify(row2))).size === v.user_data.length, "Use unique rows");
2374
+ var savedTargeting = targeting.omit({ locations: true });
2375
+ var createSaved = z13.object({ name: name3, targeting: savedTargeting });
2376
+ var updateSaved = z13.object({ saved_audience_id: redditId, name: name3.optional(), targeting: savedTargeting.optional() }).refine((v) => v.name !== void 0 || v.targeting !== void 0, "Provide audience changes");
2377
+ var href = z13.string().url().max(4096).refine((value) => {
2378
+ const url3 = new URL(value);
2379
+ return ["http:", "https:"].includes(url3.protocol) && !url3.username && !url3.password;
2380
+ }, "Use an HTTP(S) URL without embedded credentials");
2381
+ var text2 = z13.string().min(1).max(2e3);
2382
+ var amount = z13.number().finite().nonnegative();
2383
+ var conversionEvent = z13.object({
2384
+ event_at: z13.number().int().positive().safe().describe("Unix epoch milliseconds"),
2385
+ action_source: z13.enum(["WEBSITE", "APP", "OTHER", "PHYSICAL_STORE"]),
2386
+ click_id: text2.optional(),
2387
+ event_source_url: href.optional(),
2388
+ referrer_url: href.optional(),
2389
+ type: z13.object({ tracking_type: trackingType, custom_event_name: z13.string().min(1).max(64).optional() }).strict().refine((v) => v.tracking_type !== "CUSTOM" || Boolean(v.custom_event_name), "CUSTOM needs custom_event_name"),
2390
+ metadata: z13.object({ conversion_id: z13.string().min(1).max(200).describe("Stable deduplication ID; reuse for retries"), order_id: z13.string().max(100).optional(), currency: z13.string().regex(/^[A-Z]{3}$/).optional(), item_count: z13.number().int().nonnegative().optional(), value: amount.optional(), products: z13.array(z13.object({ id: text2, category: text2.optional(), name: text2.optional(), quantity: z13.number().int().nonnegative().optional(), item_price: amount.optional() }).strict()).optional() }).strict().refine((v) => v.value === void 0 || Boolean(v.currency), "Revenue value requires currency"),
2391
+ user: z13.object({ email: hash2.optional(), external_id: hash2.optional(), phone_number: hash2.optional(), aaid: hash2.optional(), idfa: hash2.optional(), ip_address: z13.union([z13.ipv4(), z13.ipv6()]).optional(), user_agent: text2.optional(), uuid: text2.optional(), data_processing_options: z13.object({ country: text2.optional(), region: text2.optional(), modes: z13.array(z13.literal("LDU")).optional() }).strict().optional(), screen_dimensions: z13.object({ height: z13.number().int().min(0).max(32767), width: z13.number().int().min(0).max(32767) }).strict().optional() }).strict().optional().describe("Pre-hash customer match keys using Reddit\u2019s normalization rules; device IP/user-agent and Pixel UUID stay unhashed")
2392
+ }).strict();
2393
+ var sendEvents = z13.object({ pixel_id: redditId, mode: z13.enum(["TEST", "LIVE"]).default("TEST"), test_id: z13.string().min(1).optional(), events: z13.array(conversionEvent).min(1).max(1e3) }).refine((v) => v.mode === "TEST" ? Boolean(v.test_id) : !v.test_id, "TEST requires test_id; LIVE must omit test_id").refine((v) => new Set(v.events.map((e) => `${e.action_source}:${e.metadata.conversion_id}`)).size === v.events.length, "Use unique conversion IDs within each action source");
2394
+ function redditManagementTools(provider) {
2395
+ const account = { account_id: redditId }, page2 = { page_size: z13.number().int().min(1).max(1e3).default(50), cursor: z13.string().url().optional() };
2396
+ const read = (name4, description, input, handler) => defineTool2({ name: name4, namespace: "reddit", description, input, annotations: { readOnly: true }, handler });
2397
+ const write2 = (name4, description, payload, kind = "update") => guardedWriteTool2({ name: name4, namespace: "reddit", provider: "reddit", description, payload, kind });
2398
+ return [
2399
+ read("reddit_audiences", "List custom audiences available to the account, including ownership, type, size and processing readiness.", z13.object({ ...account, name: z13.string().optional(), ...page2 }), (v) => provider.management.list(v, "custom_audiences")),
2400
+ read("reddit_get_audience", "Read one custom audience already available to the selected account. Availability does not grant editing rights to a shared audience.", z13.object({ ...account, audience_id: redditId }), (v) => provider.management.audience(v.account_id, v.audience_id)),
2401
+ write2("reddit_create_customer_audience", "Create an empty customer-list audience. Membership upload is a separate approval with pre-hashed identifiers.", customerAudience.omit({ type: true }), "create"),
2402
+ write2("reddit_create_pixel_audience", "Create website retargeting from one account-available Pixel and explicit event/window settings.", pixelAudience.omit({ type: true }), "create"),
2403
+ write2("reddit_create_engagement_audience", "Create engagement retargeting from verified account-owned campaigns with explicit events/window settings.", engagementAudience.omit({ type: true }), "create"),
2404
+ write2("reddit_update_audience_users", "Add/remove at most 2,500 pre-hashed customer rows from an owned CUSTOMER_LIST audience. Preview shows count and digest, not identifiers.", audienceUsers),
2405
+ write2("reddit_delete_audience", "Permanently delete an account-owned custom audience. Ads using it can lose eligibility; shared foreign audiences cannot be deleted.", z13.object({ audience_id: redditId }), "remove"),
2406
+ read("reddit_saved_audiences", "List reusable saved targeting audiences and their native readiness/usage counts.", z13.object({ ...account, ...page2 }), (v) => provider.management.list(v, "saved_audiences")),
2407
+ read("reddit_get_saved_audience", "Read an account-owned saved audience and its native targeting.", z13.object({ ...account, saved_audience_id: redditId }), (v) => provider.management.saved(v.account_id, v.saved_audience_id)),
2408
+ write2("reddit_create_saved_audience", "Create reusable native REDDIT_AUDIENCE targeting, with expansion explicitly off unless supplied. Audience references must be account-available.", createSaved, "create"),
2409
+ write2("reddit_update_saved_audience", "Change name or supplied saved targeting dimensions, preserving omitted settings. Changes can affect all ad groups using it.", updateSaved),
2410
+ write2("reddit_delete_saved_audience", "Mark an owned saved audience DELETED using native PATCH. Reports active ad-group usage before approval.", z13.object({ saved_audience_id: redditId }), "remove"),
2411
+ read("reddit_pixels", "List Pixels already available to the selected ad account. Current v3 has no public Pixel creation/update endpoint.", z13.object({ ...account, ...page2 }), (v) => provider.management.list(v, "pixels")),
2412
+ read("reddit_pixel_last_fired", "Read native last-fired timestamps after proving the Pixel is available to this account. Missing timestamps remain unavailable.", z13.object({ ...account, pixel_id: redditId }), (v) => provider.management.lastFired(v.account_id, v.pixel_id)),
2413
+ write2("reddit_send_conversion_events", "Submit up to 1,000 deduplicated events to an account-available Pixel. Requires existing adsconversions scope. TEST needs Events Manager test_id; explicit LIVE affects measurement. Customer keys must be pre-hashed.", sendEvents, "create")
2414
+ ];
2415
+ }
2416
+
2417
+ // src/management.ts
2418
+ var row = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
2419
+ var digest5 = (value) => createHash6("sha256").update(JSON.stringify(value)).digest("hex");
2420
+ var RedditManagementService = class {
2421
+ constructor(client, creatives) {
2422
+ this.client = client;
2423
+ this.creatives = creatives;
2424
+ }
2425
+ client;
2426
+ creatives;
2427
+ async list(input, collection) {
2428
+ const path2 = `ad_accounts/${redditId.parse(input.account_id)}/${collection}`, url3 = input.cursor ? this.client.nextUrl(input.cursor, path2) : path2;
2429
+ const response = await this.client.get(url3, input.cursor ? {} : { "page.size": input.page_size, ...input.name !== void 0 ? { name: input.name } : {} });
2430
+ if (!Array.isArray(response.data) || response.data.some((value) => !redditId.safeParse(row(value).id).success)) throw new AdportError8("PROVIDER_ERROR", "reddit: malformed audience/Pixel collection");
2431
+ const next = response.pagination?.next_url ? this.client.nextUrl(response.pagination.next_url, path2) : void 0;
2432
+ if (next === this.client.nextUrl(url3, path2)) throw new AdportError8("PROVIDER_ERROR", "reddit: pagination repeated the current page");
2433
+ return { items: response.data, truncated: Boolean(next), ...next ? { next_cursor: next } : {} };
2434
+ }
2435
+ async available(account, collection, resource2) {
2436
+ redditId.parse(account);
2437
+ redditId.parse(resource2);
2438
+ const rows = await this.client.getPaged(`ad_accounts/${account}/${collection}`, { "page.size": 1e3 }, 5e3);
2439
+ const found = rows.map(row).find((value) => value.id === resource2);
2440
+ if (!found) throw new AdportError8("INVALID_INPUT", "reddit: resource is not in the account\u2019s first 5,000 available audience/Pixel entries");
2441
+ return found;
2442
+ }
2443
+ async audience(account, resource2, requireOwned = false) {
2444
+ await this.available(account, "custom_audiences", resource2);
2445
+ const value = row((await this.client.get(`custom_audiences/${resource2}`)).data);
2446
+ if (value.id !== resource2 || requireOwned && value.ad_account_id !== account) throw new AdportError8("INVALID_INPUT", "reddit: audience ownership mismatch; shared audiences cannot be mutated");
2447
+ return value;
2448
+ }
2449
+ async saved(account, resource2) {
2450
+ redditId.parse(account);
2451
+ redditId.parse(resource2);
2452
+ const value = row((await this.client.get(`saved_audiences/${resource2}`)).data);
2453
+ if (value.id !== resource2 || value.ad_account_id !== account) throw new AdportError8("INVALID_INPUT", "reddit: saved-audience ownership mismatch");
2454
+ return value;
2455
+ }
2456
+ async lastFired(account, pixel) {
2457
+ await this.available(account, "pixels", pixel);
2458
+ const value = (await this.client.get(`pixels/${pixel}/last_fired_at`)).data;
2459
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new AdportError8("PROVIDER_ERROR", "reddit: malformed Pixel activity response");
2460
+ return { pixel_id: pixel, last_fired_at: value };
2461
+ }
2462
+ async validateAudienceSource(account, payload) {
2463
+ const data = customAudience.parse(payload);
2464
+ if (data.type === "PIXEL_RETARGETING") for (const pixel of data.pixel_audience_config.pixel_ids) await this.available(account, "pixels", pixel);
2465
+ if (data.type === "ENGAGEMENT_RETARGETING") for (const campaign of data.engagement_audience_config.campaign_ids) await this.creatives.owned(account, "campaigns", campaign);
2466
+ return data;
2467
+ }
2468
+ async receipt(path2, method, fields, account, resource2) {
2469
+ const result = method === "POST" ? await this.client.post(path2, { data: fields }) : await this.client.patch(path2, { data: fields }), value = row(result.data);
2470
+ const ids2 = redditId.safeParse(value.id).success ? [String(value.id)] : [];
2471
+ if (ids2.length !== 1 || resource2 && value.id !== resource2 || value.ad_account_id !== account || Object.entries(fields).some(([key, expected]) => !matches(value[key], expected))) throw new AdportError8("PROVIDER_ERROR", "reddit: audience receipt ID/account/settings mismatch; reconcile before retrying", { resource_ids: ids2 });
2472
+ return { applied: true, resourceIds: ids2 };
2473
+ }
2474
+ empty(value, resource2) {
2475
+ if (value !== null && (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length)) throw new AdportError8("PROVIDER_ERROR", "reddit: unexpected empty mutation receipt; reconcile before retrying", { resource_ids: [resource2] });
2476
+ return { applied: true, resourceIds: [resource2] };
2477
+ }
2478
+ async plan(op, _guard) {
2479
+ const account = redditId.parse(op.accountId), p = op.payload, type = op.tool;
2480
+ const create = ["reddit_create_customer_audience", "reddit_create_pixel_audience", "reddit_create_engagement_audience", "reddit_create_saved_audience", "reddit_send_conversion_events"].includes(type);
2481
+ const remove = ["reddit_delete_audience", "reddit_delete_saved_audience"].includes(type);
2482
+ if (op.provider !== "reddit" || op.kind !== (create ? "create" : remove ? "remove" : "update")) throw new AdportError8("INVALID_INPUT", "reddit: provider or operation kind mismatch");
2483
+ const plan = (summary, changes, execute) => ({ summary, changes, coercions: [], budgetDeltas: [], execute });
2484
+ switch (type) {
2485
+ case "reddit_create_customer_audience":
2486
+ case "reddit_create_pixel_audience":
2487
+ case "reddit_create_engagement_audience": {
2488
+ const nativeType = type === "reddit_create_customer_audience" ? "CUSTOMER_LIST" : type === "reddit_create_pixel_audience" ? "PIXEL_RETARGETING" : "ENGAGEMENT_RETARGETING";
2489
+ const data = await this.validateAudienceSource(account, { ...p, type: nativeType });
2490
+ return plan(`Create Reddit ${nativeType} audience`, [JSON.stringify(data), "Does not create an ad or change existing targeting."], () => this.receipt(`ad_accounts/${account}/custom_audiences`, "POST", data, account));
2491
+ }
2492
+ case "reddit_update_audience_users": {
2493
+ const { audience_id, ...data } = audienceUsers.parse(p), audience = await this.audience(account, audience_id, true);
2494
+ if (audience.type !== "CUSTOMER_LIST" || audience.customer_list_config) throw new AdportError8("INVALID_INPUT", "reddit: direct membership changes require an owned customer list without an external data-provider configuration");
2495
+ const sha256 = digest5(data);
2496
+ return plan(`${data.action_type} ${data.user_data.length} Reddit audience rows`, [`Audience ${audience_id}; columns ${data.column_order.join(",")}; payload SHA-256 ${sha256}. Changes affect targeting using this audience; identifiers are omitted from preview.`], async () => {
2497
+ const result = this.empty((await this.client.patch(`custom_audiences/${audience_id}/users`, { data })).data, audience_id);
2498
+ return { ...result, details: { submitted_rows: data.user_data.length, action_type: data.action_type, payload_sha256: sha256 } };
2499
+ });
2500
+ }
2501
+ case "reddit_delete_audience": {
2502
+ const audience = await this.audience(account, redditId.parse(p.audience_id), true);
2503
+ return plan(`Permanently delete Reddit audience ${audience.id}`, [`${audience.name}; type ${audience.type}; targeting using this shared resource can lose eligibility.`], async () => this.empty((await this.client.delete(`custom_audiences/${audience.id}`)).data, String(audience.id)));
2504
+ }
2505
+ case "reddit_create_saved_audience": {
2506
+ const input = createSaved.parse(p), data = { ...input, type: "REDDIT_AUDIENCE", targeting: { expand_targeting: false, ...input.targeting } };
2507
+ await this.creatives.assertTargetingAvailable(account, data.targeting);
2508
+ return plan("Create Reddit saved targeting audience", [JSON.stringify(data)], () => this.receipt(`ad_accounts/${account}/saved_audiences`, "POST", data, account));
2509
+ }
2510
+ case "reddit_update_saved_audience":
2511
+ case "reddit_delete_saved_audience": {
2512
+ const input = remove ? { saved_audience_id: redditId.parse(p.saved_audience_id) } : updateSaved.parse(p), current = await this.saved(account, input.saved_audience_id);
2513
+ if (current.status === "DELETED") throw new AdportError8("INVALID_INPUT", "reddit: saved audience is already deleted");
2514
+ const data = remove ? { status: "DELETED" } : { ..."name" in input && input.name !== void 0 ? { name: input.name } : {} };
2515
+ if ("targeting" in input && input.targeting !== void 0) {
2516
+ const previous = savedTargeting.safeParse(current.targeting);
2517
+ if (!previous.success) throw new AdportError8("INVALID_INPUT", "reddit: current saved targeting contains unsupported fields; refusing a partial reset");
2518
+ data.targeting = { ...previous.data, ...input.targeting };
2519
+ await this.creatives.assertTargetingAvailable(account, data.targeting);
2520
+ }
2521
+ return plan(`${remove ? "Delete" : "Update"} Reddit saved audience ${current.id}`, [`Active ad groups: ${current.active_ad_groups_count ?? "unavailable"}; changes affect all users of this audience. ${JSON.stringify(data)}`], () => this.receipt(`saved_audiences/${current.id}`, "PATCH", data, account, String(current.id)));
2522
+ }
2523
+ case "reddit_send_conversion_events": {
2524
+ const input = sendEvents.parse(p);
2525
+ await this.available(account, "pixels", input.pixel_id);
2526
+ const data = { ...input.test_id ? { test_id: input.test_id } : {}, events: input.events }, sha256 = digest5(data), counts = {};
2527
+ for (const event of input.events) counts[event.type.tracking_type] = (counts[event.type.tracking_type] ?? 0) + 1;
2528
+ return plan(`Submit ${input.events.length} ${input.mode} Reddit conversion events`, [`Pixel ${input.pixel_id}; event types ${JSON.stringify(counts)}; payload SHA-256 ${sha256}. ${input.mode === "LIVE" ? "Real measurement submission can affect attribution and optimization." : "Uses the supplied Events Manager test ID."} Event identifiers, match keys and source URLs are omitted from preview.`], async () => {
2529
+ const result = row((await this.client.post(`pixels/${input.pixel_id}/conversion_events`, { data })).data);
2530
+ if (typeof result.message !== "string" || !result.message.trim()) throw new AdportError8("PROVIDER_ERROR", "reddit: conversion receipt has no processing message; reconcile deduplicated IDs before retrying", { resource_ids: [input.pixel_id] });
2531
+ return { applied: true, resourceIds: [input.pixel_id], details: { mode: input.mode, submitted_events: input.events.length, payload_sha256: sha256, message: this.client.diagnostic(result.message), note: "Native acceptance does not prove attribution or final processing." } };
2532
+ });
2533
+ }
2534
+ default:
2535
+ throw new AdportError8("INVALID_INPUT", `reddit: unsupported management write ${type}`);
2536
+ }
2537
+ }
2538
+ };
2539
+ function matches(actual, expected) {
2540
+ if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((value) => actual.some((candidate) => matches(candidate, value)));
2541
+ if (expected && typeof expected === "object") return actual !== null && typeof actual === "object" && !Array.isArray(actual) && Object.entries(expected).every(([key, value]) => matches(actual[key], value));
2542
+ return actual === expected;
2543
+ }
2544
+
2545
+ // src/account-context.ts
2546
+ import { AdportError as AdportError9 } from "@adport/core";
2547
+ import { z as z14 } from "zod";
2548
+ var accountMetadata = z14.object({
2549
+ id: redditId,
2550
+ name: z14.string().min(1).optional(),
2551
+ business_id: redditBusinessId.optional(),
2552
+ currency: z14.string().regex(/^[A-Z]{3}$/).optional(),
2553
+ admin_approval: z14.string().min(1).optional()
2554
+ });
2555
+ var redditAccountContext = accountMetadata.extend({
2556
+ catalog_access: z14.literal("EXPLICIT_PROJECT_GRANT_REQUIRED")
2557
+ });
2558
+ async function readAccountContext(client, accountId2) {
2559
+ redditId.parse(accountId2);
2560
+ const response = await client.get(`ad_accounts/${encodeURIComponent(accountId2)}`);
2561
+ const parsed = accountMetadata.safeParse(response.data);
2562
+ if (!parsed.success || parsed.data.id !== accountId2) {
2563
+ throw new AdportError9("PROVIDER_ERROR", "reddit: account context did not return valid metadata for the selected account");
2564
+ }
2565
+ return { ...parsed.data, catalog_access: "EXPLICIT_PROJECT_GRANT_REQUIRED" };
2566
+ }
2567
+
2568
+ // src/provider.ts
121
2569
  var REDDIT_MICROS = 1e6;
122
2570
  var BREAKDOWN = { account: void 0, campaign: "CAMPAIGN_ID", ad_group: "AD_GROUP_ID", ad: "AD_ID" };
123
2571
  var RedditAdsProvider = class {
124
- constructor(client) {
2572
+ constructor(client, media, catalogAccess) {
125
2573
  this.client = client;
2574
+ this.creatives = new RedditCreativeService(client, media);
2575
+ this.management = new RedditManagementService(client, this.creatives);
2576
+ this.catalogs = new RedditCatalogService(client, catalogAccess);
2577
+ this.catalogContent = new RedditCatalogContentService(client, this.catalogs);
2578
+ this.catalogFeeds = new RedditCatalogFeeds(client, this.catalogs);
2579
+ this.catalogProducts = new RedditCatalogProducts(client, this.catalogs);
126
2580
  }
127
2581
  client;
128
2582
  id = "reddit";
2583
+ creatives;
2584
+ management;
2585
+ catalogs;
2586
+ catalogContent;
2587
+ catalogProducts;
2588
+ catalogFeeds;
129
2589
  capabilities() {
130
2590
  return { serverDryRun: false };
131
2591
  }
132
2592
  standardActions() {
133
2593
  return {
134
- pauseCampaign: (accountId, campaignId) => ({
2594
+ pauseCampaign: (accountId2, campaignId) => ({
135
2595
  tool: "reddit_set_campaign_status",
136
- input: { account_id: accountId, campaign_id: campaignId, configured_status: "PAUSED" }
2596
+ input: { account_id: accountId2, campaign_id: campaignId, configured_status: "PAUSED" }
137
2597
  })
138
2598
  };
139
2599
  }
@@ -156,11 +2616,21 @@ var RedditAdsProvider = class {
156
2616
  status: account.suspension_reason ? `SUSPENDED:${account.suspension_reason}` : account.admin_approval
157
2617
  }));
158
2618
  }
2619
+ accountContext(accountId2) {
2620
+ return readAccountContext(this.client, accountId2);
2621
+ }
159
2622
  async report(query) {
160
2623
  const range = resolveDateRange(query.dateRange);
161
2624
  const accountIds = query.accountIds ?? (await this.listAccounts()).map((account) => account.id);
162
2625
  const rows = [];
163
- for (const accountId of accountIds) {
2626
+ const limit = query.limit ?? 1e3;
2627
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError10("INVALID_INPUT", "reddit: report limit must be a positive safe integer");
2628
+ let truncated = false;
2629
+ for (const accountId2 of accountIds) {
2630
+ if (rows.length >= limit) {
2631
+ truncated = true;
2632
+ break;
2633
+ }
164
2634
  const breakdown = BREAKDOWN[query.level];
165
2635
  const body = {
166
2636
  data: {
@@ -180,118 +2650,117 @@ var RedditAdsProvider = class {
180
2650
  time_zone_id: "UTC"
181
2651
  }
182
2652
  };
183
- const metrics = await this.fetchReportPages(accountId, body, query.limit ?? 1e3);
184
- for (const metric of metrics) rows.push(this.toReportRow(metric, accountId, query, breakdown?.toLowerCase()));
2653
+ const page2 = await this.fetchReportPages(accountId2, body, limit - rows.length);
2654
+ for (const metric of page2.metrics) rows.push(this.toReportRow(metric, accountId2, query, breakdown?.toLowerCase()));
2655
+ truncated ||= page2.truncated;
185
2656
  }
186
- return { rows };
2657
+ return { rows, ...truncated ? { truncated: true } : {} };
187
2658
  }
188
2659
  async rawReport(input) {
189
2660
  const body = {
190
2661
  data: {
191
- ...input.breakdowns?.length ? { breakdowns: input.breakdowns } : {},
192
- fields: input.fields,
2662
+ ...input.breakdowns?.length ? { breakdowns: input.breakdowns.map((value) => value.toUpperCase()) } : {},
2663
+ fields: input.fields.map((value) => value.toUpperCase()),
193
2664
  starts_at: input.starts_at,
194
2665
  ends_at: input.ends_at,
195
2666
  time_zone_id: input.time_zone_id ?? "UTC",
196
2667
  ...input.filter ? { filter: input.filter } : {}
197
2668
  }
198
2669
  };
199
- const first = await this.client.post(
200
- `ad_accounts/${encodeURIComponent(input.account_id)}/reports?page.size=${Math.min(input.page_size ?? 200, 1e3)}`,
201
- body
202
- );
203
- const metrics = [...first.data.metrics ?? []];
204
- let next = first.pagination?.next_url;
205
- while (next && metrics.length < (input.page_size ?? 200)) {
206
- const page = await this.client.get(next);
207
- metrics.push(...page.data.metrics ?? []);
208
- next = page.pagination?.next_url;
209
- }
210
- return { metrics: metrics.slice(0, input.page_size ?? 200), metrics_updated_at: first.data.metrics_updated_at };
2670
+ return this.fetchReportPages(input.account_id, body, input.page_size ?? 200);
211
2671
  }
212
2672
  async apiRead(input) {
213
- const path = validateRedditPath(input.path);
214
- assertReadScoped(path, input.account_id);
2673
+ const path2 = validateRedditPath(input.path);
2674
+ assertReadScoped(path2, input.account_id);
215
2675
  if (input.method === "POST") {
216
- if (!/(?:\/reports|\/history|\/query|\/search)$/.test(path)) {
217
- throw new AdportError2("INVALID_INPUT", "reddit: read-only POST is limited to documented reports, history, query, and search endpoints");
2676
+ if (!/(?:\/reports|\/history|\/query|\/search)$/.test(path2)) {
2677
+ throw new AdportError10("INVALID_INPUT", "reddit: read-only POST is limited to documented reports, history, query, and search endpoints");
218
2678
  }
219
- return this.client.post(path, input.body ?? {});
2679
+ return this.client.post(path2, input.body ?? {});
2680
+ }
2681
+ if (!path2.startsWith(`ad_accounts/${input.account_id}/`) && path2 !== `ad_accounts/${input.account_id}`) {
2682
+ await this.assertOwnedResource(path2, input.account_id);
220
2683
  }
221
- if (input.limit) return this.client.getPaged(path, input.params, input.limit);
222
- return this.client.get(path, input.params);
2684
+ if (input.limit) return this.client.getPaged(path2, input.params, input.limit);
2685
+ return this.client.get(path2, input.params);
223
2686
  }
224
- async listCampaigns(accountId, ids) {
2687
+ async listCampaigns(accountId2, ids2) {
225
2688
  return this.client.getPaged(
226
- `ad_accounts/${encodeURIComponent(accountId)}/campaigns`,
227
- { ...ids?.length ? { id: ids } : {}, "page.size": Math.min(ids?.length ?? 100, 100) },
228
- ids?.length ?? 1e3
2689
+ `ad_accounts/${encodeURIComponent(accountId2)}/campaigns`,
2690
+ { ...ids2?.length ? { id: ids2 } : {}, "page.size": Math.min(ids2?.length ?? 100, 100) },
2691
+ ids2?.length ?? 1e3
229
2692
  );
230
2693
  }
231
2694
  async previewWrite(op, guard) {
232
2695
  const plan = await this.plan(op, guard);
233
- return {
234
- summary: plan.summary,
235
- changes: plan.changes,
236
- coercions: plan.coercions,
237
- budgetDeltas: plan.budgetDeltas,
238
- serverValidated: false
239
- };
2696
+ const { execute: _execute, ...preview } = plan;
2697
+ return { ...preview, serverValidated: false };
240
2698
  }
241
2699
  async applyWrite(op, guard) {
242
2700
  const plan = await this.plan(op, guard);
243
- return { applied: true, resourceIds: await plan.execute() };
2701
+ const result = await plan.execute();
2702
+ return Array.isArray(result) ? { applied: true, resourceIds: result } : result;
244
2703
  }
245
- async fetchReportPages(accountId, body, limit) {
246
- const first = await this.client.post(
247
- `ad_accounts/${encodeURIComponent(accountId)}/reports?page.size=${Math.min(limit, 1e3)}`,
248
- body
249
- );
250
- const rows = [...first.data.metrics ?? []];
251
- let next = first.pagination?.next_url;
252
- while (next && rows.length < limit) {
253
- const page = await this.client.get(next);
254
- rows.push(...page.data.metrics ?? []);
255
- next = page.pagination?.next_url;
256
- }
257
- return rows.slice(0, limit);
258
- }
259
- toReportRow(raw, accountId, query, breakdown) {
260
- const value = (key) => Number(raw[key] ?? 0);
261
- const spend = value("spend") / REDDIT_MICROS;
262
- const impressions = value("impressions");
263
- const clicks = value("clicks");
264
- const conversions = value("conversion_purchase_clicks") + value("conversion_purchase_views");
265
- const conversionValue = value("conversion_purchase_total_value") / 100;
266
- const all = {
267
- spend: round2(spend),
268
- impressions,
269
- clicks,
270
- conversions,
271
- conversion_value: round2(conversionValue),
272
- ctr: impressions ? round2(clicks / impressions * 100) : 0,
273
- cpc: clicks ? round2(spend / clicks) : 0,
274
- cpm: impressions ? round2(spend / impressions * 1e3) : 0,
275
- cpa: conversions ? round2(spend / conversions) : 0,
276
- roas: spend ? round2(conversionValue / spend) : 0
2704
+ async fetchReportPages(accountId2, body, limit) {
2705
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError10("INVALID_INPUT", "reddit: report limit must be a positive safe integer");
2706
+ const path2 = `ad_accounts/${encodeURIComponent(accountId2)}/reports?page.size=${Math.min(limit, 1e3)}`;
2707
+ const rows = [], seen = /* @__PURE__ */ new Set();
2708
+ let url3 = this.client.nextUrl(path2, path2), updatedAt;
2709
+ while (true) {
2710
+ if (seen.has(url3) || seen.size >= 1e3) throw new AdportError10("PROVIDER_ERROR", "reddit: report pagination did not terminate");
2711
+ seen.add(url3);
2712
+ const page2 = await this.client.post(url3, body);
2713
+ if (!isRecord(page2.data) || !Array.isArray(page2.data.metrics) || page2.data.metrics.some((row2) => !isRecord(row2))) throw new AdportError10("PROVIDER_ERROR", "reddit: malformed report metrics");
2714
+ rows.push(...page2.data.metrics);
2715
+ if (updatedAt === void 0 && typeof page2.data.metrics_updated_at === "string") updatedAt = page2.data.metrics_updated_at;
2716
+ const next = page2.pagination?.next_url;
2717
+ if (rows.length >= limit || !next) return { metrics: rows.slice(0, limit), truncated: rows.length > limit || Boolean(next), ...updatedAt ? { metrics_updated_at: updatedAt } : {} };
2718
+ url3 = this.client.nextUrl(next, path2);
2719
+ }
2720
+ }
2721
+ toReportRow(raw, accountId2, query, breakdown) {
2722
+ const value = (key) => {
2723
+ const v = raw[key];
2724
+ if (v === null || v === void 0 || v === "" || !["number", "string"].includes(typeof v)) return void 0;
2725
+ const number2 = Number(v);
2726
+ if (!Number.isFinite(number2)) throw new AdportError10("PROVIDER_ERROR", `reddit: invalid numeric report field ${key}`);
2727
+ return number2;
277
2728
  };
278
- const entityId = breakdown ? String(raw[breakdown] ?? "") : accountId;
2729
+ const all = {};
2730
+ for (const [metric, field, divisor] of [["spend", "spend", REDDIT_MICROS], ["impressions", "impressions", 1], ["clicks", "clicks", 1], ["conversion_value", "conversion_purchase_total_value", 100]]) {
2731
+ const v = value(field);
2732
+ if (v !== void 0) all[metric] = v / divisor;
2733
+ }
2734
+ const clickConversions = value("conversion_purchase_clicks"), viewConversions = value("conversion_purchase_views");
2735
+ if (clickConversions !== void 0 && viewConversions !== void 0) all.conversions = clickConversions + viewConversions;
2736
+ for (const [metric, numerator, denominator, factor] of [["ctr", "clicks", "impressions", 100], ["cpc", "spend", "clicks", 1], ["cpm", "spend", "impressions", 1e3], ["cpa", "spend", "conversions", 1], ["roas", "conversion_value", "spend", 1]]) if (all[numerator] !== void 0 && all[denominator] !== void 0) all[metric] = all[denominator] ? all[numerator] / all[denominator] * factor : 0;
2737
+ const entityId = breakdown ? String(raw[breakdown] ?? "") : accountId2;
2738
+ if (!entityId) throw new AdportError10("PROVIDER_ERROR", "reddit: report row is missing its requested entity breakdown");
279
2739
  return {
280
2740
  provider: this.id,
281
- accountId,
2741
+ accountId: accountId2,
282
2742
  entity: { level: query.level, id: entityId, name: entityId },
283
- metrics: Object.fromEntries(query.metrics.map((metric) => [metric, all[metric]]))
2743
+ metrics: Object.fromEntries(query.metrics.filter((metric) => all[metric] !== void 0).map((metric) => [metric, all[metric]]))
284
2744
  };
285
2745
  }
286
2746
  async plan(op, guard) {
2747
+ if (["reddit_create_catalog_products", "reddit_update_catalog_products", "reddit_delete_catalog_products"].includes(op.tool)) return this.catalogProducts.plan(op);
2748
+ if (["reddit_create_catalog_feed", "reddit_update_catalog_feed", "reddit_set_catalog_feed_schedule_status", "reddit_delete_catalog_feed"].includes(op.tool)) return this.catalogFeeds.plan(op);
2749
+ if (["reddit_create_catalog_product_set", "reddit_update_catalog_product_set", "reddit_delete_catalog_product_set"].includes(op.tool)) return this.catalogContent.plan(op);
2750
+ if (["reddit_set_catalog_access", "reddit_create_catalog", "reddit_rename_catalog", "reddit_set_catalog_event_sources", "reddit_delete_catalog"].includes(op.tool)) return this.catalogs.plan(op);
2751
+ if (/^reddit_(?:create_(?:customer_audience|pixel_audience|engagement_audience|saved_audience)|update_(?:audience_users|saved_audience)|delete_(?:audience|saved_audience)|send_conversion_events)$/.test(op.tool)) return this.management.plan(op, guard);
2752
+ if (/^reddit_(?:create_(?:ad_group|ad|post|text_asset)|upload_asset|import_asset_url|stage_post_copy|update_(?:ad_group|ad|targeting)|set_(?:ad_group_budget|ad_group_bidding|ad_group_status|ad_status)|archive_entity|rename_asset|delete_asset)$/.test(op.tool)) return this.creatives.plan(op, guard);
2753
+ redditId.parse(op.accountId);
2754
+ const expectedKind = op.tool === "reddit_api_delete" ? "remove" : op.tool === "reddit_create_campaign" || op.tool === "reddit_api_create" ? "create" : "update";
2755
+ if (op.provider !== this.id || op.kind !== expectedKind) throw new AdportError10("INVALID_INPUT", "reddit: provider or operation kind mismatch");
287
2756
  const payload = op.payload;
288
2757
  switch (op.tool) {
289
2758
  case "reddit_create_campaign":
290
- return this.planCreateCampaign(op.accountId, payload, guard);
2759
+ return this.planCreateCampaign(op.accountId, createCampaign.parse(op.payload), guard);
291
2760
  case "reddit_set_campaign_status":
292
- return this.planSetStatus(op.accountId, payload);
2761
+ return this.planSetStatus(op.accountId, setCampaignStatus.parse(op.payload));
293
2762
  case "reddit_set_budget":
294
- return this.planSetBudget(op.accountId, payload);
2763
+ return this.planSetBudget(op.accountId, setCampaignBudget.parse(op.payload));
295
2764
  case "reddit_api_create":
296
2765
  return this.planApiCreate(op.accountId, payload, guard);
297
2766
  case "reddit_api_update":
@@ -299,12 +2768,12 @@ var RedditAdsProvider = class {
299
2768
  case "reddit_api_delete":
300
2769
  return this.planApiDelete(op.accountId, payload);
301
2770
  default:
302
- throw new AdportError2("PROVIDER_ERROR", `reddit: unsupported write tool ${op.tool}`);
2771
+ throw new AdportError10("PROVIDER_ERROR", `reddit: unsupported write tool ${op.tool}`);
303
2772
  }
304
2773
  }
305
- async planCreateCampaign(accountId, payload, guard) {
2774
+ async planCreateCampaign(accountId2, payload, guard) {
306
2775
  if (payload.budget_micros && !payload.conversion_pixel_id) {
307
- throw new AdportError2("INVALID_INPUT", "reddit: conversion_pixel_id is required for CBO campaigns (effective July 13, 2026)");
2776
+ throw new AdportError10("INVALID_INPUT", "reddit: conversion_pixel_id is required for CBO campaigns (effective July 13, 2026)");
308
2777
  }
309
2778
  const requested = payload.configured_status ?? "PAUSED";
310
2779
  const status2 = guard.forcePausedCreation ? "PAUSED" : requested;
@@ -327,94 +2796,131 @@ var RedditAdsProvider = class {
327
2796
  if (payload.spend_cap_micros) budgetDeltas.push({ target: `new campaign "${payload.name}" spend cap`, toMicros: payload.spend_cap_micros });
328
2797
  return {
329
2798
  summary: `Create Reddit campaign "${payload.name}" (${payload.objective}, ${status2.toLowerCase()})`,
330
- changes: [`+ POST /ad_accounts/${accountId}/campaigns ${JSON.stringify({ data })}`],
2799
+ changes: [`+ POST /ad_accounts/${accountId2}/campaigns ${JSON.stringify({ data })}`],
331
2800
  coercions,
332
2801
  budgetDeltas,
333
- execute: async () => extractIds(await this.client.post(`ad_accounts/${encodeURIComponent(accountId)}/campaigns`, { data }))
2802
+ execute: async () => verifyReceipt(await this.client.post(`ad_accounts/${encodeURIComponent(accountId2)}/campaigns`, { data }), accountId2, data)
334
2803
  };
335
2804
  }
336
- async planSetStatus(accountId, payload) {
337
- const campaign = await this.getOwnedCampaign(accountId, payload.campaign_id);
2805
+ async planSetStatus(accountId2, payload) {
2806
+ const campaign = await this.getOwnedCampaign(accountId2, payload.campaign_id);
338
2807
  return {
339
2808
  summary: `Set Reddit campaign "${campaign.name}" \u2192 ${payload.configured_status.toLowerCase()}`,
340
2809
  changes: [`~ campaign ${campaign.id} configured_status ${campaign.configured_status} \u2192 ${payload.configured_status}`],
341
2810
  coercions: [],
342
2811
  budgetDeltas: [],
343
- execute: async () => extractIds(await this.client.patch(`campaigns/${encodeURIComponent(campaign.id)}`, {
2812
+ execute: async () => verifyReceipt(await this.client.patch(`campaigns/${encodeURIComponent(campaign.id)}`, {
344
2813
  data: { configured_status: payload.configured_status }
345
- }))
2814
+ }), accountId2, { id: campaign.id, configured_status: payload.configured_status })
346
2815
  };
347
2816
  }
348
- async planSetBudget(accountId, payload) {
349
- const campaign = await this.getOwnedCampaign(accountId, payload.campaign_id);
2817
+ async planSetBudget(accountId2, payload) {
2818
+ const campaign = await this.getOwnedCampaign(accountId2, payload.campaign_id);
350
2819
  if (!campaign.is_campaign_budget_optimization) {
351
- throw new AdportError2("INVALID_INPUT", `reddit: campaign "${campaign.name}" is not a CBO campaign; budget its ad groups instead`);
2820
+ throw new AdportError10("INVALID_INPUT", `reddit: campaign "${campaign.name}" is not a CBO campaign; budget its ad groups instead`);
352
2821
  }
2822
+ if (!["DAILY_SPEND", "LIFETIME_SPEND"].includes(String(campaign.goal_type)) || !Number.isSafeInteger(campaign.goal_value) || Number(campaign.goal_value) < 0) throw new AdportError10("INVALID_INPUT", "reddit: current CBO budget/type is unavailable");
2823
+ if (payload.budget_type && payload.budget_type !== campaign.goal_type) throw new AdportError10("INVALID_INPUT", "reddit: campaign budget type is immutable; the existing type must be preserved");
353
2824
  return {
354
2825
  summary: `Change Reddit campaign "${campaign.name}" budget ${campaign.goal_value ?? "?"} \u2192 ${payload.budget_micros} micros`,
355
2826
  changes: [`~ campaign ${campaign.id} ${campaign.goal_type ?? "goal"} ${campaign.goal_value ?? "?"} \u2192 ${payload.budget_micros}`],
356
2827
  coercions: [],
357
2828
  budgetDeltas: [{ target: `campaign "${campaign.name}" budget`, fromMicros: campaign.goal_value, toMicros: payload.budget_micros }],
358
- execute: async () => extractIds(await this.client.patch(`campaigns/${encodeURIComponent(campaign.id)}`, {
359
- data: { goal_value: payload.budget_micros, ...payload.budget_type ? { goal_type: payload.budget_type } : {} }
360
- }))
2829
+ execute: async () => verifyReceipt(await this.client.patch(`campaigns/${encodeURIComponent(campaign.id)}`, {
2830
+ data: { goal_value: payload.budget_micros }
2831
+ }), accountId2, { id: campaign.id, goal_value: payload.budget_micros })
361
2832
  };
362
2833
  }
363
- async planApiCreate(accountId, payload, guard) {
364
- const path = validateRedditPath(payload.path);
365
- if (!path.startsWith(`ad_accounts/${accountId}/`)) {
366
- throw new AdportError2("INVALID_INPUT", "reddit: create path must be under the selected ad account");
2834
+ async planApiCreate(accountId2, payload, guard) {
2835
+ const path2 = validateRedditPath(payload.path);
2836
+ if (!(/* @__PURE__ */ new Set(["campaigns", "ad_groups", "ads", "custom_audiences", "saved_audiences"])).has(path2.split("/")[2] ?? "") || path2.split("/").length !== 3 || !path2.startsWith(`ad_accounts/${accountId2}/`)) {
2837
+ throw new AdportError10("INVALID_INPUT", "reddit: create path must be under the selected ad account");
367
2838
  }
368
2839
  const body = structuredClone(payload.body);
2840
+ if (!isRecord(body.data)) throw new AdportError10("INVALID_INPUT", "reddit: native create requires one data object");
2841
+ if (body.data.ad_account_id !== void 0 && body.data.ad_account_id !== accountId2) throw new AdportError10("INVALID_INPUT", "reddit: create body account differs from the selected account");
2842
+ if (path2.endsWith("/ad_groups")) {
2843
+ if (typeof body.data.campaign_id !== "string") throw new AdportError10("INVALID_INPUT", "reddit: ad-group creation requires campaign_id");
2844
+ await this.getOwnedCampaign(accountId2, body.data.campaign_id);
2845
+ }
2846
+ if (path2.endsWith("/ads")) {
2847
+ if (typeof body.data.ad_group_id !== "string") throw new AdportError10("INVALID_INPUT", "reddit: ad creation requires ad_group_id");
2848
+ const group = (await this.client.get(`ad_groups/${encodeURIComponent(body.data.ad_group_id)}`)).data;
2849
+ if (!isRecord(group) || group.id !== body.data.ad_group_id || group.ad_account_id !== accountId2 || typeof group.campaign_id !== "string") throw new AdportError10("INVALID_INPUT", "reddit: ad-group parent ownership mismatch");
2850
+ await this.getOwnedCampaign(accountId2, group.campaign_id);
2851
+ if (typeof body.data.post_id === "string") await this.creatives.assertPostOwned(accountId2, body.data.post_id);
2852
+ if (typeof body.data.profile_id === "string") await this.creatives.assertProfileAvailable(accountId2, body.data.profile_id);
2853
+ }
2854
+ if (isRecord(body.data.targeting)) await this.creatives.assertTargetingAvailable(accountId2, body.data.targeting);
2855
+ if (path2.endsWith("/custom_audiences")) {
2856
+ const config4 = isRecord(body.data.pixel_audience_config) ? body.data.pixel_audience_config : {};
2857
+ if (Array.isArray(config4.pixel_ids)) {
2858
+ const pixels = await this.client.getPaged(`ad_accounts/${accountId2}/pixels`, {}, 1e3), known = new Set(pixels.map((row2) => row2.id));
2859
+ if (config4.pixel_ids.some((value) => !known.has(value))) throw new AdportError10("INVALID_INPUT", "reddit: retargeting Pixel is not available to this account");
2860
+ }
2861
+ const engagement = isRecord(body.data.engagement_audience_config) ? body.data.engagement_audience_config : {};
2862
+ if (Array.isArray(engagement.campaign_ids)) for (const value of engagement.campaign_ids) await this.getOwnedCampaign(accountId2, redditId.parse(value));
2863
+ }
369
2864
  const coercions = [];
370
2865
  if (guard.forcePausedCreation) {
371
- coerceCreatedStatuses(body, coercions, /\/(?:campaigns|ad_groups|ads)$/.test(path));
2866
+ coerceCreatedStatuses(body, coercions, /\/(?:campaigns|ad_groups|ads)$/.test(path2));
372
2867
  }
373
2868
  return {
374
- summary: `Create Reddit resource via /${path}`,
375
- changes: [`+ POST /${path} ${JSON.stringify(body)}`],
2869
+ summary: `Create Reddit resource via /${path2}`,
2870
+ changes: [`+ POST /${path2} ${JSON.stringify(body)}`],
376
2871
  coercions,
377
2872
  budgetDeltas: collectMicros(body),
378
- execute: async () => extractIds(await this.client.post(path, body))
2873
+ execute: async () => verifyReceipt(await this.client.post(path2, body), accountId2, body.data)
379
2874
  };
380
2875
  }
381
- async planApiUpdate(accountId, payload) {
382
- const path = validateRedditPath(payload.path);
383
- await this.assertOwnedResource(path, accountId);
2876
+ async planApiUpdate(accountId2, payload) {
2877
+ const path2 = validateRedditPath(payload.path);
2878
+ const current = await this.assertOwnedResource(path2, accountId2);
384
2879
  if (containsMoney(payload.body)) {
385
- throw new AdportError2("INVALID_INPUT", "reddit: budget, bid, goal, and spend-cap updates require a typed budget tool for policy checks");
2880
+ throw new AdportError10("INVALID_INPUT", "reddit: budget, bid, goal, and spend-cap updates require a typed budget tool for policy checks");
386
2881
  }
2882
+ if (!isRecord(payload.body.data)) throw new AdportError10("INVALID_INPUT", "reddit: native update requires one data object");
2883
+ for (const key of ["ad_account_id", "account_id", "campaign_id", "ad_group_id"]) if (payload.body.data[key] !== void 0 && payload.body.data[key] !== current[key]) throw new AdportError10("INVALID_INPUT", "reddit: parent/account changes require a dedicated tool and cannot be forwarded as generic metadata");
2884
+ if (typeof payload.body.data.post_id === "string") await this.creatives.assertPostOwned(accountId2, payload.body.data.post_id);
2885
+ if (typeof payload.body.data.profile_id === "string") await this.creatives.assertProfileAvailable(accountId2, payload.body.data.profile_id);
2886
+ if (isRecord(payload.body.data.targeting)) await this.creatives.assertTargetingAvailable(accountId2, payload.body.data.targeting);
387
2887
  return {
388
- summary: `Update Reddit resource via /${path}`,
389
- changes: [`~ PATCH /${path} ${JSON.stringify(payload.body)}`],
2888
+ summary: `Update Reddit resource via /${path2}`,
2889
+ changes: [`~ PATCH /${path2} ${JSON.stringify(payload.body)}`],
390
2890
  coercions: [],
391
2891
  budgetDeltas: [],
392
- execute: async () => extractIds(await this.client.patch(path, payload.body))
2892
+ execute: async () => verifyReceipt(await this.client.patch(path2, payload.body), accountId2, { ...payload.body.data, id: path2.split("/").at(-1) })
393
2893
  };
394
2894
  }
395
- async planApiDelete(accountId, payload) {
396
- const path = validateRedditPath(payload.path);
397
- await this.assertOwnedResource(path, accountId);
2895
+ async planApiDelete(accountId2, payload) {
2896
+ const path2 = validateRedditPath(payload.path);
2897
+ await this.assertOwnedResource(path2, accountId2);
398
2898
  return {
399
- summary: `Permanently delete Reddit resource via /${path}`,
400
- changes: [`- DELETE /${path}`],
2899
+ summary: `Permanently delete Reddit resource via /${path2}`,
2900
+ changes: [`- DELETE /${path2}`],
401
2901
  coercions: [],
402
2902
  budgetDeltas: [],
403
- execute: async () => extractIds(await this.client.delete(path))
2903
+ execute: async () => {
2904
+ const result = await this.client.delete(path2), ids2 = extractIds(result), expected = path2.split("/").at(-1);
2905
+ if (ids2.length && (ids2.length !== 1 || ids2[0] !== expected)) throw new AdportError10("PROVIDER_ERROR", "reddit: deletion receipt ID mismatch; reconcile before retrying", { resource_ids: ids2 });
2906
+ return [expected];
2907
+ }
404
2908
  };
405
2909
  }
406
- async getOwnedCampaign(accountId, campaignId) {
2910
+ async getOwnedCampaign(accountId2, campaignId) {
407
2911
  const campaign = (await this.client.get(`campaigns/${encodeURIComponent(campaignId)}`)).data;
408
- if (campaign.ad_account_id !== accountId) {
409
- throw new AdportError2("INVALID_INPUT", `reddit: campaign ${campaignId} does not belong to selected account ${accountId}`);
2912
+ if (!campaign || campaign.id !== campaignId || campaign.ad_account_id !== accountId2) {
2913
+ throw new AdportError10("INVALID_INPUT", `reddit: campaign ${campaignId} does not belong to selected account ${accountId2}`);
410
2914
  }
411
2915
  return campaign;
412
2916
  }
413
- async assertOwnedResource(path, accountId) {
414
- const resource = (await this.client.get(path)).data;
415
- if (String(resource.ad_account_id ?? "") !== accountId) {
416
- throw new AdportError2("INVALID_INPUT", `reddit: /${path} does not prove ownership by selected account ${accountId}`);
2917
+ async assertOwnedResource(path2, accountId2) {
2918
+ const resource2 = (await this.client.get(path2)).data;
2919
+ if (!isRecord(resource2) || String(resource2.ad_account_id ?? "") !== accountId2) {
2920
+ throw new AdportError10("INVALID_INPUT", `reddit: /${path2} does not prove ownership by selected account ${accountId2}`);
417
2921
  }
2922
+ if (resource2.id !== path2.split("/").at(-1)) throw new AdportError10("INVALID_INPUT", "reddit: resource response ID mismatch");
2923
+ return resource2;
418
2924
  }
419
2925
  };
420
2926
  function nextDay(date) {
@@ -422,31 +2928,31 @@ function nextDay(date) {
422
2928
  value.setUTCDate(value.getUTCDate() + 1);
423
2929
  return value.toISOString().slice(0, 10);
424
2930
  }
425
- function validateRedditPath(path) {
426
- const normalized = path.replace(/^\/+|\/+$/g, "").trim();
427
- if (!/^[A-Za-z0-9_.~/-]{3,220}$/.test(normalized) || normalized.includes("..") || normalized.includes("//")) {
428
- throw new AdportError2("INVALID_INPUT", `reddit: invalid Ads API v3 path "${path}"`);
2931
+ function validateRedditPath(path2) {
2932
+ const normalized2 = path2.replace(/^\/+|\/+$/g, "").trim();
2933
+ if (!/^[A-Za-z0-9_.~/-]{3,220}$/.test(normalized2) || normalized2.includes("..") || normalized2.includes("//")) {
2934
+ throw new AdportError10("INVALID_INPUT", `reddit: invalid Ads API v3 path "${path2}"`);
429
2935
  }
430
- return normalized;
2936
+ return normalized2;
431
2937
  }
432
- function assertReadScoped(path, accountId) {
433
- if (path === `ad_accounts/${accountId}` || path.startsWith(`ad_accounts/${accountId}/`)) return;
434
- if (/^(campaigns|ad_groups|ads|structured_posts)\/[^/]+$/.test(path)) return;
435
- throw new AdportError2("INVALID_INPUT", "reddit: read path must be selected-account scoped or a single campaign/ad-group/ad/post resource");
2938
+ function assertReadScoped(path2, accountId2) {
2939
+ if (path2 === `ad_accounts/${accountId2}` || path2.startsWith(`ad_accounts/${accountId2}/`)) return;
2940
+ if (/^(campaigns|ad_groups|ads|structured_posts)\/[^/]+$/.test(path2)) return;
2941
+ throw new AdportError10("INVALID_INPUT", "reddit: read path must be selected-account scoped or a single campaign/ad-group/ad/post resource");
436
2942
  }
437
2943
  function isRecord(value) {
438
2944
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
439
2945
  }
440
2946
  function coerceCreatedStatuses(value, coercions, statusBearingPath) {
441
2947
  const data = isRecord(value.data) ? value.data : value;
442
- const visit = (item, path = "body") => {
443
- if (Array.isArray(item)) return item.forEach((child, index) => visit(child, `${path}[${index}]`));
2948
+ const visit = (item, path2 = "body") => {
2949
+ if (Array.isArray(item)) return item.forEach((child, index) => visit(child, `${path2}[${index}]`));
444
2950
  if (!isRecord(item)) return;
445
2951
  for (const [key, child] of Object.entries(item)) {
446
2952
  if (key === "configured_status" && child !== "PAUSED") {
447
2953
  item[key] = "PAUSED";
448
- coercions.push(`${path}.${key} coerced to PAUSED by policy (paused_creation)`);
449
- } else visit(child, `${path}.${key}`);
2954
+ coercions.push(`${path2}.${key} coerced to PAUSED by policy (paused_creation)`);
2955
+ } else visit(child, `${path2}.${key}`);
450
2956
  }
451
2957
  };
452
2958
  visit(value);
@@ -461,159 +2967,228 @@ function containsMoney(value) {
461
2967
  if (!isRecord(value)) return false;
462
2968
  return Object.entries(value).some(([key, child]) => MONEY_KEY.test(key) || containsMoney(child));
463
2969
  }
464
- function collectMicros(value, path = "body") {
465
- if (Array.isArray(value)) return value.flatMap((child, index) => collectMicros(child, `${path}[${index}]`));
2970
+ function collectMicros(value, path2 = "body") {
2971
+ if (Array.isArray(value)) return value.flatMap((child, index) => collectMicros(child, `${path2}[${index}]`));
466
2972
  if (!isRecord(value)) return [];
467
2973
  const deltas = [];
468
2974
  for (const [key, child] of Object.entries(value)) {
469
- if (MONEY_KEY.test(key) && Number.isInteger(child) && Number(child) > 0) {
470
- deltas.push({ target: `${path}.${key}`, toMicros: Number(child) });
2975
+ if (MONEY_KEY.test(key) && child !== null) {
2976
+ if (typeof child !== "number" || !Number.isSafeInteger(child) || child < 0) throw new AdportError10("INVALID_INPUT", "reddit: native monetary create fields must be non-negative safe integer micros");
2977
+ deltas.push({ target: `${path2}.${key}`, toMicros: Number(child) });
471
2978
  }
472
- deltas.push(...collectMicros(child, `${path}.${key}`));
2979
+ deltas.push(...collectMicros(child, `${path2}.${key}`));
473
2980
  }
474
2981
  return deltas;
475
2982
  }
476
2983
  function extractIds(envelope) {
477
- const ids = [];
478
- const visit = (value) => {
479
- if (Array.isArray(value)) return value.forEach(visit);
480
- if (!isRecord(value)) return;
481
- if (typeof value.id === "string" || typeof value.id === "number") ids.push(String(value.id));
482
- for (const child of Object.values(value)) visit(child);
483
- };
484
- visit(envelope.data);
485
- return [...new Set(ids)];
2984
+ const rows = Array.isArray(envelope.data) ? envelope.data : [envelope.data];
2985
+ return rows.filter(isRecord).flatMap((row2) => typeof row2.id === "string" ? [row2.id] : []);
486
2986
  }
487
- function round2(value) {
488
- return Math.round(value * 100) / 100;
2987
+ function verifyReceipt(envelope, account, expected) {
2988
+ const ids2 = extractIds(envelope), row2 = envelope.data;
2989
+ const keys2 = ["id", "name", "configured_status", "goal_value", "goal_type", "spend_cap", "bid_value", "campaign_id", "ad_group_id", "post_id", "objective", "is_campaign_budget_optimization"];
2990
+ if (!isRecord(row2) || ids2.length !== 1 || row2.ad_account_id !== account || keys2.some((key) => expected[key] !== void 0 && row2[key] !== expected[key])) throw new AdportError10("PROVIDER_ERROR", "reddit: mutation receipt ID/account/status/money mismatch; reconcile before retrying", { resource_ids: ids2 });
2991
+ return ids2;
489
2992
  }
490
2993
 
491
2994
  // src/tools.ts
492
- import { defineTool, guardedWriteTool } from "@adport/core";
493
- import { z } from "zod";
494
- var status = z.enum(["ACTIVE", "PAUSED"]);
495
- function redditTools(provider) {
2995
+ import { defineTool as defineTool7, guardedWriteTool as guardedWriteTool7 } from "@adport/core";
2996
+ import { z as z19 } from "zod";
2997
+
2998
+ // src/catalog-tools.ts
2999
+ import { defineTool as defineTool3, guardedWriteTool as guardedWriteTool3 } from "@adport/core";
3000
+ import { z as z15 } from "zod";
3001
+ function redditCatalogTools(provider, administration = false) {
3002
+ const read = { namespace: "reddit", catalog: { category: "creatives", exposure: "specialist" }, annotations: { readOnly: true }, presentation: "records", output: z15.looseObject({ records: z15.array(z15.record(z15.string(), z15.unknown())) }) };
496
3003
  return [
497
- defineTool({
3004
+ defineTool3({ ...read, catalog: { category: "administration", exposure: "specialist" }, name: "reddit_catalog_access", description: "List this project/ad-account\u2019s explicit catalog and creation grants. Does not enumerate native Business catalogs or infer Business authority from enabled advertiser access.", input: z15.object({ account_id: redditCatalogId }).strict(), handler: (input) => provider.catalogs.access(input.account_id) }),
3005
+ defineTool3({ ...read, name: "reddit_get_catalog", description: "Read one explicitly granted Business catalog, native counts and configuration_hash. Verifies native catalog/Business IDs; missing fields remain unavailable. No dependent product/ad inventory claim.", input: catalogInput, handler: (input) => provider.catalogs.get(input) }),
3006
+ defineTool3({ ...read, name: "reddit_catalog_creation_context", description: "Read exact owner creation-delegation and selected-account Pixel snapshots for a new Business catalog. Verifies selected Business and optional event-source IDs. No existing catalog enumeration or automatic authority expansion.", input: creationContext, handler: (input) => provider.catalogs.creationContext(input) }),
3007
+ defineTool3({ ...read, catalog: { category: "measurement", exposure: "specialist" }, name: "reddit_catalog_event_source_context", description: "Read current catalog configuration and verify selected Pixel IDs under this ad account before replacing all catalog event sources. Empty explicitly clears them. Shared effects require a separate guarded preview.", input: sourceContext, handler: (input) => provider.catalogs.sourceContext(input) }),
3008
+ guardedWriteTool3({ name: "reddit_create_catalog", namespace: "reddit", provider: "reddit", catalog: { category: "creatives", exposure: "specialist" }, kind: "create", destructive: false, description: "Create an empty catalog under exact owner Business delegation using fresh access/Pixel hashes. Verifies native ID/configuration then adopts only the verified new ID for project write access. No products, ads, spend or events; uncertain results are never replayed.", payload: catalogCreate }),
3009
+ guardedWriteTool3({ name: "reddit_rename_catalog", namespace: "reddit", provider: "reddit", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: false, description: "Rename one writable shared Business catalog using its configuration_hash and shared-effects acknowledgement. Independently checks preserved defaults/event sources. No automatic replay.", payload: catalogRename }),
3010
+ guardedWriteTool3({ name: "reddit_set_catalog_event_sources", namespace: "reddit", provider: "reddit", catalog: { category: "measurement", exposure: "specialist" }, kind: "update", destructive: true, description: "Replace all event-source Pixel IDs using fresh catalog/source-context hashes and shared/measurement-effects acknowledgement. Empty explicitly clears. Verifies selected-account availability and preserved configuration; sends no events and never replays.", payload: catalogSources }),
3011
+ guardedWriteTool3({ name: "reddit_delete_catalog", namespace: "reddit", provider: "reddit", catalog: { category: "creatives", exposure: "specialist" }, kind: "remove", destructive: true, description: "Permanently delete one exact writable catalog using its current hash, exact name and shared/contents acknowledgement. Verifies native acknowledgement and exact lookup absence; other errors remain errors. Contents are not frozen. No restore or automatic replay.", payload: catalogDelete }),
3012
+ ...administration ? [
3013
+ defineTool3({ ...read, catalog: { category: "administration", exposure: "specialist" }, name: "reddit_catalog_access_snapshot", description: "Owner settings/local owner only: inspect exact catalog or creation permission hash. Omitted from hosted MCP and public REST catalogs.", input: permissionSnapshot, handler: (input) => provider.catalogs.snapshot(input) }),
3014
+ guardedWriteTool3({ name: "reddit_set_catalog_access", namespace: "reddit", provider: "reddit", catalog: { category: "administration", exposure: "specialist" }, kind: "update", destructive: true, description: "Owner settings/local owner only: grant exact catalog read/write access, delegate creation/management of verified new IDs in one Business, or revoke access. Shared policy/audit gate; no native permissions granted. Omitted from hosted MCP/public REST.", payload: permissionChange })
3015
+ ] : []
3016
+ ];
3017
+ }
3018
+
3019
+ // src/catalog-content-tools.ts
3020
+ import { creativesOutput as creativesOutput2, defineTool as defineTool4, guardedWriteTool as guardedWriteTool4 } from "@adport/core";
3021
+ import { z as z16 } from "zod";
3022
+ function redditCatalogContentTools(provider) {
3023
+ const read = { namespace: "reddit", catalog: { category: "creatives", exposure: "specialist" }, annotations: { readOnly: true }, presentation: "records", output: z16.looseObject({ records: z16.array(z16.record(z16.string(), z16.unknown())) }) }, pagination = { cursorInput: "cursor" };
3024
+ return [
3025
+ defineTool4({ ...read, name: "reddit_catalog_product_sets", description: "Page through product sets in one explicitly granted Business catalog. Verifies each native parent; no global set enumeration.", input: setList, pagination, handler: (input) => provider.catalogContent.sets(input) }),
3026
+ defineTool4({ ...read, name: "reddit_get_catalog_product_set", description: "Read an exact native catalog/set, filter and configuration_hash. Product counts are native snapshots; absent fields remain unavailable.", input: setInput, handler: (input) => provider.catalogContent.getSet(input) }),
3027
+ defineTool4({ ...read, name: "reddit_catalog_products", description: "Page catalog products and native approval/issues through one exact catalog grant. Preserves repeated ID query parameters and opaque SKUs. Embeds Reddit-hosted native previews only.", input: productList, presentation: "creatives", output: creativesOutput2.passthrough(), pagination, handler: (input) => provider.catalogContent.products(input) }),
3028
+ defineTool4({ ...read, name: "reddit_catalog_product_set_products", description: "Page products matching one independently verified catalog/set. Rechecks catalog and set scope on every page; membership can change between pages.", input: setProductList, presentation: "creatives", output: creativesOutput2.passthrough(), pagination, handler: (input) => provider.catalogContent.products(input, true) }),
3029
+ guardedWriteTool4({ name: "reddit_create_catalog_product_set", namespace: "reddit", provider: "reddit", catalog: { category: "creatives", exposure: "specialist" }, kind: "create", destructive: false, description: "Create a shared catalog product set with a documented filter JSON string and fresh catalog hash. Uses normal approval and independent ID/catalog/configuration readback; creates no ads or spend.", payload: setCreate }),
3030
+ guardedWriteTool4({ name: "reddit_update_catalog_product_set", namespace: "reddit", provider: "reddit", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: true, description: "Update selected name/filter fields using the exact set configuration_hash and shared-effects acknowledgement. A filter replaces matching rules; omitted configuration is independently checked.", payload: setUpdate }),
3031
+ guardedWriteTool4({ name: "reddit_delete_catalog_product_set", namespace: "reddit", provider: "reddit", catalog: { category: "creatives", exposure: "specialist" }, kind: "remove", destructive: true, description: "Permanently delete an exact shared product-set definition using current hash/name and acknowledgements. Verifies native acknowledgement and exact GET404; dependent membership/ads are not frozen and errors are not absence.", payload: setDelete }),
3032
+ defineTool4({ ...read, name: "reddit_catalog_imports", description: "Page import history for one explicitly granted catalog, with repeated feed IDs and native status filters. Processing counts and missing fields remain native snapshots.", input: importList, pagination, handler: (input) => provider.catalogContent.imports(input) }),
3033
+ defineTool4({ ...read, name: "reddit_catalog_import_issues", description: "Read one catalog import\u2019s issues after proving import membership in the selected catalog within 10,000 rows. Global/foreign IDs are rejected; each page rechecks current catalog access.", input: importIssues, pagination, handler: (input) => provider.catalogContent.issues(input) }),
3034
+ defineTool4({ ...read, name: "reddit_catalog_import_report", description: "Obtain a temporary native report download URL only after current catalog/import membership proof. Does not fetch it or forward Reddit credentials. Missing/expired reports are not clean diagnostics.", input: importInput, handler: (input) => provider.catalogContent.report(input) })
3035
+ ];
3036
+ }
3037
+
3038
+ // src/catalog-feed-tools.ts
3039
+ import { defineTool as defineTool5, guardedWriteTool as guardedWriteTool5 } from "@adport/core";
3040
+ import { z as z17 } from "zod";
3041
+ function redditCatalogFeedTools(provider) {
3042
+ const read = { namespace: "reddit", catalog: { category: "creatives", exposure: "specialist" }, annotations: { readOnly: true }, presentation: "records", output: z17.looseObject({ records: z17.array(z17.record(z17.string(), z17.unknown())) }) };
3043
+ return [
3044
+ defineTool5({ ...read, name: "reddit_catalog_feeds", description: "Browse feeds in one explicitly granted Business catalog. Native lists are unpaged; Adport bounds to5,000 and snapshot-pages locally. Source paths, query values and authentication stay private.", input: feedList, pagination: { cursorInput: "cursor" }, handler: (input) => provider.catalogFeeds.list(input) }),
3045
+ defineTool5({ ...read, name: "reddit_get_catalog_feed", description: "Read one exact catalog/feed with safe source origin/fingerprint, reported schedule and configuration_hash. Missing schedule fields remain unavailable; authentication values are never returned.", input: feedInput, handler: (input) => provider.catalogFeeds.get(input) }),
3046
+ guardedWriteTool5({ name: "reddit_create_catalog_feed", namespace: "reddit", provider: "reddit", catalog: { category: "creatives", exposure: "specialist" }, kind: "create", destructive: true, description: "Create a native catalog feed with explicit REPLACE/UPDATE and schedule/null, fresh catalog hash and shared/automatic-processing acknowledgements. Can start ingestion and affect existing ads. Private source/name arguments stay out of widget approvals; apply through the agent. Readback is not ingestion/authentication proof.", payload: feedCreate, hosted: { payload: hostedFeedCreate, description: "Create a feed from a public HTTPS URL in the selected Reddit catalog. Choose REPLACE or UPDATE and confirm processing and effects on existing products and ads." }, sensitiveInputs: ["url", "username", "password", "name"] }),
3047
+ guardedWriteTool5({ name: "reddit_update_catalog_feed", namespace: "reddit", provider: "reddit", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: true, description: "Change selected native feed fields using current configuration_hash. Omitted source/authentication fields are not sent; supplied schedule replaces timing. Source/mode/auth/schedule changes need automatic-processing acknowledgement. Private source/name arguments stay out of widget approvals; no automatic replay.", payload: feedUpdate, hosted: { payload: hostedFeedUpdate, description: "Update selected Reddit feed settings using its current configuration hash. A replacement source must be a public HTTPS URL. Source, mode and schedule changes require acknowledging processing and can affect existing products and ads." }, sensitiveInputs: ["url", "username", "password", "name"] }),
3048
+ guardedWriteTool5({ name: "reddit_set_catalog_feed_schedule_status", namespace: "reddit", provider: "reddit", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: true, description: "Pause or resume one verified feed schedule with a current hash and shared/automatic-processing acknowledgements. Uses the opposite known pause state and preserves reported timing/source/mode. Does not cancel or undo an existing import.", payload: feedStatus }),
3049
+ guardedWriteTool5({ name: "reddit_delete_catalog_feed", namespace: "reddit", provider: "reddit", catalog: { category: "creatives", exposure: "specialist" }, kind: "remove", destructive: true, description: "Permanently delete an exact writable catalog/feed using its current configuration_hash and shared/deletion acknowledgements. Checks native204 acknowledgement and exactGET404. Other errors remain errors; imported products/ads are not frozen or automatically removed.", payload: feedDelete })
3050
+ ];
3051
+ }
3052
+
3053
+ // src/catalog-product-tools.ts
3054
+ import { defineTool as defineTool6, guardedWriteTool as guardedWriteTool6 } from "@adport/core";
3055
+ import { z as z18 } from "zod";
3056
+ function redditCatalogProductTools(provider) {
3057
+ const catalog = { category: "creatives", exposure: "specialist" }, write2 = { namespace: "reddit", provider: "reddit", catalog };
3058
+ return [
3059
+ defineTool6({ name: "reddit_catalog_product_context", namespace: "reddit", catalog, annotations: { readOnly: true }, presentation: "records", description: "Read up to 100 exact external SKUs in one granted Business catalog, exhausting scoped native pagination. Returns a selection_hash and present/absent state for manual product changes; not a global inventory.", input: productContext, output: z18.looseObject({ records: z18.array(z18.record(z18.string(), z18.unknown())) }), handler: (input) => provider.catalogProducts.context(input) }),
3060
+ guardedWriteTool6({ ...write2, name: "reddit_create_catalog_products", kind: "create", destructive: true, description: "Create up to 100 absent SKUs through native batch upsert with fresh selection_hash and complete product copy/price/URLs. Rechecks absence, uses normal approval and independent readback. Native concurrent upsert races and feed overwrites remain possible.", payload: productsCreate }),
3061
+ guardedWriteTool6({ ...write2, name: "reddit_update_catalog_products", kind: "update", destructive: true, description: "Update selected fields on up to 100 existing external SKUs with current selection_hash. Merges all known writable fields, refuses unknown configuration, verifies complete readback and reports uncertain/partial outcomes without replay.", payload: productsUpdate }),
3062
+ guardedWriteTool6({ ...write2, name: "reddit_delete_catalog_products", kind: "remove", destructive: true, description: "Permanently delete up to 100 exact present external SKUs with selection_hash and explicit acknowledgement. Verifies per-SKU native receipts and exhausted absence readback. Feeds can recreate products; internal Reddit IDs are not SKUs.", payload: productsDelete })
3063
+ ];
3064
+ }
3065
+
3066
+ // src/tools.ts
3067
+ function redditTools(provider, options = {}) {
3068
+ return [
3069
+ defineTool7({
3070
+ name: "reddit_account_context",
3071
+ namespace: "reddit",
3072
+ description: "Read the selected ad account\u2019s basic metadata and parent Business ID. Business/catalog enumeration and catalog access require separate explicit project grants.",
3073
+ input: z19.object({ account_id: redditId }).strict(),
3074
+ output: redditAccountContext,
3075
+ catalog: { category: "core", exposure: "standard" },
3076
+ annotations: { readOnly: true },
3077
+ handler: (input) => provider.accountContext(input.account_id)
3078
+ }),
3079
+ ...redditCatalogProductTools(provider),
3080
+ ...redditCatalogFeedTools(provider),
3081
+ ...redditCatalogContentTools(provider),
3082
+ ...redditCatalogTools(provider, options.catalogAccessManagement === true),
3083
+ ...redditCreativeTools(provider),
3084
+ ...redditManagementTools(provider),
3085
+ defineTool7({
498
3086
  name: "reddit_api_read",
499
3087
  namespace: "reddit",
500
3088
  description: "Call a documented Reddit Ads API v3 GET or read-only reports/history/query/search POST endpoint, scoped to the selected ad account.",
501
- input: z.object({
502
- account_id: z.string(),
503
- path: z.string().min(3).describe("Relative v3 path, e.g. ad_accounts/{id}/ad_groups or campaigns/{campaign_id}"),
504
- method: z.enum(["GET", "POST"]).default("GET"),
505
- params: z.record(z.string(), z.unknown()).optional(),
506
- body: z.record(z.string(), z.unknown()).optional(),
507
- limit: z.number().int().positive().max(5e3).optional().describe("Follow list pagination for GET responses")
3089
+ input: z19.object({
3090
+ account_id: z19.string(),
3091
+ path: z19.string().min(3).describe("Relative v3 path, e.g. ad_accounts/{id}/ad_groups or campaigns/{campaign_id}"),
3092
+ method: z19.enum(["GET", "POST"]).default("GET"),
3093
+ params: z19.record(z19.string(), z19.unknown()).optional(),
3094
+ body: z19.record(z19.string(), z19.unknown()).optional(),
3095
+ limit: z19.number().int().positive().max(5e3).optional().describe("Follow list pagination for GET responses")
508
3096
  }),
509
3097
  annotations: { readOnly: true },
510
3098
  handler: (input) => provider.apiRead(input)
511
3099
  }),
512
- defineTool({
3100
+ defineTool7({
513
3101
  name: "reddit_campaigns",
514
3102
  namespace: "reddit",
515
3103
  description: "List Reddit campaigns and their native configured/effective status, CBO budget, objective, and funding instrument.",
516
- input: z.object({ account_id: z.string(), campaign_ids: z.array(z.string()).optional() }),
3104
+ input: z19.object({ account_id: z19.string(), campaign_ids: z19.array(z19.string()).optional() }),
517
3105
  annotations: { readOnly: true },
518
3106
  async handler(input) {
519
3107
  return { campaigns: await provider.listCampaigns(input.account_id, input.campaign_ids) };
520
3108
  }
521
3109
  }),
522
- defineTool({
3110
+ defineTool7({
523
3111
  name: "reddit_report",
524
3112
  namespace: "reddit",
525
- description: "Query Reddit Ads API v3 reporting directly. Spend, CPC, CPM, and applicable conversion fields are returned by Reddit in micros.",
526
- input: z.object({
527
- account_id: z.string(),
528
- breakdowns: z.array(z.string()).max(4).optional(),
529
- fields: z.array(z.string()).min(1).default(["spend", "impressions", "clicks"]),
530
- starts_at: z.string().datetime({ offset: true }),
531
- ends_at: z.string().datetime({ offset: true }),
532
- time_zone_id: z.string().default("UTC"),
533
- filter: z.string().optional(),
534
- page_size: z.number().int().positive().max(1e3).default(200)
3113
+ description: "Query Reddit Ads API v3 reporting directly. Spend/CPC/CPM use micros; conversion TOTAL_VALUE fields use cents. Missing metrics remain unavailable.",
3114
+ input: z19.object({
3115
+ account_id: z19.string(),
3116
+ breakdowns: z19.array(z19.string()).max(4).optional(),
3117
+ fields: z19.array(z19.string()).min(1).default(["SPEND", "IMPRESSIONS", "CLICKS"]),
3118
+ starts_at: z19.string().datetime({ offset: true }),
3119
+ ends_at: z19.string().datetime({ offset: true }),
3120
+ time_zone_id: z19.string().default("UTC"),
3121
+ filter: z19.string().optional(),
3122
+ page_size: z19.number().int().positive().max(1e3).default(200)
535
3123
  }),
536
3124
  annotations: { readOnly: true },
537
3125
  handler: (input) => provider.rawReport(input)
538
3126
  }),
539
- guardedWriteTool({
3127
+ guardedWriteTool7({
540
3128
  name: "reddit_create_campaign",
541
3129
  namespace: "reddit",
542
3130
  description: "Create a Reddit campaign through API v3. Campaigns are forced PAUSED. CBO budgets and spend caps are integer micros.",
543
3131
  provider: "reddit",
544
3132
  kind: "create",
545
- payload: z.object({
546
- name: z.string().min(1),
547
- objective: z.string().min(1).default("TRAFFIC").describe("Current Reddit objective enum; Reddit has announced an enum migration for Sep 30, 2026"),
548
- funding_instrument_id: z.string().min(1),
549
- configured_status: status.optional(),
550
- budget_micros: z.number().int().positive().optional().describe("Sets CBO goal_value; requires conversion_pixel_id"),
551
- budget_type: z.enum(["DAILY_SPEND", "LIFETIME_SPEND"]).default("DAILY_SPEND"),
552
- conversion_pixel_id: z.string().optional(),
553
- spend_cap_micros: z.number().int().positive().optional()
554
- })
3133
+ payload: createCampaign
555
3134
  }),
556
- guardedWriteTool({
3135
+ guardedWriteTool7({
557
3136
  name: "reddit_set_campaign_status",
558
3137
  namespace: "reddit",
559
3138
  description: "Activate or pause a Reddit campaign after verifying ad-account ownership.",
560
3139
  provider: "reddit",
561
3140
  kind: "update",
562
- payload: z.object({ campaign_id: z.string(), configured_status: status })
3141
+ payload: setCampaignStatus
563
3142
  }),
564
- guardedWriteTool({
3143
+ guardedWriteTool7({
565
3144
  name: "reddit_set_budget",
566
3145
  namespace: "reddit",
567
3146
  description: "Change a Reddit CBO campaign goal_value in integer micros, with current-value lookup and policy checks.",
568
3147
  provider: "reddit",
569
3148
  kind: "update",
570
- payload: z.object({
571
- campaign_id: z.string(),
572
- budget_micros: z.number().int().positive(),
573
- budget_type: z.enum(["DAILY_SPEND", "LIFETIME_SPEND"]).optional()
574
- })
3149
+ payload: setCampaignBudget
575
3150
  }),
576
- guardedWriteTool({
3151
+ guardedWriteTool7({
577
3152
  name: "reddit_api_create",
578
3153
  namespace: "reddit",
579
3154
  description: "Create via an account-scoped Reddit Ads API v3 endpoint. Campaign status is forced PAUSED and native micros fields are policy-checked.",
580
3155
  provider: "reddit",
581
3156
  kind: "create",
582
- payload: z.object({ path: z.string().min(3), body: z.record(z.string(), z.unknown()) })
3157
+ payload: z19.object({ path: z19.string().min(3), body: z19.record(z19.string(), z19.unknown()) })
583
3158
  }),
584
- guardedWriteTool({
3159
+ guardedWriteTool7({
585
3160
  name: "reddit_api_update",
586
3161
  namespace: "reddit",
587
3162
  description: "PATCH non-budget fields on a Reddit Ads API v3 resource after verifying ad-account ownership.",
588
3163
  provider: "reddit",
589
3164
  kind: "update",
590
- payload: z.object({ path: z.string().min(3), body: z.record(z.string(), z.unknown()) })
3165
+ payload: z19.object({ path: z19.string().min(3), body: z19.record(z19.string(), z19.unknown()) })
591
3166
  }),
592
- guardedWriteTool({
3167
+ guardedWriteTool7({
593
3168
  name: "reddit_api_delete",
594
3169
  namespace: "reddit",
595
3170
  description: "Permanently DELETE a Reddit Ads API v3 resource after verifying ad-account ownership.",
596
3171
  provider: "reddit",
597
3172
  kind: "remove",
598
3173
  destructive: true,
599
- payload: z.object({ path: z.string().min(3) })
3174
+ payload: z19.object({ path: z19.string().min(3) })
600
3175
  })
601
3176
  ];
602
3177
  }
603
3178
 
604
3179
  // src/index.ts
605
3180
  async function resolveRedditCredentials(store) {
606
- const record = await store.get("reddit");
607
- const data = record?.data;
3181
+ const record2 = await store.get("reddit");
3182
+ const data = record2?.data;
608
3183
  if (data?.client_id && data.client_secret && data.refresh_token && data.user_agent) {
609
- const source = record?.source ?? "byo";
3184
+ const source2 = record2?.source ?? "byo";
610
3185
  return {
611
3186
  clientId: data.client_id,
612
3187
  clientSecret: data.client_secret,
613
3188
  refreshToken: data.refresh_token,
614
3189
  userAgent: data.user_agent,
615
3190
  onRefreshToken: async (refreshToken) => {
616
- await store.set({ provider: "reddit", source, data: { ...data, refresh_token: refreshToken } });
3191
+ await store.set({ provider: "reddit", source: source2, data: { ...data, refresh_token: refreshToken } });
617
3192
  }
618
3193
  };
619
3194
  }
@@ -630,18 +3205,29 @@ async function resolveRedditCredentials(store) {
630
3205
  async function createRedditModule(store) {
631
3206
  const credentials = await resolveRedditCredentials(store);
632
3207
  if (!credentials) return void 0;
633
- const provider = new RedditAdsProvider(new RedditAdsClient(credentials));
634
- return { provider, tools: redditTools(provider) };
3208
+ const provider = new RedditAdsProvider(new RedditAdsClient(credentials), void 0, new FileRedditCatalogAccessStore());
3209
+ return { provider, tools: redditTools(provider, { catalogAccessManagement: true }) };
635
3210
  }
636
3211
  export {
3212
+ FileRedditCatalogAccessStore,
637
3213
  REDDIT_API_BASE,
638
3214
  REDDIT_API_VERSION,
639
3215
  REDDIT_MICROS,
640
3216
  REDDIT_TOKEN_URL,
641
3217
  RedditAdsClient,
642
3218
  RedditAdsProvider,
3219
+ RedditCatalogService,
3220
+ catalogGrant,
3221
+ catalogScope,
3222
+ catalogScopeKey,
643
3223
  createRedditModule,
3224
+ creationScope,
3225
+ redditBusinessId,
3226
+ redditCatalogId,
3227
+ redditCatalogTools,
644
3228
  redditTools,
3229
+ requireCatalogAccess,
3230
+ requireCatalogCreationAccess,
645
3231
  resolveRedditCredentials
646
3232
  };
647
3233
  //# sourceMappingURL=index.js.map