@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,297 @@
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 { toMajor } from '../money.js';
5
+ import { oauth2Refresh } from '../oauth.js';
6
+
7
+
8
+ const VERSION = '202611';
9
+ const TOKEN_URL = 'https://www.linkedin.com/oauth/v2/accessToken';
10
+ const URN = { account: 'sponsoredAccount', group: 'sponsoredCampaignGroup', campaign: 'sponsoredCampaign', creative: 'sponsoredCreative' };
11
+ const num = (v) => String(v).replace(/^urn:li:[A-Za-z]+:/, '');
12
+ const urn = (kind, id) => (String(id).startsWith('urn:') ? String(id) : `urn:li:${URN[kind]}:${num(id)}`);
13
+ const enc = encodeURIComponent;
14
+ const money = (amount, currencyCode) => ({ amount: toMajor(amount).toFixed(2), currencyCode });
15
+ const FACET_PREFIX = {
16
+ locations: 'geo', profileLocations: 'geo', titles: 'title', jobFunctions: 'function', seniorities: 'seniority', industries: 'industry',
17
+ employers: 'organization', schools: 'organization', staffCountRanges: 'staffCountRange', skills: 'skill', segments: 'adSegment',
18
+ };
19
+ const CTAS = ['APPLY', 'DOWNLOAD', 'VIEW_QUOTE', 'LEARN_MORE', 'SIGN_UP', 'SUBSCRIBE', 'REGISTER', 'JOIN', 'ATTEND', 'REQUEST_DEMO', 'SEE_MORE', 'BUY_NOW', 'SHOP_NOW'];
20
+
21
+ function parseError(status, body) {
22
+ const msg = body?.message ?? body?.errorDetails?.inputErrors?.map((e) => e.description).join('; ');
23
+ if (status === 426) return { kind: 'vendor', message: msg, userMessage: `LinkedIn retired the API version this client pins (${VERSION}); set linkedinVersion to a current YYYYMM.` };
24
+ if (status === 403 && /Account Management list|not configured to access the related advertiser|Not permitted to create the creative/i.test(msg ?? '')) {
25
+ return { kind: 'permission', message: msg, userMessage: 'LinkedIn: this ad account is not registered to your developer app. In Development tier each ad account must be added to the app in the developer portal.' };
26
+ }
27
+ if (status === 403) return { kind: 'permission', message: msg, userMessage: `LinkedIn refused: the token needs the ads scopes AND the user needs a role on this ad account. ${msg ?? ''}`.trim() };
28
+ if (status === 429) return { kind: 'rate_limit', message: msg, userMessage: 'LinkedIn: the app\'s daily API quota is used up.' };
29
+ if (status >= 500) return { kind: 'vendor', message: msg, userMessage: `LinkedIn server error; the write may have applied, read it back before retrying. ${msg ?? ''}`.trim() };
30
+ return msg ? { message: msg } : null;
31
+ }
32
+
33
+ const restli = (method) => ({ 'X-RestLi-Method': method });
34
+ const createdId = (res) => res.headers?.get?.('x-restli-id') ?? res.body?.id;
35
+
36
+ /** Build targetingCriteria from simple facet lists; bare ids get their facet's URN prefix. */
37
+ function targeting(a) {
38
+ if (a.targetingCriteria) return a.targetingCriteria;
39
+ const and = [];
40
+ for (const [facet, prefix] of Object.entries(FACET_PREFIX)) {
41
+ const vals = a[facet];
42
+ if (!vals?.length) continue;
43
+ and.push({ or: { [`urn:li:adTargetingFacet:${facet}`]: vals.map((v) => (String(v).startsWith('urn:') ? v : `urn:li:${prefix}:${v}`)) } });
44
+ }
45
+ if (!and.length) throw new AdsError('validation', 'LinkedIn campaigns need targeting: give locations (geo ids) and optionally titles, industries, seniorities..., or a full targetingCriteria.', { field: 'locations' });
46
+ return { include: { and } };
47
+ }
48
+
49
+ async function account(ctx, accountId) {
50
+ return ctx.request({ path: `/adAccounts/${num(accountId)}` });
51
+ }
52
+
53
+ export default definePlatform({
54
+ id: 'linkedin_ads',
55
+ provider: 'linkedin',
56
+ label: 'LinkedIn Ads',
57
+ money: 'major',
58
+ credentials: [
59
+ { name: 'accessToken', required: 'unlessRefresh', env: 'LINKEDIN_ADS_ACCESS_TOKEN', desc: 'Token with r_ads, rw_ads, r_ads_reporting.' },
60
+ { name: 'refreshToken', env: 'LINKEDIN_ADS_REFRESH_TOKEN' },
61
+ { name: 'clientId', env: 'LINKEDIN_ADS_CLIENT_ID' },
62
+ { name: 'clientSecret', env: 'LINKEDIN_ADS_CLIENT_SECRET' },
63
+ { name: 'linkedinVersion', env: 'LINKEDIN_VERSION', desc: `API version YYYYMM (default ${VERSION}). LinkedIn retires each version after about a year.` },
64
+ ],
65
+ baseUrl: 'https://api.linkedin.com/rest',
66
+ authHeaders: (c) => ({
67
+ authorization: `Bearer ${c.accessToken}`,
68
+ 'LinkedIn-Version': /^20\d{2}(0[1-9]|1[0-2])$/.test(c.linkedinVersion ?? '') ? c.linkedinVersion : VERSION,
69
+ 'X-Restli-Protocol-Version': '2.0.0',
70
+ }),
71
+ refresh: (c, ctx) => (c.clientSecret ? oauth2Refresh(ctx, c, { tokenUrl: TOKEN_URL }) : null),
72
+ parseError,
73
+ notes: [
74
+ 'Vocabulary: campaign = LinkedIn campaign group, adGroup = LinkedIn campaign (targeting, budget, bid), ad = creative.',
75
+ 'Everything is created as DRAFT. Nothing serves unless the group, the campaign and a creative are all ACTIVE.',
76
+ 'Only DRAFT objects can be hard-deleted; anything else is moved to PENDING_DELETION (history is kept).',
77
+ 'A daily budget can be overspent by up to 50% on high-opportunity days.',
78
+ 'audience counts under 300 are reported as 0 by LinkedIn (privacy floor), not empty.',
79
+ ],
80
+ setup: {
81
+ app: 'A LinkedIn developer app (linkedin.com/developers) associated with a company Page, with the Advertising API product added.',
82
+ scopes: ['r_ads', 'rw_ads', 'r_ads_reporting'],
83
+ review: 'The Advertising API product starts at the Development tier (read for any account you can access, edit for up to 5 registered ad accounts); apply for the Standard tier to manage more. Request only the scopes your app was granted: one ungranted scope fails the whole consent screen.',
84
+ hosted: { connect: 'app', note: 'Hosted Hermoso connects with one click where supported, with no developer app of your own.' },
85
+ docs: 'https://learn.microsoft.com/linkedin/marketing/',
86
+ },
87
+ ops: {
88
+ listAccounts: {
89
+ run: async (ctx, a) => {
90
+ const users = await ctx.request({ path: '/adAccountUsers?q=authenticatedUser&count=100' });
91
+ const roles = new Map((users.elements ?? []).map((u) => [num(u.account), u.role]));
92
+ if (!roles.size) return { items: [] };
93
+ const r = await ctx.request({ path: `/adAccounts?ids=List(${[...roles.keys()].join(',')})` });
94
+ return { items: Object.entries(r.results ?? {}).map(([id, x]) => row(x, { id, name: x.name, status: x.status, currency: x.currency, type: x.type, test: x.test, role: roles.get(id) }, a)) };
95
+ },
96
+ },
97
+ listCampaigns: {
98
+ params: { accountId: { required: true } },
99
+ run: async (ctx, a) => {
100
+ const r = await ctx.request({ path: `/adAccounts/${num(a.accountId)}/adCampaignGroups?q=search&search=(status:(values:List(ACTIVE,PAUSED,ARCHIVED,DRAFT)))&sortOrder=DESCENDING&pageSize=100` });
101
+ return { items: (r.elements ?? []).map((g) => row(g, { id: String(g.id), name: g.name, status: g.status, totalBudget: g.totalBudget?.amount, currency: g.totalBudget?.currencyCode }, a)) };
102
+ },
103
+ },
104
+ getCampaign: {
105
+ params: { accountId: { required: true }, id: { required: true } },
106
+ run: async (ctx, a) => {
107
+ const g = await ctx.request({ path: `/adAccounts/${num(a.accountId)}/adCampaignGroups/${num(a.id)}` });
108
+ return row(g, { id: String(g.id), name: g.name, status: g.status, totalBudget: g.totalBudget?.amount, runSchedule: g.runSchedule }, a);
109
+ },
110
+ },
111
+ createCampaign: {
112
+ params: { accountId: { required: true }, name: { required: true }, lifetimeBudget: {}, startTime: { type: 'string', desc: 'ISO date-time; default now.' }, endTime: { type: 'string', desc: 'Required with a lifetime budget.' } },
113
+ run: async (ctx, a) => {
114
+ assertBornPaused(a, 'campaign group');
115
+ if (a.lifetimeBudget != null && !a.endTime) throw new AdsError('validation', 'A total budget needs endTime.', { field: 'endTime' });
116
+ const body = { account: urn('account', a.accountId), name: a.name, status: 'DRAFT',
117
+ runSchedule: { start: a.startTime ? Date.parse(a.startTime) : Date.now(), ...(a.endTime ? { end: Date.parse(a.endTime) } : {}) } };
118
+ if (a.lifetimeBudget != null) body.totalBudget = money(a.lifetimeBudget, (await account(ctx, a.accountId)).currency);
119
+ const res = await ctx.request({ method: 'POST', path: `/adAccounts/${num(a.accountId)}/adCampaignGroups`, json: { ...body, ...(a.fields ?? {}) }, raw: true });
120
+ return { id: num(createdId(res)), status: 'DRAFT' };
121
+ },
122
+ },
123
+ listAdGroups: {
124
+ params: { accountId: { required: true }, campaignId: { desc: 'Campaign group id to filter by.' } },
125
+ run: async (ctx, a) => {
126
+ const group = a.campaignId ? `campaignGroup:(values:List(${enc(urn('group', a.campaignId))})),` : '';
127
+ const r = await ctx.request({ path: `/adAccounts/${num(a.accountId)}/adCampaigns?q=search&search=(${group}status:(values:List(ACTIVE,PAUSED,ARCHIVED,DRAFT)))&sortOrder=DESCENDING&pageSize=100` });
128
+ return { items: (r.elements ?? []).map((c) => row(c, { id: String(c.id), name: c.name, status: c.status, objective: c.objectiveType, costType: c.costType, dailyBudget: c.dailyBudget?.amount, totalBudget: c.totalBudget?.amount, campaignId: num(c.campaignGroup ?? ''), servingStatuses: c.servingStatuses }, a)) };
129
+ },
130
+ },
131
+ createAdGroup: {
132
+ params: {
133
+ accountId: { required: true }, campaignId: { required: true, desc: 'Campaign group id.' }, name: { required: true },
134
+ dailyBudget: {}, lifetimeBudget: {}, objectiveType: { type: 'string', desc: 'e.g. WEBSITE_VISIT, LEAD_GENERATION, BRAND_AWARENESS, ENGAGEMENT, VIDEO_VIEW.' },
135
+ costType: { type: 'string', enum: ['CPM', 'CPC', 'CPV'], desc: 'Default CPM.' }, bid: { type: 'number', desc: 'Unit cost (bid) amount.' },
136
+ locations: { type: 'array', desc: 'Geo ids (from searchTargeting) — required unless targetingCriteria is given.' },
137
+ titles: { type: 'array' }, industries: { type: 'array' }, seniorities: { type: 'array' }, jobFunctions: { type: 'array' }, skills: { type: 'array' }, employers: { type: 'array' },
138
+ targetingCriteria: { type: 'object' }, locale: { type: 'string', desc: 'e.g. en_US.' },
139
+ politicalIntent: { type: 'string', enum: ['POLITICAL', 'NOT_POLITICAL', 'NOT_DECLARED'], desc: 'EU-targeted campaigns must declare POLITICAL or NOT_POLITICAL.' },
140
+ },
141
+ run: async (ctx, a) => {
142
+ assertBornPaused(a, 'campaign');
143
+ if (a.dailyBudget == null && a.lifetimeBudget == null) throw new AdsError('validation', 'A LinkedIn campaign needs dailyBudget or lifetimeBudget.', { field: 'dailyBudget' });
144
+ const currency = (await account(ctx, a.accountId)).currency;
145
+ const [language, country] = (a.locale ?? 'en_US').split('_');
146
+ const body = {
147
+ account: urn('account', a.accountId), campaignGroup: urn('group', a.campaignId), name: a.name, status: 'DRAFT',
148
+ type: 'SPONSORED_UPDATES', costType: a.costType ?? 'CPM', locale: { country, language },
149
+ offsiteDeliveryEnabled: false, politicalIntent: a.politicalIntent ?? 'NOT_DECLARED',
150
+ unitCost: money(a.bid ?? 0.01, currency), targetingCriteria: targeting(a), runSchedule: { start: Date.now() },
151
+ ...(a.objectiveType ? { objectiveType: a.objectiveType } : {}),
152
+ ...(a.dailyBudget != null ? { dailyBudget: money(a.dailyBudget, currency) } : {}),
153
+ ...(a.lifetimeBudget != null ? { totalBudget: money(a.lifetimeBudget, currency) } : {}),
154
+ ...(a.fields ?? {}),
155
+ };
156
+ if (a.bid == null) body.unitCost.amount = '0';
157
+ const res = await ctx.request({ method: 'POST', path: `/adAccounts/${num(a.accountId)}/adCampaigns`, json: body, raw: true });
158
+ return { id: num(createdId(res)), status: 'DRAFT', note: 'Validation of DRAFT objects is deferred: activation can still surface errors.' };
159
+ },
160
+ },
161
+ listAds: {
162
+ params: { accountId: { required: true }, adGroupId: { required: true, desc: 'LinkedIn campaign id.' } },
163
+ run: async (ctx, a) => {
164
+ const r = await ctx.request({ path: `/adAccounts/${num(a.accountId)}/creatives?q=criteria&campaigns=List(${enc(urn('campaign', a.adGroupId))})&sortOrder=DESCENDING&pageSize=100`, headers: restli('FINDER') });
165
+ return { items: (r.elements ?? []).map((c) => row(c, { id: c.id, status: c.intendedStatus, serving: c.isServing, holds: c.servingHoldReasons, reference: c.content?.reference }, a)) };
166
+ },
167
+ },
168
+ uploadAsset: {
169
+ params: { organizationId: { type: 'string', required: true, desc: 'Company Page (organization) id or URN that will own the image.' }, url: { type: 'string', required: true, desc: 'Public image URL.' } },
170
+ run: async (ctx, a) => {
171
+ const owner = String(a.organizationId).startsWith('urn:') ? a.organizationId : `urn:li:organization:${a.organizationId}`;
172
+ const init = await ctx.request({ method: 'POST', path: '/images?action=initializeUpload', json: { initializeUploadRequest: { owner } } });
173
+ const { uploadUrl, image } = init.value ?? {};
174
+ const res = await (ctx.publicFetch ?? ctx.fetch)(a.url);
175
+ if (!res.ok) throw new AdsError('validation', `Could not download ${a.url} (HTTP ${res.status})`, { field: 'url' });
176
+ const c = await ctx.creds();
177
+ const put = await ctx.fetch(uploadUrl, { method: 'PUT', headers: { authorization: `Bearer ${c.accessToken}`, 'content-type': 'application/octet-stream' }, body: Buffer.from(await res.arrayBuffer()) });
178
+ if (!put.ok) throw new AdsError('vendor', `LinkedIn image upload failed (HTTP ${put.status}).`);
179
+ return { imageUrn: image, note: 'Wait until the image status is AVAILABLE before using it in a creative.' };
180
+ },
181
+ },
182
+ createAd: {
183
+ params: {
184
+ accountId: { required: true }, adGroupId: { required: true, desc: 'LinkedIn campaign id.' },
185
+ postUrn: { type: 'string', desc: 'Sponsor an existing post (urn:li:share:..., urn:li:ugcPost:...).' },
186
+ organizationId: { type: 'string', desc: 'For a new ad post: the company Page that authors it.' },
187
+ commentary: { type: 'string', desc: 'Post text for a new ad post.' }, imageUrn: { type: 'string' }, headline: { type: 'string' },
188
+ landingPage: { type: 'string' }, cta: { type: 'string', enum: CTAS }, name: { type: 'string' },
189
+ },
190
+ run: async (ctx, a) => {
191
+ assertBornPaused(a, 'creative');
192
+ checkLength('name', a.name, 255);
193
+ let reference = a.postUrn;
194
+ if (reference) {
195
+ if (!/^urn:li:(share|ugcPost|adInMailContent):/.test(reference)) throw new AdsError('validation', 'postUrn must be a urn:li:share:, urn:li:ugcPost: or urn:li:adInMailContent: URN.', { field: 'postUrn' });
196
+ } else {
197
+ if (!a.organizationId || !a.commentary) throw new AdsError('validation', 'Give postUrn, or organizationId + commentary for a new ad post.', { field: 'postUrn' });
198
+ checkLength('commentary', a.commentary, 3000);
199
+ if ((a.landingPage || a.cta) && !a.imageUrn) throw new AdsError('validation', 'A landing page or call to action needs an image on the post (LinkedIn drops them on text-only posts).', { field: 'landingPage' });
200
+ if (a.cta && !a.landingPage) throw new AdsError('validation', 'A call to action needs landingPage.', { field: 'cta' });
201
+ const author = String(a.organizationId).startsWith('urn:') ? a.organizationId : `urn:li:organization:${a.organizationId}`;
202
+ const post = { author, commentary: a.commentary, visibility: 'PUBLIC',
203
+ adContext: { dscAdAccount: urn('account', a.accountId), dscStatus: 'ACTIVE' },
204
+ distribution: { feedDistribution: 'NONE', thirdPartyDistributionChannels: [] },
205
+ lifecycleState: 'PUBLISHED', isReshareDisabledByAuthor: true,
206
+ ...(a.imageUrn ? { content: { media: { id: a.imageUrn, ...(a.headline ? { title: a.headline } : {}) } } } : {}),
207
+ ...(a.landingPage ? { contentLandingPage: a.landingPage } : {}), ...(a.cta ? { contentCallToActionLabel: a.cta } : {}) };
208
+ const res = await ctx.request({ method: 'POST', path: '/posts', json: post, raw: true });
209
+ reference = createdId(res);
210
+ }
211
+ const res = await ctx.request({ method: 'POST', path: `/adAccounts/${num(a.accountId)}/creatives`, json: { campaign: urn('campaign', a.adGroupId), content: { reference }, intendedStatus: 'DRAFT', ...(a.name ? { name: a.name } : {}), ...(a.fields ?? {}) }, raw: true });
212
+ return { id: createdId(res), postUrn: reference, status: 'DRAFT' };
213
+ },
214
+ },
215
+ setStatus: {
216
+ params: { accountId: { required: true }, id: { required: true }, level: {}, status: { required: true } },
217
+ run: async (ctx, a) => {
218
+ const status = gateStatus(a);
219
+ const level = pickLevel(a, { campaign: 'adCampaignGroups', adGroup: 'adCampaigns', ad: 'creatives' }, ctx.platform);
220
+ const path = level === 'creatives' ? `/adAccounts/${num(a.accountId)}/creatives/${enc(urn('creative', a.id))}` : `/adAccounts/${num(a.accountId)}/${level}/${num(a.id)}`;
221
+ const field = level === 'creatives' ? 'intendedStatus' : 'status';
222
+ await ctx.request({ method: 'POST', path, headers: restli('PARTIAL_UPDATE'), json: { patch: { $set: { [field]: status } } } });
223
+ return { id: String(a.id), status, ...(status === STATUS.ACTIVE ? { note: 'Serving needs the campaign group, the campaign and a creative all ACTIVE.' } : {}) };
224
+ },
225
+ },
226
+ setBudget: {
227
+ params: { accountId: { required: true }, id: { required: true }, level: { desc: 'campaign (group total budget) or adGroup (campaign budget). Default adGroup.' }, amount: { required: true }, kind: { type: 'string', enum: ['daily', 'total'] } },
228
+ run: async (ctx, a) => {
229
+ const level = a.level ?? 'adGroup';
230
+ const path = level === 'campaign' ? `/adAccounts/${num(a.accountId)}/adCampaignGroups/${num(a.id)}` : `/adAccounts/${num(a.accountId)}/adCampaigns/${num(a.id)}`;
231
+ const cur = await ctx.request({ path });
232
+ const field = level === 'campaign' ? 'totalBudget' : (a.kind === 'total' || (!a.kind && !cur.dailyBudget && cur.totalBudget) ? 'totalBudget' : 'dailyBudget');
233
+ const currency = cur[field]?.currencyCode ?? (await account(ctx, a.accountId)).currency;
234
+ gateBudget(a, cur[field]?.amount != null ? Number(cur[field].amount) : null);
235
+ await ctx.request({ method: 'POST', path, headers: restli('PARTIAL_UPDATE'), json: { patch: { $set: { [field]: money(a.amount, currency) } } } });
236
+ return { id: String(a.id), [field]: toMajor(a.amount), currency };
237
+ },
238
+ },
239
+ deleteObject: {
240
+ params: { accountId: { required: true }, id: { required: true }, level: { required: true }, confirm: {}, confirmName: {}, confirmChildren: {} },
241
+ run: async (ctx, a) => {
242
+ const level = pickLevel(a, { campaign: 'adCampaignGroups', adGroup: 'adCampaigns', ad: 'creatives' }, ctx.platform);
243
+ const path = level === 'creatives' ? `/adAccounts/${num(a.accountId)}/creatives/${enc(urn('creative', a.id))}` : `/adAccounts/${num(a.accountId)}/${level}/${num(a.id)}`;
244
+ const cur = await ctx.request({ path });
245
+ const status = cur.status ?? cur.intendedStatus;
246
+ const children = [];
247
+ if (level === 'adCampaignGroups') {
248
+ const k = await ctx.request({ path: `/adAccounts/${num(a.accountId)}/adCampaigns?q=search&search=(campaignGroup:(values:List(${enc(urn('group', a.id))})),status:(values:List(ACTIVE,PAUSED,DRAFT)))&pageSize=100` });
249
+ children.push({ label: 'campaigns', count: (k.elements ?? []).length });
250
+ } else if (level === 'adCampaigns') {
251
+ const k = await ctx.request({ path: `/adAccounts/${num(a.accountId)}/creatives?q=criteria&campaigns=List(${enc(urn('campaign', a.id))})&pageSize=100`, headers: restli('FINDER') });
252
+ children.push({ label: 'creatives', count: (k.elements ?? []).length });
253
+ }
254
+ gateDelete(a, { what: a.level, name: cur.name, children, live: status === 'ACTIVE' });
255
+ if (status === 'DRAFT') {
256
+ await ctx.request({ method: 'DELETE', path, headers: restli('DELETE') });
257
+ return { id: String(a.id), deleted: true };
258
+ }
259
+ await ctx.request({ method: 'POST', path, headers: restli('PARTIAL_UPDATE'), json: { patch: { $set: { [level === 'creatives' ? 'intendedStatus' : 'status']: 'PENDING_DELETION' } } } });
260
+ return { id: String(a.id), status: 'PENDING_DELETION', note: 'Objects that ran cannot be hard-deleted on LinkedIn; reporting history is kept.' };
261
+ },
262
+ },
263
+ report: {
264
+ params: {
265
+ accountId: { required: true }, since: {}, until: {},
266
+ pivot: { type: 'string', desc: 'CAMPAIGN_GROUP, CAMPAIGN (default), CREATIVE, or a MEMBER_* demographic.' },
267
+ granularity: { type: 'string', enum: ['ALL', 'DAILY', 'MONTHLY', 'YEARLY'] }, metrics: { type: 'array' },
268
+ },
269
+ run: async (ctx, a) => {
270
+ const { since, until } = dateRange(a);
271
+ const [sy, sm, sd] = since.split('-').map(Number); const [uy, um, ud] = until.split('-').map(Number);
272
+ const pivot = a.pivot ?? 'CAMPAIGN';
273
+ let fields = a.metrics ?? ['impressions', 'clicks', 'costInLocalCurrency', 'externalWebsiteConversions', 'oneClickLeads', 'likes', 'shares', 'comments'];
274
+ if (pivot.startsWith('MEMBER_')) fields = fields.filter((f) => !['conversionValueInLocalCurrency', 'cardImpressions', 'cardClicks', 'approximateMemberReach'].includes(f) && !f.startsWith('viralCard'));
275
+ const path = `/adAnalytics?q=analytics&pivot=${pivot}&timeGranularity=${a.granularity ?? 'ALL'}&dateRange=(start:(year:${sy},month:${sm},day:${sd}),end:(year:${uy},month:${um},day:${ud}))&accounts=List(${enc(urn('account', a.accountId))})&fields=${[...fields, 'dateRange', 'pivotValues'].join(',')}`;
276
+ const r = await ctx.request({ path });
277
+ return { rows: r.elements ?? [], ...(pivot.startsWith('MEMBER_') ? { note: 'LinkedIn drops demographic values with fewer than 3 events and returns the top 100, so rows will not sum to totals.' } : {}) };
278
+ },
279
+ },
280
+ searchTargeting: {
281
+ params: { type: { required: true, desc: `Facet: ${Object.keys(FACET_PREFIX).join(', ')}.` }, query: { required: true } },
282
+ run: async (ctx, a) => {
283
+ if (!FACET_PREFIX[a.type]) throw new AdsError('validation', `type must be one of ${Object.keys(FACET_PREFIX).join(', ')}`, { field: 'type' });
284
+ const facet = enc(`urn:li:adTargetingFacet:${a.type}`);
285
+ try {
286
+ const r = await ctx.request({ path: `/adTargetingEntities?q=typeahead&queryVersion=QUERY_USES_URNS&facet=${facet}&query=${enc(a.query)}&locale=(language:en,country:US)` });
287
+ return { items: (r.elements ?? []).map((e) => ({ id: e.urn, name: e.name, facet: a.type })) };
288
+ } catch (e) {
289
+ if (!/finder/i.test(e.vendor ?? '')) throw e;
290
+ const r = await ctx.request({ path: `/adTargetingEntities?q=adTargetingFacet&queryVersion=QUERY_USES_URNS&facet=${facet}&locale=(language:en,country:US)` });
291
+ const q = String(a.query).toLowerCase();
292
+ return { items: (r.elements ?? []).filter((x) => String(x.name).toLowerCase().includes(q)).map((x) => ({ id: x.urn, name: x.name, facet: a.type })) };
293
+ }
294
+ },
295
+ },
296
+ },
297
+ });