@hermoso/ads 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,259 @@
1
+ import { definePlatform, row, pickLevel, dateRange } from '../platform.js';
2
+ import { AdsError } from '../errors.js';
3
+ import { assertBornPaused, gateStatus, gateBudget, gateDelete, checkLength, STATUS } from '../safety.js';
4
+ import { toMicros, fromMicros } from '../money.js';
5
+ import { oauth2Refresh } from '../oauth.js';
6
+ import { hashEmail } from '../hash.js';
7
+
8
+
9
+ const TOKEN_URL = 'https://www.reddit.com/api/v1/access_token';
10
+ const acct = (id) => (String(id).startsWith('a2_') ? String(id) : `a2_${id}`);
11
+ const OBJECTIVES = ['BRAND_AWARENESS', 'SALES', 'CLICKS', 'LEAD_GENERATION', 'APP_INSTALLS', 'CONVERSIONS', 'IMPRESSIONS', 'VIDEO_VIEWABLE_IMPRESSIONS', 'CATALOG_SALES'];
12
+ const COST_CAP_SUNSET = '2027-02-10';
13
+ const COST_CAP_OBJECTIVES = ['SALES', 'CONVERSIONS', 'LEAD_GENERATION', 'APP_INSTALLS', 'CATALOG_SALES'];
14
+ const PATH = { campaign: 'campaigns', adGroup: 'ad_groups', ad: 'ads' };
15
+
16
+ function parseError(status, body) {
17
+ const e = body?.error ?? body;
18
+ const fields = (e?.fields ?? []).map((f) => `${f.field} — ${f.message}`).join('; ');
19
+ const message = fields || e?.message || e?.explanation || (typeof e === 'string' ? e : null);
20
+ if (status === 403 && /no permission/i.test(message ?? '')) {
21
+ return { kind: 'permission', message, userMessage: `Reddit: the login's ROLE in the Ads business does not allow this (catalog actions need the Catalog manager role). Reconnecting will not help. ${message}` };
22
+ }
23
+ if (status === 410) return { kind: 'refused', message, userMessage: `Reddit has retired this operation; retrying or reconnecting cannot help. ${message ?? ''}`.trim() };
24
+ if (/modified in the last|three hours/i.test(message ?? '')) {
25
+ return { kind: 'refused', message, userMessage: 'Reddit refuses to delete anything modified in the last 3 hours. Archive it instead (setStatus ARCHIVED), which works immediately.' };
26
+ }
27
+ return message ? { message } : null;
28
+ }
29
+
30
+ export default definePlatform({
31
+ id: 'reddit_ads',
32
+ label: 'Reddit Ads',
33
+ money: 'micros',
34
+ credentials: [
35
+ { name: 'clientId', required: true, env: 'REDDIT_ADS_CLIENT_ID' },
36
+ { name: 'clientSecret', required: true, env: 'REDDIT_ADS_CLIENT_SECRET' },
37
+ { name: 'refreshToken', required: true, env: 'REDDIT_ADS_REFRESH_TOKEN', desc: 'From an authorization with duration=permanent.' },
38
+ { name: 'userAgent', env: 'REDDIT_ADS_USER_AGENT', desc: 'Descriptive User-Agent, e.g. "web:my-ads-tool:v1.0 (+https://example.com)".' },
39
+ ],
40
+ baseUrl: 'https://ads-api.reddit.com/api/v3',
41
+ authHeaders: (c) => ({ authorization: `Bearer ${c.accessToken}`, 'user-agent': c.userAgent || 'node:hermoso-ads:v0.1' }),
42
+ refresh: (c, ctx) => oauth2Refresh({ ...ctx, fetch: (u, init) => ctx.fetch(u, { ...init, headers: { ...init.headers, 'user-agent': c.userAgent || 'node:hermoso-ads:v0.1' } }) }, c, { tokenUrl: TOKEN_URL, basicAuth: true }),
43
+ parseError,
44
+ notes: [
45
+ 'Authorize with duration=permanent, or Reddit issues no refresh token and access ends after about an hour.',
46
+ 'Delete means configured_status DELETED (or ARCHIVED, reversible); Reddit refuses deletes within 3 hours of an edit.',
47
+ 'Archive and delete do not cascade: children keep their own status.',
48
+ `Cost Cap (MAXIMIZE_VOLUME) on conversion objectives is retired from ${COST_CAP_SUNSET}; use TARGET_CPX.`,
49
+ ],
50
+ setup: {
51
+ app: 'A Reddit app (reddit.com/prefs/apps, type "web app") with your redirect URI, used by a login that has a role in a Reddit Ads business.',
52
+ scopes: ['adsread', 'adsedit', 'adsconversions', 'history', 'read', 'identity'],
53
+ review: 'No separate review: any registered app can call the Ads API for businesses the authorizing user can manage. Authorize with duration=permanent.',
54
+ hosted: { connect: 'app', note: 'Hosted Hermoso connects with one click where supported, with no developer app of your own.' },
55
+ docs: 'https://ads-api.reddit.com/docs/',
56
+ },
57
+ ops: {
58
+ listAccounts: {
59
+ run: async (ctx, a) => {
60
+ let biz;
61
+ try { biz = await ctx.request({ path: '/me/businesses' }); } catch (e) {
62
+ if (e.kind === 'not_found') return { items: [], note: 'This login has no Reddit Ads business.' };
63
+ throw e;
64
+ }
65
+ const items = [];
66
+ for (const b of biz.data ?? []) {
67
+ const r = await ctx.request({ path: `/businesses/${b.id}/ad_accounts` });
68
+ for (const x of r.data ?? []) items.push(row(x, { id: x.id, name: x.name, currency: x.currency, business: b.name }, a));
69
+ }
70
+ return { items };
71
+ },
72
+ },
73
+ listCampaigns: {
74
+ params: { accountId: { required: true } },
75
+ run: async (ctx, a) => {
76
+ const r = await ctx.request({ path: `/ad_accounts/${acct(a.accountId)}/campaigns`, query: { 'page.size': Math.min(a.limit ?? 100, 1000), 'page.token': a.cursor } });
77
+ return { items: (r.data ?? []).map((c) => row(c, { id: c.id, name: c.name, status: c.configured_status, effectiveStatus: c.effective_status, objective: c.objective, spendCap: fromMicros(c.spend_cap), dailyBudget: c.goal_type === 'DAILY_SPEND' ? fromMicros(c.goal_value) : undefined }, a)), next: r.pagination?.next_page_token ?? null };
78
+ },
79
+ },
80
+ getCampaign: {
81
+ params: { id: { required: true } },
82
+ run: async (ctx, a) => { const c = (await ctx.request({ path: `/campaigns/${a.id}` })).data; return row(c, { id: c.id, name: c.name, status: c.configured_status, effectiveStatus: c.effective_status, objective: c.objective, goalType: c.goal_type, goalValue: fromMicros(c.goal_value) }, a); },
83
+ },
84
+ createCampaign: {
85
+ params: {
86
+ accountId: { required: true }, name: { required: true }, objective: { type: 'string', enum: OBJECTIVES, required: true },
87
+ dailyBudget: { desc: 'Campaign budget optimization: a daily budget on the campaign.' }, lifetimeBudget: {}, spendCap: { type: 'number', desc: 'Lifetime cap, minimum 100.' },
88
+ bidStrategy: { type: 'string', enum: ['BIDLESS', 'MAXIMIZE_VOLUME', 'TARGET_CPX'] },
89
+ },
90
+ run: async (ctx, a) => {
91
+ assertBornPaused(a, 'campaign');
92
+ checkCostCap(a.objective, a.bidStrategy);
93
+ const data = { name: a.name, objective: a.objective, configured_status: 'PAUSED', ...(a.fields ?? {}) };
94
+ if (a.spendCap != null) {
95
+ if (Number(a.spendCap) < 100) throw new AdsError('validation', 'Reddit\'s minimum spend cap is 100.', { field: 'spendCap' });
96
+ data.spend_cap = toMicros(a.spendCap, 'spendCap');
97
+ }
98
+ if (a.dailyBudget != null || a.lifetimeBudget != null) {
99
+ data.goal_type = a.dailyBudget != null ? 'DAILY_SPEND' : 'LIFETIME_SPEND';
100
+ data.goal_value = toMicros(a.dailyBudget ?? a.lifetimeBudget, 'dailyBudget');
101
+ data.bid_strategy = a.bidStrategy ?? 'BIDLESS';
102
+ }
103
+ const r = await ctx.request({ method: 'POST', path: `/ad_accounts/${acct(a.accountId)}/campaigns`, json: { data } });
104
+ return { id: r.data?.id, status: STATUS.PAUSED, stored: r.data?.configured_status };
105
+ },
106
+ },
107
+ listAdGroups: {
108
+ params: { accountId: { required: true }, campaignId: {} },
109
+ run: async (ctx, a) => {
110
+ const r = await ctx.request({ path: `/ad_accounts/${acct(a.accountId)}/ad_groups`, query: { 'page.size': Math.min(a.limit ?? 100, 1000), 'page.token': a.cursor } });
111
+ const items = (r.data ?? []).filter((g) => !a.campaignId || g.campaign_id === a.campaignId);
112
+ return { items: items.map((g) => row(g, { id: g.id, name: g.name, status: g.configured_status, campaignId: g.campaign_id, bidStrategy: g.bid_strategy, bid: fromMicros(g.bid_value), dailyBudget: g.goal_type === 'DAILY_SPEND' ? fromMicros(g.goal_value) : undefined }, a)), next: r.pagination?.next_page_token ?? null };
113
+ },
114
+ },
115
+ createAdGroup: {
116
+ params: {
117
+ accountId: { required: true }, campaignId: { required: true }, name: { required: true },
118
+ dailyBudget: { desc: 'Omit when the campaign has its own budget.' }, bidType: { type: 'string', enum: ['CPC', 'CPM', 'CPV', 'CPV6', 'CPV15'], desc: 'Default CPC.' },
119
+ bidStrategy: { type: 'string', enum: ['BIDLESS', 'MANUAL_BIDDING', 'MAXIMIZE_VOLUME', 'TARGET_CPX'] }, bid: { type: 'number' },
120
+ communities: { type: 'array', desc: 'Subreddit names.' }, geolocations: { type: 'array', desc: 'Country codes or geo ids.' }, interests: { type: 'array' }, keywords: { type: 'array' },
121
+ targeting: { type: 'object', desc: 'Full Reddit targeting object.' }, startTime: { type: 'string' }, endTime: { type: 'string' },
122
+ },
123
+ run: async (ctx, a) => {
124
+ assertBornPaused(a, 'ad group');
125
+ const targeting = a.targeting ?? Object.fromEntries(Object.entries({ communities: a.communities, geolocations: a.geolocations, interests: a.interests, keywords: a.keywords }).filter(([, v]) => v?.length));
126
+ const data = {
127
+ name: a.name, campaign_id: a.campaignId, configured_status: 'PAUSED', bid_type: a.bidType ?? 'CPC', bid_strategy: a.bidStrategy ?? (a.bid != null ? 'MANUAL_BIDDING' : 'BIDLESS'),
128
+ start_time: a.startTime ?? new Date().toISOString(), ...(a.endTime ? { end_time: a.endTime } : {}),
129
+ ...(a.dailyBudget != null ? { goal_type: 'DAILY_SPEND', goal_value: toMicros(a.dailyBudget, 'dailyBudget') } : {}),
130
+ ...(a.bid != null ? { bid_value: toMicros(a.bid, 'bid') } : {}), ...(Object.keys(targeting).length ? { targeting } : {}), ...(a.fields ?? {}),
131
+ };
132
+ const r = await ctx.request({ method: 'POST', path: `/ad_accounts/${acct(a.accountId)}/ad_groups`, json: { data } });
133
+ return { id: r.data?.id, status: STATUS.PAUSED };
134
+ },
135
+ },
136
+ updateAdGroup: {
137
+ params: { id: { required: true }, name: {}, bid: { type: 'number' }, targeting: { type: 'object' } },
138
+ run: async (ctx, a) => {
139
+ const cur = (await ctx.request({ path: `/ad_groups/${a.id}` })).data;
140
+ const data = { ...(a.name ? { name: a.name } : {}), ...(a.targeting ? { targeting: a.targeting } : {}), ...(a.fields ?? {}) };
141
+ if (a.bid != null) {
142
+ data.bid_value = toMicros(a.bid, 'bid');
143
+ if (cur.configured_status === 'ACTIVE' && (cur.bid_value == null || data.bid_value > Number(cur.bid_value))) gateBudget({ ...a, amount: a.bid }, fromMicros(cur.bid_value));
144
+ }
145
+ const r = await ctx.request({ method: 'PATCH', path: `/ad_groups/${a.id}`, json: { data } });
146
+ return { id: a.id, adGroup: r.data };
147
+ },
148
+ },
149
+ listAds: {
150
+ params: { accountId: { required: true }, adGroupId: {} },
151
+ run: async (ctx, a) => {
152
+ const r = await ctx.request({ path: `/ad_accounts/${acct(a.accountId)}/ads`, query: { 'page.size': Math.min(a.limit ?? 100, 1000), 'page.token': a.cursor } });
153
+ const items = (r.data ?? []).filter((x) => !a.adGroupId || x.ad_group_id === a.adGroupId);
154
+ return { items: items.map((x) => row(x, { id: x.id, name: x.name, status: x.configured_status, adGroupId: x.ad_group_id, postId: x.post_id, clickUrl: x.click_url, review: x.rejection_reason }, a)) };
155
+ },
156
+ },
157
+ createAd: {
158
+ params: { accountId: { required: true }, adGroupId: { required: true }, name: { required: true }, postId: { type: 'string', required: true, desc: 'The promoted post (t3_...).' }, clickUrl: { type: 'string' } },
159
+ run: async (ctx, a) => {
160
+ assertBornPaused(a, 'ad');
161
+ const r = await ctx.request({ method: 'POST', path: `/ad_accounts/${acct(a.accountId)}/ads`, json: { data: { name: a.name, ad_group_id: a.adGroupId, post_id: a.postId, configured_status: 'PAUSED', ...(a.clickUrl ? { click_url: a.clickUrl } : {}), ...(a.fields ?? {}) } } });
162
+ return { id: r.data?.id, status: STATUS.PAUSED };
163
+ },
164
+ },
165
+ listAudiences: {
166
+ params: { accountId: { required: true } },
167
+ run: async (ctx, a) => {
168
+ const r = await ctx.request({ path: `/ad_accounts/${acct(a.accountId)}/custom_audiences` });
169
+ return { items: (r.data ?? []).map((x) => row(x, { id: x.id, name: x.name, type: x.type, size: x.size_range ?? x.size, status: x.status }, a)) };
170
+ },
171
+ },
172
+ createAudience: {
173
+ params: { accountId: { required: true }, name: { required: true }, emails: { type: 'array', desc: 'Hashed here with SHA-256 after trim + lowercase.' } },
174
+ run: async (ctx, a) => {
175
+ const r = await ctx.request({ method: 'POST', path: `/ad_accounts/${acct(a.accountId)}/custom_audiences`, json: { data: { name: a.name, type: 'CUSTOMER_LIST' } } });
176
+ const id = r.data?.id;
177
+ const hashed = (a.emails ?? []).map(hashEmail).filter(Boolean);
178
+ if (hashed.length) await ctx.request({ method: 'PATCH', path: `/custom_audiences/${id}/users`, json: { data: { action_type: 'ADD', column_order: ['EMAIL_SHA256'], user_data: hashed.map((h) => [h]) } } });
179
+ return { id, added: hashed.length };
180
+ },
181
+ },
182
+ setStatus: {
183
+ params: { id: { required: true }, level: {}, status: { required: true } },
184
+ run: async (ctx, a) => {
185
+ const status = gateStatus(a);
186
+ const path = PATH[pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform)];
187
+ const r = await ctx.request({ method: 'PATCH', path: `/${path}/${a.id}`, json: { data: { configured_status: status } } });
188
+ return { id: a.id, status: r.data?.configured_status ?? status };
189
+ },
190
+ },
191
+ setBudget: {
192
+ params: { id: { required: true }, level: { desc: 'campaign (with its own budget) or adGroup. Default adGroup.' }, amount: { required: true } },
193
+ run: async (ctx, a) => {
194
+ const path = PATH[a.level ?? 'adGroup'];
195
+ if (!path || path === 'ads') throw new AdsError('validation', 'level must be campaign or adGroup', { field: 'level' });
196
+ const cur = (await ctx.request({ path: `/${path}/${a.id}` })).data;
197
+ if (cur.goal_value == null) throw new AdsError('validation', 'This object has no budget of its own (it may live on the campaign).', { field: 'level' });
198
+ gateBudget(a, fromMicros(cur.goal_value));
199
+ await ctx.request({ method: 'PATCH', path: `/${path}/${a.id}`, json: { data: { goal_value: toMicros(a.amount), goal_type: cur.goal_type } } });
200
+ return { id: a.id, budget: Number(a.amount), previous: fromMicros(cur.goal_value), goalType: cur.goal_type };
201
+ },
202
+ },
203
+ deleteObject: {
204
+ params: { accountId: { required: true }, id: { required: true }, level: { required: true }, archive: { type: 'boolean', desc: 'Archive (reversible) instead of delete.' }, confirm: {}, confirmName: {}, confirmChildren: {} },
205
+ run: async (ctx, a) => {
206
+ const level = pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform);
207
+ const cur = (await ctx.request({ path: `/${PATH[level]}/${a.id}` })).data;
208
+ const children = [];
209
+ if (level === 'campaign') children.push({ label: 'ad groups', count: (await ctx.request({ path: `/ad_accounts/${acct(a.accountId)}/ad_groups` })).data?.filter((g) => g.campaign_id === a.id && g.configured_status !== 'DELETED').length ?? 0 });
210
+ if (level === 'adGroup') children.push({ label: 'ads', count: (await ctx.request({ path: `/ad_accounts/${acct(a.accountId)}/ads` })).data?.filter((x) => x.ad_group_id === a.id && x.configured_status !== 'DELETED').length ?? 0 });
211
+ gateDelete(a, { what: level, name: cur?.name, children, live: cur?.configured_status === 'ACTIVE', note: 'Reddit does not cascade: children keep their own status.' });
212
+ const terminal = a.archive ? 'ARCHIVED' : 'DELETED';
213
+ await ctx.request({ method: 'PATCH', path: `/${PATH[level]}/${a.id}`, json: { data: { configured_status: terminal } } });
214
+ return { id: a.id, status: terminal };
215
+ },
216
+ },
217
+ report: {
218
+ params: { accountId: { required: true }, since: {}, until: {}, breakdowns: { type: 'array', desc: 'Up to 3 of CAMPAIGN_ID, AD_GROUP_ID, AD_ID, DATE, COUNTRY, COMMUNITY, PLACEMENT...' }, metrics: { type: 'array' } },
219
+ run: async (ctx, a) => {
220
+ const { since, until } = dateRange(a);
221
+ const breakdowns = a.breakdowns ?? ['CAMPAIGN_ID'];
222
+ if (breakdowns.length > 3 && !(breakdowns.length === 4 && breakdowns.includes('COUNTRY') && breakdowns.includes('REGION'))) throw new AdsError('validation', 'At most 3 breakdowns (4 with COUNTRY and REGION).', { field: 'breakdowns' });
223
+ const r = await ctx.request({ method: 'POST', path: `/ad_accounts/${acct(a.accountId)}/reports`, json: { data: {
224
+ fields: a.metrics ?? ['IMPRESSIONS', 'CLICKS', 'SPEND', 'CTR', 'CPC', 'ECPM', 'REACH'], breakdowns,
225
+ starts_at: `${since}T00:00:00Z`, ends_at: `${until}T23:00:00Z` } } });
226
+ const money = ['spend', 'cpc', 'ecpm', 'cpv'];
227
+ const rows = (r.data?.metrics ?? []).map((m) => Object.fromEntries(Object.entries(m).map(([k, v]) => [k, money.includes(k) || k.startsWith('cost_per_') ? fromMicros(v) : v])));
228
+ return { rows, updatedAt: r.data?.metrics_updated_at, ...(rows.length ? {} : { note: 'Nothing delivered in this window (this is not a row of zeros).' }) };
229
+ },
230
+ },
231
+ searchTargeting: {
232
+ params: { type: { required: true, enum: ['communities', 'locations', 'interests', 'keywords'] }, query: { required: true }, country: { type: 'string' } },
233
+ run: async (ctx, a) => {
234
+ if (a.type === 'communities') {
235
+ const r = await ctx.request({ path: '/targeting/communities/search', query: { query: a.query, 'page.size': a.limit ?? 25 } });
236
+ return { items: (r.data ?? []).map((x) => ({ id: x.name ?? x.id, name: x.name, subscribers: x.subscriber_count })) };
237
+ }
238
+ if (a.type === 'locations') {
239
+ const r = await ctx.request({ path: '/targeting/geolocations', query: { country: a.country, cities_search: a.query } });
240
+ return { items: (r.data ?? []).map((x) => ({ id: x.id, name: x.name, type: x.type })) };
241
+ }
242
+ if (a.type === 'interests') {
243
+ const r = await ctx.request({ path: '/targeting/interests' });
244
+ const q = String(a.query).toLowerCase();
245
+ return { items: (r.data ?? []).filter((x) => String(x.name).toLowerCase().includes(q)).map((x) => ({ id: x.id, name: x.name })) };
246
+ }
247
+ checkLength('query', a.query, 100);
248
+ const r = await ctx.request({ method: 'POST', path: '/targeting/keyword_suggestions', json: { data: { seed_keywords: [a.query] } } });
249
+ return { items: (r.data ?? []).map((x) => ({ id: x.keyword ?? x, name: x.keyword ?? x })) };
250
+ },
251
+ },
252
+ },
253
+ });
254
+
255
+ function checkCostCap(objective, strategy, now = new Date()) {
256
+ if (strategy === 'MAXIMIZE_VOLUME' && COST_CAP_OBJECTIVES.includes(objective) && now.toISOString().slice(0, 10) >= COST_CAP_SUNSET) {
257
+ throw new AdsError('validation', `Reddit retired Cost Cap (MAXIMIZE_VOLUME) for ${objective} on ${COST_CAP_SUNSET}; use TARGET_CPX or BIDLESS.`, { field: 'bidStrategy' });
258
+ }
259
+ }
@@ -0,0 +1,276 @@
1
+ import { definePlatform, row, pickLevel, dateRange } from '../platform.js';
2
+ import { AdsError } from '../errors.js';
3
+ import { assertBornPaused, gateStatus, gateBudget, gateDelete, checkLength, STATUS } from '../safety.js';
4
+ import { toMicros, fromMicros } from '../money.js';
5
+ import { oauth2Refresh } from '../oauth.js';
6
+ import { hashEmail } from '../hash.js';
7
+
8
+
9
+ const TOKEN_URL = 'https://accounts.snapchat.com/login/oauth2/access_token';
10
+ const OBJECTIVES = ['AWARENESS_AND_ENGAGEMENT', 'SALES', 'TRAFFIC', 'APP_PROMOTION', 'LEADS'];
11
+ const LEGACY = ['BRAND_AWARENESS', 'WEB_CONVERSION', 'APP_INSTALL', 'ENGAGEMENT', 'VIDEO_VIEW', 'LEAD_GENERATION', 'CATALOG_SALES', 'PROMOTE_STORIES', 'PROMOTE_PLACES'];
12
+ const TIER = { campaign: ['campaigns', 'ad_account_id', 'adaccounts'], adGroup: ['adsquads', 'campaign_id', 'campaigns'], ad: ['ads', 'ad_squad_id', 'adsquads'] };
13
+ const MIN_DAILY = 5;
14
+
15
+ function firstError(body) {
16
+ if (!body || typeof body !== 'object') return null;
17
+ if (body.request_status && body.request_status !== 'SUCCESS') return body.debug_message ?? body.display_message ?? body.error_code ?? body.request_status;
18
+ for (const [k, v] of Object.entries(body)) {
19
+ if (!Array.isArray(v)) continue;
20
+ const bad = v.find((x) => x && x.sub_request_status && x.sub_request_status !== 'SUCCESS');
21
+ if (bad) return bad.sub_request_error_reason ?? `${k}: ${bad.sub_request_status}`;
22
+ }
23
+ return null;
24
+ }
25
+
26
+ /** Unwrap {campaigns:[{campaign:{...}}]} into the inner objects. */
27
+ function unwrap(body, plural) {
28
+ const singular = { campaigns: 'campaign', adsquads: 'adsquad', ads: 'ad', creatives: 'creative', media: 'media', segments: 'segment', adaccounts: 'adaccount', organizations: 'organization' }[plural];
29
+ return (body?.[plural] ?? []).map((x) => x[singular] ?? x);
30
+ }
31
+
32
+ export default definePlatform({
33
+ id: 'snapchat_ads',
34
+ label: 'Snapchat Ads',
35
+ money: 'micros',
36
+ credentials: [
37
+ { name: 'clientId', required: true, env: 'SNAPCHAT_ADS_CLIENT_ID' },
38
+ { name: 'clientSecret', required: true, env: 'SNAPCHAT_ADS_CLIENT_SECRET' },
39
+ { name: 'refreshToken', required: true, env: 'SNAPCHAT_ADS_REFRESH_TOKEN' },
40
+ ],
41
+ baseUrl: 'https://adsapi.snapchat.com/v1',
42
+ authHeaders: (c) => ({ authorization: `Bearer ${c.accessToken}` }),
43
+ refresh: (c, ctx) => oauth2Refresh(ctx, c, { tokenUrl: TOKEN_URL }),
44
+ checkBody: (body) => { const m = firstError(body); return m ? { kind: /not found/i.test(m) ? 'not_found' : 'validation', message: m } : null; },
45
+ parseError: (status, body) => {
46
+ const m = firstError(body) ?? body?.message;
47
+ if (status === 403) return { kind: 'permission', message: m, userMessage: `Snapchat: your role on this ad account does not allow this (the connection is fine). ${m ?? ''}`.trim() };
48
+ if (status === 415) return { kind: 'vendor', message: m, userMessage: 'Snapchat rejected the request format (415).' };
49
+ if (/not found/i.test(m ?? '')) return { kind: 'not_found', message: m };
50
+ return m ? { message: m } : null;
51
+ },
52
+ notes: [
53
+ 'Budgets and bids are micro-currency on the wire; pass plain amounts here. Minimum daily budget is 5.',
54
+ 'Creative headline limit is 34 characters and brand name 32: longer copy is refused, never cut.',
55
+ 'Every creative needs a public profile id (profileId).',
56
+ 'Updates are JSON Patch (application/json-patch+json).',
57
+ ],
58
+ setup: {
59
+ app: 'An OAuth app created in Snapchat Business Manager (Business Details > OAuth Apps) with your redirect URI.',
60
+ scopes: ['snapchat-marketing-api'],
61
+ review: 'No allowlist: the OAuth app works for any ad account the authorizing member can manage.',
62
+ hosted: { connect: 'app', note: 'Hosted Hermoso connects with one click where supported, with no developer app of your own.' },
63
+ docs: 'https://developers.snap.com/api/marketing-api/Ads-API/introduction',
64
+ },
65
+ ops: {
66
+ listAccounts: {
67
+ run: async (ctx, a) => {
68
+ const r = await ctx.request({ path: '/me/organizations', query: { with_ad_accounts: true } });
69
+ const items = [];
70
+ for (const org of unwrap(r, 'organizations')) for (const x of org.ad_accounts ?? []) items.push(row(x, { id: x.id, name: x.name, currency: x.currency, timezone: x.timezone, status: x.status, organization: org.name }, a));
71
+ return { items };
72
+ },
73
+ },
74
+ listCampaigns: {
75
+ params: { accountId: { required: true } },
76
+ run: async (ctx, a) => {
77
+ const r = await ctx.request({ path: `/adaccounts/${a.accountId}/campaigns`, query: { limit: 200 } });
78
+ return { items: unwrap(r, 'campaigns').map((c) => row(c, { id: c.id, name: c.name, status: c.status, objective: c.objective_v2_properties?.objective_v2_type ?? c.objective, dailyBudget: fromMicros(c.daily_budget_micro), lifetimeBudget: fromMicros(c.lifetime_spend_cap_micro) }, a)) };
79
+ },
80
+ },
81
+ getCampaign: {
82
+ params: { id: { required: true } },
83
+ run: async (ctx, a) => { const [c] = unwrap(await ctx.request({ path: `/campaigns/${a.id}` }), 'campaigns'); return row(c, { id: c.id, name: c.name, status: c.status, objective: c.objective_v2_properties?.objective_v2_type, adAccountId: c.ad_account_id }, a); },
84
+ },
85
+ createCampaign: {
86
+ params: { accountId: { required: true }, name: { required: true }, objective: { type: 'string', enum: OBJECTIVES, required: true }, dailyBudget: {}, startTime: { type: 'string' }, endTime: { type: 'string' } },
87
+ run: async (ctx, a) => {
88
+ assertBornPaused(a, 'campaign');
89
+ checkLength('name', a.name, 375);
90
+ if (LEGACY.includes(a.objective)) throw new AdsError('validation', `${a.objective} is a retired Snapchat objective; use one of ${OBJECTIVES.join(', ')}.`, { field: 'objective' });
91
+ if (!OBJECTIVES.includes(a.objective)) throw new AdsError('validation', `objective must be one of ${OBJECTIVES.join(', ')}`, { field: 'objective' });
92
+ const c = { name: a.name, ad_account_id: a.accountId, buy_model: 'AUCTION', status: 'PAUSED', start_time: a.startTime ?? new Date().toISOString(), ...(a.endTime ? { end_time: a.endTime } : {}),
93
+ objective_v2_properties: { objective_v2_type: a.objective }, ...(a.dailyBudget != null ? { daily_budget_micro: budgetMicro(a.dailyBudget) } : {}), ...(a.fields ?? {}) };
94
+ const [d] = unwrap(await ctx.request({ method: 'POST', path: `/adaccounts/${a.accountId}/campaigns`, json: { campaigns: [c] } }), 'campaigns');
95
+ return { id: d?.id, status: STATUS.PAUSED };
96
+ },
97
+ },
98
+ listAdGroups: {
99
+ params: { accountId: { desc: 'Ad account (or campaignId).' }, campaignId: {} },
100
+ run: async (ctx, a) => {
101
+ const path = a.campaignId ? `/campaigns/${a.campaignId}/adsquads` : `/adaccounts/${a.accountId}/adsquads`;
102
+ const r = await ctx.request({ path, query: { limit: 200 } });
103
+ return { items: unwrap(r, 'adsquads').map((s) => row(s, { id: s.id, name: s.name, status: s.status, campaignId: s.campaign_id, dailyBudget: fromMicros(s.daily_budget_micro), bid: fromMicros(s.bid_micro), optimizationGoal: s.optimization_goal }, a)) };
104
+ },
105
+ },
106
+ createAdGroup: {
107
+ params: {
108
+ accountId: { required: true }, campaignId: { required: true }, name: { required: true }, countries: { type: 'array', required: true, desc: 'Two-letter country codes.' },
109
+ dailyBudget: {}, lifetimeBudget: {}, optimizationGoal: { type: 'string', desc: 'Default IMPRESSIONS (SWIPES, PIXEL_PURCHASE, ...).' },
110
+ bidStrategy: { type: 'string', enum: ['AUTO_BID', 'LOWEST_COST_WITH_MAX_BID'] }, bid: { type: 'number', desc: 'Required unless AUTO_BID.' }, pixelId: { type: 'string' }, targeting: { type: 'object' },
111
+ },
112
+ run: async (ctx, a) => {
113
+ assertBornPaused(a, 'ad squad');
114
+ checkLength('name', a.name, 375);
115
+ const strategy = a.bidStrategy ?? 'AUTO_BID';
116
+ if (['TARGET_COST', 'MIN_ROAS'].includes(strategy)) throw new AdsError('validation', `${strategy} is not available on Snapchat.`, { field: 'bidStrategy' });
117
+ if (strategy !== 'AUTO_BID' && a.bid == null) throw new AdsError('validation', `${strategy} needs bid.`, { field: 'bid' });
118
+ const goal = a.optimizationGoal ?? 'IMPRESSIONS';
119
+ if (goal.startsWith('PIXEL_') && !a.pixelId) throw new AdsError('validation', `${goal} needs pixelId.`, { field: 'pixelId' });
120
+ const [camp] = unwrap(await ctx.request({ path: `/campaigns/${a.campaignId}` }), 'campaigns');
121
+ if (camp?.ad_account_id && camp.ad_account_id !== a.accountId) throw new AdsError('validation', 'That campaign belongs to another ad account.', { field: 'campaignId' });
122
+ const s = { name: a.name, campaign_id: a.campaignId, type: 'SNAP_ADS', billing_event: 'IMPRESSION', bid_strategy: strategy, optimization_goal: goal, status: 'PAUSED',
123
+ placement_v2: { config: 'AUTOMATIC' }, targeting: a.targeting ?? { regulated_content: false, geos: a.countries.map((c) => ({ country_code: String(c).toLowerCase() })) },
124
+ ...(a.dailyBudget != null ? { daily_budget_micro: budgetMicro(a.dailyBudget) } : {}), ...(a.lifetimeBudget != null ? { lifetime_budget_micro: toMicros(a.lifetimeBudget, 'lifetimeBudget') } : {}),
125
+ ...(a.bid != null ? { bid_micro: toMicros(a.bid, 'bid') } : {}), ...(a.pixelId ? { pixel_id: a.pixelId } : {}), ...(a.fields ?? {}) };
126
+ const [d] = unwrap(await ctx.request({ method: 'POST', path: `/campaigns/${a.campaignId}/adsquads`, json: { adsquads: [s] } }), 'adsquads');
127
+ return { id: d?.id, status: STATUS.PAUSED };
128
+ },
129
+ },
130
+ listAds: {
131
+ params: { accountId: {}, adGroupId: {} },
132
+ run: async (ctx, a) => {
133
+ const path = a.adGroupId ? `/adsquads/${a.adGroupId}/ads` : `/adaccounts/${a.accountId}/ads`;
134
+ const r = await ctx.request({ path, query: { limit: 200 } });
135
+ return { items: unwrap(r, 'ads').map((x) => row(x, { id: x.id, name: x.name, status: x.status, adGroupId: x.ad_squad_id, creativeId: x.creative_id, review: x.review_status, reviewReasons: x.review_status_reasons }, a)) };
136
+ },
137
+ },
138
+ uploadAsset: {
139
+ params: { accountId: { required: true }, url: { type: 'string', required: true }, kind: { type: 'string', enum: ['image', 'video'] }, name: { type: 'string' }, aiGenerated: { type: 'boolean', desc: 'Declare the media as AI-generated.' } },
140
+ run: async (ctx, a) => {
141
+ const kind = a.kind ?? (/\.(mp4|mov)(\?|$)/i.test(a.url) ? 'video' : 'image');
142
+ const [stub] = unwrap(await ctx.request({ method: 'POST', path: `/adaccounts/${a.accountId}/media`, json: { media: [{ name: a.name ?? `upload-${Date.now()}`, type: kind === 'video' ? 'VIDEO' : 'IMAGE', ad_account_id: a.accountId, ...(a.aiGenerated ? { ai_content_source: 'USER_AI_GEN' } : {}) }] } }), 'media');
143
+ const res = await (ctx.publicFetch ?? ctx.fetch)(a.url);
144
+ if (!res.ok) throw new AdsError('validation', `Could not download ${a.url} (HTTP ${res.status})`, { field: 'url' });
145
+ const bytes = Buffer.from(await res.arrayBuffer());
146
+ if (bytes.length > 32 * 1024 * 1024) throw new AdsError('validation', 'Files over 32 MB need Snapchat\'s chunked upload, which is not supported here.', { field: 'url' });
147
+ const form = new FormData();
148
+ form.append('file', new Blob([bytes]), a.url.split('/').pop()?.split('?')[0] || 'upload');
149
+ await ctx.request({ method: 'POST', path: `/media/${stub.id}/upload`, body: form });
150
+ return { kind, mediaId: stub.id };
151
+ },
152
+ },
153
+ createCreative: {
154
+ params: {
155
+ accountId: { required: true }, mediaId: { type: 'string', required: true }, name: { required: true }, profileId: { type: 'string', required: true, desc: 'Public profile id (required on every creative).' },
156
+ headline: { type: 'string', required: true, desc: 'Max 34 characters.' }, brandName: { type: 'string', desc: 'Max 32 characters.' },
157
+ url: { type: 'string', desc: 'Website (makes it a WEB_VIEW creative).' }, cta: { type: 'string', desc: 'e.g. MORE, SHOP_NOW, SIGN_UP.' },
158
+ },
159
+ run: async (ctx, a) => {
160
+ checkLength('headline', a.headline, 34);
161
+ checkLength('brandName', a.brandName, 32);
162
+ checkLength('url', a.url, 2048);
163
+ checkLength('name', a.name, 375);
164
+ const c = { ad_account_id: a.accountId, name: a.name, type: a.url ? 'WEB_VIEW' : 'SNAP_AD', top_snap_media_id: a.mediaId, headline: a.headline,
165
+ profile_properties: { profile_id: a.profileId }, ...(a.brandName ? { brand_name: a.brandName } : {}),
166
+ ...(a.url ? { web_view_properties: { url: a.url }, call_to_action: a.cta ?? 'MORE' } : {}), ...(a.fields ?? {}) };
167
+ const [d] = unwrap(await ctx.request({ method: 'POST', path: `/adaccounts/${a.accountId}/creatives`, json: { creatives: [c] } }), 'creatives');
168
+ return { id: d?.id, type: c.type };
169
+ },
170
+ },
171
+ createAd: {
172
+ params: { adGroupId: { required: true }, creativeId: { type: 'string', required: true }, name: { required: true }, type: { type: 'string', desc: 'Ad type matching the creative (SNAP_AD, REMOTE_WEBPAGE...). Default from the creative.' } },
173
+ run: async (ctx, a) => {
174
+ assertBornPaused(a, 'ad');
175
+ let type = a.type;
176
+ if (!type) {
177
+ const [cr] = unwrap(await ctx.request({ path: `/creatives/${a.creativeId}` }), 'creatives');
178
+ type = cr?.type === 'WEB_VIEW' ? 'REMOTE_WEBPAGE' : (cr?.type ?? 'SNAP_AD');
179
+ }
180
+ const [d] = unwrap(await ctx.request({ method: 'POST', path: `/adsquads/${a.adGroupId}/ads`, json: { ads: [{ ad_squad_id: a.adGroupId, creative_id: a.creativeId, name: a.name, type, status: 'PAUSED', ...(a.fields ?? {}) }] } }), 'ads');
181
+ return { id: d?.id, status: STATUS.PAUSED, ...(d?.review_status === 'REJECTED' ? { warning: `Rejected: ${d.review_status_reasons}` } : {}) };
182
+ },
183
+ },
184
+ listAudiences: {
185
+ params: { accountId: { required: true } },
186
+ run: async (ctx, a) => ({ items: unwrap(await ctx.request({ path: `/adaccounts/${a.accountId}/segments` }), 'segments').map((x) => row(x, { id: x.id, name: x.name, source: x.source_type, size: x.approximate_number_users, status: x.status }, a)) }),
187
+ },
188
+ createAudience: {
189
+ params: { accountId: { required: true }, name: { required: true }, kind: { type: 'string', enum: ['customer_list', 'lookalike'], required: true }, emails: { type: 'array' }, seedSegmentId: { type: 'string' }, countries: { type: 'array' } },
190
+ run: async (ctx, a) => {
191
+ checkLength('name', a.name, 375);
192
+ const seg = a.kind === 'lookalike'
193
+ ? { name: a.name, ad_account_id: a.accountId, source_type: 'LOOKALIKE', retention_in_days: 180, creation_spec: { seed_segment_id: a.seedSegmentId, type: 'BALANCE', countries: a.countries ?? ['US'] } }
194
+ : { name: a.name, ad_account_id: a.accountId, source_type: 'FIRST_PARTY', retention_in_days: 9999 };
195
+ if (a.kind === 'lookalike' && !a.seedSegmentId) throw new AdsError('validation', 'A lookalike needs seedSegmentId.', { field: 'seedSegmentId' });
196
+ const [d] = unwrap(await ctx.request({ method: 'POST', path: `/adaccounts/${a.accountId}/segments`, json: { segments: [{ ...seg, ...(a.fields ?? {}) }] } }), 'segments');
197
+ const hashed = (a.emails ?? []).map(hashEmail).filter(Boolean);
198
+ if (hashed.length) await ctx.request({ method: 'POST', path: `/segments/${d.id}/users`, json: { users: [{ schema: ['EMAIL_SHA256'], data: hashed.map((h) => [h]) }] } });
199
+ return { id: d?.id, added: hashed.length };
200
+ },
201
+ },
202
+ setStatus: {
203
+ params: { id: { required: true }, level: {}, status: { required: true } },
204
+ run: async (ctx, a) => {
205
+ const status = gateStatus(a);
206
+ if (status === STATUS.ARCHIVED) throw new AdsError('validation', 'Snapchat has no archive; pause or delete instead.', { field: 'status' });
207
+ await patch(ctx, pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform), a.id, { status });
208
+ return { id: a.id, status };
209
+ },
210
+ },
211
+ setBudget: {
212
+ params: { id: { required: true }, level: { desc: 'campaign or adGroup (default).' }, amount: { required: true } },
213
+ run: async (ctx, a) => {
214
+ const level = a.level ?? 'adGroup';
215
+ if (!['campaign', 'adGroup'].includes(level)) throw new AdsError('validation', 'level must be campaign or adGroup', { field: 'level' });
216
+ const [cur] = unwrap(await ctx.request({ path: `/${TIER[level][0]}/${a.id}` }), TIER[level][0]);
217
+ gateBudget(a, fromMicros(cur?.daily_budget_micro));
218
+ await patch(ctx, level, a.id, { daily_budget_micro: budgetMicro(a.amount) }, cur);
219
+ return { id: a.id, dailyBudget: Number(a.amount) };
220
+ },
221
+ },
222
+ deleteObject: {
223
+ params: { id: { required: true }, level: { required: true }, confirm: {}, confirmName: {}, confirmChildren: {} },
224
+ run: async (ctx, a) => {
225
+ const level = pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform);
226
+ const [plural] = TIER[level];
227
+ const [cur] = unwrap(await ctx.request({ path: `/${plural}/${a.id}` }), plural);
228
+ if (!cur) throw new AdsError('not_found', `${level} ${a.id} not found.`);
229
+ const children = [];
230
+ if (level === 'campaign') children.push({ label: 'ad squads', count: unwrap(await ctx.request({ path: `/campaigns/${a.id}/adsquads` }), 'adsquads').length });
231
+ if (level === 'adGroup') children.push({ label: 'ads', count: unwrap(await ctx.request({ path: `/adsquads/${a.id}/ads` }), 'ads').length });
232
+ gateDelete(a, { what: level, name: cur.name, children, live: cur.status === 'ACTIVE' });
233
+ await ctx.request({ method: 'DELETE', path: `/${plural}/${a.id}` });
234
+ return { id: a.id, deleted: true };
235
+ },
236
+ },
237
+ report: {
238
+ params: { id: { desc: 'Campaign/ad squad/ad id, or accountId for the whole account.' }, accountId: {}, level: { type: 'string', enum: ['account', 'campaign', 'adGroup', 'ad'] }, since: {}, until: {}, granularity: { type: 'string', enum: ['TOTAL', 'DAY', 'HOUR', 'LIFETIME'] }, metrics: { type: 'array' } },
239
+ run: async (ctx, a) => {
240
+ const { since, until } = dateRange(a);
241
+ const level = a.level ?? (a.id ? 'campaign' : 'account');
242
+ const path = level === 'account' ? `/adaccounts/${a.accountId}/stats` : `/${TIER[level][0]}/${a.id}/stats`;
243
+ const r = await ctx.request({ path, query: { granularity: a.granularity ?? 'TOTAL', fields: (a.metrics ?? ['impressions', 'swipes', 'spend']).join(','), start_time: `${since}T00:00:00.000Z`, end_time: `${until}T00:00:00.000Z` } });
244
+ const total = (r.total_stats ?? []).map((x) => x.total_stat);
245
+ const series = (r.timeseries_stats ?? []).map((x) => x.timeseries_stat);
246
+ const fix = (s) => (s?.stats?.spend != null ? { ...s, stats: { ...s.stats, spend: fromMicros(s.stats.spend) } } : s);
247
+ return { rows: total.length ? total.map(fix) : series.flatMap((s) => (s.timeseries ?? []).map(fix)) };
248
+ },
249
+ },
250
+ searchTargeting: {
251
+ params: { type: { required: true, enum: ['countries', 'regions', 'metros'] }, query: { required: true }, countryCode: { type: 'string', desc: 'For regions and metros.' } },
252
+ run: async (ctx, a) => {
253
+ const path = a.type === 'countries' ? '/targeting/geo/country' : `/targeting/geo/${String(a.countryCode ?? 'us').toLowerCase()}/${a.type === 'regions' ? 'region' : 'metro'}`;
254
+ const r = await ctx.request({ path, query: { limit: 200 } });
255
+ const rows = (r.targeting_dimensions ?? []).map((x) => x[Object.keys(x).find((k) => k !== 'sub_request_status')]).map((x) => x?.country ?? x?.region ?? x?.metro ?? x).filter(Boolean);
256
+ const q = String(a.query).toLowerCase();
257
+ return { items: rows.filter((x) => String(x.name ?? '').toLowerCase().includes(q)).slice(0, a.limit ?? 50).map((x) => ({ id: String(x.id ?? x.code), name: x.name, code: x.code ?? x.code2 })) };
258
+ },
259
+ },
260
+ },
261
+ });
262
+
263
+ function budgetMicro(amount) {
264
+ const m = toMicros(amount, 'dailyBudget');
265
+ if (m < MIN_DAILY * 1e6) throw new AdsError('validation', `Snapchat's minimum daily budget is ${MIN_DAILY}.`, { field: 'dailyBudget' });
266
+ return m;
267
+ }
268
+
269
+ /** Updates are RFC 6902 JSON Patch on the nested path (the parent id is needed). */
270
+ async function patch(ctx, level, id, changes, cur) {
271
+ const [plural, parentField, parentPlural] = TIER[level];
272
+ const obj = cur ?? unwrap(await ctx.request({ path: `/${plural}/${id}` }), plural)[0];
273
+ if (!obj) throw new AdsError('not_found', `${level} ${id} not found.`);
274
+ const ops = Object.entries(changes).map(([k, v]) => (v == null ? { op: 'remove', path: `/${k}` } : { op: 'replace', path: `/${k}`, value: v }));
275
+ return ctx.request({ method: 'PATCH', path: `/${parentPlural}/${obj[parentField]}/${plural}/${id}`, headers: { 'content-type': 'application/json-patch+json' }, body: JSON.stringify(ops) });
276
+ }
@@ -0,0 +1,57 @@
1
+ import { definePlatform, row, dateRange } from '../platform.js';
2
+ import { AdsError } from '../errors.js';
3
+
4
+
5
+ const BASE = 'https://backstage.taboola.com/backstage/api/1.0';
6
+ const TOKEN_URL = 'https://backstage.taboola.com/backstage/oauth/token';
7
+
8
+ export default definePlatform({
9
+ id: 'taboola_ads',
10
+ label: 'Taboola',
11
+ money: 'major',
12
+ credentials: [
13
+ { name: 'clientId', required: true, env: 'TABOOLA_CLIENT_ID' },
14
+ { name: 'clientSecret', required: true, env: 'TABOOLA_CLIENT_SECRET' },
15
+ { name: 'accountId', env: 'TABOOLA_ACCOUNT_ID', desc: 'Default account id (the slug used in paths).' },
16
+ ],
17
+ baseUrl: BASE,
18
+ authHeaders: (c) => ({ authorization: `Bearer ${c.accessToken}` }),
19
+ mintsToken: true,
20
+ refresh: async (c, ctx) => {
21
+ const body = new URLSearchParams({ client_id: c.clientId, client_secret: c.clientSecret, grant_type: 'client_credentials' });
22
+ const res = await ctx.fetch(TOKEN_URL, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: body.toString() });
23
+ const j = await res.json().catch(() => ({}));
24
+ if (!res.ok || !j.access_token) throw new AdsError('auth', 'Taboola refused the client credentials.', { platform: 'taboola_ads' });
25
+ return { accessToken: j.access_token, expiresAt: Date.now() + Number(j.expires_in ?? 43200) * 1000 };
26
+ },
27
+ notes: ['Read-only: campaign lists and the campaign summary report.', 'Conversions can still change for up to 30 days.'],
28
+ setup: {
29
+ app: 'No developer app: create API credentials (client id + secret) in Taboola Ads under API keys.',
30
+ scopes: ['(client credentials, no scopes)'],
31
+ review: 'Self-serve; credentials are valid for a year.',
32
+ hosted: { connect: 'own', note: 'Taboola issues API credentials per account.' },
33
+ docs: 'https://developers.taboola.com/backstage-api/',
34
+ },
35
+ ops: {
36
+ listAccounts: { run: async (ctx, a) => ({ items: ((await ctx.request({ path: '/users/current/allowed-accounts' })).results ?? []).map((x) => row(x, { id: x.account_id, numericId: x.id, name: x.name, currency: x.currency, timezone: x.time_zone_name }, a)) }) },
37
+ listCampaigns: {
38
+ params: { accountId: { desc: 'Account slug (default from credentials).' } },
39
+ run: async (ctx, a) => {
40
+ const acct = a.accountId ?? (await ctx.creds()).accountId;
41
+ if (!acct) throw new AdsError('validation', 'accountId is required.', { field: 'accountId' });
42
+ const r = await ctx.request({ path: `/${acct}/campaigns/`, query: { fetch_level: 'R' } });
43
+ return { items: (r.results ?? []).map((c) => row(c, { id: String(c.id), name: c.name, status: c.status, active: c.is_active, cpc: c.cpc, dailyCap: c.daily_cap, spendingLimit: c.spending_limit, approval: c.approval_state }, a)) };
44
+ },
45
+ },
46
+ report: {
47
+ params: { accountId: {}, since: {}, until: {} },
48
+ run: async (ctx, a) => {
49
+ const acct = a.accountId ?? (await ctx.creds()).accountId;
50
+ const { since, until } = dateRange(a);
51
+ if ((Date.parse(until) - Date.parse(since)) / 86400000 > 92) throw new AdsError('validation', 'Use a window of at most 92 days.', { field: 'since' });
52
+ const r = await ctx.request({ path: `/${acct}/reports/campaign-summary/dimensions/campaign_breakdown`, query: { start_date: since, end_date: until } });
53
+ return { rows: r.results ?? [] };
54
+ },
55
+ },
56
+ },
57
+ });