@adport/provider-linkedin 0.8.0 → 0.9.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.d.ts +1665 -3
- package/dist/index.js +2298 -95
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,11 +1,78 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import { AdportError as
|
|
2
|
+
import { AdportError as AdportError14 } from "@adport/core";
|
|
3
3
|
|
|
4
4
|
// src/client.ts
|
|
5
5
|
import { AdportError } from "@adport/core";
|
|
6
6
|
import { z } from "zod";
|
|
7
|
+
|
|
8
|
+
// src/native-errors.ts
|
|
9
|
+
var row = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
10
|
+
async function linkedinErrorDetails(response, secrets) {
|
|
11
|
+
const details = { http_status: response.status };
|
|
12
|
+
const safe = (value, pattern) => typeof value === "string" && pattern.test(value) && !secrets.some((secret) => secret && value.includes(secret)) ? value : void 0;
|
|
13
|
+
const requestId = safe(response.headers.get("x-li-uuid") ?? response.headers.get("x-li-request-id"), /^[A-Za-z0-9._:+/=-]{1,200}$/);
|
|
14
|
+
if (requestId) details.request_id = requestId;
|
|
15
|
+
let body;
|
|
16
|
+
try {
|
|
17
|
+
const reader = response.body?.getReader();
|
|
18
|
+
if (!reader) return details;
|
|
19
|
+
const chunks = [];
|
|
20
|
+
let size = 0;
|
|
21
|
+
try {
|
|
22
|
+
while (true) {
|
|
23
|
+
const part = await reader.read();
|
|
24
|
+
if (part.done) break;
|
|
25
|
+
size += part.value.byteLength;
|
|
26
|
+
if (size > 32 * 1024) {
|
|
27
|
+
await reader.cancel();
|
|
28
|
+
return details;
|
|
29
|
+
}
|
|
30
|
+
chunks.push(part.value);
|
|
31
|
+
}
|
|
32
|
+
} finally {
|
|
33
|
+
reader.releaseLock();
|
|
34
|
+
}
|
|
35
|
+
const bytes = new Uint8Array(size);
|
|
36
|
+
let offset = 0;
|
|
37
|
+
for (const part of chunks) {
|
|
38
|
+
bytes.set(part, offset);
|
|
39
|
+
offset += part.byteLength;
|
|
40
|
+
}
|
|
41
|
+
body = row(JSON.parse(new TextDecoder().decode(bytes)));
|
|
42
|
+
} catch {
|
|
43
|
+
return details;
|
|
44
|
+
}
|
|
45
|
+
const code = safe(body.code, /^[A-Z][A-Z0-9_]{0,99}$/);
|
|
46
|
+
if (code) details.native_code = code;
|
|
47
|
+
if (typeof body.serviceErrorCode === "number" && Number.isSafeInteger(body.serviceErrorCode) && body.serviceErrorCode >= 0) details.service_error_code = body.serviceErrorCode;
|
|
48
|
+
const errors = row(body.errorDetails), collected = [];
|
|
49
|
+
for (const [key, conditional] of [["inputErrors", false], ["conditionalInputErrors", true]]) {
|
|
50
|
+
const values = errors[key];
|
|
51
|
+
if (!Array.isArray(values)) continue;
|
|
52
|
+
for (const value of values.slice(0, 20)) {
|
|
53
|
+
const error = row(value), path = row(row(error.input).inputPath), nativeCode = safe(error.code, /^[A-Z][A-Z0-9_]{0,99}$/);
|
|
54
|
+
const field = safe(path.fieldPath ?? path.parameterPath, /^\/[A-Za-z][A-Za-z0-9_/.:[\]-]{0,255}$/);
|
|
55
|
+
if (!nativeCode && !field) continue;
|
|
56
|
+
const item = { conditional, ...nativeCode ? { code: nativeCode } : {}, ...field ? { field_path: field } : {} };
|
|
57
|
+
for (const bound of ["minValue", "maxValue"]) {
|
|
58
|
+
const number = error[bound];
|
|
59
|
+
if (typeof number === "string" && /^-?\d{1,50}(?:\.\d{1,50})?$/.test(number)) item[bound === "minValue" ? "min_value" : "max_value"] = number;
|
|
60
|
+
}
|
|
61
|
+
for (const length of ["minLength", "maxLength"]) {
|
|
62
|
+
const number = error[length];
|
|
63
|
+
if (typeof number === "number" && Number.isSafeInteger(number) && number >= 0) item[length === "minLength" ? "min_length" : "max_length"] = number;
|
|
64
|
+
}
|
|
65
|
+
collected.push(item);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (collected.length) details.input_errors = collected;
|
|
69
|
+
return details;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// src/client.ts
|
|
7
73
|
var LINKEDIN_API_BASE = "https://api.linkedin.com/rest/";
|
|
8
74
|
var LINKEDIN_API_VERSION = "202608";
|
|
75
|
+
var LINKEDIN_CREATIVE_METADATA_VERSION = "202610";
|
|
9
76
|
var LINKEDIN_TOKEN_URL = "https://www.linkedin.com/oauth/v2/accessToken";
|
|
10
77
|
var tokenSchema = z.object({ access_token: z.string().min(1), expires_in: z.number().positive(), refresh_token: z.string().min(1).optional(), refresh_token_expires_in: z.number().nonnegative().optional() });
|
|
11
78
|
function buildLinkedInAuthUrl(clientId, redirectUri, state) {
|
|
@@ -35,6 +102,14 @@ function restli(value) {
|
|
|
35
102
|
if (typeof value === "object") return `(${Object.entries(value).map(([key, child]) => `${encodeURIComponent(key)}:${restli(child)}`).join(",")})`;
|
|
36
103
|
return encodeURIComponent(String(value)).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
37
104
|
}
|
|
105
|
+
function exactJson(text2) {
|
|
106
|
+
return JSON.parse(text2, (_key, value, context) => {
|
|
107
|
+
if (typeof value === "number" && !Number.isFinite(value)) throw new AdportError("PROVIDER_ERROR", "linkedin: native number cannot be decoded exactly");
|
|
108
|
+
if (typeof value !== "number" || !Number.isInteger(value) || Number.isSafeInteger(value)) return value;
|
|
109
|
+
if (!context?.source || !/^-?\d+$/.test(context.source)) throw new AdportError("PROVIDER_ERROR", "linkedin: native integer cannot be decoded exactly");
|
|
110
|
+
return context.source;
|
|
111
|
+
});
|
|
112
|
+
}
|
|
38
113
|
var LinkedInAdsClient = class {
|
|
39
114
|
constructor(credentials, fetchImpl = fetch) {
|
|
40
115
|
this.credentials = credentials;
|
|
@@ -47,34 +122,120 @@ var LinkedInAdsClient = class {
|
|
|
47
122
|
refreshing;
|
|
48
123
|
async get(path, schema, params = {}) {
|
|
49
124
|
const response = await this.request(path, "GET", params);
|
|
50
|
-
const
|
|
51
|
-
if (!parsed.success)
|
|
125
|
+
const raw = exactJson(await response.text()), parsed = schema.safeParse(raw);
|
|
126
|
+
if (!parsed.success) {
|
|
127
|
+
const issues = parsed.error.issues.slice(0, 12).flatMap((issue) => {
|
|
128
|
+
if (!issue.path.every((part) => typeof part === "number" && Number.isSafeInteger(part) && part >= 0 || typeof part === "string" && /^[A-Za-z_][A-Za-z0-9_]{0,80}$/.test(part))) return [];
|
|
129
|
+
let value = raw;
|
|
130
|
+
for (const part of issue.path) value = value && typeof value === "object" && Object.hasOwn(value, part) ? value[part] : void 0;
|
|
131
|
+
return [{ field_path: "/" + issue.path.join("/"), code: issue.code, received_type: value === null ? "null" : Array.isArray(value) ? "array" : typeof value, ..."expected" in issue && typeof issue.expected === "string" ? { expected_type: issue.expected } : {} }];
|
|
132
|
+
});
|
|
133
|
+
throw new AdportError("PROVIDER_ERROR", "linkedin: malformed API response", { resource: path.split("/")[0], schema_issues: issues });
|
|
134
|
+
}
|
|
52
135
|
return parsed.data;
|
|
53
136
|
}
|
|
54
137
|
async create(path, body) {
|
|
55
138
|
const response = await this.request(path, "POST", {}, body);
|
|
56
|
-
const
|
|
57
|
-
if (response.status !== 201 || !
|
|
58
|
-
return
|
|
139
|
+
const id2 = response.headers.get("x-restli-id");
|
|
140
|
+
if (response.status !== 201 || !id2 || !/^[1-9]\d*$/.test(id2)) throw new AdportError("PROVIDER_ERROR", "linkedin: create did not return 201 and x-restli-id; inspect the account before retrying");
|
|
141
|
+
return id2;
|
|
59
142
|
}
|
|
60
143
|
async update(path, fields) {
|
|
61
|
-
|
|
144
|
+
await this.partialUpdate(path, { $set: fields });
|
|
145
|
+
}
|
|
146
|
+
async partialUpdate(path, patch, params = {}) {
|
|
147
|
+
const response = await this.request(path, "POST", params, { patch }, true);
|
|
62
148
|
if (response.status !== 204) throw new AdportError("PROVIDER_ERROR", "linkedin: partial update did not return 204; inspect the account before retrying");
|
|
63
149
|
}
|
|
64
|
-
async
|
|
65
|
-
|
|
150
|
+
async createCreative(path, body, params = {}) {
|
|
151
|
+
const response = await this.request(path, "POST", params, body), raw = response.headers.get("x-restli-id");
|
|
152
|
+
let id2;
|
|
153
|
+
try {
|
|
154
|
+
id2 = raw ? decodeURIComponent(raw) : void 0;
|
|
155
|
+
} catch {
|
|
156
|
+
}
|
|
157
|
+
if (response.status !== 201 || !id2 || !/^urn:li:sponsoredCreative:[1-9]\d*$/.test(id2)) throw new AdportError("PROVIDER_ERROR", "linkedin: creative create did not return 201 and a valid sponsoredCreative URN; inspect the account before retrying");
|
|
158
|
+
return id2;
|
|
159
|
+
}
|
|
160
|
+
async createPost(body) {
|
|
161
|
+
const response = await this.request("posts", "POST", {}, body), raw = response.headers.get("x-restli-id");
|
|
162
|
+
let id2;
|
|
163
|
+
try {
|
|
164
|
+
id2 = raw ? decodeURIComponent(raw) : void 0;
|
|
165
|
+
} catch {
|
|
166
|
+
}
|
|
167
|
+
if (response.status !== 201 || !id2 || !/^urn:li:(?:share|ugcPost):[1-9]\d*$/.test(id2)) throw new AdportError("PROVIDER_ERROR", "linkedin: post create did not return 201 and an exact post URN; reconcile before retrying");
|
|
168
|
+
return id2;
|
|
169
|
+
}
|
|
170
|
+
async creativeMetadata(path, schema) {
|
|
171
|
+
const response = await this.request(path, "GET", { fields: "id,account,campaign,name,intendedStatus,content,leadgenCallToAction,metadata" }, void 0, false, true, LINKEDIN_CREATIVE_METADATA_VERSION);
|
|
172
|
+
const parsed = schema.safeParse(await response.json());
|
|
173
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "linkedin: malformed creative metadata response");
|
|
174
|
+
return parsed.data;
|
|
175
|
+
}
|
|
176
|
+
async creativeMediaType(url3) {
|
|
177
|
+
const target = new URL(url3);
|
|
178
|
+
if (target.protocol !== "https:" || target.username || target.password || !(target.hostname === "licdn.com" || target.hostname.endsWith(".licdn.com"))) return void 0;
|
|
179
|
+
const response = await this.fetchImpl(target.href, { method: "HEAD", redirect: "error", signal: AbortSignal.timeout(1e4) });
|
|
180
|
+
if (!response.ok) return void 0;
|
|
181
|
+
const mime = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
|
|
182
|
+
return ["image/jpeg", "image/png", "image/webp", "image/gif", "image/avif"].includes(mime ?? "") ? "image" : ["video/mp4", "video/webm", "video/quicktime"].includes(mime ?? "") ? "video" : void 0;
|
|
183
|
+
}
|
|
184
|
+
async action(path, action, body, schema) {
|
|
185
|
+
const response = await this.request(path, "POST", { action }, body), parsed = schema.safeParse(await response.json());
|
|
186
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "linkedin: malformed action response; inspect the account before retrying");
|
|
187
|
+
return parsed.data;
|
|
188
|
+
}
|
|
189
|
+
async remove(path) {
|
|
190
|
+
const response = await this.request(path, "DELETE", {});
|
|
191
|
+
if (response.status !== 204) throw new AdportError("PROVIDER_ERROR", "linkedin: delete did not return 204; inspect the account before retrying");
|
|
192
|
+
}
|
|
193
|
+
async setCampaignConversion(campaignId, conversionId, associated) {
|
|
194
|
+
if (![campaignId, conversionId].every((value) => /^[1-9]\d*$/.test(value))) throw new AdportError("INVALID_INPUT", "linkedin: invalid campaign/conversion identity");
|
|
195
|
+
const campaign = `urn:li:sponsoredCampaign:${campaignId}`, conversion2 = `urn:lla:llaPartnerConversion:${conversionId}`;
|
|
196
|
+
const path = `campaignConversions/(campaign:${restli(campaign)},conversion:${restli(conversion2)})`;
|
|
197
|
+
const response = await this.request(path, associated ? "PUT" : "DELETE", {}, associated ? { campaign, conversion: conversion2 } : void 0);
|
|
198
|
+
if (response.status !== 204) throw new AdportError("PROVIDER_ERROR", "linkedin: campaign-conversion change was not acknowledged; reconcile the association before retrying");
|
|
199
|
+
}
|
|
200
|
+
async uploadImage(url3, bytes) {
|
|
201
|
+
const target = new URL(url3);
|
|
202
|
+
if (target.origin !== "https://www.linkedin.com" || !target.pathname.startsWith("/dms-uploads/") || target.username || target.password || target.hash) throw new AdportError("PROVIDER_ERROR", "linkedin: unrecognized native image upload destination");
|
|
203
|
+
const response = await this.fetchImpl(target.href, { method: "PUT", headers: { authorization: `Bearer ${await this.accessToken()}`, "content-type": "application/octet-stream" }, body: bytes, redirect: "error", signal: AbortSignal.timeout(6e4) });
|
|
204
|
+
if (!response.ok) throw new AdportError("PROVIDER_ERROR", `linkedin: image upload HTTP ${response.status}; inspect its initialized image before retrying`);
|
|
205
|
+
}
|
|
206
|
+
validateMediaUpload(url3, kind, resource) {
|
|
207
|
+
const target = new URL(url3), key = resource.split(":").at(-1);
|
|
208
|
+
const path = kind === "video" ? `/dms-uploads/${key}/uploadedVideo` : void 0;
|
|
209
|
+
if (target.origin !== "https://www.linkedin.com" || target.username || target.password || target.hash || (kind === "video" ? target.pathname !== path : !/^\/dms-uploads\/[A-Za-z0-9_-]+\/(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+$/.test(target.pathname))) throw new AdportError("PROVIDER_ERROR", "linkedin: unrecognized native media upload destination");
|
|
210
|
+
return target;
|
|
211
|
+
}
|
|
212
|
+
async uploadMedia(url3, bytes, kind, resource) {
|
|
213
|
+
const target = this.validateMediaUpload(url3, kind, resource);
|
|
214
|
+
const response = await this.fetchImpl(target.href, { method: "PUT", headers: { "content-type": "application/octet-stream", ...kind === "document" ? { authorization: `Bearer ${await this.accessToken()}` } : {} }, body: bytes, redirect: "error", signal: AbortSignal.timeout(9e4) });
|
|
215
|
+
if (response.status !== (kind === "video" ? 200 : 201)) throw new AdportError("PROVIDER_ERROR", "linkedin: native media transfer was not acknowledged");
|
|
216
|
+
const etag = response.headers.get("etag")?.replace(/^"(.*)"$/, "$1");
|
|
217
|
+
if (kind === "video" && (!etag || etag.length > 8192 || /[\r\n]/.test(etag))) throw new AdportError("PROVIDER_ERROR", "linkedin: video part ETag was not acknowledged");
|
|
218
|
+
return etag ?? "";
|
|
219
|
+
}
|
|
220
|
+
async finalizeVideo(body) {
|
|
221
|
+
const response = await this.request("videos", "POST", { action: "finalizeUpload" }, body);
|
|
222
|
+
if (response.status !== 200) throw new AdportError("PROVIDER_ERROR", "linkedin: video finalization was not acknowledged");
|
|
223
|
+
}
|
|
224
|
+
async request(path, method, params, body, partial2 = false, retry = true, version = LINKEDIN_API_VERSION) {
|
|
225
|
+
const campaignConversion = /^campaignConversions\/\(campaign:urn%3Ali%3AsponsoredCampaign%3A[1-9]\d*,conversion:urn%3Alla%3AllaPartnerConversion%3A[1-9]\d*\)$/.test(path);
|
|
226
|
+
if (!campaignConversion && !/^[a-zA-Z]+(?:\/(?:[a-zA-Z0-9]+|urn%3Ali%3A[a-zA-Z]+%3A[a-zA-Z0-9_-]+))*$/.test(path)) throw new AdportError("INVALID_INPUT", "linkedin: invalid API resource path");
|
|
66
227
|
const query = Object.entries(params).map(([key, value]) => `${encodeURIComponent(key)}=${key === "fields" && typeof value === "string" ? value.split(",").map(restli).join(",") : restli(value)}`).join("&");
|
|
67
|
-
const
|
|
68
|
-
|
|
228
|
+
const url3 = new URL(path, LINKEDIN_API_BASE);
|
|
229
|
+
url3.search = query;
|
|
69
230
|
const token = await this.accessToken();
|
|
70
|
-
const response = await this.fetchImpl(
|
|
231
|
+
const response = await this.fetchImpl(url3.href, {
|
|
71
232
|
method,
|
|
72
233
|
headers: {
|
|
73
234
|
authorization: `Bearer ${token}`,
|
|
74
|
-
"Linkedin-Version":
|
|
235
|
+
"Linkedin-Version": version,
|
|
75
236
|
"X-Restli-Protocol-Version": "2.0.0",
|
|
76
237
|
...body !== void 0 ? { "content-type": "application/json" } : {},
|
|
77
|
-
...
|
|
238
|
+
...partial2 ? { "X-RestLi-Method": "PARTIAL_UPDATE" } : method === "DELETE" ? { "X-RestLi-Method": "DELETE" } : params.q ? { "X-RestLi-Method": "FINDER" } : {}
|
|
78
239
|
},
|
|
79
240
|
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
80
241
|
redirect: "error",
|
|
@@ -82,11 +243,12 @@ var LinkedInAdsClient = class {
|
|
|
82
243
|
});
|
|
83
244
|
if (response.status === 401 && method === "GET" && retry && this.canRefresh()) {
|
|
84
245
|
if (this.tokens.accessToken === token) this.tokens.expiresAt = 0;
|
|
85
|
-
return this.request(path, method, params, body,
|
|
246
|
+
return this.request(path, method, params, body, partial2, false, version);
|
|
86
247
|
}
|
|
87
248
|
if (!response.ok) {
|
|
88
249
|
const advice = response.status === 403 ? " Check Advertising API approval, r_ads_reporting/rw_ads scopes and account roles; reauthorization alone may not help." : response.status === 401 ? " Reauthorize your own LinkedIn app; a non-refreshable token must be replaced." : "";
|
|
89
|
-
|
|
250
|
+
const details = await linkedinErrorDetails(response, [token, this.tokens.refreshToken, this.credentials.clientSecret]);
|
|
251
|
+
throw new AdportError("PROVIDER_ERROR", `linkedin: HTTP ${response.status}${details.native_code ? ` [${details.native_code}]` : ""}.${advice}`, details);
|
|
90
252
|
}
|
|
91
253
|
return response;
|
|
92
254
|
}
|
|
@@ -112,8 +274,8 @@ var LinkedInAdsClient = class {
|
|
|
112
274
|
};
|
|
113
275
|
|
|
114
276
|
// src/provider.ts
|
|
115
|
-
import { z as
|
|
116
|
-
import { AdportError as
|
|
277
|
+
import { z as z16 } from "zod";
|
|
278
|
+
import { AdportError as AdportError13, resolveDateRange } from "@adport/core";
|
|
117
279
|
|
|
118
280
|
// src/schemas.ts
|
|
119
281
|
import { z as z2 } from "zod";
|
|
@@ -137,8 +299,9 @@ var reportRowSchema = z2.looseObject({
|
|
|
137
299
|
});
|
|
138
300
|
var NON_DISCRIMINATION_NOTICE = "LinkedIn tools may not be used to discriminate based on personal characteristics such as gender, age, race, or ethnicity. Learn more: https://www.linkedin.com/legal/ads-policy";
|
|
139
301
|
var NON_POLITICAL_CONSENT = "I confirm this is not political advertising. None of my ads qualify as political advertising under the law of the targeted countries, including EU law for ads targeted to the EU.";
|
|
140
|
-
var
|
|
141
|
-
var
|
|
302
|
+
var targetingEntity = z2.union([z2.string().regex(/^urn:li:[a-zA-Z]+:[a-zA-Z0-9_()-]+$/), z2.string().regex(/^urn:li:staffCountRange:\(\d+,\d+\)$/)]);
|
|
303
|
+
var facets = z2.record(z2.string().regex(/^urn:li:adTargetingFacet:[a-zA-Z]+$/), z2.array(targetingEntity).min(1));
|
|
304
|
+
var targetingSchema = z2.object({ include: z2.object({ and: z2.array(z2.object({ or: facets }).strict()).min(1) }).strict(), exclude: z2.object({ or: facets }).strict().optional() }).strict();
|
|
142
305
|
var micros = z2.number().int().positive().safe();
|
|
143
306
|
var createCampaignSchema = z2.object({
|
|
144
307
|
name: z2.string().trim().min(1).max(200),
|
|
@@ -161,30 +324,2047 @@ var createCampaignSchema = z2.object({
|
|
|
161
324
|
var setStatusSchema = z2.object({ campaign_id: linkedinId, status: z2.enum(["PAUSED", "ACTIVE"]), non_political_consent: z2.literal(true).optional().describe(`Required when activating: ${NON_POLITICAL_CONSENT}`) });
|
|
162
325
|
var setBudgetSchema = z2.object({ campaign_id: linkedinId, budget_type: z2.enum(["DAILY", "TOTAL"]), budget_micros: micros });
|
|
163
326
|
|
|
327
|
+
// src/creatives.ts
|
|
328
|
+
import { AdportError as AdportError2, LocalMediaResolver } from "@adport/core";
|
|
329
|
+
import { z as z4 } from "zod";
|
|
330
|
+
|
|
331
|
+
// src/creative-tools.ts
|
|
332
|
+
import { creativesOutput, defineTool, guardedWriteTool, mediaSourceFields } from "@adport/core";
|
|
333
|
+
import { z as z3 } from "zod";
|
|
334
|
+
var creativeUrn = z3.string().regex(/^urn:li:sponsoredCreative:[1-9]\d*$/);
|
|
335
|
+
var imageUrn = z3.string().regex(/^urn:li:image:[A-Za-z0-9_-]+$/);
|
|
336
|
+
var href = z3.string().url().refine((value) => {
|
|
337
|
+
const url3 = new URL(value);
|
|
338
|
+
return ["http:", "https:"].includes(url3.protocol) && !url3.username && !url3.password;
|
|
339
|
+
}, "Use an HTTP(S) URL without embedded credentials");
|
|
340
|
+
var name = z3.string().trim().min(1).max(200);
|
|
341
|
+
var headline = z3.string().min(1).max(25);
|
|
342
|
+
var description = z3.string().min(1).max(75);
|
|
343
|
+
var textAd = z3.object({ headline, description, landingPage: href, image: imageUrn.optional() }).strict();
|
|
344
|
+
var createText = z3.object({ campaign_id: linkedinId, name: name.optional(), headline, description, landing_page: href, image: imageUrn.optional(), status: z3.enum(["PAUSED", "ACTIVE", "DRAFT"]).default("PAUSED"), non_political_consent: z3.literal(true).describe(NON_POLITICAL_CONSENT) });
|
|
345
|
+
var updateText = z3.object({ creative_id: creativeUrn, headline: headline.optional(), description: description.optional(), landing_page: href.optional(), image: imageUrn.optional() }).refine((v) => Object.keys(v).length > 1, "Provide text-ad changes");
|
|
346
|
+
var uploadImage = z3.object({ name, ...mediaSourceFields }).refine((v) => Boolean(v.media_id) !== Boolean(v.file_path), "Choose project media_id or local file_path");
|
|
347
|
+
var creativeStatus = z3.object({ creative_id: creativeUrn, status: z3.enum(["PAUSED", "ACTIVE", "ARCHIVED"]), non_political_consent: z3.literal(true).optional().describe(`Required for activation: ${NON_POLITICAL_CONSENT}`) });
|
|
348
|
+
function linkedinCreativeTools(provider) {
|
|
349
|
+
const account2 = { account_id: linkedinId };
|
|
350
|
+
const read = (name5, description3, input, handler) => defineTool({ name: name5, namespace: "linkedin", description: description3, input, annotations: { readOnly: true }, handler });
|
|
351
|
+
const write = (name5, description3, payload, kind = "update") => guardedWriteTool({ name: name5, namespace: "linkedin", provider: "linkedin", description: description3, payload, kind });
|
|
352
|
+
return [
|
|
353
|
+
defineTool({ name: "linkedin_creatives", namespace: "linkedin", description: "View account-owned creatives and actual text-ad copy/images. With include_media, non-text formats use individual API202610 metadata reads for native copy and primary previews. Full sponsored-post contents require separate Page access; missing details remain explicit.", input: z3.object({ ...account2, campaign_ids: z3.array(linkedinId).max(100).optional(), creative_ids: z3.array(creativeUrn).max(100).optional(), statuses: z3.array(z3.enum(["ACTIVE", "PAUSED", "DRAFT", "ARCHIVED", "CANCELED", "PENDING_DELETION", "REMOVED"])).optional(), page_size: z3.number().int().min(1).max(100).default(20), page_token: z3.string().optional(), include_media: z3.boolean().default(true) }), output: creativesOutput.passthrough(), presentation: "creatives", pagination: { cursorInput: "page_token", cursorOutput: "next_page_token" }, annotations: { readOnly: true }, handler: (v) => provider.creatives.list(v) }),
|
|
354
|
+
read("linkedin_get_creative", "Read one creative, verifying account and parent campaign ownership before returning native content/review settings.", z3.object({ ...account2, creative_id: creativeUrn }), (v) => provider.creatives.owned(v.account_id, v.creative_id)),
|
|
355
|
+
read("linkedin_get_image", "Read a native image associated with the selected account, including processing readiness and an expiring preview URL.", z3.object({ ...account2, image_id: imageUrn }), (v) => provider.creatives.image(v.account_id, v.image_id)),
|
|
356
|
+
read("linkedin_get_library_image", "Read one exact image through the selected account media-library finder, including archived entries, native readiness and preview. Searches at most 5,000 entries and fails explicitly if membership cannot be confirmed.", z3.object({ ...account2, image_id: imageUrn }), (v) => provider.creatives.libraryImage(v.account_id, v.image_id)),
|
|
357
|
+
defineTool({ name: "linkedin_images", namespace: "linkedin", description: "View the selected account\u2019s native media-library images, processing status and expiring previews. Archive status affects library visibility, not delivery of existing ads.", input: z3.object({ ...account2, library_status: z3.enum(["ACTIVE", "ARCHIVED"]).default("ACTIVE"), start: z3.number().int().nonnegative().default(0), count: z3.number().int().min(1).max(100).default(20) }), output: creativesOutput.passthrough(), presentation: "creatives", pagination: { cursorInput: "start", cursorOutput: "next_start" }, annotations: { readOnly: true }, handler: (v) => provider.creatives.images(v) }),
|
|
358
|
+
write("linkedin_create_text_ad", "Create a native text creative under a TEXT_AD campaign, paused by policy. Requires explicit non-political advertiser confirmation; optional image must belong to the account.", createText, "create"),
|
|
359
|
+
write("linkedin_update_text_ad", "Edit supplied text-ad headline/body/destination/image fields, preserving omitted content and delivery status. Can trigger creative review.", updateText),
|
|
360
|
+
write("linkedin_rename_creative", "Rename one verified creative without changing its content or intended delivery status.", z3.object({ creative_id: creativeUrn, name })),
|
|
361
|
+
write("linkedin_set_creative_status", "Pause, activate or archive one verified creative. Activation requires explicit advertiser confirmation; parent campaign status remains separate.", creativeStatus),
|
|
362
|
+
write("linkedin_delete_creative", "Delete an eligible draft creative, or request PENDING_DELETION for other states using the native lifecycle.", z3.object({ creative_id: creativeUrn }), "remove"),
|
|
363
|
+
write("linkedin_upload_image", "Initialize and upload SHA-256-bound PNG/JPEG/GIF bytes to an account-owned native image/media-library entry. Check readiness with linkedin_get_library_image after upload acceptance.", uploadImage, "create"),
|
|
364
|
+
write("linkedin_update_image", "Rename or archive/unarchive an image in the selected account\u2019s native media library. Preserves the image and existing ads; this is not image deletion or an ad-status change.", z3.object({ image_id: imageUrn, asset_name: name.optional(), library_status: z3.enum(["ACTIVE", "ARCHIVED"]).optional() }).refine((v) => v.asset_name !== void 0 || v.library_status !== void 0, "Provide image library changes"))
|
|
365
|
+
];
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// src/creatives.ts
|
|
369
|
+
var record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
370
|
+
var campaignUrn = z4.string().regex(/^urn:li:sponsoredCampaign:[1-9]\d*$/);
|
|
371
|
+
var creativeSchema = z4.looseObject({ id: creativeUrn, account: accountUrn, campaign: campaignUrn, intendedStatus: z4.string(), content: z4.record(z4.string(), z4.unknown()).optional() });
|
|
372
|
+
var safeUrl = (value) => {
|
|
373
|
+
if (typeof value !== "string") return void 0;
|
|
374
|
+
try {
|
|
375
|
+
const url3 = new URL(value);
|
|
376
|
+
return url3.protocol === "https:" && !url3.username && !url3.password ? value : void 0;
|
|
377
|
+
} catch {
|
|
378
|
+
return void 0;
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
var landingUrl = (value) => {
|
|
382
|
+
if (typeof value !== "string") return [];
|
|
383
|
+
try {
|
|
384
|
+
const url3 = new URL(value);
|
|
385
|
+
return ["http:", "https:"].includes(url3.protocol) && !url3.username && !url3.password ? [value] : [];
|
|
386
|
+
} catch {
|
|
387
|
+
return [];
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
var aurn = (account2) => `urn:li:sponsoredAccount:${linkedinId.parse(account2)}`;
|
|
391
|
+
var imageSchema = z4.looseObject({ id: imageUrn, owner: z4.string(), status: z4.string(), downloadUrlExpiresAt: z4.number().int().positive().max(864e13).optional(), mediaLibraryMetadata: z4.looseObject({ associatedAccount: accountUrn }).optional() });
|
|
392
|
+
var LinkedInCreativeService = class {
|
|
393
|
+
constructor(client, provider, media = new LocalMediaResolver()) {
|
|
394
|
+
this.client = client;
|
|
395
|
+
this.provider = provider;
|
|
396
|
+
this.media = media;
|
|
397
|
+
}
|
|
398
|
+
client;
|
|
399
|
+
provider;
|
|
400
|
+
media;
|
|
401
|
+
async owned(account2, resource) {
|
|
402
|
+
const value = await this.client.get(`adAccounts/${linkedinId.parse(account2)}/creatives/${encodeURIComponent(creativeUrn.parse(resource))}`, creativeSchema);
|
|
403
|
+
if (value.account !== aurn(account2) || value.id !== resource) throw new AdportError2("INVALID_INPUT", "linkedin: creative account/ID mismatch");
|
|
404
|
+
await this.provider.getCampaign(account2, value.campaign.split(":").at(-1));
|
|
405
|
+
return value;
|
|
406
|
+
}
|
|
407
|
+
async image(account2, resource) {
|
|
408
|
+
const value = await this.client.get(`images/${encodeURIComponent(imageUrn.parse(resource))}`, imageSchema, { associatedAccount: aurn(account2) });
|
|
409
|
+
if (value.id !== resource || value.owner !== aurn(account2) && value.mediaLibraryMetadata?.associatedAccount !== aurn(account2)) throw new AdportError2("INVALID_INPUT", "linkedin: image is not owned by or registered in the selected account");
|
|
410
|
+
return value;
|
|
411
|
+
}
|
|
412
|
+
async images(input) {
|
|
413
|
+
const account2 = linkedinId.parse(input.account_id);
|
|
414
|
+
await this.provider.getAccount(account2);
|
|
415
|
+
const { data, next } = await this.libraryPage(account2, input.start, input.count, input.library_status);
|
|
416
|
+
const creatives = data.elements.map((value) => {
|
|
417
|
+
const metadata3 = value.mediaLibraryMetadata, url3 = safeUrl(value.downloadUrl);
|
|
418
|
+
return { id: value.id, provider: "linkedin", account_id: account2, name: String(metadata3.assetName ?? value.id), type: "IMAGE_ASSET", status: value.status, headlines: [], descriptions: [`Media library: ${metadata3.mediaLibraryStatus}; native processing: ${value.status}`], landing_urls: [], media: url3 ? [{ type: "image", url: url3, ...value.downloadUrlExpiresAt ? { expires_at: new Date(value.downloadUrlExpiresAt).toISOString() } : {} }] : [], actions: [{ label: "Edit image library entry", tool: "linkedin_update_image", arguments: { account_id: account2, image_id: value.id }, fields: [{ key: "asset_name", label: "Name", type: "text", value: String(metadata3.assetName ?? "") }, { key: "library_status", label: "Library status", type: "select", value: String(metadata3.mediaLibraryStatus), options: [{ label: "Active in library", value: "ACTIVE" }, { label: "Archived in library", value: "ARCHIVED" }] }] }] };
|
|
419
|
+
});
|
|
420
|
+
return { items: data.elements, creatives, truncated: next, ...next ? { next_start: input.start + data.elements.length } : {} };
|
|
421
|
+
}
|
|
422
|
+
async libraryPage(account2, start, count2, status) {
|
|
423
|
+
const data = await this.client.get("images", z4.looseObject({ elements: z4.array(imageSchema), paging: z4.object({ start: z4.number().int().nonnegative(), count: z4.number().int().nonnegative(), total: z4.number().int().nonnegative().optional(), links: z4.array(z4.looseObject({ rel: z4.string() })).optional() }).optional() }), { q: "associatedAccount", associatedAccount: aurn(account2), ...status ? { mediaLibraryStatus: { value: status } } : {}, start, count: count2 });
|
|
424
|
+
if (data.elements.length > count2 || data.elements.some((value) => value.mediaLibraryMetadata?.associatedAccount !== aurn(account2) || status && value.mediaLibraryMetadata.mediaLibraryStatus !== status) || data.paging && data.paging.start !== start) throw new AdportError2("PROVIDER_ERROR", "linkedin: image library account/status/paging mismatch");
|
|
425
|
+
const next = Boolean(data.paging?.links?.some((link) => link.rel === "next")) || (data.paging?.total !== void 0 ? start + data.elements.length < data.paging.total : data.elements.length >= count2);
|
|
426
|
+
return { data, next };
|
|
427
|
+
}
|
|
428
|
+
/** Account-library membership is its own native authorization surface. */
|
|
429
|
+
async libraryImage(accountId, resource) {
|
|
430
|
+
const account2 = linkedinId.parse(accountId);
|
|
431
|
+
imageUrn.parse(resource);
|
|
432
|
+
await this.provider.getAccount(account2);
|
|
433
|
+
const seen = /* @__PURE__ */ new Set();
|
|
434
|
+
let start = 0;
|
|
435
|
+
while (start < 5e3) {
|
|
436
|
+
const { data, next } = await this.libraryPage(account2, start, 100);
|
|
437
|
+
if (data.elements.some((value) => seen.has(value.id)) || new Set(data.elements.map((value) => value.id)).size !== data.elements.length) throw new AdportError2("PROVIDER_ERROR", "linkedin: image-library pagination repeated an image");
|
|
438
|
+
const found = data.elements.find((value) => value.id === resource);
|
|
439
|
+
if (found) return found;
|
|
440
|
+
if (!next) throw new AdportError2("INVALID_INPUT", "linkedin: image has no selected-account library metadata");
|
|
441
|
+
if (!data.elements.length) throw new AdportError2("PROVIDER_ERROR", "linkedin: image-library pagination did not advance");
|
|
442
|
+
data.elements.forEach((value) => seen.add(value.id));
|
|
443
|
+
start += data.elements.length;
|
|
444
|
+
}
|
|
445
|
+
throw new AdportError2("PROVIDER_ERROR", "linkedin: image-library lookup reached its 5,000-image limit; membership is unconfirmed");
|
|
446
|
+
}
|
|
447
|
+
async list(input) {
|
|
448
|
+
const account2 = linkedinId.parse(input.account_id), params = { q: "criteria", sortOrder: "ASCENDING", pageSize: input.page_size, ...input.page_token ? { pageToken: input.page_token } : {}, ...input.campaign_ids?.length ? { campaigns: input.campaign_ids.map((id2) => `urn:li:sponsoredCampaign:${linkedinId.parse(id2)}`) } : {}, ...input.creative_ids?.length ? { creatives: input.creative_ids } : {}, intendedStatuses: input.statuses ?? ["ACTIVE", "PAUSED", "DRAFT", "ARCHIVED", "CANCELED", "PENDING_DELETION", "REMOVED"] };
|
|
449
|
+
const data = await this.client.get(`adAccounts/${account2}/creatives`, z4.looseObject({ elements: z4.array(creativeSchema), metadata: z4.object({ nextPageToken: z4.string().optional() }).optional() }), params);
|
|
450
|
+
if (data.elements.some((value) => value.account !== aurn(account2) || input.campaign_ids?.length && !input.campaign_ids.some((id2) => value.campaign === `urn:li:sponsoredCampaign:${id2}`) || input.creative_ids?.length && !input.creative_ids.includes(value.id) || input.statuses?.length && !input.statuses.includes(value.intendedStatus))) throw new AdportError2("PROVIDER_ERROR", "linkedin: creative collection account/campaign/filter mismatch");
|
|
451
|
+
const next = data.metadata?.nextPageToken;
|
|
452
|
+
if (next && next === input.page_token) throw new AdportError2("PROVIDER_ERROR", "linkedin: creative pagination repeated its token");
|
|
453
|
+
const images = /* @__PURE__ */ new Map(), warnings = [], wanted = [...new Set(data.elements.map((value) => record(value.content?.textAd).image).filter((value) => typeof value === "string"))];
|
|
454
|
+
let cursor = 0;
|
|
455
|
+
if (input.include_media) await Promise.all(Array.from({ length: Math.min(4, wanted.length) }, async () => {
|
|
456
|
+
while (cursor < wanted.length) {
|
|
457
|
+
const resource = wanted[cursor++];
|
|
458
|
+
try {
|
|
459
|
+
images.set(resource, await this.image(account2, resource));
|
|
460
|
+
} catch (error) {
|
|
461
|
+
warnings.push({ provider: "linkedin", message: `Referenced image ${resource} unavailable: ${error instanceof Error ? error.message : "native read failed"}` });
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}));
|
|
465
|
+
const enriched = /* @__PURE__ */ new Map(), references = data.elements.filter((value) => !value.content?.textAd);
|
|
466
|
+
let metadataCursor = 0;
|
|
467
|
+
if (input.include_media) await Promise.all(Array.from({ length: Math.min(4, references.length) }, async () => {
|
|
468
|
+
while (metadataCursor < references.length) {
|
|
469
|
+
const value = references[metadataCursor++];
|
|
470
|
+
try {
|
|
471
|
+
const detail = await this.provider.sponsored.metadata(account2, value.id);
|
|
472
|
+
if (detail.campaign !== value.campaign) throw new Error("creative campaign changed during hydration");
|
|
473
|
+
if (detail.metadata) enriched.set(value.id, detail);
|
|
474
|
+
if (detail.preview_warning) warnings.push({ provider: "linkedin", message: detail.preview_warning });
|
|
475
|
+
} catch (error) {
|
|
476
|
+
warnings.push({ provider: "linkedin", message: `Creative metadata ${value.id} unavailable: ${error instanceof Error ? error.message : "native read failed"}` });
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}));
|
|
480
|
+
const creatives = data.elements.map((value) => {
|
|
481
|
+
const detail = enriched.get(value.id);
|
|
482
|
+
if (detail) return this.provider.sponsored.metadataCard(account2, detail);
|
|
483
|
+
const copy = record(value.content?.textAd), supported = textAd.safeParse(copy).success, image = images.get(String(copy.image)), url3 = safeUrl(image?.downloadUrl), args = { account_id: account2, creative_id: value.id };
|
|
484
|
+
const editable2 = !["REMOVED", "PENDING_DELETION", "CANCELED"].includes(value.intendedStatus), actions = editable2 ? [{ label: "Pause or archive creative", tool: "linkedin_set_creative_status", arguments: args, fields: [{ key: "status", label: "Status", type: "select", value: value.intendedStatus === "ARCHIVED" ? "ARCHIVED" : "PAUSED", options: [{ label: "Paused", value: "PAUSED" }, { label: "Archived", value: "ARCHIVED" }] }] }, { label: "Rename creative", tool: "linkedin_rename_creative", arguments: args, fields: [{ key: "name", label: "Name", type: "text", value: String(value.name ?? "") }] }] : [];
|
|
485
|
+
if (supported && editable2) actions.push({ label: "Edit text-ad copy", tool: "linkedin_update_text_ad", arguments: args, fields: [{ key: "headline", label: "Headline", type: "text", value: String(copy.headline), max_length: 25 }, { key: "description", label: "Description", type: "text", value: String(copy.description), max_length: 75 }, { key: "landing_page", label: "Destination", type: "text", value: String(copy.landingPage) }] });
|
|
486
|
+
return { id: value.id, provider: "linkedin", account_id: account2, name: String(value.name ?? value.id), type: supported ? "TEXT_AD" : value.content?.reference ? "SPONSORED_CONTENT_REFERENCE" : "CREATIVE", status: value.intendedStatus, campaign_id: value.campaign.split(":").at(-1), headlines: typeof copy.headline === "string" ? [copy.headline] : [], descriptions: typeof copy.description === "string" ? [copy.description] : [], landing_urls: landingUrl(copy.landingPage), media: url3 ? [{ type: "image", url: url3, ...typeof image?.downloadUrlExpiresAt === "number" ? { expires_at: new Date(image.downloadUrlExpiresAt).toISOString() } : {} }] : [], actions };
|
|
487
|
+
});
|
|
488
|
+
const referenceCount = data.elements.filter((value) => value.content?.reference && !enriched.has(value.id)).length;
|
|
489
|
+
if (referenceCount) warnings.push({ provider: "linkedin", message: `${referenceCount} sponsored-content references have no descriptive metadata. Native references remain in items; full post/media content needs source-specific access.` });
|
|
490
|
+
return { items: data.elements, creatives, warnings, truncated: Boolean(next), ...next ? { next_page_token: next } : {} };
|
|
491
|
+
}
|
|
492
|
+
async update(account2, resource, path, fields, expected) {
|
|
493
|
+
await this.client.update(path, fields);
|
|
494
|
+
try {
|
|
495
|
+
const value = await this.owned(account2, resource);
|
|
496
|
+
if (!matches(value, expected)) throw new Error("settings did not match readback");
|
|
497
|
+
} catch {
|
|
498
|
+
throw new AdportError2("PROVIDER_ERROR", "linkedin: creative update readback mismatch; reconcile before retrying", { resource_ids: [resource] });
|
|
499
|
+
}
|
|
500
|
+
return { applied: true, resourceIds: [resource] };
|
|
501
|
+
}
|
|
502
|
+
async plan(op, guard) {
|
|
503
|
+
const account2 = linkedinId.parse(op.accountId), p = op.payload, create = ["linkedin_create_text_ad", "linkedin_upload_image"].includes(op.tool), remove = op.tool === "linkedin_delete_creative";
|
|
504
|
+
if (op.provider !== "linkedin" || op.kind !== (create ? "create" : remove ? "remove" : "update")) throw new AdportError2("INVALID_INPUT", "linkedin: provider or creative operation kind mismatch");
|
|
505
|
+
const plan = (summary, changes, execute, coercions = []) => ({ summary, changes, execute, coercions, budgetDeltas: [] });
|
|
506
|
+
if (op.tool === "linkedin_upload_image") {
|
|
507
|
+
const input = uploadImage.parse(p), file = await this.media.read(input, { maxBytes: 50 * 1024 * 1024, contentTypes: ["image/png", "image/jpeg", "image/gif"] });
|
|
508
|
+
await this.provider.getAccount(account2);
|
|
509
|
+
return plan("Upload a LinkedIn account image", [`Initialize an account-owned native image and media-library entry named ${JSON.stringify(input.name)}; ${file.name}, ${file.bytes.byteLength} bytes; SHA-256 ${file.sha256}. Processing availability requires a later linkedin_get_library_image read.`], async () => {
|
|
510
|
+
const init = await this.client.action("images", "initializeUpload", { initializeUploadRequest: { owner: aurn(account2), mediaLibraryMetadata: { associatedAccount: aurn(account2), assetName: input.name } } }, z4.object({ value: z4.object({ image: imageUrn, uploadUrl: z4.string().url(), uploadUrlExpiresAt: z4.number().int().positive().safe() }) }));
|
|
511
|
+
const value = init.value;
|
|
512
|
+
try {
|
|
513
|
+
if (value.uploadUrlExpiresAt <= Date.now()) throw new AdportError2("PROVIDER_ERROR", "linkedin: initialized image upload URL expired");
|
|
514
|
+
await this.client.uploadImage(value.uploadUrl, file.bytes);
|
|
515
|
+
} catch (error) {
|
|
516
|
+
throw new AdportError2("PROVIDER_ERROR", error instanceof Error ? error.message : "linkedin: image transfer failed", { resource_ids: [value.image] });
|
|
517
|
+
}
|
|
518
|
+
return { applied: true, resourceIds: [value.image], details: { next_tool: "linkedin_get_library_image", status: "UPLOAD_ACCEPTED", note: "Native upload acceptance does not prove processing readiness." } };
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
if (op.tool === "linkedin_create_text_ad") {
|
|
522
|
+
const input = createText.parse(p), campaign = await this.provider.getCampaign(account2, input.campaign_id);
|
|
523
|
+
if (campaign.type !== "TEXT_AD") throw new AdportError2("INVALID_INPUT", "linkedin: text creatives require a TEXT_AD parent campaign");
|
|
524
|
+
if (input.image && (await this.image(account2, input.image)).status !== "AVAILABLE") throw new AdportError2("INVALID_INPUT", "linkedin: image is not AVAILABLE");
|
|
525
|
+
const status = guard.forcePausedCreation ? "PAUSED" : input.status, fields2 = { campaign: `urn:li:sponsoredCampaign:${input.campaign_id}`, intendedStatus: status, ...input.name ? { name: input.name } : {}, content: { textAd: { headline: input.headline, description: input.description, landingPage: input.landing_page, ...input.image ? { image: input.image } : {} } } };
|
|
526
|
+
return plan("Create a LinkedIn text ad", [NON_DISCRIMINATION_NOTICE, `Advertiser confirmation: ${NON_POLITICAL_CONSENT}`, JSON.stringify(fields2)], async () => {
|
|
527
|
+
const resource2 = await this.client.createCreative(`adAccounts/${account2}/creatives`, fields2);
|
|
528
|
+
try {
|
|
529
|
+
if (!matches(await this.owned(account2, resource2), fields2)) throw new Error("settings mismatch");
|
|
530
|
+
} catch {
|
|
531
|
+
throw new AdportError2("PROVIDER_ERROR", "linkedin: created creative readback mismatch; reconcile before retrying", { resource_ids: [resource2] });
|
|
532
|
+
}
|
|
533
|
+
return { applied: true, resourceIds: [resource2] };
|
|
534
|
+
}, status !== input.status ? ["intendedStatus coerced to PAUSED by policy (paused_creation)"] : []);
|
|
535
|
+
}
|
|
536
|
+
if (op.tool === "linkedin_update_image") {
|
|
537
|
+
const resource2 = imageUrn.parse(p.image_id), value = await this.libraryImage(account2, resource2), current2 = value.mediaLibraryMetadata;
|
|
538
|
+
if (current2?.associatedAccount !== aurn(account2)) throw new AdportError2("INVALID_INPUT", "linkedin: image has no selected-account library metadata to update");
|
|
539
|
+
const fields2 = { ...p.asset_name !== void 0 ? { assetName: z4.string().trim().min(1).max(200).parse(p.asset_name) } : {}, ...p.library_status !== void 0 ? { mediaLibraryStatus: z4.enum(["ACTIVE", "ARCHIVED"]).parse(p.library_status) } : {} };
|
|
540
|
+
if (!Object.keys(fields2).length) throw new AdportError2("INVALID_INPUT", "linkedin: provide image library changes");
|
|
541
|
+
return plan(`Update LinkedIn image library ${resource2}`, [`${JSON.stringify(fields2)}; current library ${current2.mediaLibraryStatus}, native processing ${value.status}. Image bytes and existing ad delivery remain unchanged.`], async () => {
|
|
542
|
+
await this.client.partialUpdate(`images/${encodeURIComponent(resource2)}`, { mediaLibraryMetadata: { $set: fields2 } }, { associatedAccount: aurn(account2) });
|
|
543
|
+
try {
|
|
544
|
+
if (!matches((await this.libraryImage(account2, resource2)).mediaLibraryMetadata, fields2)) throw new Error("metadata mismatch");
|
|
545
|
+
} catch {
|
|
546
|
+
throw new AdportError2("PROVIDER_ERROR", "linkedin: image-library update readback mismatch; reconcile before retrying", { resource_ids: [resource2] });
|
|
547
|
+
}
|
|
548
|
+
return { applied: true, resourceIds: [resource2] };
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
const resource = creativeUrn.parse(p.creative_id), current = await this.owned(account2, resource), path = `adAccounts/${account2}/creatives/${encodeURIComponent(resource)}`;
|
|
552
|
+
if (["REMOVED", "PENDING_DELETION", "CANCELED"].includes(current.intendedStatus)) throw new AdportError2("INVALID_INPUT", "linkedin: creative is already removed, canceled or pending deletion");
|
|
553
|
+
if (op.tool === "linkedin_delete_creative") {
|
|
554
|
+
const campaign = await this.provider.getCampaign(account2, current.campaign.split(":").at(-1)), direct = current.intendedStatus === "DRAFT" || campaign.status === "DRAFT";
|
|
555
|
+
return plan(`${direct ? "Delete" : "Request deletion of"} LinkedIn creative ${resource}`, [direct ? "Native DELETE removes this eligible draft/failed creative." : "Native PARTIAL_UPDATE sets intendedStatus PENDING_DELETION; this is a request, not proof of completed deletion."], async () => {
|
|
556
|
+
if (direct) {
|
|
557
|
+
await this.client.remove(path);
|
|
558
|
+
return { applied: true, resourceIds: [resource], details: { deletion: "DELETED" } };
|
|
559
|
+
}
|
|
560
|
+
const result = await this.update(account2, resource, path, { intendedStatus: "PENDING_DELETION" }, { intendedStatus: "PENDING_DELETION" });
|
|
561
|
+
return { ...result, details: { deletion: "PENDING_DELETION" } };
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
let fields, updatePath = path;
|
|
565
|
+
if (op.tool === "linkedin_update_text_ad") {
|
|
566
|
+
const input = updateText.parse(p), content2 = record(current.content), copy = textAd.safeParse(content2.textAd);
|
|
567
|
+
if (!copy.success || Object.keys(content2).some((key) => key !== "textAd")) throw new AdportError2("INVALID_INPUT", "linkedin: current text-ad content has unsupported fields; refusing a partial replacement");
|
|
568
|
+
if (input.image && (await this.image(account2, input.image)).status !== "AVAILABLE") throw new AdportError2("INVALID_INPUT", "linkedin: replacement image is not AVAILABLE");
|
|
569
|
+
fields = { content: { textAd: { ...copy.data, ...input.headline !== void 0 ? { headline: input.headline } : {}, ...input.description !== void 0 ? { description: input.description } : {}, ...input.landing_page !== void 0 ? { landingPage: input.landing_page } : {}, ...input.image !== void 0 ? { image: input.image } : {} } } };
|
|
570
|
+
updatePath = `creatives/${encodeURIComponent(resource)}`;
|
|
571
|
+
} else if (op.tool === "linkedin_rename_creative") fields = { name: z4.string().trim().min(1).max(200).parse(p.name) };
|
|
572
|
+
else if (op.tool === "linkedin_set_creative_status") {
|
|
573
|
+
const input = creativeStatus.parse(p);
|
|
574
|
+
if (input.status === "ACTIVE" && !input.non_political_consent) throw new AdportError2("INVALID_INPUT", `linkedin: activation requires explicit advertiser confirmation: ${NON_POLITICAL_CONSENT}`);
|
|
575
|
+
fields = { intendedStatus: input.status };
|
|
576
|
+
} else throw new AdportError2("INVALID_INPUT", `linkedin: unsupported creative write ${op.tool}`);
|
|
577
|
+
const expected = { ...fields, ...fields.intendedStatus === void 0 ? { intendedStatus: current.intendedStatus } : {} };
|
|
578
|
+
return plan(`Update LinkedIn creative ${resource}`, [...fields.intendedStatus === "ACTIVE" ? [NON_DISCRIMINATION_NOTICE, `Advertiser confirmation: ${NON_POLITICAL_CONSENT}`] : [], `Current intendedStatus ${current.intendedStatus}; only supplied fields change. Copy changes can trigger review. ${JSON.stringify(fields)}`], () => this.update(account2, resource, updatePath, fields, expected));
|
|
579
|
+
}
|
|
580
|
+
};
|
|
581
|
+
function matches(actual, expected) {
|
|
582
|
+
if (expected && typeof expected === "object" && !Array.isArray(expected)) return actual !== null && typeof actual === "object" && !Array.isArray(actual) && Object.entries(expected).every(([key, value]) => matches(actual[key], value));
|
|
583
|
+
return actual === expected;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// src/media.ts
|
|
587
|
+
import { createHash } from "crypto";
|
|
588
|
+
import { AdportError as AdportError3, LocalMediaResolver as LocalMediaResolver2, creativesOutput as creativesOutput2, defineTool as defineTool2, guardedWriteTool as guardedWriteTool2, mediaSourceFields as mediaSourceFields2 } from "@adport/core";
|
|
589
|
+
import { z as z5 } from "zod";
|
|
590
|
+
var videoUrn = z5.string().regex(/^urn:li:video:[A-Za-z0-9_-]+$/);
|
|
591
|
+
var documentUrn = z5.string().regex(/^urn:li:document:[A-Za-z0-9_-]+$/);
|
|
592
|
+
var name2 = z5.string().trim().min(1).max(200);
|
|
593
|
+
var hash = z5.string().regex(/^[a-f0-9]{64}$/);
|
|
594
|
+
var source = z5.object(mediaSourceFields2).refine((v) => Boolean(v.media_id) !== Boolean(v.file_path), "Choose project media_id or local file_path");
|
|
595
|
+
var uploadVideo = source.safeExtend({ name: name2, owner_organization: z5.string().regex(/^urn:li:organization:[1-9]\d*$/), campaign_id: linkedinId.optional() });
|
|
596
|
+
var uploadDocument = source.safeExtend({ name: name2 });
|
|
597
|
+
var updateVideo = z5.object({ video_id: videoUrn, expected_library_hash: hash, asset_name: name2.optional(), library_status: z5.enum(["ACTIVE", "ARCHIVED"]).optional() }).strict().refine((v) => v.asset_name !== void 0 || v.library_status !== void 0, "Provide video library changes");
|
|
598
|
+
var metadata = z5.looseObject({ associatedAccount: accountUrn, assetName: z5.string(), mediaLibraryStatus: z5.enum(["ACTIVE", "ARCHIVED"]) });
|
|
599
|
+
var videoSchema = z5.looseObject({ id: videoUrn, owner: z5.string(), status: z5.enum(["WAITING_UPLOAD", "PROCESSING", "PROCESSING_FAILED", "AVAILABLE"]), mediaLibraryMetadata: metadata.optional() });
|
|
600
|
+
var documentSchema = z5.looseObject({ id: documentUrn, owner: z5.string(), status: z5.enum(["WAITING_UPLOAD", "PROCESSING", "PROCESSING_FAILED", "AVAILABLE"]) });
|
|
601
|
+
var aurn2 = (account2) => `urn:li:sponsoredAccount:${linkedinId.parse(account2)}`;
|
|
602
|
+
var kinds = { linkedin_upload_video: "create", linkedin_upload_document: "create", linkedin_update_video: "update" };
|
|
603
|
+
var LINKEDIN_MEDIA_WRITES = new Set(Object.keys(kinds));
|
|
604
|
+
var snapshot = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
605
|
+
var libraryHash = (value) => snapshot({ id: value.id, owner: value.owner, status: value.status, associatedAccount: value.mediaLibraryMetadata?.associatedAccount, assetName: value.mediaLibraryMetadata?.assetName, mediaLibraryStatus: value.mediaLibraryMetadata?.mediaLibraryStatus });
|
|
606
|
+
var safeMediaUrl = (value) => {
|
|
607
|
+
if (typeof value !== "string") return void 0;
|
|
608
|
+
try {
|
|
609
|
+
const u = new URL(value);
|
|
610
|
+
return u.protocol === "https:" && !u.username && !u.password && (u.hostname === "licdn.com" || u.hostname.endsWith(".licdn.com")) ? value : void 0;
|
|
611
|
+
} catch {
|
|
612
|
+
return void 0;
|
|
613
|
+
}
|
|
614
|
+
};
|
|
615
|
+
var LinkedInMediaService = class {
|
|
616
|
+
constructor(client, provider, media = new LocalMediaResolver2()) {
|
|
617
|
+
this.client = client;
|
|
618
|
+
this.provider = provider;
|
|
619
|
+
this.media = media;
|
|
620
|
+
}
|
|
621
|
+
client;
|
|
622
|
+
provider;
|
|
623
|
+
media;
|
|
624
|
+
async context(account2, campaignId) {
|
|
625
|
+
const current = await this.provider.getAccount(linkedinId.parse(account2));
|
|
626
|
+
const campaign = campaignId ? await this.provider.getCampaign(account2, campaignId) : void 0, reference3 = campaign ? campaign.associatedEntity : current.reference;
|
|
627
|
+
const organization = typeof reference3 === "string" && /^urn:li:organization:[1-9]\d*$/.test(reference3) ? reference3 : void 0;
|
|
628
|
+
return { account_id: account2, account_status: current.status, ...campaignId ? { campaign_id: campaignId } : {}, ...organization ? { video_owner: organization } : {}, document_owner: aurn2(account2), video_upload_available: Boolean(organization), note: "Video uploads bind owner_organization to this account\u2019s reference or the selected owned campaign\u2019s associatedEntity and register in its media library. LinkedIn still checks Page ADMIN/DSC and rw_ads permissions at apply. No grant or Page access is inferred. PDF document uploads use the selected sponsored-account owner. Uploading does not create a post or ad." };
|
|
629
|
+
}
|
|
630
|
+
async page(account2, start, count2, status) {
|
|
631
|
+
const result = await this.client.get("videos", z5.looseObject({ elements: z5.array(videoSchema), paging: z5.object({ start: z5.number().int().nonnegative(), count: z5.number().int().nonnegative(), total: z5.number().int().nonnegative().optional(), links: z5.array(z5.looseObject({ rel: z5.string() })).optional() }).optional() }), { q: "associatedAccount", associatedAccount: aurn2(account2), ...status ? { mediaLibraryStatus: status } : {}, start, count: count2 });
|
|
632
|
+
if (result.elements.length > count2 || result.elements.some((v) => v.mediaLibraryMetadata?.associatedAccount !== aurn2(account2) || status && v.mediaLibraryMetadata.mediaLibraryStatus !== status) || result.paging && result.paging.start !== start || new Set(result.elements.map((v) => v.id)).size !== result.elements.length) throw new AdportError3("PROVIDER_ERROR", "linkedin: video library account/status/pagination mismatch");
|
|
633
|
+
const next = Boolean(result.paging?.links?.some((v) => v.rel === "next")) || (result.paging?.total !== void 0 ? start + result.elements.length < result.paging.total : result.elements.length >= count2);
|
|
634
|
+
if (next && !result.elements.length) throw new AdportError3("PROVIDER_ERROR", "linkedin: video library continuation did not advance");
|
|
635
|
+
return { items: result.elements, next };
|
|
636
|
+
}
|
|
637
|
+
async libraryVideo(account2, resource) {
|
|
638
|
+
videoUrn.parse(resource);
|
|
639
|
+
await this.provider.getAccount(linkedinId.parse(account2));
|
|
640
|
+
const seen = /* @__PURE__ */ new Set();
|
|
641
|
+
let start = 0;
|
|
642
|
+
while (start < 5e3) {
|
|
643
|
+
const page = await this.page(account2, start, 100);
|
|
644
|
+
if (page.items.some((v) => seen.has(v.id))) throw new AdportError3("PROVIDER_ERROR", "linkedin: video library repeated a resource");
|
|
645
|
+
const found = page.items.find((v) => v.id === resource);
|
|
646
|
+
if (found) return { ...found, library_snapshot_hash: libraryHash(found) };
|
|
647
|
+
if (!page.next) throw new AdportError3("INVALID_INPUT", "linkedin: video was not found in the selected account library");
|
|
648
|
+
page.items.forEach((v) => seen.add(v.id));
|
|
649
|
+
start += page.items.length;
|
|
650
|
+
}
|
|
651
|
+
throw new AdportError3("PROVIDER_ERROR", "linkedin: video membership is unconfirmed after 5,000 entries");
|
|
652
|
+
}
|
|
653
|
+
async videos(input) {
|
|
654
|
+
const account2 = linkedinId.parse(input.account_id);
|
|
655
|
+
await this.provider.getAccount(account2);
|
|
656
|
+
const result = await this.page(account2, input.start, input.count, input.library_status);
|
|
657
|
+
return { items: result.items.map((v) => ({ ...v, library_snapshot_hash: libraryHash(v) })), truncated: result.next, ...result.next ? { next_start: input.start + result.items.length } : {}, creatives: result.items.map((v) => {
|
|
658
|
+
const library = v.mediaLibraryMetadata, video = v.status === "AVAILABLE" ? safeMediaUrl(v.downloadUrl) : void 0, thumbnail = safeMediaUrl(v.thumbnail);
|
|
659
|
+
return { id: v.id, provider: "linkedin", account_id: account2, name: library.assetName, type: "VIDEO_ASSET", status: v.status, headlines: [], descriptions: [`Media library: ${library.mediaLibraryStatus}; processing: ${v.status}${typeof v.processingFailureReason === "string" ? ` \u2014 ${v.processingFailureReason}` : ""}`], landing_urls: [], media: video ? [{ type: "video", url: video, ...thumbnail ? { poster_url: thumbnail } : {} }] : thumbnail ? [{ type: "image", url: thumbnail }] : [], actions: [{ label: "Edit video library entry", tool: "linkedin_update_video", arguments: { account_id: account2, video_id: v.id, expected_library_hash: libraryHash(v) }, fields: [{ key: "asset_name", label: "Name", type: "text", value: library.assetName }, { key: "library_status", label: "Library status", type: "select", value: library.mediaLibraryStatus, options: [{ label: "Active in library", value: "ACTIVE" }, { label: "Archived in library", value: "ARCHIVED" }] }] }] };
|
|
660
|
+
}) };
|
|
661
|
+
}
|
|
662
|
+
async document(account2, resource) {
|
|
663
|
+
documentUrn.parse(resource);
|
|
664
|
+
await this.provider.getAccount(linkedinId.parse(account2));
|
|
665
|
+
const value = await this.client.get(`documents/${encodeURIComponent(resource)}`, documentSchema);
|
|
666
|
+
if (value.id !== resource || value.owner !== aurn2(account2)) throw new AdportError3("INVALID_INPUT", "linkedin: document is not owned by the selected sponsored account");
|
|
667
|
+
return value;
|
|
668
|
+
}
|
|
669
|
+
async plan(op) {
|
|
670
|
+
if (op.provider !== "linkedin" || !LINKEDIN_MEDIA_WRITES.has(op.tool) || op.kind !== kinds[op.tool]) throw new AdportError3("INVALID_INPUT", "linkedin: invalid media operation kind");
|
|
671
|
+
const account2 = linkedinId.parse(op.accountId);
|
|
672
|
+
if (op.tool === "linkedin_update_video") {
|
|
673
|
+
const input2 = updateVideo.parse(op.payload), current = await this.libraryVideo(account2, input2.video_id), library = current.mediaLibraryMetadata;
|
|
674
|
+
if (current.library_snapshot_hash !== input2.expected_library_hash) throw new AdportError3("PENDING_MISMATCH", "linkedin: video processing or library metadata changed; read the video again");
|
|
675
|
+
if (input2.library_status && input2.library_status !== library.mediaLibraryStatus && (input2.library_status === "ARCHIVED" ? !["AVAILABLE", "PROCESSING_FAILED"].includes(current.status) : current.status !== "AVAILABLE")) throw new AdportError3("INVALID_INPUT", "linkedin: native processing state does not permit this library archive transition");
|
|
676
|
+
const fields = { ...input2.asset_name ? { assetName: input2.asset_name } : {}, ...input2.library_status ? { mediaLibraryStatus: input2.library_status } : {} };
|
|
677
|
+
return this.planResult(`Update LinkedIn video library ${input2.video_id}`, [`${JSON.stringify(fields)}; source bytes, posts, ads and delivery statuses are preserved.`], async () => {
|
|
678
|
+
await this.client.partialUpdate(`videos/${encodeURIComponent(input2.video_id)}`, { mediaLibraryMetadata: { $set: fields } }, { associatedAccount: aurn2(account2) });
|
|
679
|
+
try {
|
|
680
|
+
const updated = (await this.libraryVideo(account2, input2.video_id)).mediaLibraryMetadata;
|
|
681
|
+
if (Object.entries(fields).some(([key, value]) => updated[key] !== value)) throw new Error("readback mismatch");
|
|
682
|
+
} catch {
|
|
683
|
+
throw new AdportError3("PROVIDER_ERROR", "linkedin: video library update acknowledged but readback not confirmed; reconcile before retrying", { resource_ids: [input2.video_id] });
|
|
684
|
+
}
|
|
685
|
+
return { applied: true, resourceIds: [input2.video_id] };
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
const isVideo = op.tool === "linkedin_upload_video", videoInput = isVideo ? uploadVideo.parse(op.payload) : void 0, input = videoInput ?? uploadDocument.parse(op.payload), context = await this.context(account2, videoInput?.campaign_id);
|
|
689
|
+
if (isVideo && !context.video_owner) throw new AdportError3("INVALID_INPUT", "linkedin: this account has no native organization reference for video ownership; establish the correct advertiser/Page association before uploading");
|
|
690
|
+
if (videoInput && context.video_owner !== videoInput.owner_organization) throw new AdportError3("PENDING_MISMATCH", "linkedin: requested organization does not match the current account/campaign reference; read media context again");
|
|
691
|
+
const file = await this.media.read(input, { maxBytes: isVideo ? 5e8 : 1e8, contentTypes: isVideo ? ["video/mp4"] : ["application/pdf"] });
|
|
692
|
+
if (isVideo && file.bytes.length < 75e3) throw new AdportError3("INVALID_INPUT", "linkedin: advertising videos must be at least 75 kB; duration and codec eligibility are checked during native processing");
|
|
693
|
+
return this.planResult(`Upload LinkedIn ${isVideo ? "video" : "PDF document"} \u201C${input.name}\u201D`, [`+ ${file.contentType}; ${file.bytes.length} bytes; SHA-256 ${file.sha256}.`, `Owner ${isVideo ? context.video_owner : context.document_owner}${isVideo ? `; account library ${aurn2(account2)}` : ""}.`, "Source bytes are immutable and rechecked at preview/apply. Native processing acceptance is separate from availability. No post, creative, campaign or delivery status is created or changed.", ...isVideo ? ["No captions or custom thumbnail are attached by this upload. LinkedIn can generate a default thumbnail. Page ADMIN/DSC permissions are checked natively at apply."] : ["PDF only in this workflow; LinkedIn validates document structure and its 300-page limit. Office formats remain a separate file-ingestion extension."]], async () => {
|
|
694
|
+
let resource, stage = "initialize";
|
|
695
|
+
try {
|
|
696
|
+
if (isVideo) {
|
|
697
|
+
const initialized = await this.client.action("videos", "initializeUpload", { initializeUploadRequest: { owner: context.video_owner, fileSizeBytes: file.bytes.length, uploadCaptions: false, uploadThumbnail: false, mediaLibraryMetadata: { associatedAccount: aurn2(account2), assetName: input.name } } }, z5.object({ value: z5.object({ video: videoUrn, uploadToken: z5.string(), uploadUrlsExpireAt: z5.number().int().positive(), uploadInstructions: z5.array(z5.object({ firstByte: z5.number().int().nonnegative(), lastByte: z5.number().int().nonnegative(), uploadUrl: z5.string().url() })).min(1).max(128) }) }));
|
|
698
|
+
const value = initialized.value;
|
|
699
|
+
resource = value.video;
|
|
700
|
+
stage = "validate upload instructions";
|
|
701
|
+
let offset = 0;
|
|
702
|
+
for (const [index, part] of value.uploadInstructions.entries()) {
|
|
703
|
+
if (part.firstByte !== offset || part.firstByte >= file.bytes.length || part.lastByte < part.firstByte || part.lastByte - part.firstByte + 1 > 4 * 1024 * 1024 || part.lastByte >= file.bytes.length && index !== value.uploadInstructions.length - 1) throw new Error("invalid native upload byte range");
|
|
704
|
+
this.client.validateMediaUpload(part.uploadUrl, "video", resource);
|
|
705
|
+
offset = Math.min(part.lastByte + 1, file.bytes.length);
|
|
706
|
+
}
|
|
707
|
+
if (offset !== file.bytes.length || value.uploadUrlsExpireAt <= Date.now()) throw new Error("incomplete or expired upload instructions");
|
|
708
|
+
const parts = [];
|
|
709
|
+
stage = "transfer video parts";
|
|
710
|
+
for (const part of value.uploadInstructions) parts.push(await this.client.uploadMedia(part.uploadUrl, file.bytes.subarray(part.firstByte, Math.min(part.lastByte + 1, file.bytes.length)), "video", resource));
|
|
711
|
+
if (new Set(parts).size !== parts.length) throw new Error("repeated native part acknowledgement");
|
|
712
|
+
stage = "finalize video";
|
|
713
|
+
await this.client.finalizeVideo({ finalizeUploadRequest: { video: resource, uploadToken: value.uploadToken, uploadedPartIds: parts } });
|
|
714
|
+
} else {
|
|
715
|
+
const initialized = await this.client.action("documents", "initializeUpload", { initializeUploadRequest: { owner: context.document_owner } }, z5.object({ value: z5.object({ document: documentUrn, uploadUrl: z5.string().url(), uploadUrlExpiresAt: z5.number().int().positive() }) }));
|
|
716
|
+
resource = initialized.value.document;
|
|
717
|
+
stage = "transfer document";
|
|
718
|
+
if (initialized.value.uploadUrlExpiresAt <= Date.now()) throw new Error("expired document upload URL");
|
|
719
|
+
await this.client.uploadMedia(initialized.value.uploadUrl, file.bytes, "document", resource);
|
|
720
|
+
}
|
|
721
|
+
} catch (error) {
|
|
722
|
+
throw new AdportError3("PROVIDER_ERROR", `linkedin: ${stage} was not confirmed. No mutation was retried. Reconcile the returned native ID before another upload.`, { resource_ids: resource ? [resource] : [], stage, ...error instanceof AdportError3 ? { reason: error.message } : {} });
|
|
723
|
+
}
|
|
724
|
+
return { applied: true, resourceIds: [resource], details: { status: "UPLOAD_ACCEPTED", processing_complete: false, sha256: file.sha256, byte_length: file.bytes.length, next_tool: isVideo ? "linkedin_get_library_video" : "linkedin_get_document" } };
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
planResult(summary, changes, execute) {
|
|
728
|
+
return { summary, changes, coercions: [], budgetDeltas: [], notes: ["Preview is local; LinkedIn has no server dry-run for media. Uploads can remain WAITING_UPLOAD/PROCESSING or fail native processing. No request is automatically retried."], execute };
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
function linkedinMediaTools(provider) {
|
|
732
|
+
const account2 = { account_id: linkedinId };
|
|
733
|
+
return [
|
|
734
|
+
defineTool2({ name: "linkedin_media_context", namespace: "linkedin", description: "Read the account organization reference or an owned campaign\u2019s associatedEntity for video ownership, plus the sponsored-account document owner. Pass video_owner as owner_organization on upload. Does not infer Page permissions or request new grants.", input: z5.object({ ...account2, campaign_id: linkedinId.optional() }), annotations: { readOnly: true }, handler: (v) => provider.media.context(v.account_id, v.campaign_id) }),
|
|
735
|
+
defineTool2({ name: "linkedin_videos", namespace: "linkedin", description: "View account-library video readiness, actual native previews and bound name/archive actions. ACTIVE/ARCHIVED describe library visibility, not ad delivery. Continue next_start as start.", input: z5.object({ ...account2, library_status: z5.enum(["ACTIVE", "ARCHIVED"]).optional(), start: z5.number().int().nonnegative().default(0), count: z5.number().int().min(1).max(100).default(20) }), output: creativesOutput2.passthrough(), annotations: { readOnly: true }, presentation: "creatives", pagination: { cursorInput: "start", cursorOutput: "next_start" }, handler: (v) => provider.media.videos(v) }),
|
|
736
|
+
defineTool2({ name: "linkedin_get_library_video", namespace: "linkedin", description: "Resolve an exact video through the selected account\u2019s media-library finder, including archived entries. Returns processing status and library_snapshot_hash; membership lookup is bounded to 5,000 entries.", input: z5.object({ ...account2, video_id: videoUrn }), annotations: { readOnly: true }, handler: (v) => provider.media.libraryVideo(v.account_id, v.video_id) }),
|
|
737
|
+
defineTool2({ name: "linkedin_get_document", namespace: "linkedin", description: "Read a PDF document\u2019s native processing status and expiring download URL, requiring its owner to match the selected sponsored account. Organization/member-owned documents need their own access workflow.", input: z5.object({ ...account2, document_id: documentUrn }), annotations: { readOnly: true }, handler: (v) => provider.media.document(v.account_id, v.document_id) }),
|
|
738
|
+
guardedWriteTool2({ name: "linkedin_upload_video", namespace: "linkedin", provider: "linkedin", kind: "create", destructive: false, description: "Upload checksum-bound MP4 parts and finalize in the account\u2019s video library. owner_organization must match media context; optional campaign_id selects its owned associatedEntity. Native Page ADMIN/DSC permission required. No post/ad is created. Processing readiness is a separate read; hosted uploads use media_id.", payload: uploadVideo }),
|
|
739
|
+
guardedWriteTool2({ name: "linkedin_upload_document", namespace: "linkedin", provider: "linkedin", kind: "create", destructive: false, description: "Upload a checksum-bound PDF owned by the selected sponsored account. No post or ad is published; native processing and the 300-page limit are checked separately. Hosted uploads use media_id. Office formats are not accepted by this tool.", payload: uploadDocument }),
|
|
740
|
+
guardedWriteTool2({ name: "linkedin_update_video", namespace: "linkedin", provider: "linkedin", kind: "update", description: "Rename or archive/unarchive an account-library video with expected_library_hash. Native processing transitions are checked; bytes, posts and ad delivery remain unchanged. Readback verifies the metadata update.", payload: updateVideo })
|
|
741
|
+
];
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// src/management.ts
|
|
745
|
+
import { AdportError as AdportError4 } from "@adport/core";
|
|
746
|
+
import { z as z7 } from "zod";
|
|
747
|
+
|
|
748
|
+
// src/management-tools.ts
|
|
749
|
+
import { defineTool as defineTool3, guardedWriteTool as guardedWriteTool3 } from "@adport/core";
|
|
750
|
+
import { z as z6 } from "zod";
|
|
751
|
+
var micros2 = z6.number().int().positive().safe();
|
|
752
|
+
var time = z6.number().int().positive().safe();
|
|
753
|
+
var name3 = z6.string().trim().min(1).refine((value) => Buffer.byteLength(value, "utf8") <= 200, "Name must fit 200 UTF-8 bytes");
|
|
754
|
+
var groupCreate = z6.object({ name: name3, start_time: time, end_time: time.optional(), total_budget_micros: micros2.optional(), status: z6.enum(["DRAFT", "ACTIVE"]).default("DRAFT"), non_political_consent: z6.literal(true).optional().describe(`Required for ACTIVE creation: ${NON_POLITICAL_CONSENT}`) }).refine((v) => !v.end_time || v.end_time > v.start_time, "End must follow start").refine((v) => !v.total_budget_micros || Boolean(v.end_time), "Group total budget requires end_time");
|
|
755
|
+
var metadata2 = { name: name3.optional(), start_time: time.optional(), end_time: time.optional() };
|
|
756
|
+
var updateCampaign = z6.object({ campaign_id: linkedinId, ...metadata2 }).refine((v) => Object.keys(v).length > 1, "Provide campaign changes");
|
|
757
|
+
var updateGroup = z6.object({ campaign_group_id: linkedinId, ...metadata2 }).refine((v) => Object.keys(v).length > 1, "Provide campaign-group changes");
|
|
758
|
+
var targetingUpdate = z6.object({ campaign_id: linkedinId, targeting_criteria: targetingSchema.optional(), audience_expansion_enabled: z6.boolean().optional() }).refine((v) => v.targeting_criteria !== void 0 || v.audience_expansion_enabled !== void 0, "Provide targeting or explicit expansion settings");
|
|
759
|
+
var isGeoFacet = (facet) => ["urn:li:adTargetingFacet:locations", "urn:li:adTargetingFacet:profileLocations"].includes(facet);
|
|
760
|
+
var targetingEntitiesInput = z6.object({
|
|
761
|
+
account_id: linkedinId,
|
|
762
|
+
facet: z6.string().regex(/^urn:li:adTargetingFacet:[A-Za-z]+$/),
|
|
763
|
+
query: z6.string().trim().min(1).max(255).optional().describe("Search text selects native typeahead; required for locations/profileLocations."),
|
|
764
|
+
entity_type: z6.enum(["AGE", "COMPANY", "COMPANY_SIZE", "DEGREE", "FIELD_OF_STUDY", "FUNCTION", "GENDER", "GROUP", "INDUSTRY", "INTEREST", "LOCALE", "SCHOOL", "SENIORITY", "SKILL", "TITLE", "YEARS_OF_EXPERIENCE", "MEMBER_BEHAVIOR"]).optional(),
|
|
765
|
+
use_case: z6.literal("CONNECTED_TELEVISION_ONLY_CAMPAIGN").optional(),
|
|
766
|
+
locale: z6.object({ language: z6.string().regex(/^[a-z]{2}$/), country: z6.string().regex(/^[A-Z]{2}$/) }).strict().optional(),
|
|
767
|
+
start: z6.number().int().nonnegative().safe().default(0),
|
|
768
|
+
count: z6.number().int().min(1).max(100).default(50)
|
|
769
|
+
}).strict().superRefine((value, ctx) => {
|
|
770
|
+
if (!value.query && isGeoFacet(value.facet)) ctx.addIssue({ code: "custom", path: ["query"], message: "Location facets require a typeahead query after the Bing Geo migration" });
|
|
771
|
+
if (!value.query && (value.entity_type || value.use_case)) ctx.addIssue({ code: "custom", path: ["query"], message: "entity_type/use_case require a typeahead query" });
|
|
772
|
+
if (!Number.isSafeInteger(value.start + value.count)) ctx.addIssue({ code: "custom", path: ["start"], message: "Pagination offset exceeds the safe integer range" });
|
|
773
|
+
});
|
|
774
|
+
function linkedinManagementTools(provider) {
|
|
775
|
+
const account2 = { account_id: linkedinId };
|
|
776
|
+
const read = (name5, description3, input, handler) => defineTool3({ name: name5, namespace: "linkedin", description: description3, input, annotations: { readOnly: true }, handler });
|
|
777
|
+
const write = (name5, description3, payload, kind = "update") => guardedWriteTool3({ name: name5, namespace: "linkedin", provider: "linkedin", description: description3, payload, kind });
|
|
778
|
+
return [
|
|
779
|
+
read("linkedin_get_campaign", "Read exact account-owned campaign settings, native targeting, bid, budgets and schedule.", z6.object({ ...account2, campaign_id: linkedinId }), (v) => provider.getCampaign(v.account_id, v.campaign_id)),
|
|
780
|
+
read("linkedin_get_campaign_group", "Read one account-owned campaign group, including shared/dynamic budget settings and schedule.", z6.object({ ...account2, campaign_group_id: linkedinId }), (v) => provider.management.group(v.account_id, v.campaign_group_id)),
|
|
781
|
+
read("linkedin_targeting_facets", `Read available native targeting facets and supported entity finders. ${NON_DISCRIMINATION_NOTICE}`, z6.object(account2), (v) => provider.management.facets(v.account_id)),
|
|
782
|
+
read("linkedin_targeting_entities", `Search native targeting entities with query (typeahead), or browse a supported facet without query. Locations/profileLocations require query and return modern geo URNs. Missing or contradictory paging is reported as unknown completeness. ${NON_DISCRIMINATION_NOTICE}`, targetingEntitiesInput, (v) => provider.management.entities(v)),
|
|
783
|
+
write("linkedin_create_campaign_group", "Create a native DRAFT campaign group. paused_creation coerces requested ACTIVE to non-serving DRAFT because LinkedIn does not create groups as PAUSED. Optional total cap uses micros.", groupCreate, "create"),
|
|
784
|
+
write("linkedin_update_campaign_group", "Edit supplied group name/start/end fields, preserving the existing schedule. Does not change status or budgeting mode.", updateGroup),
|
|
785
|
+
write("linkedin_set_campaign_group_status", "Pause, activate or archive an owned group. Activation requires explicit advertiser confirmation; affects eligibility of all contained campaigns.", z6.object({ campaign_group_id: linkedinId, status: z6.enum(["ACTIVE", "PAUSED", "ARCHIVED"]), non_political_consent: z6.literal(true).optional() })),
|
|
786
|
+
write("linkedin_set_campaign_group_budget", "Change an existing ordinary group lifetime cap in micros, preserving currency and end time. Dynamic group-budget mode is rejected.", z6.object({ campaign_group_id: linkedinId, budget_micros: micros2 })),
|
|
787
|
+
write("linkedin_delete_campaign_group", "Delete an empty draft group or request PENDING_DELETION for other states. Rejects groups containing non-removed campaigns; clean children first.", z6.object({ campaign_group_id: linkedinId }), "remove"),
|
|
788
|
+
write("linkedin_update_campaign", "Edit supplied campaign name/start/end fields, preserving omitted settings and status.", updateCampaign),
|
|
789
|
+
write("linkedin_update_targeting", `Replace supplied include clauses while preserving an omitted exclusion clause. Expansion changes must be explicit. ${NON_DISCRIMINATION_NOTICE}`, targetingUpdate),
|
|
790
|
+
write("linkedin_set_bid", "Change an existing campaign unitCost in integer micros, preserving its currency, pricing model and bidding strategy. Current value is required for policy checks.", z6.object({ campaign_id: linkedinId, bid_micros: micros2 })),
|
|
791
|
+
write("linkedin_delete_campaign", "Delete a draft campaign or request PENDING_DELETION for a non-draft. Rejects campaigns with non-removed creatives; clean children first.", z6.object({ campaign_id: linkedinId }), "remove")
|
|
792
|
+
];
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// src/management.ts
|
|
796
|
+
var row2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
797
|
+
var accountUrn2 = (account2) => `urn:li:sponsoredAccount:${linkedinId.parse(account2)}`;
|
|
798
|
+
var terminal = (status) => ["REMOVED", "PENDING_DELETION", "CANCELED", "CANCELLED"].includes(String(status));
|
|
799
|
+
var schedule = z7.object({ start: z7.number().int().positive().safe(), end: z7.number().int().positive().safe().optional() }).strict();
|
|
800
|
+
var LinkedInManagementService = class {
|
|
801
|
+
constructor(client, provider) {
|
|
802
|
+
this.client = client;
|
|
803
|
+
this.provider = provider;
|
|
804
|
+
}
|
|
805
|
+
client;
|
|
806
|
+
provider;
|
|
807
|
+
async group(account2, resource) {
|
|
808
|
+
const value = await this.client.get(`adAccounts/${linkedinId.parse(account2)}/adCampaignGroups/${linkedinId.parse(resource)}`, groupSchema);
|
|
809
|
+
if (String(value.id) !== resource || value.account !== accountUrn2(account2)) throw new AdportError4("INVALID_INPUT", "linkedin: campaign-group account/ID mismatch");
|
|
810
|
+
return value;
|
|
811
|
+
}
|
|
812
|
+
async facets(account2) {
|
|
813
|
+
await this.provider.getAccount(account2);
|
|
814
|
+
return this.client.get("adTargetingFacets", z7.object({ elements: z7.array(z7.record(z7.string(), z7.unknown())) }));
|
|
815
|
+
}
|
|
816
|
+
async entities(raw) {
|
|
817
|
+
const input = targetingEntitiesInput.parse(raw);
|
|
818
|
+
await this.provider.getAccount(input.account_id);
|
|
819
|
+
const value = await this.client.get("adTargetingEntities", z7.looseObject({ elements: z7.array(z7.record(z7.string(), z7.unknown())), paging: z7.looseObject({ start: z7.number().int().nonnegative().safe(), count: z7.number().int().nonnegative().safe(), total: z7.number().int().nonnegative().safe().optional(), links: z7.array(z7.looseObject({ rel: z7.string() })).optional() }).optional() }), { q: input.query ? "typeahead" : "adTargetingFacet", facet: input.facet, queryVersion: "QUERY_USES_URNS", ...input.query ? { query: input.query } : {}, ...input.entity_type ? { entityType: input.entity_type } : {}, ...input.use_case ? { useCase: input.use_case } : {}, ...input.locale ? { locale: input.locale } : {}, start: input.start, count: input.count });
|
|
820
|
+
if (value.paging && value.paging.start !== input.start) throw new AdportError4("PROVIDER_ERROR", "linkedin: targeting pagination changed its offset");
|
|
821
|
+
if (value.elements.length > input.count || value.paging && value.elements.length > value.paging.count) throw new AdportError4("PROVIDER_ERROR", "linkedin: targeting response exceeds its page size");
|
|
822
|
+
for (const entity of value.elements) {
|
|
823
|
+
if (entity.facetUrn !== void 0 && entity.facetUrn !== input.facet) throw new AdportError4("PROVIDER_ERROR", "linkedin: targeting entity belongs to a different facet");
|
|
824
|
+
if (isGeoFacet(input.facet) && (typeof entity.urn !== "string" || !/^urn:li:geo:\d+$/.test(entity.urn))) throw new AdportError4("PROVIDER_ERROR", "linkedin: location typeahead returned a missing or legacy geo URN");
|
|
825
|
+
}
|
|
826
|
+
const paging6 = value.paging, end = input.start + value.elements.length;
|
|
827
|
+
const linkedNext = Boolean(paging6?.links?.some((link) => link.rel === "next"));
|
|
828
|
+
const contradictoryTotal = paging6?.total !== void 0 && (paging6.total < end || linkedNext && paging6.total <= end);
|
|
829
|
+
const notes2 = [];
|
|
830
|
+
if (!paging6) notes2.push("Native paging is absent; completeness and continuation are unknown.");
|
|
831
|
+
else if (paging6.count !== input.count) notes2.push("Native page size differs from the request; continuation is unknown.");
|
|
832
|
+
if (contradictoryTotal) notes2.push("Native total contradicts the returned records or next link; completeness is unknown.");
|
|
833
|
+
const canAdvance = paging6?.count === input.count;
|
|
834
|
+
const more = canAdvance && (linkedNext || (!contradictoryTotal && paging6?.total !== void 0 ? end < paging6.total : value.elements.length === input.count));
|
|
835
|
+
const complete = !paging6 || !canAdvance || contradictoryTotal ? null : !more;
|
|
836
|
+
return { ...value, complete, truncated: complete === null && !more ? null : more, ...more ? { next_start: input.start + input.count } : {}, ...notes2.length ? { notes: notes2 } : {} };
|
|
837
|
+
}
|
|
838
|
+
metadata(current, input) {
|
|
839
|
+
const fields = input.name !== void 0 ? { name: input.name } : {};
|
|
840
|
+
if (input.start_time !== void 0 || input.end_time !== void 0) {
|
|
841
|
+
const previous = current.runSchedule === void 0 ? void 0 : schedule.safeParse(current.runSchedule);
|
|
842
|
+
if (previous && !previous.success) throw new AdportError4("INVALID_INPUT", "linkedin: unsupported current schedule; refusing a partial reset");
|
|
843
|
+
const merged = { ...previous?.data ?? {}, ...input.start_time !== void 0 ? { start: input.start_time } : {}, ...input.end_time !== void 0 ? { end: input.end_time } : {} }, parsed = schedule.safeParse(merged);
|
|
844
|
+
if (!parsed.success || parsed.data.end !== void 0 && parsed.data.end <= parsed.data.start) throw new AdportError4("INVALID_INPUT", "linkedin: schedule needs start and an end later than start");
|
|
845
|
+
fields.runSchedule = parsed.data;
|
|
846
|
+
}
|
|
847
|
+
return fields;
|
|
848
|
+
}
|
|
849
|
+
async patch(account2, entity, resource, fields, expected) {
|
|
850
|
+
await this.client.update(`adAccounts/${account2}/${entity}/${resource}`, fields);
|
|
851
|
+
try {
|
|
852
|
+
const value = entity === "adCampaignGroups" ? await this.group(account2, resource) : await this.provider.getCampaign(account2, resource);
|
|
853
|
+
if (!matches2(value, expected)) throw new Error("settings mismatch");
|
|
854
|
+
} catch {
|
|
855
|
+
throw new AdportError4("PROVIDER_ERROR", "linkedin: management update readback mismatch; reconcile before retrying", { resource_ids: [resource] });
|
|
856
|
+
}
|
|
857
|
+
return { applied: true, resourceIds: [resource] };
|
|
858
|
+
}
|
|
859
|
+
async plan(op, guard) {
|
|
860
|
+
const account2 = linkedinId.parse(op.accountId), type = op.tool, p = op.payload, create = type === "linkedin_create_campaign_group", remove = ["linkedin_delete_campaign", "linkedin_delete_campaign_group"].includes(type);
|
|
861
|
+
if (op.provider !== "linkedin" || op.kind !== (create ? "create" : remove ? "remove" : "update")) throw new AdportError4("INVALID_INPUT", "linkedin: provider or management operation kind mismatch");
|
|
862
|
+
const plan = (summary, changes, execute, budgetDeltas = [], coercions = []) => ({ summary, changes, execute, budgetDeltas, coercions });
|
|
863
|
+
if (create) {
|
|
864
|
+
const input = groupCreate.parse(p), owner2 = await this.provider.getAccount(account2), status = guard.forcePausedCreation ? "DRAFT" : input.status;
|
|
865
|
+
if (status === "ACTIVE" && !input.non_political_consent) throw new AdportError4("INVALID_INPUT", `linkedin: active group creation requires explicit advertiser confirmation: ${NON_POLITICAL_CONSENT}`);
|
|
866
|
+
const fields2 = { account: accountUrn2(account2), name: input.name, runSchedule: { start: input.start_time, ...input.end_time ? { end: input.end_time } : {} }, status, ...input.total_budget_micros ? { totalBudget: { amount: microsToDecimal(input.total_budget_micros), currencyCode: owner2.currency } } : {} };
|
|
867
|
+
return plan("Create LinkedIn campaign group", [...status === "ACTIVE" ? [NON_DISCRIMINATION_NOTICE, `Advertiser confirmation: ${NON_POLITICAL_CONSENT}`] : [], `Native initial status ${status}; paused_creation uses non-serving DRAFT. ${JSON.stringify(fields2)}`], async () => {
|
|
868
|
+
const resource2 = await this.client.create(`adAccounts/${account2}/adCampaignGroups`, fields2);
|
|
869
|
+
try {
|
|
870
|
+
if (!matches2(await this.group(account2, resource2), fields2)) throw new Error("settings mismatch");
|
|
871
|
+
} catch {
|
|
872
|
+
throw new AdportError4("PROVIDER_ERROR", "linkedin: created group readback mismatch; reconcile before retrying", { resource_ids: [resource2] });
|
|
873
|
+
}
|
|
874
|
+
return { applied: true, resourceIds: [resource2] };
|
|
875
|
+
}, input.total_budget_micros ? [{ target: "new campaign-group total cap", toMicros: input.total_budget_micros }] : [], input.status !== status ? ["status coerced to non-serving DRAFT by policy (paused_creation); native group creation does not accept PAUSED"] : []);
|
|
876
|
+
}
|
|
877
|
+
const isGroup = ["linkedin_update_campaign_group", "linkedin_set_campaign_group_status", "linkedin_set_campaign_group_budget", "linkedin_delete_campaign_group"].includes(type), resource = linkedinId.parse(p[isGroup ? "campaign_group_id" : "campaign_id"]), entity = isGroup ? "adCampaignGroups" : "adCampaigns";
|
|
878
|
+
const current = isGroup ? await this.group(account2, resource) : await this.provider.getCampaign(account2, resource);
|
|
879
|
+
if (terminal(current.status)) throw new AdportError4("INVALID_INPUT", "linkedin: resource is removed, canceled or pending deletion");
|
|
880
|
+
if (remove) {
|
|
881
|
+
if (isGroup) {
|
|
882
|
+
const children = (await this.provider.listCampaigns(account2)).filter((value) => value.campaignGroup === `urn:li:sponsoredCampaignGroup:${resource}` && value.status !== "REMOVED");
|
|
883
|
+
if (children.length) throw new AdportError4("INVALID_INPUT", "linkedin: remove contained campaigns before deleting their group");
|
|
884
|
+
} else {
|
|
885
|
+
const children = await this.provider.creatives.list({ account_id: account2, campaign_ids: [resource], statuses: ["ACTIVE", "PAUSED", "DRAFT", "ARCHIVED", "CANCELED", "PENDING_DELETION"], page_size: 1, include_media: false });
|
|
886
|
+
if (children.items.length || children.truncated) throw new AdportError4("INVALID_INPUT", "linkedin: remove contained creatives before deleting their campaign");
|
|
887
|
+
}
|
|
888
|
+
const direct = current.status === "DRAFT";
|
|
889
|
+
return plan(`${direct ? "Delete" : "Request deletion of"} LinkedIn ${isGroup ? "campaign group" : "campaign"} ${resource}`, [direct ? "Native DELETE for an empty draft." : "Set status PENDING_DELETION; this requests removal and does not prove completion."], async () => {
|
|
890
|
+
if (direct) {
|
|
891
|
+
await this.client.remove(`adAccounts/${account2}/${entity}/${resource}`);
|
|
892
|
+
return { applied: true, resourceIds: [resource], details: { deletion: "DELETED" } };
|
|
893
|
+
}
|
|
894
|
+
const result = await this.patch(account2, entity, resource, { status: "PENDING_DELETION" }, { status: "PENDING_DELETION" });
|
|
895
|
+
return { ...result, details: { deletion: "PENDING_DELETION" } };
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
let fields, money3 = [], notices3 = [];
|
|
899
|
+
if (type === "linkedin_update_campaign_group" || type === "linkedin_update_campaign") fields = this.metadata(current, isGroup ? updateGroup.parse(p) : updateCampaign.parse(p));
|
|
900
|
+
else if (type === "linkedin_set_campaign_group_status") {
|
|
901
|
+
const status = z7.enum(["ACTIVE", "PAUSED", "ARCHIVED"]).parse(p.status);
|
|
902
|
+
if (status === "ACTIVE" && p.non_political_consent !== true) throw new AdportError4("INVALID_INPUT", `linkedin: group activation requires explicit advertiser confirmation: ${NON_POLITICAL_CONSENT}`);
|
|
903
|
+
fields = { status };
|
|
904
|
+
if (status === "ACTIVE") notices3 = [NON_DISCRIMINATION_NOTICE, `Advertiser confirmation: ${NON_POLITICAL_CONSENT}`];
|
|
905
|
+
} else if (type === "linkedin_set_campaign_group_budget" || type === "linkedin_set_bid") {
|
|
906
|
+
if (isGroup && row2(current.budgetOptimization).budgetOptimizationStrategy === "DYNAMIC") throw new AdportError4("INVALID_INPUT", "linkedin: dynamic shared group budgets require a dedicated policy-aware workflow");
|
|
907
|
+
const key = isGroup ? "totalBudget" : "unitCost", previous = moneySchema.safeParse(current[key]);
|
|
908
|
+
if (!previous.success) throw new AdportError4("INVALID_INPUT", "linkedin: current native money value/currency is unavailable");
|
|
909
|
+
if (previous.data.currencyCode !== (await this.provider.getAccount(account2)).currency) throw new AdportError4("INVALID_INPUT", "linkedin: current money currency differs from the selected account");
|
|
910
|
+
if (isGroup && !schedule.safeParse(current.runSchedule).data?.end) throw new AdportError4("INVALID_INPUT", "linkedin: group lifetime cap requires an existing end date");
|
|
911
|
+
const target = z7.number().int().positive().safe().parse(p[isGroup ? "budget_micros" : "bid_micros"]);
|
|
912
|
+
fields = { [key]: { amount: microsToDecimal(target), currencyCode: previous.data.currencyCode } };
|
|
913
|
+
money3 = [{ target: `${entity}/${resource} ${key}`, fromMicros: decimalToMicros(previous.data.amount), toMicros: target }];
|
|
914
|
+
if (!isGroup && current.campaignGroup) {
|
|
915
|
+
const group = await this.group(account2, String(current.campaignGroup).split(":").at(-1));
|
|
916
|
+
if (row2(group.budgetOptimization).budgetOptimizationStrategy === "DYNAMIC") throw new AdportError4("INVALID_INPUT", "linkedin: campaign bid is managed by its dynamic campaign group");
|
|
917
|
+
}
|
|
918
|
+
} else if (type === "linkedin_update_targeting") {
|
|
919
|
+
const input = targetingUpdate.parse(p);
|
|
920
|
+
fields = {};
|
|
921
|
+
if (input.targeting_criteria) {
|
|
922
|
+
for (const facets2 of [...input.targeting_criteria.include.and.map((clause) => clause.or), input.targeting_criteria.exclude?.or ?? {}]) if (Object.keys(facets2).some((key) => ["urn:li:adTargetingFacet:audienceMatchingSegments", "urn:li:adTargetingFacet:dynamicSegments"].includes(key))) throw new AdportError4("INVALID_INPUT", "linkedin: custom audience reference edits require a dedicated account-availability workflow");
|
|
923
|
+
const previous = targetingSchema.safeParse(current.targetingCriteria);
|
|
924
|
+
if (!previous.success) throw new AdportError4("INVALID_INPUT", "linkedin: current targeting is unsupported; refusing a partial reset");
|
|
925
|
+
const merged = { ...previous.data, ...input.targeting_criteria };
|
|
926
|
+
validateTargeting(merged);
|
|
927
|
+
fields.targetingCriteria = merged;
|
|
928
|
+
}
|
|
929
|
+
if (input.audience_expansion_enabled !== void 0) fields.audienceExpansionEnabled = input.audience_expansion_enabled;
|
|
930
|
+
notices3 = [NON_DISCRIMINATION_NOTICE];
|
|
931
|
+
} else throw new AdportError4("INVALID_INPUT", `linkedin: unsupported management write ${type}`);
|
|
932
|
+
const expected = { ...fields, ...fields.status === void 0 ? { status: current.status } : {} };
|
|
933
|
+
return plan(`Update LinkedIn ${isGroup ? "campaign group" : "campaign"} ${resource}`, [...notices3, `${JSON.stringify(fields)}; omitted fields and current delivery status remain unchanged.`], () => this.patch(account2, entity, resource, fields, expected), money3);
|
|
934
|
+
}
|
|
935
|
+
};
|
|
936
|
+
function validateTargeting(value) {
|
|
937
|
+
const keys = value.include.and.flatMap((clause) => Object.keys(clause.or)), modern = ["urn:li:adTargetingFacet:locations", "urn:li:adTargetingFacet:profileLocations"];
|
|
938
|
+
if (value.include.and.some((clause) => !Object.keys(clause.or).length) || !modern.some((key) => keys.includes(key)) || modern.every((key) => keys.includes(key))) throw new AdportError4("INVALID_INPUT", "linkedin: targeting needs non-empty clauses and exactly one modern geo facet");
|
|
939
|
+
for (const clause of value.include.and) for (const [facet, values] of Object.entries(clause.or)) if (modern.includes(facet) && values.some((value2) => !/^urn:li:geo:[1-9]\d*$/.test(value2))) throw new AdportError4("INVALID_INPUT", "linkedin: targeting requires modern urn:li:geo identifiers");
|
|
940
|
+
}
|
|
941
|
+
function matches2(actual, expected) {
|
|
942
|
+
if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((value) => actual.some((candidate) => matches2(candidate, value)));
|
|
943
|
+
if (moneySchema.safeParse(expected).success) {
|
|
944
|
+
const target = moneySchema.parse(expected), value = moneySchema.safeParse(actual);
|
|
945
|
+
return value.success && target.currencyCode === value.data.currencyCode && decimalToMicros(target.amount) === decimalToMicros(value.data.amount);
|
|
946
|
+
}
|
|
947
|
+
if (expected && typeof expected === "object") return actual !== null && typeof actual === "object" && !Array.isArray(actual) && Object.entries(expected).every(([key, value]) => matches2(actual[key], value));
|
|
948
|
+
return actual === expected;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
// src/sponsored.ts
|
|
952
|
+
import { createHash as createHash4 } from "crypto";
|
|
953
|
+
import { AdportError as AdportError8 } from "@adport/core";
|
|
954
|
+
import { z as z11 } from "zod";
|
|
955
|
+
|
|
956
|
+
// src/sponsored-tools.ts
|
|
957
|
+
import { creativesOutput as creativesOutput4, defineTool as defineTool6, guardedWriteTool as guardedWriteTool6 } from "@adport/core";
|
|
958
|
+
import { z as z10 } from "zod";
|
|
959
|
+
|
|
960
|
+
// src/lead-creatives.ts
|
|
961
|
+
import { createHash as createHash3 } from "crypto";
|
|
962
|
+
import { AdportError as AdportError7, creativesOutput as creativesOutput3, defineTool as defineTool5, guardedWriteTool as guardedWriteTool5 } from "@adport/core";
|
|
963
|
+
import { z as z9 } from "zod";
|
|
964
|
+
|
|
965
|
+
// src/lead-forms.ts
|
|
966
|
+
import { createHash as createHash2 } from "crypto";
|
|
967
|
+
import { AdportError as AdportError6, defineTool as defineTool4, guardedWriteTool as guardedWriteTool4 } from "@adport/core";
|
|
968
|
+
import { z as z8 } from "zod";
|
|
969
|
+
|
|
970
|
+
// src/paging.ts
|
|
971
|
+
import { AdportError as AdportError5 } from "@adport/core";
|
|
972
|
+
function linkedinPageState(result, start, count2, resource) {
|
|
973
|
+
const p = result.paging;
|
|
974
|
+
if (result.elements.length > count2 || p && (p.start !== start || p.count > count2 || p.count < result.elements.length) || !p && start > 0) throw new AdportError5("PROVIDER_ERROR", "linkedin: measurement pagination returned an inconsistent offset or size");
|
|
975
|
+
const total = p?.total !== void 0 && p.total >= 0 ? p.total : void 0;
|
|
976
|
+
const next = Boolean(p?.links?.some((link) => link.rel === "next")) || (total !== void 0 ? start + result.elements.length < total : result.elements.length === (p?.count ?? count2));
|
|
977
|
+
if (next && (!result.elements.length || p?.count === 0) || total !== void 0 && result.elements.length && start + result.elements.length > total) throw new AdportError5("PROVIDER_ERROR", "linkedin: measurement pagination did not advance or contradicted its total");
|
|
978
|
+
let offset = start + (total === void 0 ? result.elements.length : p?.count ?? count2);
|
|
979
|
+
for (const link of p?.links ?? []) if (link.rel === "next" && link.href) {
|
|
980
|
+
try {
|
|
981
|
+
const url3 = new URL(link.href, `https://api.linkedin.com/rest/${resource}`), value = url3.searchParams.get("start"), candidate = value && /^\d+$/.test(value) ? Number(value) : NaN;
|
|
982
|
+
if (url3.origin === "https://api.linkedin.com" && url3.pathname === `/rest/${resource}` && url3.searchParams.getAll("start").length === 1 && Number.isSafeInteger(candidate) && candidate > start && candidate >= start + result.elements.length && candidate <= start + p.count) offset = candidate;
|
|
983
|
+
} catch {
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
return { truncated: next, complete: p ? start === 0 && !next : null, ...next && p ? { next_start: offset } : {}, ...!p ? { notes: ["Native paging metadata is absent; collection completeness is unknown and no continuation is invented."] } : p.total !== void 0 && p.total < 0 ? { notes: ["The native total is negative and is not a row count. Paging uses native links and returned segments."] } : {} };
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
// src/lead-forms.ts
|
|
990
|
+
var hash2 = z8.string().regex(/^[a-f0-9]{64}$/);
|
|
991
|
+
var leadFormId = linkedinId.max(19).refine((value) => /^[1-9]\d{0,18}$/.test(value) && BigInt(value) <= 9223372036854775807n, "Use an exact signed Long form ID");
|
|
992
|
+
var formId = leadFormId;
|
|
993
|
+
var nativeId = z8.union([formId, z8.number().int().positive().safe()]).transform(String);
|
|
994
|
+
var locale = z8.object({ country: z8.string().regex(/^[A-Z]{2}$/), language: z8.string().regex(/^[a-z]{2}$/), variant: z8.string().regex(/^[A-Za-z0-9]+$/).max(32).optional() }).strict();
|
|
995
|
+
var text = z8.object({ localized: z8.record(z8.string().regex(/^[a-z]{2}(?:_[A-Z]{2})?(?:_[A-Za-z0-9]+)?$/), z8.string().min(1).max(8192)).refine((value) => Object.keys(value).length > 0 && Object.keys(value).length <= 100) }).strict();
|
|
996
|
+
var url = z8.string().url().max(4096).refine((value) => {
|
|
997
|
+
const parsed = new URL(value);
|
|
998
|
+
return ["http:", "https:"].includes(parsed.protocol) && !parsed.username && !parsed.password;
|
|
999
|
+
}, "Use an HTTP(S) URL without credentials");
|
|
1000
|
+
var optionId = z8.number().int().nonnegative().max(2147483647);
|
|
1001
|
+
var option = z8.object({ id: optionId, text, label: z8.string().min(1).max(200).optional() }).strict();
|
|
1002
|
+
var choice = z8.object({ options: z8.array(option).min(1).max(100), defaultSelectedOption: optionId.optional() }).strict().refine((value) => new Set(value.options.map((item) => item.id)).size === value.options.length && (value.defaultSelectedOption === void 0 || value.options.some((item) => item.id === value.defaultSelectedOption)), "Use unique option IDs and an existing default option");
|
|
1003
|
+
var predefined = z8.enum(["FIRST_NAME", "LAST_NAME", "PHONE_NUMBER", "EMAIL", "CITY", "STATE", "COUNTRY", "ZIP_CODE", "JOB_TITLE", "JOB_FUNCTION", "SENIORITY", "COMPANY_NAME", "COMPANY_SIZE", "INDUSTRY", "DEGREE", "FIELD_OF_STUDY", "SCHOOL", "START_DATE", "GRADUATION_DATE", "GENDER", "WORK_EMAIL", "LINKEDIN_PROFILE_LINK", "WORK_PHONE_NUMBER"]);
|
|
1004
|
+
var question = z8.object({ name: z8.string().min(1).max(200), question: text, textPrompt: text.optional(), predefinedField: predefined.optional(), responseEditable: z8.boolean().optional(), responseRequired: z8.boolean().optional(), questionDetails: z8.union([
|
|
1005
|
+
z8.object({ textQuestionDetails: z8.object({ defaultResponse: z8.string().max(8192).optional(), maxResponseLength: z8.number().int().positive().max(1e5).optional() }).strict() }).strict(),
|
|
1006
|
+
z8.object({ multipleChoiceQuestionDetails: choice }).strict()
|
|
1007
|
+
]), questionSubmissionCriteria: z8.object({ workEmailSubmissionCriteria: z8.object({ freemiumEmailAllowed: z8.boolean() }).strict() }).strict().optional(), label: z8.string().min(1).max(200).optional() }).strict().refine((value) => !value.questionSubmissionCriteria || value.predefinedField === "WORK_EMAIL", "Work email criteria require WORK_EMAIL");
|
|
1008
|
+
var questions = z8.array(question).min(1).max(100).refine((value) => new Set(value.map((item) => item.name)).size === value.length && new Set(value.flatMap((item) => item.label ? [item.label] : [])).size === value.filter((item) => item.label).length, "Question names and labels must be unique");
|
|
1009
|
+
var consent = z8.object({ id: optionId, consent: text, checkRequired: z8.boolean(), label: z8.string().min(1).max(200).optional() }).strict();
|
|
1010
|
+
var legal = z8.object({ privacyPolicyUrl: url.optional(), legalDisclaimer: text.refine((value) => Object.values(value.localized).every((item) => item.length <= 2e3)).optional(), consents: z8.array(consent).max(100).refine((value) => new Set(value.map((item) => item.id)).size === value.length, "Consent IDs must be unique").optional() }).strict();
|
|
1011
|
+
var cta = z8.object({ callToActionLabel: z8.enum(["VISIT_COMPANY_WEBSITE", "LEARN_MORE", "VIEW_NOW", "DOWNLOAD_NOW", "TRY_NOW"]), callToActionTarget: z8.object({ landingPageUrl: url }).strict().optional() }).strict();
|
|
1012
|
+
var submission = z8.object({ message: text, callToAction: cta }).strict();
|
|
1013
|
+
var content = z8.object({ headline: text, description: text.optional(), questions, legalInfo: legal, postSubmissionInfo: submission.optional() }).strict();
|
|
1014
|
+
var editContent = content.partial().extend({ postSubmissionInfo: submission.partial().optional() });
|
|
1015
|
+
var hidden = z8.array(z8.object({ name: z8.string().min(1).max(200), value: z8.string().max(8192) }).strict()).max(20).refine((value) => new Set(value.map((item) => item.name)).size === value.length, "Hidden-field names must be unique");
|
|
1016
|
+
var createInput = z8.object({ expected_account_hash: hash2, name: z8.string().trim().min(1).max(200), creation_locale: locale, content, hidden_fields: hidden.default([]) }).strict();
|
|
1017
|
+
var clear = z8.enum(["description", "legal_disclaimer", "post_submission_info"]);
|
|
1018
|
+
var updateInput = z8.object({ form_id: formId, expected_snapshot_hash: hash2, name: z8.string().trim().min(1).max(200).optional(), creation_locale: locale.optional(), content: editContent.optional(), hidden_fields: hidden.optional(), clear_fields: z8.array(clear).max(3).default([]) }).strict();
|
|
1019
|
+
var archiveInput = z8.object({ form_id: formId, expected_snapshot_hash: hash2 }).strict();
|
|
1020
|
+
var pageInput = z8.object({ account_id: linkedinId, start: z8.number().int().nonnegative().safe().default(0), count: z8.number().int().min(1).max(100).default(25) }).strict();
|
|
1021
|
+
var owner = z8.union([z8.object({ sponsoredAccount: accountUrn }).strict(), z8.object({ organization: z8.string().regex(/^urn:li:organization:[1-9]\d*$/) }).strict()]);
|
|
1022
|
+
var native = z8.looseObject({ id: nativeId, owner, creationLocale: locale, name: z8.string(), state: z8.string(), content: z8.record(z8.string(), z8.unknown()), hiddenFields: z8.array(z8.record(z8.string(), z8.unknown())).optional(), versionId: z8.number().int().nonnegative().safe().optional(), versionTag: z8.string().optional(), created: z8.number().int().nonnegative().safe().optional(), lastModified: z8.number().int().nonnegative().safe().optional() });
|
|
1023
|
+
var publicForm = native.extend({ id: formId, snapshot_hash: hash2 });
|
|
1024
|
+
var contextOutput = { account_id: linkedinId, currency: z8.string(), account_snapshot_hash: hash2 };
|
|
1025
|
+
var paging = z8.looseObject({ start: z8.number().int().nonnegative().safe(), count: z8.number().int().nonnegative().safe(), total: z8.number().int().safe().optional(), links: z8.array(z8.looseObject({ rel: z8.string(), href: z8.string().optional() })).optional() });
|
|
1026
|
+
var records = z8.array(z8.record(z8.string(), z8.unknown()));
|
|
1027
|
+
var writes = /* @__PURE__ */ new Set(["linkedin_create_lead_form_draft", "linkedin_update_lead_form", "linkedin_archive_lead_form"]);
|
|
1028
|
+
var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1029
|
+
var canonical = (value) => Array.isArray(value) ? value.map(canonical) : object(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;
|
|
1030
|
+
var digest = (value) => createHash2("sha256").update(JSON.stringify(canonical(value))).digest("hex");
|
|
1031
|
+
var same = (a, b) => JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
|
|
1032
|
+
var account = (value) => `urn:li:sponsoredAccount:${linkedinId.parse(value)}`;
|
|
1033
|
+
var snapshot2 = (value) => digest(Object.fromEntries(Object.entries(value).filter(([key]) => !["created", "lastModified"].includes(key))));
|
|
1034
|
+
var notes = ["Form configuration only. No submitted leads are read, no lead is generated and no ad is created or activated.", "Native writes are not automatically retried. Reconcile returned resource IDs after an uncertain result."];
|
|
1035
|
+
var structural = /* @__PURE__ */ new Set(["content", "legalInfo", "postSubmissionInfo"]);
|
|
1036
|
+
var labels = { name: "Name", creationLocale: "Preferred locale", hiddenFields: "Hidden fields", headline: "Headline", description: "Description", questions: "Questions", privacyPolicyUrl: "Privacy policy URL", legalDisclaimer: "Legal disclaimer", consents: "Consents", message: "Thank-you message", callToAction: "Thank-you action" };
|
|
1037
|
+
var clearPaths = { description: ["content", "description"], legal_disclaimer: ["content", "legalInfo", "legalDisclaimer"], post_submission_info: ["content", "postSubmissionInfo"] };
|
|
1038
|
+
function at(value, path) {
|
|
1039
|
+
for (const key of path) value = object(value) ? value[key] : void 0;
|
|
1040
|
+
return value;
|
|
1041
|
+
}
|
|
1042
|
+
function requestedMatch(actual, expected, key = "") {
|
|
1043
|
+
if (key === "localized") return same(actual, expected);
|
|
1044
|
+
if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((item, index) => requestedMatch(actual[index], item));
|
|
1045
|
+
if (object(expected)) return object(actual) && Object.entries(expected).every(([key2, item]) => requestedMatch(actual[key2], item, key2));
|
|
1046
|
+
return same(actual, expected);
|
|
1047
|
+
}
|
|
1048
|
+
function fieldsOf(current, requested) {
|
|
1049
|
+
return Object.entries(requested).flatMap(([key, after]) => structural.has(key) && object(after) ? fieldsOf(object(current) ? current[key] : void 0, after) : [{ label: labels[key] ?? key, ...object(current) && Object.hasOwn(current, key) ? { before: current[key] } : {}, after }]);
|
|
1050
|
+
}
|
|
1051
|
+
function wireContent(value) {
|
|
1052
|
+
if (!object(value)) return value;
|
|
1053
|
+
const omit = (row4, key) => Object.fromEntries(Object.entries(row4).filter(([field]) => field !== key));
|
|
1054
|
+
return {
|
|
1055
|
+
...value,
|
|
1056
|
+
...Array.isArray(value.questions) ? { questions: value.questions.map((item) => object(item) ? omit(item, "questionId") : item) } : {},
|
|
1057
|
+
...object(value.legalInfo) ? { legalInfo: omit(value.legalInfo, "legalInfoId") } : {}
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
function validateLocale(value, preferred) {
|
|
1061
|
+
if (Array.isArray(value)) {
|
|
1062
|
+
for (const item of value) validateLocale(item, preferred);
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
if (!object(value)) return;
|
|
1066
|
+
if (object(value.localized) && typeof value.localized[preferred] !== "string") throw new AdportError6("INVALID_INPUT", "linkedin: every localized form string must contain the preferred creation locale");
|
|
1067
|
+
for (const [key, item] of Object.entries(value)) if (key !== "localized") validateLocale(item, preferred);
|
|
1068
|
+
}
|
|
1069
|
+
function merge(current, requested) {
|
|
1070
|
+
return { ...current, ...Object.fromEntries(Object.entries(requested).map(([key, item]) => [key, structural.has(key) && object(item) && object(current[key]) ? merge(current[key], item) : item])) };
|
|
1071
|
+
}
|
|
1072
|
+
var LinkedInLeadFormService = class {
|
|
1073
|
+
constructor(client, provider) {
|
|
1074
|
+
this.client = client;
|
|
1075
|
+
this.provider = provider;
|
|
1076
|
+
}
|
|
1077
|
+
client;
|
|
1078
|
+
provider;
|
|
1079
|
+
supports(tool) {
|
|
1080
|
+
return writes.has(tool);
|
|
1081
|
+
}
|
|
1082
|
+
async context(selected) {
|
|
1083
|
+
const value = await this.provider.getAccount(linkedinId.parse(selected));
|
|
1084
|
+
return { account_id: selected, currency: value.currency, account_snapshot_hash: digest({ id: value.id, currency: value.currency, status: value.status }) };
|
|
1085
|
+
}
|
|
1086
|
+
owned(selected, value, selectedForm) {
|
|
1087
|
+
if (!("sponsoredAccount" in value.owner) || value.owner.sponsoredAccount !== account(selected) || selectedForm !== void 0 && value.id !== selectedForm) throw new AdportError6("PROVIDER_ERROR", "linkedin: lead form owner or ID does not match the selected advertiser");
|
|
1088
|
+
return { ...value, snapshot_hash: snapshot2(value) };
|
|
1089
|
+
}
|
|
1090
|
+
async one(selected, form) {
|
|
1091
|
+
return this.owned(selected, await this.client.get(`leadForms/${formId.parse(form)}`, native), form);
|
|
1092
|
+
}
|
|
1093
|
+
record(value) {
|
|
1094
|
+
const preferred = [value.creationLocale.language, value.creationLocale.country, value.creationLocale.variant].filter(Boolean).join("_");
|
|
1095
|
+
const headline2 = object(value.content.headline) && object(value.content.headline.localized) ? value.content.headline.localized[preferred] : void 0;
|
|
1096
|
+
return { id: value.id, name: value.name, status: value.state, locale: preferred, ...typeof headline2 === "string" ? { headline: headline2 } : {}, ...Array.isArray(value.content.questions) ? { questions: value.content.questions.length } : {}, ...value.versionId !== void 0 ? { version: value.versionId } : {} };
|
|
1097
|
+
}
|
|
1098
|
+
async list(raw) {
|
|
1099
|
+
const input = pageInput.parse(raw), context = await this.context(input.account_id);
|
|
1100
|
+
const page = await this.client.get("leadForms", z8.looseObject({ elements: z8.array(native), paging: paging.optional() }), { q: "owner", owner: { sponsoredAccount: account(input.account_id) }, start: input.start, count: input.count });
|
|
1101
|
+
const elements = page.elements.map((value) => this.owned(input.account_id, value));
|
|
1102
|
+
if (new Set(elements.map((value) => value.id)).size !== elements.length) throw new AdportError6("PROVIDER_ERROR", "linkedin: repeated lead form identity");
|
|
1103
|
+
const state = linkedinPageState(page, input.start, input.count, "leadForms");
|
|
1104
|
+
return { ...context, ...page, elements, records: elements.map((value) => this.record(value)), ...state, notes: [...notes, ...state.notes ?? []] };
|
|
1105
|
+
}
|
|
1106
|
+
async get(selected, form) {
|
|
1107
|
+
const context = await this.context(selected), value = await this.one(selected, form);
|
|
1108
|
+
return { ...context, form: value, records: [this.record(value)], notes };
|
|
1109
|
+
}
|
|
1110
|
+
async verified(resource, check) {
|
|
1111
|
+
try {
|
|
1112
|
+
if (!await check()) throw new Error("configuration mismatch");
|
|
1113
|
+
} catch {
|
|
1114
|
+
throw new AdportError6("PROVIDER_ERROR", "linkedin: lead form write readback unconfirmed; reconcile returned resource ID before another approval", { resource_ids: [resource] });
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
async plan(op) {
|
|
1118
|
+
const create = op.tool === "linkedin_create_lead_form_draft";
|
|
1119
|
+
if (op.provider !== "linkedin" || !writes.has(op.tool) || op.kind !== (create ? "create" : "update")) throw new AdportError6("INVALID_INPUT", "linkedin: lead form operation kind mismatch");
|
|
1120
|
+
const context = await this.context(op.accountId), base2 = { coercions: [], budgetDeltas: [], notes };
|
|
1121
|
+
if (create) {
|
|
1122
|
+
const input2 = createInput.parse(op.payload);
|
|
1123
|
+
if (input2.expected_account_hash !== context.account_snapshot_hash) throw new AdportError6("INVALID_INPUT", "linkedin: advertiser snapshot changed; read its lead forms again");
|
|
1124
|
+
const body = { owner: { sponsoredAccount: account(op.accountId) }, name: input2.name, creationLocale: input2.creation_locale, content: input2.content, hiddenFields: input2.hidden_fields, state: "DRAFT" };
|
|
1125
|
+
if (Buffer.byteLength(JSON.stringify(body)) > 256 * 1024) throw new AdportError6("INVALID_INPUT", "linkedin: form configuration exceeds 256 KiB");
|
|
1126
|
+
validateLocale(body.content, [input2.creation_locale.language, input2.creation_locale.country, input2.creation_locale.variant].filter(Boolean).join("_"));
|
|
1127
|
+
return { ...base2, summary: `Create LinkedIn lead form draft "${input2.name}"`, changes: [`+ ${JSON.stringify(body)}`], review: { provider: "linkedin", accountId: op.accountId, kind: "create", title: "Create lead form draft", subject: input2.name, fields: [{ label: "State", after: "DRAFT" }, ...fieldsOf(void 0, { creationLocale: body.creationLocale, content: body.content, hiddenFields: body.hiddenFields })], notices: ["Draft only. No creative is linked and no form is published. Omitted question/CTA settings use native defaults reported by readback."] }, execute: async () => {
|
|
1128
|
+
const resource = await this.client.create("leadForms", body);
|
|
1129
|
+
await this.verified(resource, async () => requestedMatch(await this.one(op.accountId, resource), body));
|
|
1130
|
+
return { applied: true, resourceIds: [resource] };
|
|
1131
|
+
} };
|
|
1132
|
+
}
|
|
1133
|
+
const input = op.tool === "linkedin_archive_lead_form" ? archiveInput.parse(op.payload) : updateInput.parse(op.payload), current = await this.one(op.accountId, input.form_id);
|
|
1134
|
+
if (current.snapshot_hash !== input.expected_snapshot_hash) throw new AdportError6("INVALID_INPUT", "linkedin: lead form snapshot changed; read the current form");
|
|
1135
|
+
if (op.tool === "linkedin_archive_lead_form") {
|
|
1136
|
+
if (current.state !== "PUBLISHED") throw new AdportError6("INVALID_INPUT", "linkedin: the documented archive transition requires a PUBLISHED form");
|
|
1137
|
+
return { ...base2, summary: `Archive LinkedIn lead form "${current.name}"`, changes: ["~ state PUBLISHED \u2192 ARCHIVED"], review: { provider: "linkedin", accountId: op.accountId, kind: "update", title: "Archive lead form", subject: current.name, fields: [{ label: "State", before: current.state, after: "ARCHIVED" }], notices: ["Archiving changes whether this form and its linked creatives can serve. No restore transition is exposed by this tool."] }, execute: async () => {
|
|
1138
|
+
await this.client.partialUpdate(`leadForms/${current.id}`, { $set: { state: "ARCHIVED" } });
|
|
1139
|
+
await this.verified(current.id, async () => (await this.one(op.accountId, current.id)).state === "ARCHIVED");
|
|
1140
|
+
return { applied: true, resourceIds: [current.id] };
|
|
1141
|
+
} };
|
|
1142
|
+
}
|
|
1143
|
+
const update = updateInput.parse(op.payload);
|
|
1144
|
+
if (!["DRAFT", "PUBLISHED"].includes(current.state)) throw new AdportError6("INVALID_INPUT", "linkedin: this form state cannot be edited");
|
|
1145
|
+
if (update.content?.postSubmissionInfo && !object(current.content.postSubmissionInfo) && !submission.safeParse(update.content.postSubmissionInfo).success) throw new AdportError6("INVALID_INPUT", "linkedin: adding thank-you information requires both message and callToAction");
|
|
1146
|
+
const requested = { ...update.name !== void 0 ? { name: update.name } : {}, ...update.creation_locale ? { creationLocale: update.creation_locale } : {}, ...update.content ? { content: update.content } : {}, ...update.hidden_fields ? { hiddenFields: update.hidden_fields } : {} };
|
|
1147
|
+
if (Buffer.byteLength(JSON.stringify(requested)) > 256 * 1024) throw new AdportError6("INVALID_INPUT", "linkedin: form configuration exceeds 256 KiB");
|
|
1148
|
+
if (current.state === "PUBLISHED" && (update.name !== void 0 || update.creation_locale || update.hidden_fields || update.content?.questions || update.content?.legalInfo?.consents)) throw new AdportError6("INVALID_INPUT", "linkedin: schema/name/locale/hidden-field edits require DRAFT; published forms allow copy, legal URL/disclaimer and thank-you edits subject to native eligibility");
|
|
1149
|
+
const removed = [], review = fieldsOf(current, requested);
|
|
1150
|
+
for (const field of new Set(update.clear_fields)) {
|
|
1151
|
+
const path = clearPaths[field];
|
|
1152
|
+
if (at(requested, path) !== void 0 || at(current, path) === void 0) throw new AdportError6("INVALID_INPUT", "linkedin: a cleared field must exist and cannot also be supplied");
|
|
1153
|
+
removed.push(path);
|
|
1154
|
+
review.push({ label: labels[path.at(-1)] ?? field, before: at(current, path), after: null });
|
|
1155
|
+
}
|
|
1156
|
+
const wanted = merge(current, requested), preferred = update.creation_locale ?? current.creationLocale;
|
|
1157
|
+
for (const path of removed) {
|
|
1158
|
+
let target = wanted;
|
|
1159
|
+
for (const key of path.slice(0, -1)) {
|
|
1160
|
+
target[key] = { ...target[key] };
|
|
1161
|
+
target = target[key];
|
|
1162
|
+
}
|
|
1163
|
+
delete target[path.at(-1)];
|
|
1164
|
+
}
|
|
1165
|
+
validateLocale(wanted.content, [preferred.language, preferred.country, preferred.variant].filter(Boolean).join("_"));
|
|
1166
|
+
if (requestedMatch(current, requested) && !removed.length) throw new AdportError6("INVALID_INPUT", "linkedin: no supplied form settings would change");
|
|
1167
|
+
const set = Object.fromEntries(Object.keys(requested).map((key) => [key, wanted[key]]));
|
|
1168
|
+
if (update.content || removed.length) set.content = wanted.content;
|
|
1169
|
+
const patch = { $set: { ...set, ...set.content ? { content: wireContent(set.content) } : {} } };
|
|
1170
|
+
if (Buffer.byteLength(JSON.stringify(patch)) > 256 * 1024) throw new AdportError6("INVALID_INPUT", "linkedin: merged form configuration exceeds 256 KiB");
|
|
1171
|
+
return { ...base2, summary: `Update LinkedIn lead form "${current.name}"`, changes: [`~ ${JSON.stringify(patch)}`], review: { provider: "linkedin", accountId: op.accountId, kind: "update", title: "Update lead form", subject: current.name, fields: review, notices: ["Supplied localized maps and question/consent/hidden-field arrays replace their previous values. Other settings remain unchanged.", "Question/schema edits can require CRM field remapping. LinkedIn determines published edit eligibility; forms linked to InMail or Conversation Ads may reject edits."] }, execute: async () => {
|
|
1172
|
+
await this.client.partialUpdate(`leadForms/${current.id}`, patch);
|
|
1173
|
+
await this.verified(current.id, async () => {
|
|
1174
|
+
const value = await this.one(op.accountId, current.id);
|
|
1175
|
+
return value.state === current.state && requestedMatch(value, set) && removed.every((path) => at(value, path) === void 0);
|
|
1176
|
+
});
|
|
1177
|
+
return { applied: true, resourceIds: [current.id] };
|
|
1178
|
+
} };
|
|
1179
|
+
}
|
|
1180
|
+
};
|
|
1181
|
+
function linkedinLeadFormTools(provider) {
|
|
1182
|
+
return [
|
|
1183
|
+
defineTool4({ name: "linkedin_lead_forms", namespace: "linkedin", description: "List advertiser-owned lead form configuration with exact string IDs, paging and snapshot hashes. No submitted leads or extra scopes.", input: pageInput, output: z8.looseObject({ ...contextOutput, elements: z8.array(publicForm), records, paging: paging.optional(), complete: z8.boolean().nullable(), truncated: z8.boolean(), next_start: z8.number().int().nonnegative().safe().optional(), notes: z8.array(z8.string()) }), presentation: "records", pagination: { cursorInput: "start", cursorOutput: "next_start" }, annotations: { readOnly: true }, handler: (input) => provider.leadForms.list(input) }),
|
|
1184
|
+
defineTool4({ name: "linkedin_get_lead_form", namespace: "linkedin", description: "Read one advertiser-owned lead form and its snapshot_hash. IDs must be exact decimal strings; form configuration excludes submitted lead data.", input: z8.object({ account_id: linkedinId, form_id: formId }).strict(), output: z8.object({ ...contextOutput, form: publicForm, records, notes: z8.array(z8.string()) }), presentation: "records", annotations: { readOnly: true }, handler: (input) => provider.leadForms.get(input.account_id, input.form_id) }),
|
|
1185
|
+
guardedWriteTool4({ name: "linkedin_create_lead_form_draft", namespace: "linkedin", provider: "linkedin", kind: "create", destructive: false, payload: createInput, description: "Create an advertiser-owned DRAFT with localized questions, legal/thank-you content and hidden fields. Bind expected_account_hash from linkedin_lead_forms. No publication, creative linking, lead collection or scope changes." }),
|
|
1186
|
+
guardedWriteTool4({ name: "linkedin_update_lead_form", namespace: "linkedin", provider: "linkedin", kind: "update", payload: updateInput, description: "Edit an owned form with expected_snapshot_hash. Full schema edits require DRAFT; published copy/legal/thank-you edits remain subject to native eligibility. Supplied arrays and localized maps replace; omitted settings stay. CRM remapping may be required." }),
|
|
1187
|
+
guardedWriteTool4({ name: "linkedin_archive_lead_form", namespace: "linkedin", provider: "linkedin", kind: "update", payload: archiveInput, description: "Archive a PUBLISHED owned form with expected_snapshot_hash. This can stop its linked creatives serving; no restore transition is exposed. No deletion or scope changes." })
|
|
1188
|
+
];
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
// src/lead-creatives.ts
|
|
1192
|
+
var id = leadFormId;
|
|
1193
|
+
var hash3 = z9.string().regex(/^[a-f0-9]{64}$/);
|
|
1194
|
+
var leadCta = z9.enum(["APPLY", "DOWNLOAD", "VIEW_QUOTE", "LEARN_MORE", "SIGN_UP", "SUBSCRIBE", "REGISTER", "REQUEST_DEMO", "JOIN", "ATTEND", "UNLOCK_FULL_DOCUMENT", "SHOP_NOW", "BUY_NOW", "SEE_MORE"]);
|
|
1195
|
+
var leadBinding = z9.object({ form_id: id, expected_form_hash: hash3, expected_campaign_hash: hash3, label: leadCta, gated_preview_page_count: z9.number().int().nonnegative().max(2147483647).optional(), confirm_public_post: z9.literal(true).optional(), expected_source_hash: hash3.optional() }).strict();
|
|
1196
|
+
var selection = { creative_id: creativeUrn, expected_creative_hash: hash3, form_id: id, expected_form_hash: hash3, expected_campaign_hash: hash3, label: leadCta };
|
|
1197
|
+
var updateInput2 = z9.object(selection).strict();
|
|
1198
|
+
var native2 = z9.looseObject({ id: creativeUrn, account: accountUrn, campaign: z9.string().regex(/^urn:li:sponsoredCampaign:[1-9]\d*$/), intendedStatus: z9.string(), content: z9.record(z9.string(), z9.unknown()).optional(), leadgenCallToAction: z9.looseObject({ destination: z9.string().regex(/^urn:li:adForm:[1-9]\d*$/), label: z9.string() }).optional() });
|
|
1199
|
+
var object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1200
|
+
var canonical2 = (value) => Array.isArray(value) ? value.map(canonical2) : object2(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, canonical2(child)])) : value;
|
|
1201
|
+
var digest2 = (value) => createHash3("sha256").update(JSON.stringify(canonical2(value)) ?? "undefined").digest("hex");
|
|
1202
|
+
var select = (value, keys) => Object.fromEntries(keys.filter((key) => Object.hasOwn(value, key)).map((key) => [key, value[key]]));
|
|
1203
|
+
var aurn3 = (account2) => `urn:li:sponsoredAccount:${linkedinId.parse(account2)}`;
|
|
1204
|
+
var postUrn = z9.string().regex(/^urn:li:(?:share|ugcPost):[1-9]\d*$/);
|
|
1205
|
+
var documentUrn2 = z9.string().regex(/^urn:li:document:[A-Za-z0-9_-]+$/);
|
|
1206
|
+
var terminal2 = /* @__PURE__ */ new Set(["REMOVED", "CANCELED", "PENDING_DELETION", "ARCHIVED"]);
|
|
1207
|
+
var formats = { STANDARD_UPDATE: "LEAD_GENERATION_FORM_SPONSORED_CONTENT", SINGLE_VIDEO: "VIDEO_LEAD_GENERATION_FORM_SPONSORED_CONTENT", CAROUSEL: "LEAD_GENERATION_FORM_CAROUSEL_SPONSORED_CONTENT", SPONSORED_UPDATE_NATIVE_DOCUMENT: "SPONSORED_UPDATE_NATIVE_DOCUMENT" };
|
|
1208
|
+
var notices = ["Form configuration only; no submitted leads are accessed.", "Changing an existing label can affect a serving ad. Changing the destination requires DRAFT; no creative or campaign is activated by this operation."];
|
|
1209
|
+
var LinkedInLeadCreativeService = class {
|
|
1210
|
+
constructor(client, provider) {
|
|
1211
|
+
this.client = client;
|
|
1212
|
+
this.provider = provider;
|
|
1213
|
+
}
|
|
1214
|
+
client;
|
|
1215
|
+
provider;
|
|
1216
|
+
supports(tool) {
|
|
1217
|
+
return tool === "linkedin_set_creative_lead_form";
|
|
1218
|
+
}
|
|
1219
|
+
campaignHash(campaign) {
|
|
1220
|
+
return digest2(select(campaign, ["id", "account", "status", "type", "format", "objectiveType", "associatedEntity"]));
|
|
1221
|
+
}
|
|
1222
|
+
creativeHash(creative) {
|
|
1223
|
+
return digest2(select(creative, ["id", "account", "campaign", "intendedStatus", "content", "name", "leadgenCallToAction"]));
|
|
1224
|
+
}
|
|
1225
|
+
sourceHash(creative) {
|
|
1226
|
+
return digest2(select(creative, ["id", "account", "campaign", "content"]));
|
|
1227
|
+
}
|
|
1228
|
+
campaign(campaign, contentFormat) {
|
|
1229
|
+
if (campaign.type !== "SPONSORED_UPDATES" || campaign.objectiveType !== "LEAD_GENERATION" || !Object.values(formats).includes(String(campaign.format)) || contentFormat && campaign.format !== formats[contentFormat]) throw new AdportError7("INVALID_INPUT", "linkedin: choose a supported sponsored-content LEAD_GENERATION campaign matching the selected content format");
|
|
1230
|
+
if (terminal2.has(String(campaign.status))) throw new AdportError7("INVALID_INPUT", "linkedin: lead-generation campaign is archived, canceled, removed or pending deletion");
|
|
1231
|
+
}
|
|
1232
|
+
async form(account2, formId2, eligible = true) {
|
|
1233
|
+
const result = await this.provider.leadForms.get(account2, id.parse(formId2));
|
|
1234
|
+
if (eligible && !["DRAFT", "PUBLISHED"].includes(result.form.state)) throw new AdportError7("INVALID_INPUT", "linkedin: lead form is not DRAFT or PUBLISHED");
|
|
1235
|
+
return result;
|
|
1236
|
+
}
|
|
1237
|
+
async createBinding(account2, campaign, raw, contentFormat) {
|
|
1238
|
+
const input = leadBinding.parse(raw);
|
|
1239
|
+
this.campaign(campaign, contentFormat);
|
|
1240
|
+
if (this.campaignHash(campaign) !== input.expected_campaign_hash) throw new AdportError7("PENDING_MISMATCH", "linkedin: lead campaign changed; read lead-ad context again");
|
|
1241
|
+
const result = await this.form(account2, input.form_id);
|
|
1242
|
+
if (result.form.snapshot_hash !== input.expected_form_hash) throw new AdportError7("PENDING_MISMATCH", "linkedin: lead form changed; read lead-ad context again");
|
|
1243
|
+
if (contentFormat !== "SPONSORED_UPDATE_NATIVE_DOCUMENT" && input.gated_preview_page_count !== void 0) throw new AdportError7("INVALID_INPUT", "linkedin: gated preview pages apply only to document lead ads");
|
|
1244
|
+
return { destination: `urn:li:adForm:${input.form_id}`, label: input.label };
|
|
1245
|
+
}
|
|
1246
|
+
async context(input) {
|
|
1247
|
+
const form = await this.form(input.account_id, input.form_id);
|
|
1248
|
+
const campaign = input.campaign_id ? await this.provider.getCampaign(input.account_id, input.campaign_id) : void 0;
|
|
1249
|
+
if (campaign) this.campaign(campaign);
|
|
1250
|
+
const source2 = input.source_creative_id ? await this.provider.creatives.owned(input.account_id, input.source_creative_id) : void 0;
|
|
1251
|
+
return { ...form, ...campaign ? { campaign, campaign_snapshot_hash: this.campaignHash(campaign) } : {}, ...source2 ? { source_creative: source2, source_snapshot_hash: this.sourceHash(source2) } : {}, notes: [...form.notes, "Use the returned form/campaign hashes for lead-ad creation. A source hash binds reference reuse; a lead-generation document must use freshly uploaded, unused document bytes."] };
|
|
1252
|
+
}
|
|
1253
|
+
async get(account2, creativeId, includePreview = false) {
|
|
1254
|
+
const creative = native2.parse(await this.provider.creatives.owned(account2, creativeId)), campaign = await this.provider.getCampaign(account2, creative.campaign.split(":").at(-1));
|
|
1255
|
+
this.campaign(campaign);
|
|
1256
|
+
const form = creative.leadgenCallToAction ? await this.form(account2, creative.leadgenCallToAction.destination.split(":").at(-1), false) : void 0;
|
|
1257
|
+
const hashes = { creative_snapshot_hash: this.creativeHash(creative), campaign_snapshot_hash: this.campaignHash(campaign) };
|
|
1258
|
+
const association2 = form ? [`Lead form: ${form.form.name}`, `Call to action: ${creative.leadgenCallToAction.label.replaceAll("_", " ")}`] : ["No lead form is attached."];
|
|
1259
|
+
let base2 = { id: creative.id, provider: "linkedin", account_id: account2, campaign_id: String(campaign.id), name: typeof creative.name === "string" ? creative.name : creative.id, type: "LEAD_GENERATION", status: creative.intendedStatus, headlines: [], descriptions: association2, landing_urls: [], media: [], actions: [] };
|
|
1260
|
+
const warnings = [];
|
|
1261
|
+
if (includePreview) {
|
|
1262
|
+
try {
|
|
1263
|
+
const metadata3 = await this.provider.sponsored.metadata(account2, creativeId);
|
|
1264
|
+
if (this.creativeHash(metadata3) !== hashes.creative_snapshot_hash) throw new Error("creative changed during preview");
|
|
1265
|
+
const card = this.provider.sponsored.metadataCard(account2, metadata3);
|
|
1266
|
+
base2 = { ...card, descriptions: [...card.descriptions, ...association2], actions: [] };
|
|
1267
|
+
if (!metadata3.metadata || metadata3.preview_warning) warnings.push({ provider: "linkedin", message: metadata3.preview_warning ?? "Native creative copy/media were not returned. Form association remains available." });
|
|
1268
|
+
} catch {
|
|
1269
|
+
warnings.push({ provider: "linkedin", message: "Native creative preview could not be verified. Form association remains available; read it again before an edit." });
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
return { account_id: account2, creative, campaign, ...hashes, ...form ? { form: form.form } : {}, creatives: [base2], warnings, truncated: false, notes: [...notices, ...creative.intendedStatus !== "DRAFT" ? ["The form destination is immutable outside DRAFT. Use an agent to select a new form on an eligible DRAFT creative."] : []] };
|
|
1273
|
+
}
|
|
1274
|
+
async assertUnusedDocument(account2, resource) {
|
|
1275
|
+
documentUrn2.parse(resource);
|
|
1276
|
+
const seen = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set(), checkedPosts = /* @__PURE__ */ new Set();
|
|
1277
|
+
let cursor;
|
|
1278
|
+
for (let page = 0; page < 50; page++) {
|
|
1279
|
+
const result = await this.client.get(`adAccounts/${linkedinId.parse(account2)}/creatives`, z9.looseObject({ elements: z9.array(native2), metadata: z9.object({ nextPageToken: z9.string().optional() }).optional() }), { q: "criteria", intendedStatuses: ["ACTIVE", "PAUSED", "DRAFT", "ARCHIVED", "CANCELED", "PENDING_DELETION", "REMOVED"], pageSize: 100, sortOrder: "ASCENDING", ...cursor ? { pageToken: cursor } : {} });
|
|
1280
|
+
if (result.elements.length > 100 || result.elements.some((value) => value.account !== aurn3(account2) || seen.has(value.id)) || new Set(result.elements.map((value) => value.id)).size !== result.elements.length) throw new AdportError7("PROVIDER_ERROR", "linkedin: document-use scan returned foreign or repeated creative identities");
|
|
1281
|
+
const references = /* @__PURE__ */ new Set();
|
|
1282
|
+
const collect = (value) => {
|
|
1283
|
+
if (Array.isArray(value)) {
|
|
1284
|
+
value.forEach(collect);
|
|
1285
|
+
return;
|
|
1286
|
+
}
|
|
1287
|
+
if (!object2(value)) return;
|
|
1288
|
+
for (const [key, child] of Object.entries(value)) {
|
|
1289
|
+
if (key === "reference" || key === "post") {
|
|
1290
|
+
const parsed = postUrn.safeParse(child);
|
|
1291
|
+
if (!parsed.success) throw new AdportError7("PROVIDER_ERROR", "linkedin: document-use reference shape is unconfirmed");
|
|
1292
|
+
references.add(parsed.data);
|
|
1293
|
+
} else collect(child);
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
for (const creative of result.elements) {
|
|
1297
|
+
seen.add(creative.id);
|
|
1298
|
+
collect(creative.content);
|
|
1299
|
+
}
|
|
1300
|
+
const wanted = [...references].filter((value) => !checkedPosts.has(value));
|
|
1301
|
+
let nextPost = 0, failure;
|
|
1302
|
+
await Promise.all(Array.from({ length: Math.min(4, wanted.length) }, async () => {
|
|
1303
|
+
while (!failure && nextPost < wanted.length) {
|
|
1304
|
+
const postId = wanted[nextPost++];
|
|
1305
|
+
try {
|
|
1306
|
+
const post = await this.client.get(`posts/${encodeURIComponent(postId)}`, z9.looseObject({ id: postUrn, content: z9.record(z9.string(), z9.unknown()).optional() }), { viewContext: "AUTHOR" });
|
|
1307
|
+
if (post.id !== postId) throw new AdportError7("PROVIDER_ERROR", "linkedin: document-use post ID mismatch");
|
|
1308
|
+
const media = object2(post.content?.media) ? post.content.media : {};
|
|
1309
|
+
if (media.id === resource) throw new AdportError7("INVALID_INPUT", "linkedin: document is already referenced by a creative; upload a fresh document for this lead ad");
|
|
1310
|
+
checkedPosts.add(postId);
|
|
1311
|
+
} catch (error) {
|
|
1312
|
+
failure = error;
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
}));
|
|
1316
|
+
if (failure) throw failure;
|
|
1317
|
+
const next = result.metadata?.nextPageToken;
|
|
1318
|
+
if (!next) return;
|
|
1319
|
+
if (!result.elements.length || cursors.has(next) || seen.size >= 5e3) throw new AdportError7("PROVIDER_ERROR", "linkedin: document-use scan is incomplete or exceeded 5,000 creatives; uniqueness is unconfirmed");
|
|
1320
|
+
cursors.add(next);
|
|
1321
|
+
cursor = next;
|
|
1322
|
+
}
|
|
1323
|
+
throw new AdportError7("PROVIDER_ERROR", "linkedin: document-use scan did not finish; uniqueness is unconfirmed");
|
|
1324
|
+
}
|
|
1325
|
+
async plan(op) {
|
|
1326
|
+
if (op.provider !== "linkedin" || !this.supports(op.tool) || op.kind !== "update") throw new AdportError7("INVALID_INPUT", "linkedin: lead creative operation kind mismatch");
|
|
1327
|
+
const input = updateInput2.parse(op.payload), current = await this.get(op.accountId, input.creative_id), form = await this.form(op.accountId, input.form_id);
|
|
1328
|
+
if (current.creative_snapshot_hash !== input.expected_creative_hash || current.campaign_snapshot_hash !== input.expected_campaign_hash || form.form.snapshot_hash !== input.expected_form_hash) throw new AdportError7("PENDING_MISMATCH", "linkedin: creative, campaign or form changed; read current context again");
|
|
1329
|
+
if (terminal2.has(current.creative.intendedStatus)) throw new AdportError7("INVALID_INPUT", "linkedin: creative is archived, canceled, removed or pending deletion");
|
|
1330
|
+
const previous = current.creative.leadgenCallToAction, wanted = { destination: `urn:li:adForm:${input.form_id}`, label: input.label };
|
|
1331
|
+
if (current.creative.intendedStatus !== "DRAFT" && previous?.destination !== wanted.destination) throw new AdportError7("INVALID_INPUT", "linkedin: form destination can change only while a creative is DRAFT");
|
|
1332
|
+
if (digest2(previous) === digest2(wanted)) throw new AdportError7("INVALID_INPUT", "linkedin: form and label already match the requested values");
|
|
1333
|
+
const fields = [{ label: "Lead form", before: previous?.destination ?? null, after: wanted.destination }, { label: "Call to action", before: previous?.label ?? null, after: wanted.label }];
|
|
1334
|
+
return { summary: `Update LinkedIn creative lead form ${input.creative_id}`, changes: fields.map((value) => `~ ${value.label}: ${JSON.stringify(value.before)} \u2192 ${JSON.stringify(value.after)}`), budgetDeltas: [], coercions: [], review: { provider: "linkedin", accountId: op.accountId, kind: "update", title: "Edit lead form association", subject: current.creatives[0].name, fields, notices }, execute: async () => {
|
|
1335
|
+
await this.client.update(`adAccounts/${op.accountId}/creatives/${encodeURIComponent(input.creative_id)}`, { leadgenCallToAction: wanted });
|
|
1336
|
+
try {
|
|
1337
|
+
const readback = await this.provider.creatives.owned(op.accountId, input.creative_id);
|
|
1338
|
+
const expected = { ...current.creative, leadgenCallToAction: wanted };
|
|
1339
|
+
if (this.creativeHash(readback) !== this.creativeHash(expected)) throw new Error("creative config changed");
|
|
1340
|
+
} catch {
|
|
1341
|
+
throw new AdportError7("PROVIDER_ERROR", "linkedin: lead creative write readback unconfirmed; reconcile resource ID before a new approval", { resource_ids: [input.creative_id] });
|
|
1342
|
+
}
|
|
1343
|
+
return { applied: true, resourceIds: [input.creative_id], details: { lead_form_id: input.form_id, intended_status: current.creative.intendedStatus, next_tool: "linkedin_creative_lead_form" } };
|
|
1344
|
+
} };
|
|
1345
|
+
}
|
|
1346
|
+
};
|
|
1347
|
+
function linkedinLeadCreativeTools(provider) {
|
|
1348
|
+
return [
|
|
1349
|
+
defineTool5({ name: "linkedin_lead_ad_context", namespace: "linkedin", description: "Read an advertiser-owned lead form plus optional supported LEAD_GENERATION campaign/source creative, with creation hashes. No submitted leads. Native Page permissions are separate from form access.", input: z9.object({ account_id: linkedinId, form_id: id, campaign_id: linkedinId.optional(), source_creative_id: creativeUrn.optional() }).strict(), output: z9.looseObject({ account_id: linkedinId, records: z9.array(z9.record(z9.string(), z9.unknown())) }), presentation: "records", annotations: { readOnly: true }, handler: (input) => provider.leadCreatives.context(input) }),
|
|
1350
|
+
defineTool5({ name: "linkedin_creative_lead_form", namespace: "linkedin", description: "View a creative\u2019s owned lead form, CTA and hashes, with verified native copy/media when available. Agents prepare label or DRAFT-destination edits for the normal native approval card.", input: z9.object({ account_id: linkedinId, creative_id: creativeUrn }).strict(), output: creativesOutput3.passthrough(), presentation: "creatives", annotations: { readOnly: true }, handler: (input) => provider.leadCreatives.get(input.account_id, input.creative_id, true) }),
|
|
1351
|
+
guardedWriteTool5({ name: "linkedin_set_creative_lead_form", namespace: "linkedin", provider: "linkedin", kind: "update", payload: updateInput2, description: "Attach/replace an owned lead form on a DRAFT creative, or edit the label of its existing form. Exact creative/campaign/form snapshots required. Preserves content and delivery status; label changes can affect serving ads. No publication, events or submitted leads." })
|
|
1352
|
+
];
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
// src/sponsored-tools.ts
|
|
1356
|
+
var postUrn2 = z10.string().regex(/^urn:li:(?:share|ugcPost):[1-9]\d*$/);
|
|
1357
|
+
var organizationUrn = z10.string().regex(/^urn:li:organization:[1-9]\d*$/);
|
|
1358
|
+
var href2 = z10.string().url().refine((value) => {
|
|
1359
|
+
const url3 = new URL(value);
|
|
1360
|
+
return ["http:", "https:"].includes(url3.protocol) && !url3.username && !url3.password;
|
|
1361
|
+
}, "Use an HTTP(S) URL without embedded credentials");
|
|
1362
|
+
var postCta = z10.enum(["APPLY", "DOWNLOAD", "VIEW_QUOTE", "LEARN_MORE", "SIGN_UP", "SUBSCRIBE", "REGISTER", "JOIN", "ATTEND", "REQUEST_DEMO", "SEE_MORE", "BUY_NOW", "SHOP_NOW"]);
|
|
1363
|
+
var title = z10.string().min(1).max(399);
|
|
1364
|
+
var alt = z10.string().max(4085);
|
|
1365
|
+
var hash4 = z10.string().regex(/^[a-f0-9]{64}$/);
|
|
1366
|
+
var sponsoredContent = z10.discriminatedUnion("type", [
|
|
1367
|
+
z10.object({ type: z10.literal("TEXT") }).strict(),
|
|
1368
|
+
z10.object({ type: z10.literal("IMAGE"), image_id: imageUrn, title, alt_text: alt.optional() }).strict(),
|
|
1369
|
+
z10.object({ type: z10.literal("VIDEO"), video_id: z10.string().regex(/^urn:li:video:[A-Za-z0-9_-]+$/), title, alt_text: alt.optional() }).strict(),
|
|
1370
|
+
z10.object({ type: z10.literal("DOCUMENT"), document_id: z10.string().regex(/^urn:li:document:[A-Za-z0-9_-]+$/), title }).strict(),
|
|
1371
|
+
z10.object({ type: z10.literal("ARTICLE"), source: href2, title, description: z10.string().max(400).optional(), thumbnail: imageUrn.optional() }).strict(),
|
|
1372
|
+
z10.object({ type: z10.literal("CAROUSEL"), cards: z10.array(z10.object({ image_id: imageUrn, title, alt_text: alt.optional(), landing_page: href2 }).strict()).min(2).max(10) }).strict()
|
|
1373
|
+
]);
|
|
1374
|
+
var createBase = { campaign_id: linkedinId, name: z10.string().trim().min(1).max(200), status: z10.enum(["PAUSED", "ACTIVE", "DRAFT"]).default("PAUSED"), non_political_consent: z10.literal(true).describe(NON_POLITICAL_CONSENT), lead_form: leadBinding.optional() };
|
|
1375
|
+
var createSponsored = z10.object({ ...createBase, author_organization: organizationUrn, commentary: z10.string().min(1).max(3e3), content: sponsoredContent, landing_page: href2.optional(), call_to_action: postCta.optional() }).strict();
|
|
1376
|
+
var createReference = z10.object({ ...createBase, source_creative_id: creativeUrn }).strict();
|
|
1377
|
+
var postSelection = z10.object({ creative_id: creativeUrn.optional(), post_id: postUrn2.optional(), author_organization: organizationUrn.optional(), campaign_id: linkedinId.optional() }).strict().refine((value) => value.creative_id ? !value.post_id && !value.author_organization && !value.campaign_id : Boolean(value.post_id && value.author_organization), "Choose creative_id alone, or post_id with author_organization and an optional owned campaign_id");
|
|
1378
|
+
var postTarget = { post_id: postUrn2, author_organization: organizationUrn, campaign_id: linkedinId.optional(), expected_post_hash: hash4, expected_associations_hash: hash4 };
|
|
1379
|
+
var updateSponsoredPost = z10.object({ ...postTarget, commentary: z10.string().max(3e3).optional(), landing_page: href2.optional(), call_to_action: postCta.optional(), dsc_name: z10.string().trim().min(1).max(200).optional() }).strict().refine((value) => value.commentary !== void 0 || value.landing_page !== void 0 || value.call_to_action !== void 0 || value.dsc_name !== void 0, "Provide supported post changes");
|
|
1380
|
+
var archiveSponsoredPost = z10.object(postTarget).strict();
|
|
1381
|
+
var deleteSponsoredPost = z10.object(postTarget).strict();
|
|
1382
|
+
var LINKEDIN_SPONSORED_WRITES = /* @__PURE__ */ new Set(["linkedin_create_sponsored_ad", "linkedin_create_reference_ad", "linkedin_update_sponsored_post", "linkedin_archive_sponsored_post", "linkedin_delete_sponsored_post"]);
|
|
1383
|
+
function linkedinSponsoredTools(provider) {
|
|
1384
|
+
return [
|
|
1385
|
+
defineTool6({ name: "linkedin_creative_preview", namespace: "linkedin", description: "Render an owned creative using native headline, introduction, body, landing page and primary asset metadata (single-creative API202610). Metadata is read-only; missing fields stay unavailable. Account/campaign ownership is checked.", input: z10.object({ account_id: linkedinId, creative_id: creativeUrn }), output: creativesOutput4.passthrough(), presentation: "creatives", annotations: { readOnly: true }, handler: (input) => provider.sponsored.preview(input.account_id, input.creative_id) }),
|
|
1386
|
+
defineTool6({ name: "linkedin_get_sponsored_post", namespace: "linkedin", description: "Read a creative\u2019s actual post and referenced media, or an account-owned dark post, with content/association hashes. Posts reads additionally require native Page/social permissions. Only account-owned dark posts receive shared-copy edit forms.", input: postSelection.safeExtend({ account_id: linkedinId }), output: creativesOutput4.passthrough(), presentation: "creatives", annotations: { readOnly: true }, handler: ({ account_id, ...input }) => provider.sponsored.postContext(account_id, input) }),
|
|
1387
|
+
guardedWriteTool6({ name: "linkedin_create_sponsored_ad", namespace: "linkedin", provider: "linkedin", kind: "create", description: "Create a text, image, video, document, article or carousel creative and dark post. ACTIVE is coerced PAUSED by policy; DRAFT stays editable. For lead campaigns provide lead_form with current hashes and confirm_public_post. Fresh lead documents support gated preview pages; no document/post reuse. Uses AVAILABLE owned media and the parent campaign\u2019s exact organization/format. Native post is PUBLISHED/PUBLIC but feedDistribution NONE and reshares disabled: accessible by URL, not an organic Page-feed post. Page authorization still applies; no server dry-run.", payload: createSponsored, destructive: false }),
|
|
1388
|
+
guardedWriteTool6({ name: "linkedin_create_reference_ad", namespace: "linkedin", provider: "linkedin", kind: "create", description: "Create a paused creative reusing the post of an existing creative in this same account, under a compatible owned campaign/Page. Does not publish another post or change the source ad. For lead campaigns supply lead_form with current form/campaign/source hashes; document lead ads require a fresh document through sponsored-ad creation.", payload: createReference, destructive: false }),
|
|
1389
|
+
guardedWriteTool6({ name: "linkedin_update_sponsored_post", namespace: "linkedin", provider: "linkedin", kind: "update", description: "Edit supplied commentary, destination, CTA or DSC name on an account-owned dark post. Affects all its creatives; preview enumerates and hash-binds them. Preserves media, author, distribution, post lifecycle and every creative delivery status. Native Page read/write permissions required.", payload: updateSponsoredPost }),
|
|
1390
|
+
guardedWriteTool6({ name: "linkedin_archive_sponsored_post", namespace: "linkedin", provider: "linkedin", kind: "update", description: "Irreversibly archive an account-owned dark post through adContext.dscStatus=ARCHIVED. Native LinkedIn cancels its linked creatives. Preview enumerates and hash-binds all associations; this cannot be undone. Requires native Page permissions.", payload: archiveSponsoredPost }),
|
|
1391
|
+
guardedWriteTool6({ name: "linkedin_delete_sponsored_post", namespace: "linkedin", provider: "linkedin", kind: "remove", description: "Permanently delete an account-owned dark post only after all selected-account creative references are REMOVED/CANCELED or absent. Complete bounded association lookup and exact content/association hashes are required. Does not delete uploaded media. Requires native Page permissions.", payload: deleteSponsoredPost })
|
|
1392
|
+
];
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
// src/sponsored.ts
|
|
1396
|
+
var row3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1397
|
+
var aurn4 = (account2) => `urn:li:sponsoredAccount:${linkedinId.parse(account2)}`;
|
|
1398
|
+
var nativeCreative = z11.looseObject({ id: creativeUrn, account: accountUrn, campaign: z11.string().regex(/^urn:li:sponsoredCampaign:[1-9]\d*$/), intendedStatus: z11.string(), content: z11.record(z11.string(), z11.unknown()).optional(), metadata: z11.looseObject({ adFormat: z11.string().optional(), adHeadline: z11.string().optional(), adIntroductionText: z11.string().optional(), adLine: z11.string().optional(), assetURL: z11.string().optional(), landingPage: z11.string().optional() }).optional() });
|
|
1399
|
+
var nativePost = z11.looseObject({ id: postUrn2, author: organizationUrn, commentary: z11.string(), lifecycleState: z11.string(), distribution: z11.looseObject({ feedDistribution: z11.string(), thirdPartyDistributionChannels: z11.array(z11.string()).optional() }), content: z11.record(z11.string(), z11.unknown()).optional() });
|
|
1400
|
+
var canonical3 = (value) => Array.isArray(value) ? value.map(canonical3) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, canonical3(child)])) : value;
|
|
1401
|
+
var hash5 = (value) => createHash4("sha256").update(JSON.stringify(canonical3(value)) ?? "undefined").digest("hex");
|
|
1402
|
+
var reference = (value) => {
|
|
1403
|
+
const content2 = row3(value);
|
|
1404
|
+
return postUrn2.parse(content2.reference ?? row3(content2.documentAd).reference ?? row3(content2.standardUpdateAd).reference ?? row3(content2.videoAd).reference);
|
|
1405
|
+
};
|
|
1406
|
+
var url2 = (value, media = false) => {
|
|
1407
|
+
if (typeof value !== "string") return void 0;
|
|
1408
|
+
try {
|
|
1409
|
+
const parsed = new URL(value);
|
|
1410
|
+
return !parsed.username && !parsed.password && (media ? parsed.protocol === "https:" && (parsed.hostname === "licdn.com" || parsed.hostname.endsWith(".licdn.com")) : ["https:", "http:"].includes(parsed.protocol)) ? value : void 0;
|
|
1411
|
+
} catch {
|
|
1412
|
+
return void 0;
|
|
1413
|
+
}
|
|
1414
|
+
};
|
|
1415
|
+
var formats2 = { TEXT: "STANDARD_UPDATE", IMAGE: "STANDARD_UPDATE", ARTICLE: "STANDARD_UPDATE", VIDEO: "SINGLE_VIDEO", DOCUMENT: "SPONSORED_UPDATE_NATIVE_DOCUMENT", CAROUSEL: "CAROUSEL" };
|
|
1416
|
+
var terminal3 = (status) => ["REMOVED", "CANCELED"].includes(status);
|
|
1417
|
+
var contains = (actual, expected) => Array.isArray(expected) ? Array.isArray(actual) && actual.length === expected.length && expected.every((value, index) => contains(actual[index], value)) : expected && typeof expected === "object" ? Object.entries(expected).every(([key, value]) => contains(row3(actual)[key], value)) : actual === expected;
|
|
1418
|
+
var LinkedInSponsoredService = class {
|
|
1419
|
+
constructor(client, provider) {
|
|
1420
|
+
this.client = client;
|
|
1421
|
+
this.provider = provider;
|
|
1422
|
+
}
|
|
1423
|
+
client;
|
|
1424
|
+
provider;
|
|
1425
|
+
async metadata(account2, resource) {
|
|
1426
|
+
linkedinId.parse(account2);
|
|
1427
|
+
creativeUrn.parse(resource);
|
|
1428
|
+
const value = await this.client.creativeMetadata(`adAccounts/${account2}/creatives/${encodeURIComponent(resource)}`, nativeCreative);
|
|
1429
|
+
if (value.id !== resource || value.account !== aurn4(account2)) throw new AdportError8("INVALID_INPUT", "linkedin: creative metadata account/ID mismatch");
|
|
1430
|
+
await this.provider.getCampaign(account2, value.campaign.split(":").at(-1));
|
|
1431
|
+
if (value.metadata?.assetURL) {
|
|
1432
|
+
const visual = url2(value.metadata.assetURL, true);
|
|
1433
|
+
try {
|
|
1434
|
+
const type = visual ? await this.client.creativeMediaType(visual) : void 0;
|
|
1435
|
+
if (visual && type) return { ...value, primary_media: { type, url: visual } };
|
|
1436
|
+
} catch {
|
|
1437
|
+
}
|
|
1438
|
+
return { ...value, preview_warning: "Native primary asset MIME/readiness could not be verified on the allowed LinkedIn CDN. No media type is inferred from the ad format." };
|
|
1439
|
+
}
|
|
1440
|
+
return value;
|
|
1441
|
+
}
|
|
1442
|
+
metadataCard(account2, value) {
|
|
1443
|
+
const metadata3 = value.metadata, destination = url2(metadata3?.landingPage);
|
|
1444
|
+
return {
|
|
1445
|
+
id: value.id,
|
|
1446
|
+
provider: "linkedin",
|
|
1447
|
+
account_id: account2,
|
|
1448
|
+
campaign_id: value.campaign.split(":").at(-1),
|
|
1449
|
+
name: typeof value.name === "string" ? value.name : value.id,
|
|
1450
|
+
type: metadata3?.adFormat ?? "SPONSORED_CONTENT_REFERENCE",
|
|
1451
|
+
status: value.intendedStatus,
|
|
1452
|
+
headlines: metadata3?.adHeadline ? [metadata3.adHeadline] : [],
|
|
1453
|
+
descriptions: [metadata3?.adIntroductionText, metadata3?.adLine].filter((v) => Boolean(v)),
|
|
1454
|
+
landing_urls: destination ? [destination] : [],
|
|
1455
|
+
media: value.primary_media ? [value.primary_media] : [],
|
|
1456
|
+
actions: terminal3(value.intendedStatus) || value.intendedStatus === "PENDING_DELETION" ? [] : [
|
|
1457
|
+
{ label: "Pause or archive creative", tool: "linkedin_set_creative_status", arguments: { account_id: account2, creative_id: value.id }, fields: [{ key: "status", label: "Status", type: "select", value: "PAUSED", options: [{ label: "Paused", value: "PAUSED" }, { label: "Archived", value: "ARCHIVED" }] }] },
|
|
1458
|
+
{ label: "Rename creative", tool: "linkedin_rename_creative", arguments: { account_id: account2, creative_id: value.id }, fields: [{ key: "name", label: "Name", type: "text", value: typeof value.name === "string" ? value.name : "" }] }
|
|
1459
|
+
]
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
async preview(account2, resource) {
|
|
1463
|
+
const value = await this.metadata(account2, resource);
|
|
1464
|
+
return { items: [value], creatives: [this.metadataCard(account2, value)], truncated: false, warnings: [...value.metadata ? [] : [{ provider: "linkedin", message: "Native descriptive metadata was not returned; copy and previews remain unavailable. Post/source reads may require additional Page permissions." }], ...value.preview_warning ? [{ provider: "linkedin", message: value.preview_warning }] : []] };
|
|
1465
|
+
}
|
|
1466
|
+
async associations(account2, post) {
|
|
1467
|
+
const items = [], tokens = /* @__PURE__ */ new Set(), ids = /* @__PURE__ */ new Set();
|
|
1468
|
+
let token;
|
|
1469
|
+
for (let page = 0; page < 100; page++) {
|
|
1470
|
+
const result = await this.client.get(`adAccounts/${linkedinId.parse(account2)}/creatives`, z11.looseObject({ elements: z11.array(nativeCreative), metadata: z11.object({ nextPageToken: z11.string().optional() }).optional() }), { q: "criteria", contentReferences: [postUrn2.parse(post)], intendedStatuses: ["ACTIVE", "PAUSED", "DRAFT", "ARCHIVED", "CANCELED", "PENDING_DELETION", "REMOVED"], sortOrder: "ASCENDING", pageSize: 100, ...token ? { pageToken: token } : {} });
|
|
1471
|
+
if (result.elements.length > 100 || result.elements.some((value) => value.account !== aurn4(account2) || reference(value.content) !== post || ids.has(value.id)) || new Set(result.elements.map((value) => value.id)).size !== result.elements.length) throw new AdportError8("PROVIDER_ERROR", "linkedin: post associations account/reference/page mismatch");
|
|
1472
|
+
items.push(...result.elements);
|
|
1473
|
+
result.elements.forEach((value) => ids.add(value.id));
|
|
1474
|
+
const next = result.metadata?.nextPageToken;
|
|
1475
|
+
if (!next) return items.sort((a, b) => a.id.localeCompare(b.id));
|
|
1476
|
+
if (!result.elements.length || tokens.has(next) || items.length >= 5e3) throw new AdportError8("PROVIDER_ERROR", "linkedin: post associations are incomplete, repeated or exceed 5,000 creatives");
|
|
1477
|
+
tokens.add(next);
|
|
1478
|
+
token = next;
|
|
1479
|
+
}
|
|
1480
|
+
throw new AdportError8("PROVIDER_ERROR", "linkedin: post association page limit reached; membership is incomplete");
|
|
1481
|
+
}
|
|
1482
|
+
async readPost(resource) {
|
|
1483
|
+
try {
|
|
1484
|
+
const post = await this.client.get(`posts/${encodeURIComponent(postUrn2.parse(resource))}`, nativePost, { viewContext: "AUTHOR" });
|
|
1485
|
+
if (post.id !== resource) throw new AdportError8("PROVIDER_ERROR", "linkedin: post readback returned a different ID");
|
|
1486
|
+
return post;
|
|
1487
|
+
} catch (error) {
|
|
1488
|
+
throw new AdportError8("PROVIDER_ERROR", `linkedin: sponsored post read failed. Posts additionally require r_organization_social and an eligible Page role; existing advertising access does not imply that permission. ${error instanceof Error ? error.message : ""}`);
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
ownDarkPost(account2, post, author) {
|
|
1492
|
+
if (post.author !== author || row3(post.adContext).dscAdAccount !== aurn4(account2) || post.distribution.feedDistribution !== "NONE" || post.distribution.thirdPartyDistributionChannels?.length) throw new AdportError8("INVALID_INPUT", "linkedin: mutations require a selected-account dark post with the verified organization author and no organic/external distribution");
|
|
1493
|
+
}
|
|
1494
|
+
async organization(account2, author, campaignId) {
|
|
1495
|
+
organizationUrn.parse(author);
|
|
1496
|
+
const value = campaignId ? await this.provider.getCampaign(account2, campaignId) : await this.provider.getAccount(account2);
|
|
1497
|
+
if ((campaignId ? value.associatedEntity : value.reference) !== author) throw new AdportError8("PENDING_MISMATCH", "linkedin: organization differs from the current owned account/campaign association");
|
|
1498
|
+
}
|
|
1499
|
+
async postContext(account2, raw) {
|
|
1500
|
+
const input = postSelection.parse(raw);
|
|
1501
|
+
let resource, author, campaignId;
|
|
1502
|
+
if (input.creative_id) {
|
|
1503
|
+
const source2 = await this.provider.creatives.owned(account2, input.creative_id), campaign = await this.provider.getCampaign(account2, source2.campaign.split(":").at(-1));
|
|
1504
|
+
resource = reference(source2.content);
|
|
1505
|
+
author = organizationUrn.parse(campaign.associatedEntity);
|
|
1506
|
+
campaignId = String(campaign.id);
|
|
1507
|
+
} else {
|
|
1508
|
+
resource = input.post_id;
|
|
1509
|
+
author = input.author_organization;
|
|
1510
|
+
campaignId = input.campaign_id;
|
|
1511
|
+
await this.organization(account2, author, campaignId);
|
|
1512
|
+
}
|
|
1513
|
+
const post = await this.readPost(resource);
|
|
1514
|
+
if (post.id !== resource || post.author !== author || row3(post.adContext).dscAdAccount !== void 0 && row3(post.adContext).dscAdAccount !== aurn4(account2)) throw new AdportError8("INVALID_INPUT", "linkedin: post ID/author/advertiser mismatch");
|
|
1515
|
+
if (!input.creative_id) this.ownDarkPost(account2, post, author);
|
|
1516
|
+
const associations = await this.associations(account2, resource), associationFacts = associations.map((value) => ({ id: value.id, campaign: value.campaign, intendedStatus: value.intendedStatus, content: value.content }));
|
|
1517
|
+
const hashes = { post_snapshot_hash: hash5(post), associations_snapshot_hash: hash5(associationFacts) };
|
|
1518
|
+
const owned = row3(post.adContext).dscAdAccount === aurn4(account2) && post.distribution.feedDistribution === "NONE" && !post.distribution.thirdPartyDistributionChannels?.length;
|
|
1519
|
+
const media = [], content2 = row3(post.content), primary = row3(content2.media), article = row3(content2.article), carousel = row3(content2.carousel);
|
|
1520
|
+
if (Array.isArray(carousel.cards) && carousel.cards.length > 10) throw new AdportError8("PROVIDER_ERROR", "linkedin: native carousel exceeds the supported ten-card contract");
|
|
1521
|
+
const entries = [primary, ...article.thumbnail ? [{ id: article.thumbnail, title: article.title }] : [], ...Array.isArray(carousel.cards) ? carousel.cards.map((value) => row3(row3(value).media)) : []].filter((value) => typeof value.id === "string");
|
|
1522
|
+
const ids = [...new Set(entries.map((value) => String(value.id)))], previews = /* @__PURE__ */ new Map();
|
|
1523
|
+
const warnings = [];
|
|
1524
|
+
for (const id2 of ids) {
|
|
1525
|
+
try {
|
|
1526
|
+
const asset = id2.startsWith("urn:li:image:") ? await this.provider.creatives.libraryImage(account2, id2) : id2.startsWith("urn:li:video:") ? await this.provider.media.libraryVideo(account2, id2) : void 0;
|
|
1527
|
+
const preview = asset?.status === "AVAILABLE" ? url2(row3(asset).downloadUrl, true) : void 0;
|
|
1528
|
+
if (preview) previews.set(id2, { type: id2.startsWith("urn:li:video:") ? "video" : "image", url: preview });
|
|
1529
|
+
} catch (error) {
|
|
1530
|
+
warnings.push({ provider: "linkedin", message: `Post asset ${id2} unavailable: ${error instanceof Error ? error.message : "native read failed"}` });
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
for (const entry of entries) {
|
|
1534
|
+
const preview = previews.get(String(entry.id));
|
|
1535
|
+
if (preview) media.push({ ...preview, ...typeof entry.altText === "string" || typeof entry.title === "string" ? { alt: String(entry.altText ?? entry.title) } : {} });
|
|
1536
|
+
}
|
|
1537
|
+
const args = { account_id: account2, post_id: post.id, author_organization: author, ...campaignId ? { campaign_id: campaignId } : {}, expected_post_hash: hashes.post_snapshot_hash, expected_associations_hash: hashes.associations_snapshot_hash };
|
|
1538
|
+
const destinations = [post.contentLandingPage, article.source, ...Array.isArray(carousel.cards) ? carousel.cards.map((value) => row3(value).landingPage) : []].map((value) => url2(value)).filter((value) => Boolean(value));
|
|
1539
|
+
const editFields = [{ key: "commentary", label: "Commentary shared by all linked creatives", type: "text", value: post.commentary, max_length: 3e3 }];
|
|
1540
|
+
if (typeof row3(post.adContext).dscName === "string" && String(row3(post.adContext).dscName).trim()) editFields.push({ key: "dsc_name", label: "Shared post name", type: "text", value: String(row3(post.adContext).dscName), max_length: 200 });
|
|
1541
|
+
if (url2(post.contentLandingPage) && !article.source) editFields.push({ key: "landing_page", label: "Shared post destination", type: "text", value: String(post.contentLandingPage) });
|
|
1542
|
+
const cta2 = postCta.safeParse(post.contentCallToActionLabel);
|
|
1543
|
+
if (cta2.success) editFields.push({ key: "call_to_action", label: "Shared post call to action", type: "select", value: cta2.data, options: postCta.options.map((value) => ({ label: value.replaceAll("_", " "), value })) });
|
|
1544
|
+
const card = {
|
|
1545
|
+
id: post.id,
|
|
1546
|
+
provider: "linkedin",
|
|
1547
|
+
account_id: account2,
|
|
1548
|
+
name: typeof row3(post.adContext).dscName === "string" ? String(row3(post.adContext).dscName) : post.id,
|
|
1549
|
+
type: carousel.cards ? "CAROUSEL_POST" : article.source ? "ARTICLE_POST" : typeof primary.id === "string" && primary.id.startsWith("urn:li:document:") ? "DOCUMENT_POST" : "SPONSORED_POST",
|
|
1550
|
+
status: post.lifecycleState,
|
|
1551
|
+
headlines: [primary.title, article.title].filter((value) => typeof value === "string"),
|
|
1552
|
+
descriptions: [post.commentary, ...Array.isArray(carousel.cards) ? carousel.cards.map((value) => row3(row3(value).media).title).filter((value) => typeof value === "string") : []],
|
|
1553
|
+
landing_urls: destinations,
|
|
1554
|
+
media,
|
|
1555
|
+
actions: owned && row3(post.adContext).dscStatus === "ACTIVE" && post.lifecycleState === "PUBLISHED" ? [{ label: `Edit shared post copy (${associations.length} linked creatives)`, tool: "linkedin_update_sponsored_post", arguments: args, fields: editFields }] : []
|
|
1556
|
+
};
|
|
1557
|
+
return { post, associations: associationFacts, ...hashes, creatives: [card], warnings, truncated: false };
|
|
1558
|
+
}
|
|
1559
|
+
campaignFormat(campaign, expected, lead = false) {
|
|
1560
|
+
if (lead) {
|
|
1561
|
+
this.provider.leadCreatives.campaign(campaign, expected);
|
|
1562
|
+
return;
|
|
1563
|
+
}
|
|
1564
|
+
if (campaign.type !== "SPONSORED_UPDATES" || campaign.format !== expected) throw new AdportError8("INVALID_INPUT", `linkedin: this content requires a SPONSORED_UPDATES campaign with format ${expected}`);
|
|
1565
|
+
if (campaign.objectiveType === "LEAD_GENERATION") throw new AdportError8("INVALID_INPUT", "linkedin: lead-generation creation/reuse requires dedicated account-owned form and single-use document checks");
|
|
1566
|
+
if (["REMOVED", "CANCELED", "PENDING_DELETION", "ARCHIVED"].includes(String(campaign.status))) throw new AdportError8("INVALID_INPUT", "linkedin: parent campaign is archived, removed, canceled or pending deletion");
|
|
1567
|
+
}
|
|
1568
|
+
async plan(op, guard) {
|
|
1569
|
+
const account2 = linkedinId.parse(op.accountId), create = ["linkedin_create_sponsored_ad", "linkedin_create_reference_ad"].includes(op.tool);
|
|
1570
|
+
if (op.provider !== "linkedin" || !LINKEDIN_SPONSORED_WRITES.has(op.tool) || op.kind !== (create ? "create" : op.tool === "linkedin_delete_sponsored_post" ? "remove" : "update")) throw new AdportError8("INVALID_INPUT", "linkedin: invalid sponsored content operation kind");
|
|
1571
|
+
const plan = (summary, changes2, execute, coercions = []) => ({ summary, changes: changes2, execute, coercions, budgetDeltas: [] });
|
|
1572
|
+
if (create) {
|
|
1573
|
+
const input2 = op.tool === "linkedin_create_sponsored_ad" ? createSponsored.parse(op.payload) : createReference.parse(op.payload), campaign = await this.provider.getCampaign(account2, input2.campaign_id);
|
|
1574
|
+
const status = guard.forcePausedCreation && input2.status === "ACTIVE" ? "PAUSED" : input2.status;
|
|
1575
|
+
let fields2, postId, inlinePost, documentToCheck;
|
|
1576
|
+
let formCta, leadContentFormat;
|
|
1577
|
+
if ("content" in input2) {
|
|
1578
|
+
const content2 = input2.content;
|
|
1579
|
+
this.campaignFormat(campaign, formats2[content2.type], Boolean(input2.lead_form));
|
|
1580
|
+
if (input2.lead_form) {
|
|
1581
|
+
if (!input2.lead_form.confirm_public_post) throw new AdportError8("INVALID_INPUT", "linkedin: creating this lead ad publishes a URL-accessible dark post; confirm_public_post is required");
|
|
1582
|
+
if (input2.lead_form.expected_source_hash) throw new AdportError8("INVALID_INPUT", "linkedin: an inline lead ad does not reuse a source creative");
|
|
1583
|
+
formCta = await this.provider.leadCreatives.createBinding(account2, campaign, input2.lead_form, formats2[content2.type]);
|
|
1584
|
+
leadContentFormat = formats2[content2.type];
|
|
1585
|
+
if (content2.type === "DOCUMENT") {
|
|
1586
|
+
documentToCheck = content2.document_id;
|
|
1587
|
+
await this.provider.leadCreatives.assertUnusedDocument(account2, documentToCheck);
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
if (campaign.associatedEntity !== input2.author_organization) throw new AdportError8("PENDING_MISMATCH", "linkedin: author differs from the current campaign organization");
|
|
1591
|
+
if (["WEBSITE_VISIT", "WEBSITE_VISITS", "WEBSITE_CONVERSION", "WEBSITE_CONVERSIONS"].includes(String(campaign.objectiveType)) && !input2.landing_page && content2.type !== "ARTICLE") throw new AdportError8("INVALID_INPUT", "linkedin: this campaign objective requires an explicit landing page");
|
|
1592
|
+
if (input2.call_to_action && !input2.landing_page && content2.type !== "ARTICLE") throw new AdportError8("INVALID_INPUT", "linkedin: a call to action requires a destination");
|
|
1593
|
+
const images = content2.type === "IMAGE" ? [content2.image_id] : content2.type === "ARTICLE" && content2.thumbnail ? [content2.thumbnail] : content2.type === "CAROUSEL" ? content2.cards.map((card) => card.image_id) : [];
|
|
1594
|
+
for (const id2 of new Set(images)) if ((await this.provider.creatives.libraryImage(account2, id2)).status !== "AVAILABLE") throw new AdportError8("INVALID_INPUT", "linkedin: image is not AVAILABLE");
|
|
1595
|
+
if (content2.type === "VIDEO") {
|
|
1596
|
+
const video = await this.provider.media.libraryVideo(account2, content2.video_id);
|
|
1597
|
+
if (video.status !== "AVAILABLE" || video.owner !== input2.author_organization) throw new AdportError8("INVALID_INPUT", "linkedin: video must be AVAILABLE and owned by the author organization");
|
|
1598
|
+
}
|
|
1599
|
+
if (content2.type === "DOCUMENT" && (await this.provider.media.document(account2, content2.document_id)).status !== "AVAILABLE") throw new AdportError8("INVALID_INPUT", "linkedin: document is not AVAILABLE");
|
|
1600
|
+
const nativeContent = content2.type === "TEXT" ? void 0 : content2.type === "ARTICLE" ? { article: { source: content2.source, title: content2.title, ...content2.description !== void 0 ? { description: content2.description } : {}, ...content2.thumbnail ? { thumbnail: content2.thumbnail } : {} } } : content2.type === "CAROUSEL" ? { carousel: { cards: content2.cards.map((card) => ({ media: { id: card.image_id, title: card.title, ...card.alt_text !== void 0 ? { altText: card.alt_text } : {} }, landingPage: card.landing_page })) } } : { media: { id: content2.type === "IMAGE" ? content2.image_id : content2.type === "VIDEO" ? content2.video_id : content2.document_id, title: content2.title, ..."alt_text" in content2 && content2.alt_text !== void 0 ? { altText: content2.alt_text } : {} } };
|
|
1601
|
+
const post = { author: input2.author_organization, commentary: input2.commentary, visibility: "PUBLIC", lifecycleState: "PUBLISHED", distribution: { feedDistribution: "NONE", targetEntities: [], thirdPartyDistributionChannels: [] }, isReshareDisabledByAuthor: true, adContext: { dscAdAccount: aurn4(account2), dscStatus: "ACTIVE" }, ...nativeContent ? { content: nativeContent } : {}, ...input2.landing_page ? { contentLandingPage: input2.landing_page } : {}, ...input2.call_to_action ? { contentCallToActionLabel: input2.call_to_action } : {} };
|
|
1602
|
+
inlinePost = post;
|
|
1603
|
+
fields2 = { creative: { campaign: `urn:li:sponsoredCampaign:${input2.campaign_id}`, intendedStatus: status, name: input2.name, ...formCta ? { leadgenCallToAction: formCta } : {}, inlineContent: { post } } };
|
|
1604
|
+
} else {
|
|
1605
|
+
const source2 = await this.provider.creatives.owned(account2, input2.source_creative_id), parent = await this.provider.getCampaign(account2, source2.campaign.split(":").at(-1));
|
|
1606
|
+
const format = String(parent.format), leadFormats = { LEAD_GENERATION_FORM_SPONSORED_CONTENT: "STANDARD_UPDATE", VIDEO_LEAD_GENERATION_FORM_SPONSORED_CONTENT: "SINGLE_VIDEO", LEAD_GENERATION_FORM_CAROUSEL_SPONSORED_CONTENT: "CAROUSEL" }, sourceFormat = leadFormats[format] ?? format;
|
|
1607
|
+
this.campaignFormat(parent, sourceFormat, parent.objectiveType === "LEAD_GENERATION" && Boolean(input2.lead_form));
|
|
1608
|
+
this.campaignFormat(campaign, sourceFormat, Boolean(input2.lead_form));
|
|
1609
|
+
if (!Object.values(formats2).includes(sourceFormat) || !organizationUrn.safeParse(parent.associatedEntity).success || parent.associatedEntity !== campaign.associatedEntity) throw new AdportError8("INVALID_INPUT", "linkedin: source and destination sponsored campaigns must use a supported matching format and organization");
|
|
1610
|
+
if (input2.lead_form) {
|
|
1611
|
+
if (sourceFormat === formats2.DOCUMENT) throw new AdportError8("INVALID_INPUT", "linkedin: lead document creatives cannot reuse a post/document already referenced by another creative; upload a fresh document");
|
|
1612
|
+
if (!input2.lead_form.expected_source_hash || this.provider.leadCreatives.sourceHash(source2) !== input2.lead_form.expected_source_hash) throw new AdportError8("PENDING_MISMATCH", "linkedin: source creative changed or its hash is missing; read lead-ad context again");
|
|
1613
|
+
formCta = await this.provider.leadCreatives.createBinding(account2, campaign, input2.lead_form, sourceFormat);
|
|
1614
|
+
leadContentFormat = sourceFormat;
|
|
1615
|
+
}
|
|
1616
|
+
postId = reference(source2.content);
|
|
1617
|
+
fields2 = { campaign: `urn:li:sponsoredCampaign:${input2.campaign_id}`, intendedStatus: status, name: input2.name, ...formCta ? { leadgenCallToAction: formCta } : {}, content: sourceFormat === formats2.DOCUMENT ? { documentAd: { reference: postId } } : { reference: postId } };
|
|
1618
|
+
}
|
|
1619
|
+
const inline = "creative" in fields2;
|
|
1620
|
+
return plan(`Create LinkedIn ${inline ? "sponsored ad and dark post" : "post-reference ad"} \u201C${input2.name}\u201D`, [NON_DISCRIMINATION_NOTICE, `Advertiser confirmation: ${NON_POLITICAL_CONSENT}`, ...inline ? ["Native dark post uses lifecycle PUBLISHED and visibility PUBLIC; anyone with a direct URL may view it. feedDistribution NONE and disabled resharing prevent organic feed distribution. The creative is DRAFT or PAUSED under policy. Native Page permissions still apply."] : ["Reuses an existing account creative\u2019s post. Does not publish or edit another post."], JSON.stringify(fields2)], async () => {
|
|
1621
|
+
let resource;
|
|
1622
|
+
try {
|
|
1623
|
+
if (inline && formCta) {
|
|
1624
|
+
if (documentToCheck) await this.provider.leadCreatives.assertUnusedDocument(account2, documentToCheck);
|
|
1625
|
+
await this.provider.leadCreatives.createBinding(account2, await this.provider.getCampaign(account2, input2.campaign_id), input2.lead_form, leadContentFormat);
|
|
1626
|
+
}
|
|
1627
|
+
if (inline && formCta && documentToCheck && input2.lead_form?.gated_preview_page_count !== void 0) {
|
|
1628
|
+
postId = await this.client.createPost(inlinePost);
|
|
1629
|
+
const base2 = fields2.creative;
|
|
1630
|
+
const content2 = documentToCheck ? { documentAd: { reference: postId, ...input2.lead_form?.gated_preview_page_count !== void 0 ? { gatedLeadgenPreviewPageCount: input2.lead_form.gated_preview_page_count } : {} } } : { reference: postId };
|
|
1631
|
+
const { inlineContent: _post, ...creative } = base2;
|
|
1632
|
+
resource = await this.client.createCreative(`adAccounts/${account2}/creatives`, { ...creative, content: content2 });
|
|
1633
|
+
} else {
|
|
1634
|
+
if (formCta) {
|
|
1635
|
+
await this.provider.leadCreatives.createBinding(account2, await this.provider.getCampaign(account2, input2.campaign_id), input2.lead_form, leadContentFormat);
|
|
1636
|
+
if ("source_creative_id" in input2 && this.provider.leadCreatives.sourceHash(await this.provider.creatives.owned(account2, input2.source_creative_id)) !== input2.lead_form.expected_source_hash) throw new AdportError8("PENDING_MISMATCH", "linkedin: source changed before creative creation");
|
|
1637
|
+
}
|
|
1638
|
+
resource = await this.client.createCreative(`adAccounts/${account2}/creatives`, fields2, inline ? { action: "createInline" } : {});
|
|
1639
|
+
}
|
|
1640
|
+
} catch (error) {
|
|
1641
|
+
if (!postId || !inline || !formCta) throw error;
|
|
1642
|
+
const existing = error instanceof AdportError8 && Array.isArray(error.details?.resource_ids) ? error.details.resource_ids : [];
|
|
1643
|
+
throw new AdportError8("PROVIDER_ERROR", "linkedin: lead-ad creation was not fully confirmed; a dark post may exist. Reconcile these IDs before any new approval; no automatic replay.", { resource_ids: [postId, ...existing] });
|
|
1644
|
+
}
|
|
1645
|
+
let postState;
|
|
1646
|
+
try {
|
|
1647
|
+
const value = await this.provider.creatives.owned(account2, resource);
|
|
1648
|
+
if (value.campaign !== `urn:li:sponsoredCampaign:${input2.campaign_id}` || value.intendedStatus !== status || value.name !== input2.name || postId && reference(value.content) !== postId) throw new Error("creative receipt mismatch");
|
|
1649
|
+
if (formCta && !contains(value.leadgenCallToAction, formCta)) throw new Error("lead form association did not match");
|
|
1650
|
+
if (documentToCheck && input2.lead_form?.gated_preview_page_count !== void 0 && row3(value.content?.documentAd).gatedLeadgenPreviewPageCount !== input2.lead_form.gated_preview_page_count) throw new Error("gated preview did not match");
|
|
1651
|
+
postId = reference(value.content);
|
|
1652
|
+
if (inlinePost) {
|
|
1653
|
+
const post = await this.readPost(postId);
|
|
1654
|
+
this.ownDarkPost(account2, post, String(inlinePost.author));
|
|
1655
|
+
if (!["PUBLISHED", "PUBLISH_REQUESTED"].includes(post.lifecycleState) || post.visibility !== "PUBLIC" || post.isReshareDisabledByAuthor !== true || post.commentary !== inlinePost.commentary || !contains(post.content, inlinePost.content) || ["contentLandingPage", "contentCallToActionLabel"].some((key) => inlinePost[key] !== void 0 && post[key] !== inlinePost[key])) throw new Error("post copy, distribution, media or lifecycle did not match");
|
|
1656
|
+
postState = post.lifecycleState;
|
|
1657
|
+
}
|
|
1658
|
+
} catch {
|
|
1659
|
+
throw new AdportError8("PROVIDER_ERROR", "linkedin: sponsored creative was created but creative/post readback was not confirmed; post reads require native Page permission. Reconcile these IDs before any retry", { resource_ids: [resource, ...postId ? [postId] : []] });
|
|
1660
|
+
}
|
|
1661
|
+
return { applied: true, resourceIds: [resource, ...inline && formCta && postId ? [postId] : []], details: { post_id: postId, intended_status: status, ...postState ? { post_lifecycle_state: postState, post_readback_verified: true } : {}, next_tool: formCta ? "linkedin_creative_lead_form" : "linkedin_creative_preview", note: inline ? `The dark post is URL-accessible; no organic feed distribution was requested. Creative delivery is separate and remains ${status}.` : "Existing post reused without another publication." } };
|
|
1662
|
+
}, input2.status !== status ? ["intendedStatus coerced to PAUSED by policy (paused_creation)"] : []);
|
|
1663
|
+
}
|
|
1664
|
+
const changes = op.tool === "linkedin_update_sponsored_post" ? updateSponsoredPost.parse(op.payload) : void 0;
|
|
1665
|
+
const input = changes ?? (op.tool === "linkedin_archive_sponsored_post" ? archiveSponsoredPost.parse(op.payload) : deleteSponsoredPost.parse(op.payload));
|
|
1666
|
+
const context = await this.postContext(account2, { post_id: input.post_id, author_organization: input.author_organization, ...input.campaign_id ? { campaign_id: input.campaign_id } : {} });
|
|
1667
|
+
this.ownDarkPost(account2, context.post, input.author_organization);
|
|
1668
|
+
if (context.post_snapshot_hash !== input.expected_post_hash || context.associations_snapshot_hash !== input.expected_associations_hash) throw new AdportError8("PENDING_MISMATCH", "linkedin: post content, processing or linked creative settings changed; read post context again");
|
|
1669
|
+
if (changes?.landing_page !== void 0 && row3(context.post.content?.article).source) throw new AdportError8("INVALID_INPUT", "linkedin: an article destination is its immutable article source; create a replacement article creative instead");
|
|
1670
|
+
if (changes?.call_to_action && !changes.landing_page && !url2(context.post.contentLandingPage) && !url2(row3(context.post.content?.article).source)) throw new AdportError8("INVALID_INPUT", "linkedin: a call to action requires a current or explicitly supplied destination");
|
|
1671
|
+
const path = `posts/${encodeURIComponent(input.post_id)}`;
|
|
1672
|
+
if (op.tool === "linkedin_delete_sponsored_post") {
|
|
1673
|
+
if (context.associations.some((value) => !terminal3(value.intendedStatus))) throw new AdportError8("INVALID_INPUT", "linkedin: remove or cancel all creative references before permanently deleting this post");
|
|
1674
|
+
return plan(`Delete LinkedIn dark post ${input.post_id}`, [`Permanently remove ${input.post_id}. Uploaded media is separate. References: ${JSON.stringify(context.associations)}`], async () => {
|
|
1675
|
+
await this.client.remove(path);
|
|
1676
|
+
return { applied: true, resourceIds: [input.post_id], details: { deletion: "DELETED", uploaded_media_deleted: false } };
|
|
1677
|
+
});
|
|
1678
|
+
}
|
|
1679
|
+
if (row3(context.post.adContext).dscStatus !== "ACTIVE" || context.post.lifecycleState !== "PUBLISHED") throw new AdportError8("INVALID_INPUT", "linkedin: only an ACTIVE, PUBLISHED dark post can be edited or archived");
|
|
1680
|
+
const fields = changes ? { ...changes.commentary !== void 0 ? { commentary: changes.commentary } : {}, ...changes.landing_page !== void 0 ? { contentLandingPage: changes.landing_page } : {}, ...changes.call_to_action !== void 0 ? { contentCallToActionLabel: changes.call_to_action } : {} } : {};
|
|
1681
|
+
const adFields = op.tool === "linkedin_archive_sponsored_post" ? { dscStatus: "ARCHIVED" } : changes?.dsc_name !== void 0 ? { dscName: changes.dsc_name } : {};
|
|
1682
|
+
const patch = { ...Object.keys(fields).length ? { $set: fields } : {}, ...Object.keys(adFields).length ? { adContext: { $set: adFields } } : {} };
|
|
1683
|
+
return plan(`${op.tool === "linkedin_archive_sponsored_post" ? "Irreversibly archive" : "Edit shared"} LinkedIn dark post ${input.post_id}`, [`Affects all ${context.associations.length} linked creatives: ${JSON.stringify(context.associations)}`, ...op.tool === "linkedin_archive_sponsored_post" ? ["Native archiving cannot be undone and cancels associated creatives."] : ["Only supplied copy/destination/CTA/name fields change. Media, author, distribution and lifecycle are preserved. Copy changes may trigger review."], JSON.stringify(patch)], async () => {
|
|
1684
|
+
await this.client.partialUpdate(path, patch);
|
|
1685
|
+
try {
|
|
1686
|
+
const updated = await this.readPost(input.post_id);
|
|
1687
|
+
this.ownDarkPost(account2, updated, input.author_organization);
|
|
1688
|
+
if (Object.entries(fields).some(([key, value]) => updated[key] !== value) || Object.entries(adFields).some(([key, value]) => row3(updated.adContext)[key] !== value) || updated.lifecycleState !== context.post.lifecycleState || hash5(updated.content) !== hash5(context.post.content) || hash5(updated.distribution) !== hash5(context.post.distribution)) throw new Error("post readback mismatch");
|
|
1689
|
+
if (changes) {
|
|
1690
|
+
const linked = await this.associations(account2, input.post_id);
|
|
1691
|
+
if (hash5(linked.map((value) => ({ id: value.id, campaign: value.campaign, intendedStatus: value.intendedStatus, content: value.content }))) !== context.associations_snapshot_hash) throw new Error("linked creative settings changed");
|
|
1692
|
+
}
|
|
1693
|
+
} catch {
|
|
1694
|
+
throw new AdportError8("PROVIDER_ERROR", "linkedin: post mutation acknowledged but readback unconfirmed; reconcile before retrying", { resource_ids: [input.post_id] });
|
|
1695
|
+
}
|
|
1696
|
+
return { applied: true, resourceIds: [input.post_id], details: { ...op.tool === "linkedin_archive_sponsored_post" ? { dsc_status: "ARCHIVED", irreversible: true, linked_creative_cancellation: "REQUESTED" } : { shared_post_updated: true }, affected_creative_ids: context.associations.map((value) => value.id) } };
|
|
1697
|
+
});
|
|
1698
|
+
}
|
|
1699
|
+
};
|
|
1700
|
+
|
|
1701
|
+
// src/planning.ts
|
|
1702
|
+
import { AdportError as AdportError9, defineTool as defineTool7, planningViewSchema } from "@adport/core";
|
|
1703
|
+
import { z as z12 } from "zod";
|
|
1704
|
+
var micros3 = z12.number().int().positive().safe();
|
|
1705
|
+
var timestamp = z12.number().int().positive().safe().max(864e13);
|
|
1706
|
+
var bidType = z12.enum(["CPM", "CPC", "CPV"]);
|
|
1707
|
+
var objective = z12.enum(["VIDEO_VIEW", "LEAD_GENERATION", "WEBSITE_CONVERSION", "BRAND_AWARENESS", "WEBSITE_VISIT", "ENGAGEMENT", "WEBSITE_TRAFFIC", "CREATIVE_ENGAGEMENT", "JOB_APPLICATION", "JOB_APPLICANT", "TALENT_LEAD"]);
|
|
1708
|
+
var optimization = z12.enum(["NONE", "MAX_IMPRESSION", "MAX_CLICK", "MAX_CONVERSION", "ENHANCED_CONVERSION", "MAX_VIDEO_VIEW", "MAX_LEAD", "MAX_QUALIFIED_LEAD", "TARGET_COST_PER_CLICK", "TARGET_COST_PER_IMPRESSION", "TARGET_COST_PER_VIDEO_VIEW", "CAP_COST_AND_MAXIMIZE_CLICKS", "CAP_COST_AND_MAXIMIZE_IMPRESSIONS", "CAP_COST_AND_MAXIMIZE_VIDEO_VIEWS", "CAP_COST_AND_MAXIMIZE_LEADS"]);
|
|
1709
|
+
var base = { account_id: linkedinId, targeting_criteria: targetingSchema, objective_type: objective.optional() };
|
|
1710
|
+
var pricingInput = z12.object({ ...base, campaign_type: z12.enum(["TEXT_AD", "SPONSORED_UPDATES", "SPONSORED_INMAILS"]), bid_type: bidType, match_type: z12.enum(["EXACT", "AUDIENCE_EXPANDED"]).default("EXACT"), country_code: z12.string().regex(/^[a-z]{2}$/).optional(), daily_budget_micros: micros3.optional(), optimization_target_type: z12.enum([...optimization.options, "AWARENESS", "WEBSITE_VISIT"]).optional() });
|
|
1711
|
+
var forecastInput = z12.object({ ...base, campaign_type: z12.enum(["SPONSORED_UPDATES", "SPONSORED_INMAILS", "DYNAMIC"]), campaign_id: linkedinId.optional(), creative_type: z12.string().regex(/^[A-Z][A-Z0-9_]*$/).max(100).optional(), time_range: z12.object({ start: timestamp, end: timestamp }).refine((v) => v.end > v.start, "End must follow start"), daily_budget_micros: micros3.optional(), total_budget_micros: micros3.optional(), competing_bid: z12.object({ bid_type: bidType, bid_micros: micros3 }).optional(), optimization_target: optimization.default("NONE"), target_cost_micros: micros3.optional(), cost_cap_micros: micros3.optional(), enable_audience_network: z12.boolean().default(false), enable_audience_expansion: z12.boolean().default(false), connected_television_only: z12.boolean().default(false) }).superRefine((v, ctx) => {
|
|
1712
|
+
const error = (message) => ctx.addIssue({ code: "custom", message });
|
|
1713
|
+
if (v.daily_budget_micros === void 0 && v.total_budget_micros === void 0) error("Supply a daily or total budget");
|
|
1714
|
+
const manual = ["NONE", "ENHANCED_CONVERSION"].includes(v.optimization_target), targetCost = v.optimization_target.startsWith("TARGET_COST_"), costCap = v.optimization_target.startsWith("CAP_COST_");
|
|
1715
|
+
if (manual !== Boolean(v.competing_bid)) error("Manual forecasting requires competing_bid; auto/target/cap forecasts omit it");
|
|
1716
|
+
if (targetCost !== (v.target_cost_micros !== void 0)) error("target_cost_micros is required only for TARGET_COST bidding");
|
|
1717
|
+
if (costCap !== (v.cost_cap_micros !== void 0)) error("cost_cap_micros is required only for CAP_COST bidding");
|
|
1718
|
+
if (v.connected_television_only && (v.campaign_type !== "SPONSORED_UPDATES" || !v.enable_audience_network)) error("Connected television requires SPONSORED_UPDATES and explicit audience-network inclusion");
|
|
1719
|
+
});
|
|
1720
|
+
var paging2 = z12.object({ start: z12.number().int().nonnegative(), count: z12.number().int().nonnegative(), total: z12.number().int().nonnegative().optional(), links: z12.array(z12.looseObject({ rel: z12.string() })).optional() }).optional();
|
|
1721
|
+
var money = moneySchema.safeExtend({ amount: moneySchema.shape.amount.max(100) });
|
|
1722
|
+
var moneyRange = z12.object({ min: money.nullish(), max: money.nullish(), default: money.nullish() });
|
|
1723
|
+
var pricingRow = z12.looseObject({ bidLimits: moneyRange.optional(), dailyBudgetLimits: moneyRange.optional(), suggestedBid: moneyRange.optional() });
|
|
1724
|
+
var pricingResponse = z12.object({ elements: z12.array(pricingRow).max(100), paging: paging2 });
|
|
1725
|
+
var numeric = z12.number().nonnegative();
|
|
1726
|
+
var point = z12.object({ timestamp, value: numeric.nullish(), adForecastRange: z12.object({ lowEnd: numeric.nullish(), highEnd: numeric.nullish() }).optional() });
|
|
1727
|
+
var forecastRow = z12.looseObject({ metricType: z12.string().regex(/^[A-Z][A-Z0-9_]*$/).max(120), granularity: z12.enum(["DAILY", "SEVEN_DAY", "THIRTY_DAY", "CUSTOM"]), timeSeries: z12.array(point).max(1e4) });
|
|
1728
|
+
var forecastResponse = z12.object({ elements: z12.array(forecastRow).max(128), paging: paging2 });
|
|
1729
|
+
var output = { account_id: linkedinId, currency: z12.string().regex(/^[A-Z]{3}$/), truncated: z12.boolean(), planning: planningViewSchema };
|
|
1730
|
+
var pricingOutput = pricingResponse.safeExtend({ ...output, request: pricingInput });
|
|
1731
|
+
var forecastOutput = forecastResponse.safeExtend({ ...output, request: forecastInput });
|
|
1732
|
+
var partial = (value) => Boolean(value.paging && value.paging.start > 0 || value.paging?.links?.some((link) => link.rel === "next")) || value.paging?.total !== void 0 && value.paging.start + value.elements.length < value.paging.total;
|
|
1733
|
+
var exactMoneyCompare = (a, b) => {
|
|
1734
|
+
const [aw, af = ""] = a.split("."), [bw, bf = ""] = b.split("."), length = Math.max(af.length, bf.length);
|
|
1735
|
+
const av = BigInt(aw + af.padEnd(length, "0")), bv = BigInt(bw + bf.padEnd(length, "0"));
|
|
1736
|
+
return av < bv ? -1 : av > bv ? 1 : 0;
|
|
1737
|
+
};
|
|
1738
|
+
var formatPoint = (value) => value == null ? null : String(value);
|
|
1739
|
+
var countMetrics = /* @__PURE__ */ new Set(["IMPRESSION", "CLICK", "VIDEO_VIEW", "LEAD", "SPONSORED_INMAIL_SEND", "CONVERSION", "REACH"]);
|
|
1740
|
+
function unit(metric, currency) {
|
|
1741
|
+
if (["SPENDING", "MAX_POTENTIAL_BUDGET"].includes(metric)) return `${currency} currency units`;
|
|
1742
|
+
if (/^COST_PER_MILLION_(IMPRESSIONS|CLICKS|VIEWS|LEADS|REACHES|MESSAGE_SENDS)$/.test(metric)) return `${currency} per 1,000,000 ${metric.slice("COST_PER_MILLION_".length).toLowerCase().replaceAll("_", " ")}`;
|
|
1743
|
+
if (/^(CLICK|VIDEO_VIEW|LEAD|REACH)_PER_MILLION_IMPRESSIONS$/.test(metric)) return `${metric.split("_PER_")[0]} per 1,000,000 impressions`;
|
|
1744
|
+
return countMetrics.has(metric) ? "count" : "native unit not documented";
|
|
1745
|
+
}
|
|
1746
|
+
var LinkedInPlanningService = class {
|
|
1747
|
+
constructor(client, provider) {
|
|
1748
|
+
this.client = client;
|
|
1749
|
+
this.provider = provider;
|
|
1750
|
+
}
|
|
1751
|
+
client;
|
|
1752
|
+
provider;
|
|
1753
|
+
money(value, currency) {
|
|
1754
|
+
return { amount: microsToDecimal(value), currencyCode: currency };
|
|
1755
|
+
}
|
|
1756
|
+
async pricing(raw) {
|
|
1757
|
+
const input = pricingInput.parse(raw), account2 = await this.provider.getAccount(input.account_id);
|
|
1758
|
+
const result = await this.client.get("adBudgetPricing", pricingResponse, { q: "criteriaV2", account: `urn:li:sponsoredAccount:${input.account_id}`, campaignType: input.campaign_type, bidType: input.bid_type, currency: account2.currency, matchType: input.match_type, targetingCriteria: input.targeting_criteria, ...input.country_code ? { countryCode: input.country_code } : {}, ...input.daily_budget_micros ? { dailyBudget: this.money(input.daily_budget_micros, account2.currency) } : {}, ...input.objective_type ? { objectiveType: input.objective_type } : {}, ...input.optimization_target_type ? { optimizationTargetType: input.optimization_target_type } : {} });
|
|
1759
|
+
const rows = [], notes2 = ["Native pricing estimates, not observed results, budget changes or a campaign-creation validation. No campaign, bid, budget or delivery setting was changed.", input.campaign_type === "SPONSORED_UPDATES" ? "For Sponsored Updates, a bid below bidLimits.min can mean poor delivery; it is not universally a hard rejection threshold." : "For formats other than Sponsored Updates, LinkedIn documents bidLimits.min as a minimum allowable bid."];
|
|
1760
|
+
for (const [index, entry] of result.elements.entries()) for (const [field, label] of [["bidLimits", "Bid limits"], ["dailyBudgetLimits", "Daily budget limits"], ["suggestedBid", "Suggested bid"]]) {
|
|
1761
|
+
const range2 = entry[field];
|
|
1762
|
+
if (!range2) continue;
|
|
1763
|
+
for (const item of [range2.min, range2.max, range2.default]) if (item && item.currencyCode !== account2.currency) throw new AdportError9("PROVIDER_ERROR", "linkedin: pricing returned a foreign currency");
|
|
1764
|
+
if (range2.min && range2.max && exactMoneyCompare(range2.min.amount, range2.max.amount) > 0 || range2.default && range2.min && exactMoneyCompare(range2.default.amount, range2.min.amount) < 0 || range2.default && range2.max && exactMoneyCompare(range2.default.amount, range2.max.amount) > 0) throw new AdportError9("PROVIDER_ERROR", "linkedin: pricing returned inverted bounds or a default outside its range");
|
|
1765
|
+
const basis = field === "dailyBudgetLimits" ? "per day" : input.bid_type === "CPM" ? "per 1,000 impressions" : input.bid_type === "CPC" ? "per click" : "per video view";
|
|
1766
|
+
rows.push({ result: String(index + 1), metric: label, minimum: range2.min?.amount ?? null, suggested: range2.default?.amount ?? null, maximum: range2.max?.amount ?? null, unit: `${account2.currency} ${basis}` });
|
|
1767
|
+
for (const item of [range2.min, range2.max, range2.default]) if (item) {
|
|
1768
|
+
try {
|
|
1769
|
+
decimalToMicros(item.amount);
|
|
1770
|
+
} catch {
|
|
1771
|
+
if (!notes2.some((note) => note.startsWith("Some native"))) notes2.push("Some native decimal amounts cannot be represented as safe integer micros. Exact native decimal strings are preserved; no rounding is performed.");
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
const truncated = partial(result);
|
|
1776
|
+
if (truncated) notes2.push("The native response indicates incomplete results; no undocumented continuation request was made.");
|
|
1777
|
+
if (!rows.length) notes2.push("LinkedIn returned no pricing amounts for this selection. Missing values remain unavailable.");
|
|
1778
|
+
notes2.push(`Selection: ${input.campaign_type}; ${input.bid_type}; ${input.match_type}${input.objective_type ? `; ${input.objective_type}` : ""}. Missing amounts remain unavailable.`);
|
|
1779
|
+
return { ...result, request: input, account_id: input.account_id, currency: account2.currency, truncated, planning: { title: "LinkedIn bid and budget pricing", columns: [...result.elements.length > 1 ? [{ key: "result", label: "Native result" }] : [], { key: "metric", label: "Pricing" }, { key: "minimum", label: "Minimum" }, { key: "suggested", label: "Default / suggested" }, { key: "maximum", label: "Maximum" }, { key: "unit", label: "Unit" }], rows, notes: notes2 } };
|
|
1780
|
+
}
|
|
1781
|
+
async forecast(raw) {
|
|
1782
|
+
const input = forecastInput.parse(raw);
|
|
1783
|
+
if (input.time_range.start <= Date.now()) throw new AdportError9("INVALID_INPUT", "linkedin: forecast start must be after the current UTC time");
|
|
1784
|
+
const account2 = await this.provider.getAccount(input.account_id);
|
|
1785
|
+
if (input.campaign_id) await this.provider.getCampaign(input.account_id, input.campaign_id);
|
|
1786
|
+
const params = { q: "criteriaV2", account: `urn:li:sponsoredAccount:${input.account_id}`, campaignType: input.campaign_type, timeRange: input.time_range, targetingCriteria: input.targeting_criteria, optimizationTarget: input.optimization_target, enableAudienceNetwork: String(input.enable_audience_network), enableAudienceExpansion: String(input.enable_audience_expansion), connectedTelevisionOnly: String(input.connected_television_only), ...input.objective_type ? { objectiveType: input.objective_type } : {}, ...input.creative_type ? { creativeType: input.creative_type } : {}, ...input.campaign_id ? { campaign: `urn:li:sponsoredCampaign:${input.campaign_id}` } : {}, ...input.daily_budget_micros ? { dailyBudget: this.money(input.daily_budget_micros, account2.currency) } : {}, ...input.total_budget_micros ? { totalBudget: this.money(input.total_budget_micros, account2.currency) } : {}, ...input.competing_bid ? { competingBid: { bidType: input.competing_bid.bid_type, bidPrice: this.money(input.competing_bid.bid_micros, account2.currency) } } : {}, ...input.target_cost_micros ? { targetCost: microsToDecimal(input.target_cost_micros) } : {}, ...input.cost_cap_micros ? { costCap: microsToDecimal(input.cost_cap_micros) } : {} };
|
|
1787
|
+
const result = await this.client.get("adSupplyForecasts", forecastResponse, params), rows = [], seen = /* @__PURE__ */ new Set();
|
|
1788
|
+
for (const entry of result.elements) for (const point2 of entry.timeSeries) {
|
|
1789
|
+
const key = `${entry.metricType}:${entry.granularity}:${point2.timestamp}`;
|
|
1790
|
+
if (seen.has(key)) throw new AdportError9("PROVIDER_ERROR", "linkedin: forecast repeated a metric/granularity/timestamp");
|
|
1791
|
+
seen.add(key);
|
|
1792
|
+
const low = point2.adForecastRange?.lowEnd, high = point2.adForecastRange?.highEnd;
|
|
1793
|
+
if (low != null && high != null && low > high) throw new AdportError9("PROVIDER_ERROR", "linkedin: forecast returned inverted bounds");
|
|
1794
|
+
rows.push({ metric: entry.metricType, period: entry.granularity, timestamp: new Date(point2.timestamp).toISOString(), value: formatPoint(point2.value), low: formatPoint(low), high: formatPoint(high), unit: unit(entry.metricType, account2.currency) });
|
|
1795
|
+
if (rows.length > 5e4) throw new AdportError9("PROVIDER_ERROR", "linkedin: native forecast exceeded the supported presentation size");
|
|
1796
|
+
}
|
|
1797
|
+
const truncated = partial(result), notes2 = ["Hypothetical native estimates with uncertainty, not observed performance or a campaign-creation validation. No campaign, ad, bid, budget, audience or delivery setting was changed.", "DAILY, SEVEN_DAY, THIRTY_DAY and CUSTOM periods can overlap; do not add them together. Timestamp is the native period start in UTC, not an end date.", "Per-million metrics retain their native scaling. Divide COST_PER_MILLION_* by 1,000,000 for cost per result; divide *_PER_MILLION_IMPRESSIONS by 1,000,000 for the corresponding ratio. These are not automatically CTR percentages or CPM.", "Missing point estimates or bounds remain unavailable. Native maximum forecast horizon, campaign eligibility and objective/format combinations are validated by LinkedIn."];
|
|
1798
|
+
if (truncated) notes2.push("The native response indicates incomplete results; no undocumented continuation request was made.");
|
|
1799
|
+
if (!rows.length) notes2.push("LinkedIn returned no forecast points for this selection.");
|
|
1800
|
+
notes2.push(`Requested UTC range: ${new Date(input.time_range.start).toISOString()} inclusive to ${new Date(input.time_range.end).toISOString()} exclusive. ${input.campaign_type}; ${input.optimization_target}.`);
|
|
1801
|
+
notes2.push("LinkedIn documents daily forecast spending up to 1.2 times the daily budget. A total budget can exhaust before the forecast range ends, leaving later periods at zero.");
|
|
1802
|
+
return { ...result, request: input, account_id: input.account_id, currency: account2.currency, truncated, planning: { title: "LinkedIn supply forecast", columns: [{ key: "metric", label: "Metric" }, { key: "period", label: "Period" }, { key: "timestamp", label: "Starts (UTC)" }, { key: "value", label: "Estimate" }, { key: "low", label: "Low" }, { key: "high", label: "High" }, { key: "unit", label: "Native unit" }], rows, notes: notes2 } };
|
|
1803
|
+
}
|
|
1804
|
+
};
|
|
1805
|
+
function linkedinPlanningTools(provider) {
|
|
1806
|
+
return [
|
|
1807
|
+
defineTool7({ name: "linkedin_budget_pricing", namespace: "linkedin", description: `Read native bid limits, suggested bids and daily budget limits for targeting, bid type and campaign format. Uses actual account currency and exact decimal results; does not validate campaign creation or change money/delivery. Planning objective/optimization codes are native, not campaign-create aliases. ${NON_DISCRIMINATION_NOTICE}`, input: pricingInput, output: pricingOutput, presentation: "planning", annotations: { readOnly: true }, handler: (input) => provider.planning.pricing(input) }),
|
|
1808
|
+
defineTool7({ name: "linkedin_supply_forecast", namespace: "linkedin", description: "Read hypothetical supply/spend/response estimates and native uncertainty bounds for a future UTC range. Choose manual bid or auto/target/cap mode; budget/bid inputs are integer account-currency micros. Preserves per-million units and overlapping native periods. Does not create, activate or validate a campaign.", input: forecastInput, output: forecastOutput, presentation: "planning", annotations: { readOnly: true }, handler: (input) => provider.planning.forecast(input) })
|
|
1809
|
+
];
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
// src/audiences.ts
|
|
1813
|
+
import { createHash as createHash5 } from "crypto";
|
|
1814
|
+
import { AdportError as AdportError10, defineTool as defineTool8, guardedWriteTool as guardedWriteTool7 } from "@adport/core";
|
|
1815
|
+
import { z as z13 } from "zod";
|
|
1816
|
+
var hash6 = z13.string().regex(/^[a-f0-9]{64}$/);
|
|
1817
|
+
var name4 = z13.string().trim().min(1).max(100);
|
|
1818
|
+
var description2 = z13.string().max(500);
|
|
1819
|
+
var nativeId2 = z13.union([linkedinId, z13.number().int().positive().safe()]).transform(String);
|
|
1820
|
+
var stamp = z13.looseObject({ time: z13.number().int().nonnegative().safe(), actor: z13.string().optional() });
|
|
1821
|
+
var template = z13.looseObject({ id: nativeId2, account: accountUrn, name: z13.string(), description: z13.string().optional(), targetingCriteria: targetingSchema, approximateMemberCount: z13.number().int().nonnegative().safe().optional(), created: stamp.optional(), lastModified: stamp.optional() });
|
|
1822
|
+
var paging3 = z13.looseObject({ start: z13.number().int().nonnegative().safe(), count: z13.number().int().nonnegative().safe(), total: z13.number().int().nonnegative().safe().optional(), links: z13.array(z13.looseObject({ rel: z13.string() })).optional() });
|
|
1823
|
+
var listInput = z13.object({ account_id: linkedinId, start: z13.number().int().nonnegative().safe().default(0), count: z13.number().int().min(1).max(100).default(50), sort_field: z13.enum(["ID", "NAME"]).default("ID"), sort_order: z13.enum(["ASCENDING", "DESCENDING"]).default("ASCENDING") }).strict();
|
|
1824
|
+
var criteria = targetingSchema.refine((value) => value.include.and.every((clause) => Object.keys(clause.or).length > 0) && (!value.exclude || Object.keys(value.exclude.or).length > 0), "Use nonempty targeting clauses");
|
|
1825
|
+
var createInput2 = z13.object({ expected_account_hash: hash6, name: name4, description: description2.optional(), targeting_criteria: criteria }).strict();
|
|
1826
|
+
var reference2 = { template_id: linkedinId, expected_snapshot_hash: hash6 };
|
|
1827
|
+
var updateInput3 = z13.object({ ...reference2, name: name4.optional(), description: description2.optional(), targeting_criteria: criteria.optional() }).strict().refine((value) => value.name !== void 0 || value.description !== void 0 || value.targeting_criteria !== void 0, "Supply an editable template field");
|
|
1828
|
+
var deleteInput = z13.object(reference2).strict();
|
|
1829
|
+
var canonical4 = (value) => Array.isArray(value) ? value.map(canonical4).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, item]) => [key, canonical4(item)])) : value;
|
|
1830
|
+
var digest3 = (value) => createHash5("sha256").update(JSON.stringify(canonical4(value)) ?? "undefined").digest("hex");
|
|
1831
|
+
var snapshot3 = (value) => digest3({ id: value.id, account: value.account, name: value.name, description: value.description ?? null, targetingCriteria: value.targetingCriteria, modified: value.lastModified?.time ?? null });
|
|
1832
|
+
var writes2 = /* @__PURE__ */ new Set(["linkedin_create_saved_audience", "linkedin_update_saved_audience", "linkedin_delete_saved_audience"]);
|
|
1833
|
+
var LinkedInAudienceService = class {
|
|
1834
|
+
constructor(client, provider) {
|
|
1835
|
+
this.client = client;
|
|
1836
|
+
this.provider = provider;
|
|
1837
|
+
}
|
|
1838
|
+
client;
|
|
1839
|
+
provider;
|
|
1840
|
+
supports(tool) {
|
|
1841
|
+
return writes2.has(tool);
|
|
1842
|
+
}
|
|
1843
|
+
async account(account2) {
|
|
1844
|
+
const value = await this.provider.getAccount(linkedinId.parse(account2));
|
|
1845
|
+
return { account_id: account2, account_snapshot_hash: digest3({ id: value.id, currency: value.currency, status: value.status }), account: value };
|
|
1846
|
+
}
|
|
1847
|
+
owned(account2, value, selected) {
|
|
1848
|
+
if (value.account !== `urn:li:sponsoredAccount:${account2}` || selected !== void 0 && value.id !== selected) throw new AdportError10("PROVIDER_ERROR", "linkedin: saved-audience advertiser/ID mismatch");
|
|
1849
|
+
return { ...value, snapshot_hash: snapshot3(value) };
|
|
1850
|
+
}
|
|
1851
|
+
async list(raw) {
|
|
1852
|
+
const input = listInput.parse(raw), context = await this.account(input.account_id);
|
|
1853
|
+
const result = await this.client.get("adTargetTemplates", z13.looseObject({ elements: z13.array(template), paging: paging3.optional() }), { q: "account", account: `urn:li:sponsoredAccount:${input.account_id}`, sortField: input.sort_field, sortOrder: input.sort_order, start: input.start, count: input.count });
|
|
1854
|
+
if (result.elements.length > input.count || result.paging && (result.paging.start !== input.start || result.paging.count > input.count || result.paging.count < result.elements.length) || !result.paging && input.start > 0 || new Set(result.elements.map((row4) => row4.id)).size !== result.elements.length) throw new AdportError10("PROVIDER_ERROR", "linkedin: saved-audience pagination returned an inconsistent offset, size or duplicate identity");
|
|
1855
|
+
const next = Boolean(result.paging?.links?.some((link) => link.rel === "next")) || (result.paging?.total !== void 0 ? input.start + result.elements.length < result.paging.total : result.elements.length === input.count);
|
|
1856
|
+
if (next && !result.elements.length || result.paging?.total !== void 0 && result.elements.length && input.start + result.elements.length > result.paging.total) throw new AdportError10("PROVIDER_ERROR", "linkedin: saved-audience pagination did not advance or contradicted its total");
|
|
1857
|
+
const complete = result.paging ? input.start === 0 && !next : null;
|
|
1858
|
+
return { ...context, ...result, elements: result.elements.map((row4) => this.owned(input.account_id, row4)), truncated: next, complete, ...next && result.paging ? { next_start: input.start + input.count } : {}, notes: [NON_DISCRIMINATION_NOTICE, "Saved templates are targeting definitions. Applying criteria to a campaign uses its separate guarded update.", ...!result.paging ? ["The native response omitted paging metadata; collection completeness is unknown and no continuation is invented."] : []] };
|
|
1859
|
+
}
|
|
1860
|
+
async get(account2, templateId) {
|
|
1861
|
+
const context = await this.account(account2), value = await this.client.get(`adTargetTemplates/${linkedinId.parse(templateId)}`, template);
|
|
1862
|
+
return { ...context, template: this.owned(account2, value, templateId) };
|
|
1863
|
+
}
|
|
1864
|
+
async plan(op) {
|
|
1865
|
+
const create = op.tool === "linkedin_create_saved_audience", remove = op.tool === "linkedin_delete_saved_audience";
|
|
1866
|
+
if (op.provider !== "linkedin" || !writes2.has(op.tool) || op.kind !== (create ? "create" : remove ? "remove" : "update")) throw new AdportError10("INVALID_INPUT", "linkedin: saved-audience operation kind mismatch");
|
|
1867
|
+
const notes2 = [NON_DISCRIMINATION_NOTICE, "Local preview only. This operation writes a saved targeting template, not a campaign, bid, budget or delivery setting.", "Native writes are not idempotent. Uncertain failures consume approval; reconcile the template ID/list before a new preview. No automatic write retry."];
|
|
1868
|
+
if (create) {
|
|
1869
|
+
const input2 = createInput2.parse(op.payload), context = await this.account(op.accountId);
|
|
1870
|
+
if (input2.expected_account_hash !== context.account_snapshot_hash) throw new AdportError10("INVALID_INPUT", "linkedin: advertiser settings changed; read saved audiences again before a new preview");
|
|
1871
|
+
const fields2 = { account: `urn:li:sponsoredAccount:${op.accountId}`, name: input2.name, ...input2.description !== void 0 ? { description: input2.description } : {}, targetingCriteria: input2.targeting_criteria };
|
|
1872
|
+
return { summary: `Create LinkedIn saved audience "${input2.name}"`, changes: [`+ ${JSON.stringify(fields2)}`], notes: notes2, coercions: [], budgetDeltas: [], execute: async () => {
|
|
1873
|
+
const resource = await this.client.create("adTargetTemplates", fields2);
|
|
1874
|
+
try {
|
|
1875
|
+
const current2 = await this.get(op.accountId, resource);
|
|
1876
|
+
if (!this.matches(current2.template, fields2)) throw new Error("settings mismatch");
|
|
1877
|
+
} catch {
|
|
1878
|
+
throw new AdportError10("PROVIDER_ERROR", "linkedin: saved-audience creation readback unconfirmed; inspect the returned ID before any new create", { resource_ids: [resource] });
|
|
1879
|
+
}
|
|
1880
|
+
return { applied: true, resourceIds: [resource] };
|
|
1881
|
+
} };
|
|
1882
|
+
}
|
|
1883
|
+
const input = remove ? deleteInput.parse(op.payload) : updateInput3.parse(op.payload), current = await this.get(op.accountId, input.template_id);
|
|
1884
|
+
if (input.expected_snapshot_hash !== current.template.snapshot_hash) throw new AdportError10("INVALID_INPUT", "linkedin: saved audience changed; read its current snapshot before requesting another preview");
|
|
1885
|
+
if (remove) return { summary: `Permanently delete LinkedIn saved audience "${current.template.name}"`, changes: [`- Saved audience template ${input.template_id}. Native deletion has no restore endpoint.`], notes: notes2, coercions: [], budgetDeltas: [], execute: async () => {
|
|
1886
|
+
await this.client.remove(`adTargetTemplates/${input.template_id}`);
|
|
1887
|
+
return { applied: true, resourceIds: [input.template_id], details: { deletion: "DELETED" } };
|
|
1888
|
+
} };
|
|
1889
|
+
const update = updateInput3.parse(input), fields = { ...update.name !== void 0 ? { name: update.name } : {}, ...update.description !== void 0 ? { description: update.description } : {}, ...update.targeting_criteria !== void 0 ? { targetingCriteria: update.targeting_criteria } : {} };
|
|
1890
|
+
if (this.matches(current.template, fields)) throw new AdportError10("INVALID_INPUT", "linkedin: saved-audience fields already match; no change to apply");
|
|
1891
|
+
const labels2 = { name: "Name", description: "Description", targetingCriteria: "Targeting criteria" };
|
|
1892
|
+
const observed = current.template;
|
|
1893
|
+
return { summary: `Update LinkedIn saved audience "${current.template.name}"`, changes: [`~ Saved template fields ${JSON.stringify(fields)}. Supplied targeting criteria replaces the full definition; omitted fields are preserved.`], review: { provider: "linkedin", accountId: op.accountId, kind: "update", title: "Update saved audience", subject: current.template.name, fields: Object.entries(fields).map(([field, after]) => ({ label: labels2[field], ...Object.hasOwn(observed, field) ? { before: observed[field] } : {}, after })), notices: notes2 }, notes: notes2, coercions: [], budgetDeltas: [], execute: async () => {
|
|
1894
|
+
await this.client.update(`adTargetTemplates/${input.template_id}`, fields);
|
|
1895
|
+
try {
|
|
1896
|
+
if (!this.matches((await this.get(op.accountId, input.template_id)).template, fields)) throw new Error("settings mismatch");
|
|
1897
|
+
} catch {
|
|
1898
|
+
throw new AdportError10("PROVIDER_ERROR", "linkedin: saved-audience update readback unconfirmed; reconcile before a new preview", { resource_ids: [input.template_id] });
|
|
1899
|
+
}
|
|
1900
|
+
return { applied: true, resourceIds: [input.template_id] };
|
|
1901
|
+
} };
|
|
1902
|
+
}
|
|
1903
|
+
matches(actual, expected) {
|
|
1904
|
+
return Object.entries(expected).every(([key, value]) => digest3(actual[key]) === digest3(value));
|
|
1905
|
+
}
|
|
1906
|
+
};
|
|
1907
|
+
function linkedinAudienceTools(provider) {
|
|
1908
|
+
return [
|
|
1909
|
+
defineTool8({ name: "linkedin_saved_audiences", namespace: "linkedin", description: "List advertiser-owned saved audience templates with native account finder, sort and offset paging. Returns account_snapshot_hash for creation and per-template snapshots. Missing paging metadata means unknown completeness.", input: listInput, annotations: { readOnly: true }, handler: (input) => provider.audiences.list(input) }),
|
|
1910
|
+
defineTool8({ name: "linkedin_get_saved_audience", namespace: "linkedin", description: "Read one saved audience template, verify advertiser/ID and return its current snapshot_hash for guarded edits/deletion.", input: z13.object({ account_id: linkedinId, template_id: linkedinId }), annotations: { readOnly: true }, handler: (input) => provider.audiences.get(input.account_id, input.template_id) }),
|
|
1911
|
+
guardedWriteTool7({ name: "linkedin_create_saved_audience", namespace: "linkedin", provider: "linkedin", kind: "create", destructive: false, description: "Create a saved targeting template using expected_account_hash from linkedin_saved_audiences. Native name\u2264100/description\u2264500. Does not send a campaign update; no automatic retry. Creation is independently read back.", payload: createInput2 }),
|
|
1912
|
+
guardedWriteTool7({ name: "linkedin_update_saved_audience", namespace: "linkedin", provider: "linkedin", kind: "update", description: "Update supplied saved-template name, description or complete targeting_criteria using expected_snapshot_hash. Omitted fields stay unchanged; empty description clears text. Verifies native readback; no campaign update or automatic retry.", payload: updateInput3 }),
|
|
1913
|
+
guardedWriteTool7({ name: "linkedin_delete_saved_audience", namespace: "linkedin", provider: "linkedin", kind: "remove", description: "Permanently delete one advertiser-owned saved targeting template using expected_snapshot_hash. Native204 confirms deletion; no restore endpoint or automatic retry.", payload: deleteInput })
|
|
1914
|
+
];
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
// src/reporting.ts
|
|
1918
|
+
import { z as z14 } from "zod";
|
|
1919
|
+
import { AdportError as AdportError11, defineTool as defineTool9 } from "@adport/core";
|
|
1920
|
+
var pivots = ["MEMBER_COMPANY_SIZE", "MEMBER_INDUSTRY", "MEMBER_SENIORITY", "MEMBER_JOB_TITLE", "MEMBER_JOB_FUNCTION", "MEMBER_COUNTRY_V2", "MEMBER_REGION_V2", "MEMBER_COMPANY"];
|
|
1921
|
+
var metrics = ["impressions", "clicks", "landingPageClicks", "costInLocalCurrency", "costInUsd", "externalWebsiteConversions", "externalWebsitePostClickConversions", "externalWebsitePostViewConversions", "oneClickLeads", "oneClickLeadFormOpens", "totalEngagements", "reactions", "comments", "shares", "follows", "videoViews", "videoCompletions", "opens", "sends"];
|
|
1922
|
+
var taxonomyUrn = z14.string().regex(/^urn:li:(?:(?:geo|industry|seniority|title|function|organization):[1-9]\d*|staffCountRange:\(\d+,\d+\))$/);
|
|
1923
|
+
var locale2 = z14.object({ language: z14.string().regex(/^[a-z]{2}$/), country: z14.string().regex(/^[A-Z]{2}$/) }).strict();
|
|
1924
|
+
var unique = (values) => new Set(values).size === values.length;
|
|
1925
|
+
var range = z14.object({ start: z14.iso.date(), end: z14.iso.date() }).strict().refine((value) => value.end >= value.start, "End must be on or after start");
|
|
1926
|
+
var demographicInput = z14.object({
|
|
1927
|
+
account_id: linkedinId,
|
|
1928
|
+
pivot: z14.enum(pivots),
|
|
1929
|
+
date_range: range,
|
|
1930
|
+
time_granularity: z14.enum(["ALL", "DAILY", "MONTHLY", "YEARLY"]).default("ALL"),
|
|
1931
|
+
metrics: z14.array(z14.enum(metrics)).min(1).max(18).refine(unique, "Choose distinct metrics").default(["impressions", "clicks", "costInLocalCurrency"]),
|
|
1932
|
+
campaign_ids: z14.array(linkedinId).min(1).max(20).refine(unique, "Choose distinct campaign IDs").optional(),
|
|
1933
|
+
limit: z14.number().int().min(1).max(1e3).default(100),
|
|
1934
|
+
resolve_names: z14.boolean().default(false),
|
|
1935
|
+
locale: locale2.optional()
|
|
1936
|
+
}).strict();
|
|
1937
|
+
var resolveEntitiesInput = z14.object({ account_id: linkedinId, urns: z14.array(taxonomyUrn).min(1).max(100).refine(unique, "Choose distinct URNs"), locale: locale2.optional() }).strict();
|
|
1938
|
+
var nativeDate = z14.object({ year: z14.number().int().min(1).max(9999), month: z14.number().int().min(1).max(12), day: z14.number().int().min(1).max(31) });
|
|
1939
|
+
var dateRange = z14.object({ start: nativeDate, end: nativeDate });
|
|
1940
|
+
var count = z14.number().int().nonnegative().safe().nullish();
|
|
1941
|
+
var decimal2 = z14.string().max(100).regex(/^\d+(?:\.\d+)?$/).nullish();
|
|
1942
|
+
var metricFields = Object.fromEntries(metrics.map((metric) => [metric, metric.startsWith("costIn") ? decimal2 : count]));
|
|
1943
|
+
var rowSchema = z14.object({ pivotValues: z14.array(taxonomyUrn).length(1), dateRange, ...metricFields });
|
|
1944
|
+
var paging4 = z14.object({ start: z14.number().int().nonnegative().safe().optional(), count: z14.number().int().nonnegative().safe().optional(), total: z14.number().int().nonnegative().safe().optional(), links: z14.array(z14.object({ rel: z14.string() })).optional() });
|
|
1945
|
+
var responseSchema = z14.object({ elements: z14.array(rowSchema).max(15e3), paging: paging4.optional() });
|
|
1946
|
+
var entitySchema = z14.object({ urn: taxonomyUrn, name: z14.string().min(1).max(1e3), facetUrn: z14.string().max(200).optional() });
|
|
1947
|
+
var resolvedEntity = z14.object({ urn: taxonomyUrn, name: z14.string().optional(), names: z14.array(z14.string()), facet_urns: z14.array(z14.string()) });
|
|
1948
|
+
var cell = z14.union([z14.string(), z14.number().finite(), z14.null()]);
|
|
1949
|
+
var demographicOutput = z14.object({
|
|
1950
|
+
account_id: linkedinId,
|
|
1951
|
+
currency: z14.string().regex(/^[A-Z]{3}$/),
|
|
1952
|
+
request: demographicInput,
|
|
1953
|
+
rows: z14.array(z14.object({ urn: taxonomyUrn, name: z14.string().optional(), date_range: range, metrics: z14.record(z14.string(), cell) })).max(1e3),
|
|
1954
|
+
records: z14.array(z14.record(z14.string(), cell)).max(1e3),
|
|
1955
|
+
returned_native_rows: z14.number().int().min(0).max(15e3),
|
|
1956
|
+
truncated: z14.boolean(),
|
|
1957
|
+
complete: z14.literal(false),
|
|
1958
|
+
coverage: z14.object({ approximate: z14.literal(true), minimum_events: z14.literal(3), top_values_per_creative_day: z14.literal(100), native_row_limit: z14.literal(15e3), pagination_supported: z14.literal(false) }),
|
|
1959
|
+
notes: z14.array(z14.string())
|
|
1960
|
+
});
|
|
1961
|
+
var resolveOutput = z14.object({ account_id: linkedinId, elements: z14.array(entitySchema).max(1e3), entities: z14.array(resolvedEntity).max(100), records: z14.array(z14.object({ id: taxonomyUrn, name: z14.string(), names: z14.array(z14.string()).optional(), facets: z14.array(z14.string()) })).max(100), paging: paging4.optional(), unresolved_urns: z14.array(taxonomyUrn).max(100), ambiguous_urns: z14.array(taxonomyUrn).max(100), notes: z14.array(z14.string()) });
|
|
1962
|
+
var pivotType = { MEMBER_COMPANY_SIZE: "staffCountRange", MEMBER_INDUSTRY: "industry", MEMBER_SENIORITY: "seniority", MEMBER_JOB_TITLE: "title", MEMBER_JOB_FUNCTION: "function", MEMBER_COUNTRY_V2: "geo", MEMBER_REGION_V2: "geo", MEMBER_COMPANY: "organization" };
|
|
1963
|
+
var toDate = (iso) => {
|
|
1964
|
+
const [year, month, day] = iso.split("-").map(Number);
|
|
1965
|
+
return { year, month, day };
|
|
1966
|
+
};
|
|
1967
|
+
var fromDate = (value) => {
|
|
1968
|
+
const result = z14.iso.date().safeParse(`${String(value.year).padStart(4, "0")}-${String(value.month).padStart(2, "0")}-${String(value.day).padStart(2, "0")}`);
|
|
1969
|
+
if (!result.success) throw new AdportError11("PROVIDER_ERROR", "linkedin: analytics returned an invalid calendar date");
|
|
1970
|
+
return result.data;
|
|
1971
|
+
};
|
|
1972
|
+
var LinkedInReportingService = class {
|
|
1973
|
+
constructor(client, provider) {
|
|
1974
|
+
this.client = client;
|
|
1975
|
+
this.provider = provider;
|
|
1976
|
+
}
|
|
1977
|
+
client;
|
|
1978
|
+
provider;
|
|
1979
|
+
async names(urns, selectedLocale) {
|
|
1980
|
+
const result = await this.client.get("adTargetingEntities", z14.object({ elements: z14.array(entitySchema).max(1e3), paging: paging4.optional() }), {
|
|
1981
|
+
q: "urns",
|
|
1982
|
+
queryVersion: "QUERY_USES_URNS",
|
|
1983
|
+
fetchType: "SINGLE_NODE",
|
|
1984
|
+
urns,
|
|
1985
|
+
...selectedLocale ? { locale: selectedLocale } : {}
|
|
1986
|
+
});
|
|
1987
|
+
const unrequested = [...new Set(result.elements.filter((entity) => !urns.includes(entity.urn)).map((entity) => entity.urn))];
|
|
1988
|
+
if (unrequested.length) throw new AdportError11("PROVIDER_ERROR", "linkedin: URN resolution returned an unrequested entity", { requested_urns: urns, returned_count: result.elements.length, unrequested_urns: unrequested });
|
|
1989
|
+
const entities = urns.flatMap((urn) => {
|
|
1990
|
+
const variants = result.elements.filter((entity) => entity.urn === urn);
|
|
1991
|
+
if (!variants.length) return [];
|
|
1992
|
+
const names = [...new Set(variants.map((entity) => entity.name))], facets2 = [...new Set(variants.flatMap((entity) => entity.facetUrn ? [entity.facetUrn] : []))];
|
|
1993
|
+
return [{ urn, ...names.length === 1 ? { name: names[0] } : {}, names, facet_urns: facets2 }];
|
|
1994
|
+
});
|
|
1995
|
+
return { ...result, entities, unresolved_urns: urns.filter((urn) => !entities.some((entity) => entity.urn === urn)), ambiguous_urns: entities.filter((entity) => entity.name === void 0).map((entity) => entity.urn) };
|
|
1996
|
+
}
|
|
1997
|
+
async resolveEntities(raw) {
|
|
1998
|
+
const input = resolveEntitiesInput.parse(raw);
|
|
1999
|
+
await this.provider.getAccount(input.account_id);
|
|
2000
|
+
const result = await this.names(input.urns, input.locale);
|
|
2001
|
+
return { account_id: input.account_id, ...result, records: result.entities.map((entity) => ({ id: entity.urn, name: entity.name ?? entity.urn, ...entity.name === void 0 ? { names: entity.names } : {}, facets: entity.facet_urns.map((facet) => facet.split(":").at(-1)) })), notes: [...result.unresolved_urns.length ? ["Some requested URNs were not resolved. Their names are unavailable; no descendant or alternate-identity lookup was made."] : [], ...result.ambiguous_urns.length ? ["Some URNs have conflicting native names. All variants are preserved; no single name was selected for them."] : []] };
|
|
2002
|
+
}
|
|
2003
|
+
async demographics(raw) {
|
|
2004
|
+
const input = demographicInput.parse(raw), account2 = await this.provider.getAccount(input.account_id);
|
|
2005
|
+
for (const campaign of input.campaign_ids ?? []) await this.provider.getCampaign(input.account_id, campaign);
|
|
2006
|
+
const params = {
|
|
2007
|
+
q: "analytics",
|
|
2008
|
+
pivot: input.pivot,
|
|
2009
|
+
timeGranularity: input.time_granularity,
|
|
2010
|
+
dateRange: { start: toDate(input.date_range.start), end: toDate(input.date_range.end) },
|
|
2011
|
+
accounts: [`urn:li:sponsoredAccount:${input.account_id}`],
|
|
2012
|
+
...input.campaign_ids ? { campaigns: input.campaign_ids.map((id2) => `urn:li:sponsoredCampaign:${id2}`) } : {},
|
|
2013
|
+
fields: ["pivotValues", "dateRange", ...input.metrics].join(",")
|
|
2014
|
+
};
|
|
2015
|
+
const result = await this.client.get("adAnalytics", responseSchema, params), seen = /* @__PURE__ */ new Set();
|
|
2016
|
+
const rows = result.elements.map((row4) => {
|
|
2017
|
+
const urn = row4.pivotValues[0], start = fromDate(row4.dateRange.start), end = fromDate(row4.dateRange.end);
|
|
2018
|
+
if (urn.split(":")[2] !== pivotType[input.pivot]) throw new AdportError11("PROVIDER_ERROR", "linkedin: unexpected demographic pivot identity");
|
|
2019
|
+
if (start > end || start < input.date_range.start || end > input.date_range.end || input.time_granularity === "ALL" && (start !== input.date_range.start || end !== input.date_range.end) || input.time_granularity === "DAILY" && start !== end) throw new AdportError11("PROVIDER_ERROR", "linkedin: native reporting dates differ from the requested scope; older or bucketed queries may need explicit month/year boundaries");
|
|
2020
|
+
const key = JSON.stringify([urn, start, end]);
|
|
2021
|
+
if (seen.has(key)) throw new AdportError11("PROVIDER_ERROR", "linkedin: duplicate demographic period/identity");
|
|
2022
|
+
seen.add(key);
|
|
2023
|
+
return { urn, date_range: { start, end }, metrics: Object.fromEntries(input.metrics.map((metric) => [metric, row4[metric] ?? null])) };
|
|
2024
|
+
});
|
|
2025
|
+
const nativePartial = result.elements.length === 15e3 || Boolean(result.paging?.start || result.paging?.links?.some((link) => link.rel === "next")) || result.paging?.total !== void 0 && result.paging.total > result.elements.length;
|
|
2026
|
+
const selected = rows.slice(0, input.limit), notes2 = [
|
|
2027
|
+
"Professional-demographic results are approximate, can lag by 12\u201324 hours, and omit values below LinkedIn\u2019s three-event privacy threshold. Native selection also limits each creative/day to its top 100 demographic values. Do not add segments into an exact account total.",
|
|
2028
|
+
"Missing metrics remain null. Empty data can mean no activity or insufficient native data access; it does not establish zero activity. These metrics do not identify individual members.",
|
|
2029
|
+
"Demographic spend is in the reported currency and is not adjusted for overdelivery. Conversion value, reach and carousel metrics are unavailable for these pivots."
|
|
2030
|
+
];
|
|
2031
|
+
if (!rows.length) notes2.push("No demographic rows returned for this selection.");
|
|
2032
|
+
if (nativePartial || rows.length > input.limit) notes2.push("The response is partial or locally limited. This endpoint has no supported pagination; narrow dates/campaigns rather than inventing a continuation cursor.");
|
|
2033
|
+
const labels2 = /* @__PURE__ */ new Map();
|
|
2034
|
+
if (input.resolve_names && selected.length) {
|
|
2035
|
+
const urns = [...new Set(selected.map((row4) => row4.urn))].slice(0, 100);
|
|
2036
|
+
try {
|
|
2037
|
+
const resolved = await this.names(urns, input.locale);
|
|
2038
|
+
resolved.entities.forEach((entity) => {
|
|
2039
|
+
if (entity.name !== void 0) labels2.set(entity.urn, entity.name);
|
|
2040
|
+
});
|
|
2041
|
+
if (resolved.unresolved_urns.length || resolved.ambiguous_urns.length || new Set(selected.map((row4) => row4.urn)).size > 100) notes2.push("Names are unavailable or ambiguous for some values; only the first 100 distinct returned URNs were resolved. Original URNs are preserved.");
|
|
2042
|
+
} catch {
|
|
2043
|
+
notes2.push("Optional name lookup was not confirmed. Original demographic URNs are preserved; the analytics read was not repeated.");
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
return {
|
|
2047
|
+
account_id: input.account_id,
|
|
2048
|
+
currency: account2.currency,
|
|
2049
|
+
request: input,
|
|
2050
|
+
rows: selected.map((row4) => ({ ...row4, ...labels2.has(row4.urn) ? { name: labels2.get(row4.urn) } : {} })),
|
|
2051
|
+
records: selected.map((row4) => ({ name: labels2.get(row4.urn) ?? row4.urn, ...Object.fromEntries(input.metrics.map((metric) => [metric, metric === "costInLocalCurrency" || metric === "costInUsd" ? row4.metrics[metric] == null ? null : `${row4.metrics[metric]} ${metric === "costInUsd" ? "USD" : account2.currency}` : row4.metrics[metric]])), period: `${row4.date_range.start} \u2013 ${row4.date_range.end}` })),
|
|
2052
|
+
returned_native_rows: rows.length,
|
|
2053
|
+
truncated: nativePartial || rows.length > input.limit,
|
|
2054
|
+
complete: false,
|
|
2055
|
+
coverage: { approximate: true, minimum_events: 3, top_values_per_creative_day: 100, native_row_limit: 15e3, pagination_supported: false },
|
|
2056
|
+
notes: notes2
|
|
2057
|
+
};
|
|
2058
|
+
}
|
|
2059
|
+
};
|
|
2060
|
+
function linkedinReportingTools(provider) {
|
|
2061
|
+
return [
|
|
2062
|
+
defineTool9({ name: "linkedin_demographic_report", namespace: "linkedin", description: "Read native professional-demographic ad metrics by company size, industry, seniority, title, function, country, region or company. UTC dates are inclusive; exact spend strings and missing values are preserved. Results are approximate/privacy-filtered, not complete audience totals. Optional bounded URN name lookup. No native paging. " + NON_DISCRIMINATION_NOTICE, input: demographicInput, output: demographicOutput, presentation: "records", annotations: { readOnly: true, openWorld: false }, handler: (input) => provider.reporting.demographics(input) }),
|
|
2063
|
+
defineTool9({ name: "linkedin_resolve_targeting_entities", namespace: "linkedin", description: "Resolve up to 100 exact demographic/targeting taxonomy URNs to native localized names. SINGLE_NODE only; no descendant expansion. Unknown names stay unresolved. Verifies selected-account access before the public taxonomy lookup.", input: resolveEntitiesInput, output: resolveOutput, presentation: "records", annotations: { readOnly: true, openWorld: false }, handler: (input) => provider.reporting.resolveEntities(input) })
|
|
2064
|
+
];
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
// src/measurement.ts
|
|
2068
|
+
import { createHash as createHash6 } from "crypto";
|
|
2069
|
+
import { AdportError as AdportError12, defineTool as defineTool10, guardedWriteTool as guardedWriteTool8 } from "@adport/core";
|
|
2070
|
+
import { z as z15 } from "zod";
|
|
2071
|
+
var nativeId3 = z15.union([linkedinId, z15.number().int().positive().safe()]).transform(String);
|
|
2072
|
+
var hash7 = z15.string().regex(/^[a-f0-9]{64}$/);
|
|
2073
|
+
var campaignUrn2 = z15.string().regex(/^urn:li:sponsoredCampaign:[1-9]\d*$/);
|
|
2074
|
+
var conversionUrn = z15.string().regex(/^urn:lla:llaPartnerConversion:[1-9]\d*$/);
|
|
2075
|
+
var tagUrn = z15.string().regex(/^urn:tscp:insightTag:[1-9]\d*$/);
|
|
2076
|
+
var websiteTypes = ["ADD_TO_CART", "DOWNLOAD", "INSTALL", "KEY_PAGE_VIEW", "LEAD", "PURCHASE", "SIGN_UP", "OTHER"];
|
|
2077
|
+
var conversionTypes = [...websiteTypes, "SAVE", "START_CHECKOUT", "SCHEDULE", "VIEW_CONTENT", "VIEW_VIDEO", "ADD_BILLING_INFO", "BOOK_APPOINTMENT", "REQUEST_QUOTE", "SEARCH", "SUBSCRIBE", "AD_CLICK", "AD_VIEW", "COMPLETE_SIGNUP", "SUBMIT_APPLICATION", "PHONE_CALL", "INVITE", "LOGIN", "SHARE", "DONATE", "ADD_TO_LIST", "START_TRIAL", "OUTBOUND_CLICK", "CONTACT", "QUALIFIED_LEAD", "MARKETING_QUALIFIED_LEAD", "SALES_QUALIFIED_LEAD"];
|
|
2078
|
+
var extendedWindows = /* @__PURE__ */ new Set(["SUBMIT_APPLICATION", "PURCHASE", "ADD_TO_CART", "QUALIFIED_LEAD", "LEAD", "MARKETING_QUALIFIED_LEAD", "SALES_QUALIFIED_LEAD"]);
|
|
2079
|
+
var windowDays = z15.union([z15.literal(1), z15.literal(7), z15.literal(30), z15.literal(90), z15.literal(180), z15.literal(365)]);
|
|
2080
|
+
var money2 = z15.object({ currencyCode: z15.string().regex(/^[A-Z]{3}$/), amount: z15.string().max(100).regex(/^\d+(?:\.\d+)?$/) }).strict();
|
|
2081
|
+
var rule = z15.object({ matchType: z15.enum(["EXACT", "STARTS_WITH", "CONTAINS"]), matchValue: z15.string().trim().min(1).max(4096) }).strict();
|
|
2082
|
+
var rules = z15.array(z15.array(rule).min(1).max(100)).max(100);
|
|
2083
|
+
var association = z15.looseObject({ campaign: campaignUrn2, conversion: conversionUrn, associatedAt: z15.number().int().nonnegative().safe().optional() });
|
|
2084
|
+
var conversion = z15.looseObject({ id: nativeId3, account: accountUrn, name: z15.string(), type: z15.string(), enabled: z15.boolean(), conversionMethod: z15.string().optional(), ownershipType: z15.enum(["OWNED", "SHARED"]).optional(), attributionType: z15.string().optional(), postClickAttributionWindowSize: z15.number().int().nonnegative().optional(), viewThroughAttributionWindowSize: z15.number().int().nonnegative().optional(), value: money2.optional(), valueType: z15.string().optional(), urlMatchRuleExpression: rules.optional(), campaigns: z15.array(campaignUrn2).optional(), associatedCampaigns: z15.array(association).optional(), lastModified: z15.number().int().nonnegative().safe().optional(), imagePixelTag: z15.string().optional() });
|
|
2085
|
+
var insightTag = z15.looseObject({ id: nativeId3, sponsoredAccounts: z15.array(accountUrn).min(1), firstPartyTrackingEnabled: z15.boolean(), tag: z15.string().optional() });
|
|
2086
|
+
var domain = z15.looseObject({ domainName: z15.string(), insightTag: tagUrn, blocked: z15.boolean(), created: z15.number().int().nonnegative().safe().optional(), lastCallbackAt: z15.number().int().nonnegative().safe().optional() });
|
|
2087
|
+
var paging5 = z15.looseObject({ start: z15.number().int().nonnegative().safe(), count: z15.number().int().nonnegative().safe(), total: z15.number().int().safe().optional(), links: z15.array(z15.looseObject({ rel: z15.string(), href: z15.string().optional() })).optional() });
|
|
2088
|
+
var pageInput2 = { start: z15.number().int().nonnegative().safe().default(0), count: z15.number().int().min(1).max(100).default(50) };
|
|
2089
|
+
var listInput2 = z15.object({ account_id: linkedinId, ...pageInput2, include_shared: z15.boolean().default(false) }).strict();
|
|
2090
|
+
var associationInput = z15.object({ account_id: linkedinId, campaign_id: linkedinId, ...pageInput2, complete_snapshot: z15.boolean().default(false) }).strict();
|
|
2091
|
+
var editable = { name: z15.string().trim().min(1).max(200), type: z15.enum(conversionTypes), enabled: z15.boolean(), attribution_type: z15.enum(["LAST_TOUCH_BY_CAMPAIGN", "LAST_TOUCH_BY_CONVERSION"]), post_click_window_days: windowDays, view_through_window_days: windowDays, value: money2, value_type: z15.enum(["DYNAMIC", "FIXED", "NO_VALUE"]), url_match_rule_expression: rules };
|
|
2092
|
+
var createInput3 = z15.object({ expected_account_hash: hash7, source: z15.enum(["INSIGHT_TAG", "CONVERSIONS_API"]).default("INSIGHT_TAG"), name: editable.name, type: editable.type, enabled: editable.enabled.default(false), attribution_type: editable.attribution_type.default("LAST_TOUCH_BY_CAMPAIGN"), post_click_window_days: windowDays.default(30), view_through_window_days: windowDays.default(7), value: money2.optional(), value_type: editable.value_type.optional(), url_match_rule_expression: rules.optional() }).strict();
|
|
2093
|
+
var updateInput4 = z15.object({ conversion_id: linkedinId, expected_snapshot_hash: hash7, name: editable.name.optional(), type: editable.type.optional(), enabled: editable.enabled.optional(), attribution_type: editable.attribution_type.optional(), post_click_window_days: windowDays.optional(), view_through_window_days: windowDays.optional(), value: money2.optional(), value_type: editable.value_type.optional(), url_match_rule_expression: rules.optional() }).strict().refine((input) => Object.keys(editable).some((key) => Object.hasOwn(input, key)), "Supply conversion fields to change");
|
|
2094
|
+
var tagCreateInput = z15.object({ expected_account_hash: hash7 }).strict();
|
|
2095
|
+
var tagUpdateInput = z15.object({ insight_tag_id: linkedinId, expected_snapshot_hash: hash7, first_party_tracking_enabled: z15.boolean() }).strict();
|
|
2096
|
+
var setAssociationInput = z15.object({ campaign_id: linkedinId, conversion_id: linkedinId, associated: z15.boolean(), expected_conversion_hash: hash7, expected_associations_hash: hash7 }).strict();
|
|
2097
|
+
var contextOutput2 = { account_id: linkedinId, currency: z15.string().regex(/^[A-Z]{3}$/), account_snapshot_hash: hash7 };
|
|
2098
|
+
var records2 = z15.array(z15.record(z15.string(), z15.unknown()));
|
|
2099
|
+
var collectionOutput = (element) => z15.looseObject({ ...contextOutput2, elements: z15.array(element), records: records2, paging: paging5.optional(), complete: z15.boolean().nullable(), truncated: z15.boolean(), next_start: z15.number().int().nonnegative().safe().optional(), notes: z15.array(z15.string()).optional() });
|
|
2100
|
+
var conversionOutput = conversion.extend({ id: linkedinId, snapshot_hash: hash7.optional(), editable: z15.boolean().optional() });
|
|
2101
|
+
var tagsOutput = z15.object({ ...contextOutput2, elements: z15.array(insightTag.extend({ id: linkedinId, snapshot_hash: hash7 })).max(1), records: records2, complete: z15.literal(true), notes: z15.array(z15.string()) });
|
|
2102
|
+
var singleConversionOutput = z15.object({ ...contextOutput2, conversion: conversion.extend({ id: linkedinId, snapshot_hash: hash7 }), records: records2 });
|
|
2103
|
+
var associationsOutput = collectionOutput(association).extend({ campaign_id: linkedinId, associations_snapshot_hash: hash7.optional() });
|
|
2104
|
+
var writes3 = /* @__PURE__ */ new Set(["linkedin_create_insight_tag", "linkedin_update_insight_tag", "linkedin_create_conversion", "linkedin_update_conversion", "linkedin_set_campaign_conversion"]);
|
|
2105
|
+
var 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, item]) => [key, key === "amount" && typeof item === "string" && /^\d+(?:\.\d+)?$/.test(item) ? item.replace(/^0+(?=\d)/, "").replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "") : canonical5(item)])) : value;
|
|
2106
|
+
var digest4 = (value) => createHash6("sha256").update(JSON.stringify(canonical5(value)) ?? "undefined").digest("hex");
|
|
2107
|
+
var same2 = (a, b) => digest4(a) === digest4(b);
|
|
2108
|
+
var matches3 = (actual, fields) => Object.entries(fields).every(([key, value]) => same2(actual[key], value));
|
|
2109
|
+
var selectedAccount = (account2) => `urn:li:sponsoredAccount:${linkedinId.parse(account2)}`;
|
|
2110
|
+
var snapshot4 = (value) => digest4(Object.fromEntries(["id", "account", "name", "type", "enabled", "conversionMethod", "attributionType", "postClickAttributionWindowSize", "viewThroughAttributionWindowSize", "value", "valueType", "urlMatchRuleExpression", "urlRules", "campaigns", "associatedCampaigns", "lastModified"].map((key) => [key, value[key] ?? null])));
|
|
2111
|
+
var tagSnapshot = (value) => digest4({ id: value.id, sponsoredAccounts: value.sponsoredAccounts, firstPartyTrackingEnabled: value.firstPartyTrackingEnabled });
|
|
2112
|
+
var notices2 = ["Local preview only. No tracking code is installed or executed and no conversion events are sent.", "Native writes are not retried automatically. Reconcile returned resource IDs before a new approval after an uncertain result."];
|
|
2113
|
+
var LinkedInMeasurementService = class {
|
|
2114
|
+
constructor(client, provider) {
|
|
2115
|
+
this.client = client;
|
|
2116
|
+
this.provider = provider;
|
|
2117
|
+
}
|
|
2118
|
+
client;
|
|
2119
|
+
provider;
|
|
2120
|
+
supports(tool) {
|
|
2121
|
+
return writes3.has(tool);
|
|
2122
|
+
}
|
|
2123
|
+
async account(account2) {
|
|
2124
|
+
const value = await this.provider.getAccount(linkedinId.parse(account2));
|
|
2125
|
+
return { account_id: account2, currency: value.currency, account_snapshot_hash: digest4({ id: value.id, currency: value.currency, status: value.status }) };
|
|
2126
|
+
}
|
|
2127
|
+
owned(account2, value, selected) {
|
|
2128
|
+
if (value.account !== selectedAccount(account2) || value.ownershipType === "SHARED" || selected !== void 0 && value.id !== selected || value.associatedCampaigns?.some((item) => item.conversion !== `urn:lla:llaPartnerConversion:${value.id}`)) throw new AdportError12("PROVIDER_ERROR", "linkedin: conversion advertiser/ID mismatch or shared ownership");
|
|
2129
|
+
return { ...value, snapshot_hash: snapshot4(value) };
|
|
2130
|
+
}
|
|
2131
|
+
async ownedConversion(account2, conversionId) {
|
|
2132
|
+
return this.owned(account2, await this.client.get(`conversions/${linkedinId.parse(conversionId)}`, conversion, { account: selectedAccount(account2) }), conversionId);
|
|
2133
|
+
}
|
|
2134
|
+
conversionRecord(value) {
|
|
2135
|
+
return { id: value.id, name: value.name, type: value.type, status: value.enabled ? "Enabled" : "Disabled", source: value.conversionMethod ?? "Insight Tag", ...value.value ? { value: `${value.value.amount} ${value.value.currencyCode}` } : {}, ...value.postClickAttributionWindowSize !== void 0 ? { click_window_days: value.postClickAttributionWindowSize } : {}, ...value.viewThroughAttributionWindowSize !== void 0 ? { view_window_days: value.viewThroughAttributionWindowSize } : {} };
|
|
2136
|
+
}
|
|
2137
|
+
async conversions(raw) {
|
|
2138
|
+
const input = listInput2.parse(raw), context = await this.account(input.account_id);
|
|
2139
|
+
const result = await this.client.get("conversions", z15.looseObject({ elements: z15.array(conversion), paging: paging5.optional() }), { q: "account", account: selectedAccount(input.account_id), start: input.start, count: input.count, ...input.include_shared ? { conversionOwnershipTypes: ["OWNED", "SHARED"] } : {} });
|
|
2140
|
+
const elements = result.elements.map((value) => input.include_shared && value.ownershipType === "SHARED" ? { ...value, editable: false } : { ...this.owned(input.account_id, value), editable: true });
|
|
2141
|
+
if (new Set(elements.map((value) => value.id)).size !== elements.length) throw new AdportError12("PROVIDER_ERROR", "linkedin: conversion finder repeated an identity");
|
|
2142
|
+
return { ...context, ...result, elements, records: elements.map((value) => this.conversionRecord(value)), ...linkedinPageState(result, input.start, input.count, "conversions") };
|
|
2143
|
+
}
|
|
2144
|
+
async getConversion(account2, conversionId) {
|
|
2145
|
+
const context = await this.account(account2), value = await this.ownedConversion(account2, conversionId);
|
|
2146
|
+
return { ...context, conversion: value, records: [this.conversionRecord(value)] };
|
|
2147
|
+
}
|
|
2148
|
+
async tags(account2) {
|
|
2149
|
+
const result = await this.client.get("insightTags", z15.looseObject({ elements: z15.array(insightTag).max(1), paging: paging5.optional() }), { q: "account", account: selectedAccount(account2) });
|
|
2150
|
+
if (result.paging?.links?.some((link) => link.rel === "next") || result.elements.some((value) => !value.sponsoredAccounts.includes(selectedAccount(account2)) || new Set(value.sponsoredAccounts).size !== value.sponsoredAccounts.length)) throw new AdportError12("PROVIDER_ERROR", "linkedin: Insight Tag membership or single-tag finder mismatch");
|
|
2151
|
+
return result.elements.map((value) => ({ ...value, snapshot_hash: tagSnapshot(value) }));
|
|
2152
|
+
}
|
|
2153
|
+
async insightTags(account2) {
|
|
2154
|
+
const context = await this.account(account2), elements = await this.tags(account2);
|
|
2155
|
+
return { ...context, elements, records: elements.map((value) => ({ id: value.id, first_party_tracking_enabled: value.firstPartyTrackingEnabled, associated_accounts: value.sponsoredAccounts, shared: value.sponsoredAccounts.length > 1 })), complete: true, notes: ["An advertiser has at most one Insight Tag. Returned tag code is inert text, never executed by the widget.", ...notices2] };
|
|
2156
|
+
}
|
|
2157
|
+
async domains(raw) {
|
|
2158
|
+
const input = z15.object({ account_id: linkedinId, ...pageInput2 }).parse(raw), context = await this.account(input.account_id), tags = await this.tags(input.account_id);
|
|
2159
|
+
if (!tags.length) return { ...context, elements: [], records: [], complete: true, truncated: false };
|
|
2160
|
+
const result = await this.client.get("insightTagDomains", z15.looseObject({ elements: z15.array(domain), paging: paging5.optional() }), { q: "account", account: selectedAccount(input.account_id), start: input.start, count: input.count });
|
|
2161
|
+
if (result.elements.some((value) => value.insightTag !== `urn:tscp:insightTag:${tags[0].id}`) || new Set(result.elements.map((value) => value.domainName)).size !== result.elements.length) throw new AdportError12("PROVIDER_ERROR", "linkedin: Insight Tag domain identity mismatch");
|
|
2162
|
+
return { ...context, ...result, records: result.elements.map((value) => ({ domain: value.domainName, status: value.blocked ? "Blocked" : "Allowed", ...value.lastCallbackAt !== void 0 ? { last_callback_at: value.lastCallbackAt } : {} })), ...linkedinPageState(result, input.start, input.count, "insightTagDomains") };
|
|
2163
|
+
}
|
|
2164
|
+
async campaignConversions(raw) {
|
|
2165
|
+
const input = associationInput.parse(raw), context = await this.account(input.account_id);
|
|
2166
|
+
await this.provider.getCampaign(input.account_id, input.campaign_id);
|
|
2167
|
+
if (input.complete_snapshot) {
|
|
2168
|
+
if (input.start !== 0) throw new AdportError12("INVALID_INPUT", "linkedin: a complete campaign-conversion snapshot starts at zero");
|
|
2169
|
+
const elements = await this.completeAssociations(input.account_id, input.campaign_id);
|
|
2170
|
+
return { ...context, campaign_id: input.campaign_id, elements, records: elements.slice(0, 100).map((value) => ({ conversion: value.conversion, campaign: value.campaign, ...value.associatedAt !== void 0 ? { associated_at: value.associatedAt } : {} })), complete: true, truncated: false, associations_snapshot_hash: digest4(elements), notes: [`Verified ${elements.length} associations across bounded native pages. The widget shows at most 100 records; elements retains the complete collection.`] };
|
|
2171
|
+
}
|
|
2172
|
+
const result = await this.client.get("campaignConversions", z15.looseObject({ elements: z15.array(association), paging: paging5.optional() }), { q: "campaigns", campaigns: [`urn:li:sponsoredCampaign:${input.campaign_id}`], start: input.start, count: input.count });
|
|
2173
|
+
if (result.elements.some((value) => value.campaign !== `urn:li:sponsoredCampaign:${input.campaign_id}`) || new Set(result.elements.map((value) => value.conversion)).size !== result.elements.length) throw new AdportError12("PROVIDER_ERROR", "linkedin: campaign-conversion scope or duplicate identity mismatch");
|
|
2174
|
+
const state = linkedinPageState(result, input.start, input.count, "campaignConversions");
|
|
2175
|
+
return { ...context, campaign_id: input.campaign_id, ...result, records: result.elements.map((value) => ({ conversion: value.conversion, campaign: value.campaign, ...value.associatedAt !== void 0 ? { associated_at: value.associatedAt } : {} })), ...state, ...state.complete === true ? { associations_snapshot_hash: digest4(result.elements) } : {} };
|
|
2176
|
+
}
|
|
2177
|
+
async completeAssociations(account2, campaign) {
|
|
2178
|
+
const values = [], seen = /* @__PURE__ */ new Set();
|
|
2179
|
+
let start = 0, knownTotal;
|
|
2180
|
+
for (let pages = 0; pages < 50; pages++) {
|
|
2181
|
+
const page = await this.campaignConversions({ account_id: account2, campaign_id: campaign, start, count: 100 });
|
|
2182
|
+
if ("paging" in page && page.paging?.total !== void 0 && page.paging.total >= 0) {
|
|
2183
|
+
if (knownTotal !== void 0 && knownTotal !== page.paging.total) throw new AdportError12("PROVIDER_ERROR", "linkedin: campaign-conversion total changed during pagination");
|
|
2184
|
+
knownTotal = page.paging.total;
|
|
2185
|
+
}
|
|
2186
|
+
for (const value of page.elements) {
|
|
2187
|
+
if (seen.has(value.conversion)) throw new AdportError12("PROVIDER_ERROR", "linkedin: repeated campaign-conversion membership");
|
|
2188
|
+
seen.add(value.conversion);
|
|
2189
|
+
values.push(value);
|
|
2190
|
+
}
|
|
2191
|
+
if (!("next_start" in page) || page.next_start === void 0) {
|
|
2192
|
+
if (page.complete === null || knownTotal !== void 0 && values.length !== knownTotal) throw new AdportError12("PROVIDER_ERROR", "linkedin: campaign-conversion membership completeness is unknown or contradicts its total");
|
|
2193
|
+
return values;
|
|
2194
|
+
}
|
|
2195
|
+
start = page.next_start;
|
|
2196
|
+
}
|
|
2197
|
+
throw new AdportError12("PROVIDER_ERROR", "linkedin: campaign-conversion membership exceeded 5,000; no write attempted");
|
|
2198
|
+
}
|
|
2199
|
+
validateConfiguration(source2, type, windows, valueType, value, expression) {
|
|
2200
|
+
if (source2 === "CONVERSIONS_API") {
|
|
2201
|
+
if (expression !== void 0 || windows.some((days) => days > 90 && !extendedWindows.has(type)) || valueType === "FIXED" && !value) throw new AdportError12("INVALID_INPUT", "linkedin: invalid Conversions API URL rules, attribution window or value configuration");
|
|
2202
|
+
} else if (!websiteTypes.includes(type) || windows.some((days) => ![1, 7, 30].includes(days)) || valueType !== void 0) throw new AdportError12("INVALID_INPUT", "linkedin: Insight Tag rules use documented website types and 1/7/30-day windows; value_type is Conversions API only");
|
|
2203
|
+
}
|
|
2204
|
+
async verified(resource, check) {
|
|
2205
|
+
try {
|
|
2206
|
+
if (!await check()) throw new Error("settings mismatch");
|
|
2207
|
+
} catch {
|
|
2208
|
+
throw new AdportError12("PROVIDER_ERROR", "linkedin: measurement write readback unconfirmed; reconcile returned resource ID before another approval", { resource_ids: [resource] });
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
async plan(op) {
|
|
2212
|
+
const create = ["linkedin_create_conversion", "linkedin_create_insight_tag"].includes(op.tool);
|
|
2213
|
+
if (op.provider !== "linkedin" || !writes3.has(op.tool) || op.kind !== (create ? "create" : "update")) throw new AdportError12("INVALID_INPUT", "linkedin: measurement operation kind mismatch");
|
|
2214
|
+
const context = await this.account(op.accountId), base2 = { notes: notices2, coercions: [], budgetDeltas: [] };
|
|
2215
|
+
if (op.tool === "linkedin_create_insight_tag") {
|
|
2216
|
+
const input2 = tagCreateInput.parse(op.payload);
|
|
2217
|
+
if (input2.expected_account_hash !== context.account_snapshot_hash || (await this.tags(op.accountId)).length) throw new AdportError12("INVALID_INPUT", "linkedin: advertiser changed or already has an Insight Tag; read current settings");
|
|
2218
|
+
const body = { sponsoredAccounts: [selectedAccount(op.accountId)] };
|
|
2219
|
+
return { ...base2, summary: "Create an unused LinkedIn Insight Tag", changes: [`+ ${JSON.stringify(body)}. Native first-party tracking defaults to true; no website installation is performed.`], review: {
|
|
2220
|
+
provider: "linkedin",
|
|
2221
|
+
accountId: op.accountId,
|
|
2222
|
+
kind: "create",
|
|
2223
|
+
title: "Create Insight Tag",
|
|
2224
|
+
fields: [{ label: "Account", after: op.accountId }, { label: "First-party tracking (native default)", after: true }],
|
|
2225
|
+
notices: ["Creates an unused tag. No website code is installed and no conversion events are sent."]
|
|
2226
|
+
}, execute: async () => {
|
|
2227
|
+
const resource = await this.client.create("insightTags", body);
|
|
2228
|
+
await this.verified(resource, async () => {
|
|
2229
|
+
const found = (await this.tags(op.accountId)).find((value2) => value2.id === resource);
|
|
2230
|
+
return !!found && same2(found.sponsoredAccounts, body.sponsoredAccounts);
|
|
2231
|
+
});
|
|
2232
|
+
return { applied: true, resourceIds: [resource] };
|
|
2233
|
+
} };
|
|
2234
|
+
}
|
|
2235
|
+
if (op.tool === "linkedin_update_insight_tag") {
|
|
2236
|
+
const input2 = tagUpdateInput.parse(op.payload), current2 = (await this.tags(op.accountId)).find((value2) => value2.id === input2.insight_tag_id);
|
|
2237
|
+
if (!current2 || current2.snapshot_hash !== input2.expected_snapshot_hash) throw new AdportError12("INVALID_INPUT", "linkedin: Insight Tag identity or snapshot changed");
|
|
2238
|
+
if (current2.sponsoredAccounts.length !== 1) throw new AdportError12("INVALID_INPUT", "linkedin: a shared Insight Tag needs multi-account authorization before changing its global tracking flag");
|
|
2239
|
+
if (current2.firstPartyTrackingEnabled === input2.first_party_tracking_enabled) throw new AdportError12("INVALID_INPUT", "linkedin: Insight Tag setting already matches");
|
|
2240
|
+
return { ...base2, summary: "Update LinkedIn Insight Tag first-party tracking", changes: [`~ firstPartyTrackingEnabled ${current2.firstPartyTrackingEnabled} \u2192 ${input2.first_party_tracking_enabled}. An installed tag uses this setting; no site code is installed here.`], review: {
|
|
2241
|
+
provider: "linkedin",
|
|
2242
|
+
accountId: op.accountId,
|
|
2243
|
+
kind: "update",
|
|
2244
|
+
title: "Update Insight Tag",
|
|
2245
|
+
subject: `Tag ${input2.insight_tag_id}`,
|
|
2246
|
+
fields: [{ label: "First-party tracking", before: current2.firstPartyTrackingEnabled, after: input2.first_party_tracking_enabled }],
|
|
2247
|
+
notices: ["An installed tag uses this setting. No website code is installed here."]
|
|
2248
|
+
}, execute: async () => {
|
|
2249
|
+
await this.client.update(`insightTags/${input2.insight_tag_id}`, { firstPartyTrackingEnabled: input2.first_party_tracking_enabled });
|
|
2250
|
+
await this.verified(input2.insight_tag_id, async () => (await this.tags(op.accountId)).some((value2) => value2.id === input2.insight_tag_id && value2.firstPartyTrackingEnabled === input2.first_party_tracking_enabled));
|
|
2251
|
+
return { applied: true, resourceIds: [input2.insight_tag_id] };
|
|
2252
|
+
} };
|
|
2253
|
+
}
|
|
2254
|
+
if (op.tool === "linkedin_set_campaign_conversion") {
|
|
2255
|
+
const input2 = setAssociationInput.parse(op.payload), current2 = await this.ownedConversion(op.accountId, input2.conversion_id), associations = await this.completeAssociations(op.accountId, input2.campaign_id);
|
|
2256
|
+
if (current2.snapshot_hash !== input2.expected_conversion_hash || digest4(associations) !== input2.expected_associations_hash) throw new AdportError12("INVALID_INPUT", "linkedin: conversion or campaign associations changed; read both again");
|
|
2257
|
+
const associatedBefore = associations.some((value2) => value2.conversion === `urn:lla:llaPartnerConversion:${input2.conversion_id}`);
|
|
2258
|
+
if (associatedBefore === input2.associated) throw new AdportError12("INVALID_INPUT", "linkedin: campaign-conversion association already matches");
|
|
2259
|
+
return { ...base2, summary: `${input2.associated ? "Associate" : "Detach"} LinkedIn conversion "${current2.name}"`, changes: [`${input2.associated ? "+" : "-"} Campaign ${input2.campaign_id} \u2194 conversion ${input2.conversion_id}. Changes campaign measurement/optimization eligibility; campaign status and budget are preserved.`], review: {
|
|
2260
|
+
provider: "linkedin",
|
|
2261
|
+
accountId: op.accountId,
|
|
2262
|
+
kind: "update",
|
|
2263
|
+
title: input2.associated ? "Associate conversion" : "Detach conversion",
|
|
2264
|
+
subject: current2.name,
|
|
2265
|
+
fields: [{ label: "Campaign", after: input2.campaign_id }, { label: "Conversion", after: input2.conversion_id }, { label: "Associated", before: associatedBefore, after: input2.associated }],
|
|
2266
|
+
notices: ["Changes campaign measurement and optimization eligibility. Campaign status and budget are preserved."]
|
|
2267
|
+
}, execute: async () => {
|
|
2268
|
+
await this.client.setCampaignConversion(input2.campaign_id, input2.conversion_id, input2.associated);
|
|
2269
|
+
await this.verified(input2.conversion_id, async () => (await this.completeAssociations(op.accountId, input2.campaign_id)).some((value2) => value2.conversion === `urn:lla:llaPartnerConversion:${input2.conversion_id}`) === input2.associated);
|
|
2270
|
+
return { applied: true, resourceIds: [input2.conversion_id], details: { campaign_id: input2.campaign_id, associated: input2.associated } };
|
|
2271
|
+
} };
|
|
2272
|
+
}
|
|
2273
|
+
const input = create ? createInput3.parse(op.payload) : updateInput4.parse(op.payload), current = create ? void 0 : await this.ownedConversion(op.accountId, input.conversion_id);
|
|
2274
|
+
if (create && input.expected_account_hash !== context.account_snapshot_hash || current && current.snapshot_hash !== input.expected_snapshot_hash) throw new AdportError12("INVALID_INPUT", "linkedin: advertiser or conversion snapshot changed; read current settings");
|
|
2275
|
+
const source2 = create ? input.source : current.conversionMethod ?? "INSIGHT_TAG";
|
|
2276
|
+
const type = input.type ?? current.type, value = input.value ?? current?.value, valueType = input.value_type ?? current?.valueType;
|
|
2277
|
+
if (create || ["type", "post_click_window_days", "view_through_window_days", "value_type", "url_match_rule_expression"].some((key) => Object.hasOwn(input, key))) this.validateConfiguration(source2, type, [input.post_click_window_days ?? current.postClickAttributionWindowSize ?? 30, input.view_through_window_days ?? current.viewThroughAttributionWindowSize ?? 7], valueType, value, input.url_match_rule_expression);
|
|
2278
|
+
if (value && value.currencyCode !== context.currency) throw new AdportError12("INVALID_INPUT", "linkedin: conversion value currency must match the selected advertiser");
|
|
2279
|
+
const fields = {};
|
|
2280
|
+
for (const [key, native3] of Object.entries({ name: "name", type: "type", enabled: "enabled", attribution_type: "attributionType", post_click_window_days: "postClickAttributionWindowSize", view_through_window_days: "viewThroughAttributionWindowSize", value: "value", value_type: "valueType", url_match_rule_expression: "urlMatchRuleExpression" })) {
|
|
2281
|
+
const value2 = input[key];
|
|
2282
|
+
if (value2 !== void 0) fields[native3] = value2;
|
|
2283
|
+
}
|
|
2284
|
+
if (create) {
|
|
2285
|
+
fields.account = selectedAccount(op.accountId);
|
|
2286
|
+
if (source2 === "CONVERSIONS_API") fields.conversionMethod = source2;
|
|
2287
|
+
}
|
|
2288
|
+
if (current && matches3(current, fields)) throw new AdportError12("INVALID_INPUT", "linkedin: conversion fields already match");
|
|
2289
|
+
const labels2 = { name: "Name", type: "Type", enabled: "Enabled", attributionType: "Attribution type", postClickAttributionWindowSize: "Post-click window (days)", viewThroughAttributionWindowSize: "View-through window (days)", value: "Value", valueType: "Value type", urlMatchRuleExpression: "URL match rules" };
|
|
2290
|
+
const observed = current;
|
|
2291
|
+
const reviewFields = Object.entries(fields).filter(([key]) => Object.hasOwn(labels2, key) && !(create && key === "name")).map(([key, value2]) => ({ label: labels2[key], ...observed && Object.hasOwn(observed, key) && observed[key] !== void 0 ? { before: observed[key] } : {}, after: value2 }));
|
|
2292
|
+
const scopeNotice = create ? `No campaign associations are created. ${source2 === "INSIGHT_TAG" ? "LinkedIn selects the native Insight Tag method from the URL rules. " : ""}Omitted value settings use native defaults reported by readback.` : "Only supplied settings change. Campaign associations are preserved; supplied URL rules replace the complete expression.";
|
|
2293
|
+
return { ...base2, summary: `${create ? "Create" : "Update"} LinkedIn conversion "${input.name ?? current.name}"`, changes: [`${create ? "+" : "~"} ${JSON.stringify(fields)}`, ...create ? ["No autoAssociationType is sent; native default creates no campaign associations."] : ["Only supplied fields change. URL expressions replace the complete expression; omitted settings and campaign associations remain unchanged."], ...source2 === "CONVERSIONS_API" ? ["Conversions API access additionally requires native rw_conversions permission; no OAuth scopes are changed here."] : []], review: {
|
|
2294
|
+
provider: "linkedin",
|
|
2295
|
+
accountId: op.accountId,
|
|
2296
|
+
kind: create ? "create" : "update",
|
|
2297
|
+
title: create ? "Create conversion" : "Update conversion",
|
|
2298
|
+
subject: current?.name ?? input.name,
|
|
2299
|
+
fields: [...create ? [{ label: "Source family", after: source2 }] : [], ...reviewFields],
|
|
2300
|
+
notices: [scopeNotice]
|
|
2301
|
+
}, execute: async () => {
|
|
2302
|
+
const resource = create ? await this.client.create("conversions", fields) : current.id;
|
|
2303
|
+
if (!create) await this.client.partialUpdate(`conversions/${resource}`, { $set: fields }, { account: selectedAccount(op.accountId) });
|
|
2304
|
+
await this.verified(resource, async () => matches3(await this.ownedConversion(op.accountId, resource), fields));
|
|
2305
|
+
return { applied: true, resourceIds: [resource] };
|
|
2306
|
+
} };
|
|
2307
|
+
}
|
|
2308
|
+
};
|
|
2309
|
+
function linkedinMeasurementTools(provider) {
|
|
2310
|
+
return [
|
|
2311
|
+
defineTool10({ name: "linkedin_insight_tags", namespace: "linkedin", description: "Read the selected advertiser\u2019s single Insight Tag, associated accounts, inert tag code and current snapshot. Returns account_snapshot_hash for creation. Does not install tracking or send events.", input: z15.object({ account_id: linkedinId }), output: tagsOutput, presentation: "records", annotations: { readOnly: true }, handler: (input) => provider.measurement.insightTags(input.account_id) }),
|
|
2312
|
+
defineTool10({ name: "linkedin_insight_tag_domains", namespace: "linkedin", description: "Read domains and callback diagnostics for the advertiser\u2019s verified Insight Tag with native offset paging. No tag execution or domain setting changes.", input: z15.object({ account_id: linkedinId, ...pageInput2 }), output: collectionOutput(domain), presentation: "records", annotations: { readOnly: true }, handler: (input) => provider.measurement.domains(input) }),
|
|
2313
|
+
defineTool10({ name: "linkedin_conversions", namespace: "linkedin", description: "List conversion rules and configuration snapshots using the selected advertiser finder and native offset paging. Disabled rules remain visible. Optional shared rules are read-only; no scope or tracking changes.", input: listInput2, output: collectionOutput(conversionOutput), presentation: "records", annotations: { readOnly: true }, handler: (input) => provider.measurement.conversions(input) }),
|
|
2314
|
+
defineTool10({ name: "linkedin_get_conversion", namespace: "linkedin", description: "Read one advertiser-owned conversion, its exact attribution/value/URL rules and snapshot_hash. Returned pixel code is inert text. No conversion event is sent.", input: z15.object({ account_id: linkedinId, conversion_id: linkedinId }), output: singleConversionOutput, presentation: "records", annotations: { readOnly: true }, handler: (input) => provider.measurement.getConversion(input.account_id, input.conversion_id) }),
|
|
2315
|
+
defineTool10({ name: "linkedin_campaign_conversions", namespace: "linkedin", description: "Read selected-campaign conversion associations with verified campaign ownership and native offset paging. complete_snapshot traverses up to 5,000 associations for a verified associations_snapshot_hash; the widget shows at most 100 rows.", input: associationInput, output: associationsOutput, presentation: "records", annotations: { readOnly: true }, handler: (input) => provider.measurement.campaignConversions(input) }),
|
|
2316
|
+
guardedWriteTool8({ name: "linkedin_create_insight_tag", namespace: "linkedin", provider: "linkedin", kind: "create", destructive: false, payload: tagCreateInput, description: "Create the advertiser\u2019s Insight Tag only if absent, using expected_account_hash from linkedin_insight_tags. Native first-party tracking defaults true; no code installation, scope changes or event sending. Verify native readback." }),
|
|
2317
|
+
guardedWriteTool8({ name: "linkedin_update_insight_tag", namespace: "linkedin", provider: "linkedin", kind: "update", destructive: true, payload: tagUpdateInput, description: "Change first-party tracking on one unshared advertiser Insight Tag using its current snapshot. Shared global settings require separate multi-account authorization. No code installation or events; verify native readback." }),
|
|
2318
|
+
guardedWriteTool8({ name: "linkedin_create_conversion", namespace: "linkedin", provider: "linkedin", kind: "create", destructive: false, payload: createInput3, description: "Create an Insight Tag or Conversions API rule using expected_account_hash. Disabled by default, with explicit attribution windows and no automatic campaign association. CAPI needs native rw_conversions access. No tracking events or OAuth changes." }),
|
|
2319
|
+
guardedWriteTool8({ name: "linkedin_update_conversion", namespace: "linkedin", provider: "linkedin", kind: "update", destructive: true, payload: updateInput4, description: "Edit supplied conversion name, enabled state, type, attribution windows, exact-currency value or complete URL expression using expected_snapshot_hash. Omitted settings stay unchanged. enabled=false disables the rule; no invented rule DELETE endpoint." }),
|
|
2320
|
+
guardedWriteTool8({ name: "linkedin_set_campaign_conversion", namespace: "linkedin", provider: "linkedin", kind: "update", destructive: true, payload: setAssociationInput, description: "Associate or detach an owned conversion from a verified advertiser campaign using current conversion and complete-association hashes. Native PUT/DELETE is independently read back. Status/budget unchanged; no events are sent." })
|
|
2321
|
+
];
|
|
2322
|
+
}
|
|
2323
|
+
|
|
164
2324
|
// src/provider.ts
|
|
165
2325
|
var FIELDS = { spend: "costInLocalCurrency", impressions: "impressions", clicks: "clicks", conversions: "externalWebsiteConversions", conversion_value: "conversionValueInLocalCurrency" };
|
|
166
2326
|
var DERIVED = { ctr: ["clicks", "impressions", 100], cpc: ["spend", "clicks", 1], cpm: ["spend", "impressions", 1e3], cpa: ["spend", "conversions", 1], roas: ["conversion_value", "spend", 1] };
|
|
167
2327
|
var STATUS = ["ACTIVE", "PAUSED", "ARCHIVED", "COMPLETED", "CANCELED", "DRAFT", "PENDING_DELETION", "REMOVED"];
|
|
168
|
-
var ACCOUNT_URN = (
|
|
2328
|
+
var ACCOUNT_URN = (id2) => `urn:li:sponsoredAccount:${linkedinId.parse(id2)}`;
|
|
169
2329
|
function decimalToMicros(amount) {
|
|
170
|
-
if (!/^\d+(?:\.\d+)?$/.test(amount)) throw new
|
|
2330
|
+
if (!/^\d+(?:\.\d+)?$/.test(amount)) throw new AdportError13("PROVIDER_ERROR", "linkedin: invalid money amount");
|
|
171
2331
|
const [whole, fraction = ""] = amount.split(".");
|
|
172
|
-
if (fraction.slice(6).replace(/0/g, "")) throw new
|
|
2332
|
+
if (fraction.slice(6).replace(/0/g, "")) throw new AdportError13("PROVIDER_ERROR", "linkedin: budget precision exceeds integer micros");
|
|
173
2333
|
const value = BigInt(whole) * 1000000n + BigInt(fraction.slice(0, 6).padEnd(6, "0"));
|
|
174
|
-
if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new
|
|
2334
|
+
if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new AdportError13("PROVIDER_ERROR", "linkedin: budget exceeds safe integer micros");
|
|
175
2335
|
return Number(value);
|
|
176
2336
|
}
|
|
177
2337
|
function microsToDecimal(value) {
|
|
178
|
-
if (!Number.isSafeInteger(value) || value < 0) throw new
|
|
2338
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new AdportError13("INVALID_INPUT", "linkedin: budget must be integer micros");
|
|
179
2339
|
const number = BigInt(value);
|
|
180
2340
|
return `${number / 1000000n}.${String(number % 1000000n).padStart(6, "0")}`;
|
|
181
2341
|
}
|
|
182
2342
|
var LinkedInAdsProvider = class {
|
|
183
|
-
constructor(client) {
|
|
2343
|
+
constructor(client, media) {
|
|
184
2344
|
this.client = client;
|
|
2345
|
+
this.creatives = new LinkedInCreativeService(client, this, media);
|
|
2346
|
+
this.management = new LinkedInManagementService(client, this);
|
|
2347
|
+
this.media = new LinkedInMediaService(client, this, media);
|
|
2348
|
+
this.sponsored = new LinkedInSponsoredService(client, this);
|
|
2349
|
+
this.planning = new LinkedInPlanningService(client, this);
|
|
2350
|
+
this.audiences = new LinkedInAudienceService(client, this);
|
|
2351
|
+
this.reporting = new LinkedInReportingService(client, this);
|
|
2352
|
+
this.measurement = new LinkedInMeasurementService(client, this);
|
|
2353
|
+
this.leadForms = new LinkedInLeadFormService(client, this);
|
|
2354
|
+
this.leadCreatives = new LinkedInLeadCreativeService(client, this);
|
|
185
2355
|
}
|
|
186
2356
|
client;
|
|
187
2357
|
id = "linkedin";
|
|
2358
|
+
creatives;
|
|
2359
|
+
management;
|
|
2360
|
+
media;
|
|
2361
|
+
sponsored;
|
|
2362
|
+
planning;
|
|
2363
|
+
audiences;
|
|
2364
|
+
reporting;
|
|
2365
|
+
measurement;
|
|
2366
|
+
leadCreatives;
|
|
2367
|
+
leadForms;
|
|
188
2368
|
capabilities() {
|
|
189
2369
|
return { serverDryRun: false };
|
|
190
2370
|
}
|
|
@@ -193,18 +2373,18 @@ var LinkedInAdsProvider = class {
|
|
|
193
2373
|
}
|
|
194
2374
|
async search(path, schema, search) {
|
|
195
2375
|
const params = { q: "search", pageSize: 100, ...search ? { search } : {} };
|
|
196
|
-
const pageSchema =
|
|
2376
|
+
const pageSchema = z16.object({ elements: z16.array(schema), metadata: z16.object({ nextPageToken: z16.string().optional() }).optional() });
|
|
197
2377
|
const rows = [], tokens = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set();
|
|
198
2378
|
while (true) {
|
|
199
2379
|
const page = await this.client.get(path, pageSchema, params);
|
|
200
|
-
for (const
|
|
201
|
-
if (seen.has(
|
|
202
|
-
seen.add(
|
|
203
|
-
rows.push(
|
|
2380
|
+
for (const row4 of page.elements) {
|
|
2381
|
+
if (seen.has(row4.id)) throw new AdportError13("PROVIDER_ERROR", "linkedin: search repeated an entity");
|
|
2382
|
+
seen.add(row4.id);
|
|
2383
|
+
rows.push(row4);
|
|
204
2384
|
}
|
|
205
2385
|
const next = page.metadata?.nextPageToken;
|
|
206
2386
|
if (!next) return rows;
|
|
207
|
-
if (tokens.has(next) || tokens.size >= 1e3) throw new
|
|
2387
|
+
if (tokens.has(next) || tokens.size >= 1e3) throw new AdportError13("PROVIDER_ERROR", "linkedin: cursor pagination did not terminate");
|
|
208
2388
|
tokens.add(next);
|
|
209
2389
|
params.pageToken = next;
|
|
210
2390
|
}
|
|
@@ -214,70 +2394,70 @@ var LinkedInAdsProvider = class {
|
|
|
214
2394
|
}
|
|
215
2395
|
async getAccount(accountId) {
|
|
216
2396
|
const data = await this.client.get(`adAccounts/${linkedinId.parse(accountId)}`, accountSchema);
|
|
217
|
-
if (String(data.id) !== accountId) throw new
|
|
2397
|
+
if (String(data.id) !== accountId) throw new AdportError13("PROVIDER_ERROR", "linkedin: account ID mismatch");
|
|
218
2398
|
return data;
|
|
219
2399
|
}
|
|
220
2400
|
async listCampaigns(accountId) {
|
|
221
2401
|
const rows = await this.search(`adAccounts/${linkedinId.parse(accountId)}/adCampaigns`, campaignSchema, { status: { values: STATUS } });
|
|
222
|
-
if (rows.some((r) => r.account !== ACCOUNT_URN(accountId))) throw new
|
|
2402
|
+
if (rows.some((r) => r.account !== ACCOUNT_URN(accountId))) throw new AdportError13("PROVIDER_ERROR", "linkedin: campaign account mismatch");
|
|
223
2403
|
return rows;
|
|
224
2404
|
}
|
|
225
2405
|
async listCampaignGroups(accountId) {
|
|
226
2406
|
const rows = await this.search(`adAccounts/${linkedinId.parse(accountId)}/adCampaignGroups`, groupSchema, { status: { values: ["ACTIVE", "PAUSED", "ARCHIVED", "DRAFT", "PENDING_DELETION", "REMOVED"] } });
|
|
227
|
-
if (rows.some((r) => r.account !== ACCOUNT_URN(accountId))) throw new
|
|
2407
|
+
if (rows.some((r) => r.account !== ACCOUNT_URN(accountId))) throw new AdportError13("PROVIDER_ERROR", "linkedin: campaign group account mismatch");
|
|
228
2408
|
return rows;
|
|
229
2409
|
}
|
|
230
2410
|
async getCampaign(accountId, campaignId) {
|
|
231
2411
|
const data = await this.client.get(`adAccounts/${linkedinId.parse(accountId)}/adCampaigns/${linkedinId.parse(campaignId)}`, campaignSchema);
|
|
232
|
-
if (String(data.id) !== campaignId || data.account !== ACCOUNT_URN(accountId)) throw new
|
|
2412
|
+
if (String(data.id) !== campaignId || data.account !== ACCOUNT_URN(accountId)) throw new AdportError13("PROVIDER_ERROR", "linkedin: campaign account/ID mismatch");
|
|
233
2413
|
return data;
|
|
234
2414
|
}
|
|
235
2415
|
async report(query) {
|
|
236
|
-
if (query.level === "ad_group") throw new
|
|
237
|
-
const
|
|
238
|
-
if (end < start) throw new
|
|
2416
|
+
if (query.level === "ad_group") throw new AdportError13("INVALID_INPUT", "linkedin: no native ad-group level; use campaign (LinkedIn campaign) or ad (creative). Campaign groups are listed separately.");
|
|
2417
|
+
const range2 = resolveDateRange(query.dateRange), start = z16.iso.date().parse(range2.start), end = z16.iso.date().parse(range2.end);
|
|
2418
|
+
if (end < start) throw new AdportError13("INVALID_INPUT", "linkedin: report end must be on/after start");
|
|
239
2419
|
const dateObject = (iso) => {
|
|
240
2420
|
const [year, month, day] = iso.split("-").map(Number);
|
|
241
2421
|
return { year, month, day };
|
|
242
2422
|
};
|
|
243
|
-
const
|
|
2423
|
+
const dateRange2 = { start: dateObject(start), end: dateObject(end) };
|
|
244
2424
|
const limit = query.limit ?? 1e3;
|
|
245
|
-
if (!Number.isSafeInteger(limit) || limit < 1) throw new
|
|
2425
|
+
if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError13("INVALID_INPUT", "linkedin: report limit must be a positive integer");
|
|
246
2426
|
const fields = /* @__PURE__ */ new Set(["pivotValues", "dateRange"]);
|
|
247
2427
|
for (const metric of query.metrics) {
|
|
248
2428
|
if (metric in FIELDS) fields.add(FIELDS[metric]);
|
|
249
2429
|
else if (metric in DERIVED) for (const dependency of DERIVED[metric].slice(0, 2)) fields.add(FIELDS[dependency]);
|
|
250
2430
|
}
|
|
251
|
-
if (fields.size === 2) throw new
|
|
2431
|
+
if (fields.size === 2) throw new AdportError13("INVALID_INPUT", "linkedin: at least one supported metric is required");
|
|
252
2432
|
const pivot = { account: "ACCOUNT", campaign: "CAMPAIGN", ad: "CREATIVE" }[query.level];
|
|
253
2433
|
const urnType = { account: "sponsoredAccount", campaign: "sponsoredCampaign", ad: "sponsoredCreative" }[query.level];
|
|
254
2434
|
const rows = [];
|
|
255
2435
|
let capped = false;
|
|
256
|
-
for (const
|
|
257
|
-
const accountId = linkedinId.parse(
|
|
2436
|
+
for (const id2 of [...new Set(query.accountIds ?? (await this.listAccounts()).map((a) => a.id))]) {
|
|
2437
|
+
const accountId = linkedinId.parse(id2), account2 = await this.getAccount(accountId);
|
|
258
2438
|
const campaigns = query.level === "campaign" ? new Map((await this.listCampaigns(accountId)).map((c) => [String(c.id), c])) : void 0;
|
|
259
|
-
const data = await this.client.get("adAnalytics",
|
|
2439
|
+
const data = await this.client.get("adAnalytics", z16.object({ elements: z16.array(reportRowSchema), paging: z16.object({ links: z16.array(z16.object({ rel: z16.string() })).optional() }).optional() }), {
|
|
260
2440
|
q: "analytics",
|
|
261
2441
|
pivot,
|
|
262
2442
|
timeGranularity: "ALL",
|
|
263
|
-
dateRange,
|
|
2443
|
+
dateRange: dateRange2,
|
|
264
2444
|
accounts: [ACCOUNT_URN(accountId)],
|
|
265
2445
|
fields: [...fields].join(",")
|
|
266
2446
|
});
|
|
267
|
-
if (data.paging?.links?.some((link) => link.rel === "next")) throw new
|
|
2447
|
+
if (data.paging?.links?.some((link) => link.rel === "next")) throw new AdportError13("PROVIDER_ERROR", "linkedin: unexpected analytics pagination; refusing incomplete data");
|
|
268
2448
|
capped ||= data.elements.length >= 15e3;
|
|
269
2449
|
const seen = /* @__PURE__ */ new Set();
|
|
270
|
-
for (const
|
|
271
|
-
const urn =
|
|
272
|
-
if (!match) throw new
|
|
2450
|
+
for (const row4 of data.elements) {
|
|
2451
|
+
const urn = row4.pivotValues[0], match = urn.match(new RegExp(`^urn:li:${urnType}:([1-9]\\d*)$`));
|
|
2452
|
+
if (!match) throw new AdportError13("PROVIDER_ERROR", "linkedin: unexpected analytics pivot");
|
|
273
2453
|
const entityId = match[1];
|
|
274
|
-
if (seen.has(entityId) || query.level === "account" && entityId !== accountId || campaigns && !campaigns.has(entityId)) throw new
|
|
2454
|
+
if (seen.has(entityId) || query.level === "account" && entityId !== accountId || campaigns && !campaigns.has(entityId)) throw new AdportError13("PROVIDER_ERROR", "linkedin: incorrectly scoped or duplicate analytics row");
|
|
275
2455
|
seen.add(entityId);
|
|
276
|
-
if (["start", "end"].some((bound) => ["year", "month", "day"].some((part) =>
|
|
277
|
-
throw new
|
|
2456
|
+
if (["start", "end"].some((bound) => ["year", "month", "day"].some((part) => row4.dateRange[bound][part] !== dateRange2[bound][part]))) {
|
|
2457
|
+
throw new AdportError13("PROVIDER_ERROR", "linkedin: provider changed the reporting date range (older queries may round to months); request the returned month boundaries explicitly");
|
|
278
2458
|
}
|
|
279
2459
|
const campaign = campaigns?.get(entityId);
|
|
280
|
-
rows.push({ provider: this.id, accountId, entity: { level: query.level, id: entityId, name: query.level === "account" ?
|
|
2460
|
+
rows.push({ provider: this.id, accountId, entity: { level: query.level, id: entityId, name: query.level === "account" ? account2.name : campaign?.name ?? entityId, ...query.level === "account" ? { status: account2.status } : campaign ? { status: campaign.status } : {} }, metrics: normalize(row4, query.metrics) });
|
|
281
2461
|
if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };
|
|
282
2462
|
}
|
|
283
2463
|
}
|
|
@@ -288,31 +2468,42 @@ var LinkedInAdsProvider = class {
|
|
|
288
2468
|
return { ...preview, serverValidated: false };
|
|
289
2469
|
}
|
|
290
2470
|
async applyWrite(op, guard) {
|
|
291
|
-
|
|
2471
|
+
const result = await (await this.plan(op, guard)).execute();
|
|
2472
|
+
return Array.isArray(result) ? { applied: true, resourceIds: result } : result;
|
|
292
2473
|
}
|
|
293
2474
|
async plan(op, guard) {
|
|
294
|
-
|
|
295
|
-
if (op.
|
|
2475
|
+
if (this.leadCreatives.supports(op.tool)) return this.leadCreatives.plan(op);
|
|
2476
|
+
if (this.leadForms.supports(op.tool)) return this.leadForms.plan(op);
|
|
2477
|
+
if (this.measurement.supports(op.tool)) return this.measurement.plan(op);
|
|
2478
|
+
if (this.audiences.supports(op.tool)) return this.audiences.plan(op);
|
|
2479
|
+
if (LINKEDIN_SPONSORED_WRITES.has(op.tool)) return this.sponsored.plan(op, guard);
|
|
2480
|
+
if (LINKEDIN_MEDIA_WRITES.has(op.tool)) return this.media.plan(op);
|
|
2481
|
+
if (/^linkedin_(?:create_campaign_group|update_(?:campaign_group|campaign|targeting)|set_(?:campaign_group_status|campaign_group_budget|bid)|delete_(?:campaign_group|campaign))$/.test(op.tool)) return this.management.plan(op, guard);
|
|
2482
|
+
if (/^linkedin_(?:create_text_ad|update_(?:text_ad|image)|rename_creative|set_creative_status|delete_creative|upload_image)$/.test(op.tool)) return this.creatives.plan(op, guard);
|
|
2483
|
+
const accountId = linkedinId.parse(op.accountId), base2 = `adAccounts/${accountId}/adCampaigns`;
|
|
2484
|
+
if (op.provider !== this.id) throw new AdportError13("INVALID_INPUT", "linkedin: provider mismatch");
|
|
296
2485
|
if (op.tool === "linkedin_create_campaign" && op.kind === "create") {
|
|
297
2486
|
const input = createCampaignSchema.parse(op.payload);
|
|
298
|
-
if (!input.daily_budget_micros && !input.total_budget_micros) throw new
|
|
299
|
-
if (input.type === "DYNAMIC" && (!input.daily_budget_micros || !input.total_budget_micros || !input.format)) throw new
|
|
300
|
-
if ((input.type === "SPONSORED_UPDATES" || input.type === "DYNAMIC" || input.objective_type === "LEAD_GENERATION") && !input.associated_entity) throw new
|
|
301
|
-
if (input.total_budget_micros && !input.end_time) throw new
|
|
302
|
-
if (input.end_time && (!input.start_time || input.end_time <= input.start_time)) throw new
|
|
2487
|
+
if (!input.daily_budget_micros && !input.total_budget_micros) throw new AdportError13("INVALID_INPUT", "linkedin: a daily or total campaign budget is required");
|
|
2488
|
+
if (input.type === "DYNAMIC" && (!input.daily_budget_micros || !input.total_budget_micros || !input.format)) throw new AdportError13("INVALID_INPUT", "linkedin: dynamic campaigns require daily and total budgets and a format");
|
|
2489
|
+
if ((input.type === "SPONSORED_UPDATES" || input.type === "DYNAMIC" || input.objective_type === "LEAD_GENERATION") && !input.associated_entity) throw new AdportError13("INVALID_INPUT", "linkedin: sponsored content, dynamic and lead-generation campaigns require an associated entity");
|
|
2490
|
+
if (input.total_budget_micros && !input.end_time) throw new AdportError13("INVALID_INPUT", "linkedin: lifetime campaign budgets require an end time");
|
|
2491
|
+
if (input.end_time && (!input.start_time || input.end_time <= input.start_time)) throw new AdportError13("INVALID_INPUT", "linkedin: scheduled end requires an earlier start time");
|
|
303
2492
|
const keys = input.targeting_criteria.include.and.flatMap((clause) => Object.keys(clause.or));
|
|
304
|
-
|
|
305
|
-
if (
|
|
306
|
-
if (
|
|
2493
|
+
const customFacets = ["urn:li:adTargetingFacet:audienceMatchingSegments", "urn:li:adTargetingFacet:dynamicSegments"];
|
|
2494
|
+
if ([...keys, ...Object.keys(input.targeting_criteria.exclude?.or ?? {})].some((key) => customFacets.includes(key))) throw new AdportError13("INVALID_INPUT", "linkedin: custom audience references require a dedicated account-availability workflow");
|
|
2495
|
+
if (input.targeting_criteria.include.and.some((clause) => !Object.keys(clause.or).length)) throw new AdportError13("INVALID_INPUT", "linkedin: targeting include clauses cannot be empty");
|
|
2496
|
+
if (!keys.includes("urn:li:adTargetingFacet:locations") && !keys.includes("urn:li:adTargetingFacet:profileLocations")) throw new AdportError13("INVALID_INPUT", "linkedin: targeting must include modern geo locations");
|
|
2497
|
+
if (keys.includes("urn:li:adTargetingFacet:locations") && keys.includes("urn:li:adTargetingFacet:profileLocations")) throw new AdportError13("INVALID_INPUT", "linkedin: choose locations or profileLocations, not both");
|
|
307
2498
|
for (const clause of input.targeting_criteria.include.and) for (const [facet, values] of Object.entries(clause.or)) {
|
|
308
|
-
if (["urn:li:adTargetingFacet:locations", "urn:li:adTargetingFacet:profileLocations"].includes(facet) && values.some((value) => !/^urn:li:geo:[1-9]\d*$/.test(value))) throw new
|
|
2499
|
+
if (["urn:li:adTargetingFacet:locations", "urn:li:adTargetingFacet:profileLocations"].includes(facet) && values.some((value) => !/^urn:li:geo:[1-9]\d*$/.test(value))) throw new AdportError13("INVALID_INPUT", "linkedin: use modern urn:li:geo location identifiers; legacy geo is no longer supported");
|
|
309
2500
|
}
|
|
310
|
-
const
|
|
2501
|
+
const account2 = await this.getAccount(accountId);
|
|
311
2502
|
const group = await this.client.get(`adAccounts/${accountId}/adCampaignGroups/${input.campaign_group_id}`, groupSchema);
|
|
312
|
-
if (group.account !== ACCOUNT_URN(accountId) || String(group.id) !== input.campaign_group_id) throw new
|
|
313
|
-
if (group.budgetOptimization?.budgetOptimizationStrategy === "DYNAMIC") throw new
|
|
2503
|
+
if (group.account !== ACCOUNT_URN(accountId) || String(group.id) !== input.campaign_group_id) throw new AdportError13("PROVIDER_ERROR", "linkedin: campaign group account/ID mismatch");
|
|
2504
|
+
if (group.budgetOptimization?.budgetOptimizationStrategy === "DYNAMIC") throw new AdportError13("INVALID_INPUT", "linkedin: this group shares a dynamic budget; ordinary campaign budget creation is not supported for it");
|
|
314
2505
|
const status = guard.forcePausedCreation ? "PAUSED" : input.status;
|
|
315
|
-
const
|
|
2506
|
+
const money3 = (amount) => ({ amount: microsToDecimal(amount), currencyCode: account2.currency });
|
|
316
2507
|
const body = {
|
|
317
2508
|
account: ACCOUNT_URN(accountId),
|
|
318
2509
|
campaignGroup: `urn:li:sponsoredCampaignGroup:${input.campaign_group_id}`,
|
|
@@ -320,7 +2511,7 @@ var LinkedInAdsProvider = class {
|
|
|
320
2511
|
type: input.type,
|
|
321
2512
|
objectiveType: input.objective_type,
|
|
322
2513
|
costType: input.cost_type,
|
|
323
|
-
unitCost:
|
|
2514
|
+
unitCost: money3(input.unit_cost_micros),
|
|
324
2515
|
locale: input.locale,
|
|
325
2516
|
targetingCriteria: input.targeting_criteria,
|
|
326
2517
|
status,
|
|
@@ -329,8 +2520,8 @@ var LinkedInAdsProvider = class {
|
|
|
329
2520
|
audienceExpansionEnabled: false,
|
|
330
2521
|
...input.associated_entity ? { associatedEntity: input.associated_entity } : {},
|
|
331
2522
|
...input.format ? { format: input.format } : {},
|
|
332
|
-
...input.daily_budget_micros ? { dailyBudget:
|
|
333
|
-
...input.total_budget_micros ? { totalBudget:
|
|
2523
|
+
...input.daily_budget_micros ? { dailyBudget: money3(input.daily_budget_micros) } : {},
|
|
2524
|
+
...input.total_budget_micros ? { totalBudget: money3(input.total_budget_micros), pacingStrategy: "LIFETIME" } : {},
|
|
334
2525
|
...input.start_time ? { runSchedule: { start: input.start_time, ...input.end_time ? { end: input.end_time } : {} } } : {}
|
|
335
2526
|
};
|
|
336
2527
|
return {
|
|
@@ -338,16 +2529,16 @@ var LinkedInAdsProvider = class {
|
|
|
338
2529
|
changes: [NON_DISCRIMINATION_NOTICE, `Advertiser confirmation: ${NON_POLITICAL_CONSENT}`, `+ ${JSON.stringify(body)}`],
|
|
339
2530
|
coercions: input.status !== status ? ["status coerced to PAUSED by policy (paused_creation)"] : [],
|
|
340
2531
|
budgetDeltas: [...input.daily_budget_micros ? [{ target: "new campaign daily budget", toMicros: input.daily_budget_micros }] : [], ...input.total_budget_micros ? [{ target: "new campaign total budget", toMicros: input.total_budget_micros }] : []],
|
|
341
|
-
execute: async () => [await this.client.create(
|
|
2532
|
+
execute: async () => [await this.client.create(base2, body)]
|
|
342
2533
|
};
|
|
343
2534
|
}
|
|
344
2535
|
if (op.kind === "update" && ["linkedin_set_campaign_status", "linkedin_set_budget"].includes(op.tool)) {
|
|
345
2536
|
const input = op.tool === "linkedin_set_budget" ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);
|
|
346
|
-
if ("status" in input && input.status === "ACTIVE" && !input.non_political_consent) throw new
|
|
2537
|
+
if ("status" in input && input.status === "ACTIVE" && !input.non_political_consent) throw new AdportError13("INVALID_INPUT", `linkedin: activation requires explicit advertiser consent: ${NON_POLITICAL_CONSENT}`);
|
|
347
2538
|
const current = await this.getCampaign(accountId, input.campaign_id);
|
|
348
2539
|
if ("budget_micros" in input) {
|
|
349
2540
|
const field = input.budget_type === "DAILY" ? "dailyBudget" : "totalBudget", budget = current[field];
|
|
350
|
-
if (!budget) throw new
|
|
2541
|
+
if (!budget) throw new AdportError13("INVALID_INPUT", `linkedin: campaign has no existing ${field}; this tool changes existing budget types only`);
|
|
351
2542
|
const fromMicros = decimalToMicros(budget.amount);
|
|
352
2543
|
return {
|
|
353
2544
|
summary: `Change LinkedIn campaign "${current.name}" budget`,
|
|
@@ -355,7 +2546,7 @@ var LinkedInAdsProvider = class {
|
|
|
355
2546
|
coercions: [],
|
|
356
2547
|
budgetDeltas: [{ target: `campaign ${current.id} ${field}`, fromMicros, toMicros: input.budget_micros }],
|
|
357
2548
|
execute: async () => {
|
|
358
|
-
await this.client.update(`${
|
|
2549
|
+
await this.client.update(`${base2}/${current.id}`, { [field]: { amount: microsToDecimal(input.budget_micros), currencyCode: budget.currencyCode } });
|
|
359
2550
|
return [String(current.id)];
|
|
360
2551
|
}
|
|
361
2552
|
};
|
|
@@ -366,21 +2557,21 @@ var LinkedInAdsProvider = class {
|
|
|
366
2557
|
coercions: [],
|
|
367
2558
|
budgetDeltas: [],
|
|
368
2559
|
execute: async () => {
|
|
369
|
-
await this.client.update(`${
|
|
2560
|
+
await this.client.update(`${base2}/${current.id}`, { status: input.status, ...input.status === "ACTIVE" ? { politicalIntent: "NOT_POLITICAL" } : {} });
|
|
370
2561
|
return [String(current.id)];
|
|
371
2562
|
}
|
|
372
2563
|
};
|
|
373
2564
|
}
|
|
374
|
-
throw new
|
|
2565
|
+
throw new AdportError13("INVALID_INPUT", `linkedin: unsupported write ${op.tool}`);
|
|
375
2566
|
}
|
|
376
2567
|
};
|
|
377
|
-
function normalize(
|
|
2568
|
+
function normalize(row4, requested) {
|
|
378
2569
|
const mapped = {};
|
|
379
2570
|
for (const [metric, field] of Object.entries(FIELDS)) {
|
|
380
|
-
const value =
|
|
2571
|
+
const value = row4[field];
|
|
381
2572
|
if (value === void 0) continue;
|
|
382
2573
|
const number = Number(value);
|
|
383
|
-
if (!Number.isFinite(number) || number < 0) throw new
|
|
2574
|
+
if (!Number.isFinite(number) || number < 0) throw new AdportError13("PROVIDER_ERROR", `linkedin: invalid ${field} metric`);
|
|
384
2575
|
mapped[metric] = number;
|
|
385
2576
|
}
|
|
386
2577
|
for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) if (mapped[numerator] !== void 0 && mapped[denominator] !== void 0) mapped[metric] = mapped[denominator] ? mapped[numerator] / mapped[denominator] * factor : 0;
|
|
@@ -388,23 +2579,34 @@ function normalize(row, requested) {
|
|
|
388
2579
|
}
|
|
389
2580
|
|
|
390
2581
|
// src/tools.ts
|
|
391
|
-
import { z as
|
|
392
|
-
import { defineTool, guardedWriteTool } from "@adport/core";
|
|
2582
|
+
import { z as z17 } from "zod";
|
|
2583
|
+
import { defineTool as defineTool11, guardedWriteTool as guardedWriteTool9 } from "@adport/core";
|
|
393
2584
|
function linkedinTools(provider) {
|
|
394
2585
|
return [
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
2586
|
+
...linkedinLeadFormTools(provider),
|
|
2587
|
+
...linkedinLeadCreativeTools(provider),
|
|
2588
|
+
...linkedinMeasurementTools(provider),
|
|
2589
|
+
...linkedinReportingTools(provider),
|
|
2590
|
+
...linkedinPlanningTools(provider),
|
|
2591
|
+
...linkedinAudienceTools(provider),
|
|
2592
|
+
...linkedinCreativeTools(provider),
|
|
2593
|
+
...linkedinManagementTools(provider),
|
|
2594
|
+
...linkedinMediaTools(provider),
|
|
2595
|
+
...linkedinSponsoredTools(provider),
|
|
2596
|
+
defineTool11({ name: "linkedin_get_account", namespace: "linkedin", description: "Read exact native account settings, status and organization reference after verifying the selected account ID. Account discovery does not establish billing readiness or Page permissions.", input: z17.object({ account_id: linkedinId }), annotations: { readOnly: true }, handler: (input) => provider.getAccount(input.account_id) }),
|
|
2597
|
+
defineTool11({ name: "linkedin_list_campaigns", namespace: "linkedin", description: "List LinkedIn campaigns, including inactive campaigns.", input: z17.object({ account_id: linkedinId }), annotations: { readOnly: true }, handler: (input) => provider.listCampaigns(input.account_id) }),
|
|
2598
|
+
defineTool11({ name: "linkedin_list_campaign_groups", namespace: "linkedin", description: "List LinkedIn campaign groups to select a parent for campaign creation.", input: z17.object({ account_id: linkedinId }), annotations: { readOnly: true }, handler: (input) => provider.listCampaignGroups(input.account_id) }),
|
|
2599
|
+
guardedWriteTool9({ name: "linkedin_create_campaign", namespace: "linkedin", provider: "linkedin", kind: "create", description: `Create a paused LinkedIn campaign with account-currency budgets in micros. Explicit non-political advertiser consent required. Preview is local. ${NON_DISCRIMINATION_NOTICE}`, payload: createCampaignSchema }),
|
|
2600
|
+
guardedWriteTool9({ name: "linkedin_set_campaign_status", namespace: "linkedin", provider: "linkedin", kind: "update", description: "Pause or activate a LinkedIn campaign. Activation requires explicit non-political advertiser consent.", payload: setStatusSchema }),
|
|
2601
|
+
guardedWriteTool9({ name: "linkedin_set_budget", namespace: "linkedin", provider: "linkedin", kind: "update", description: "Change an existing daily or total LinkedIn campaign budget in integer micros, preserving currency and other budget fields.", payload: setBudgetSchema })
|
|
400
2602
|
];
|
|
401
2603
|
}
|
|
402
2604
|
|
|
403
2605
|
// src/index.ts
|
|
404
|
-
function
|
|
2606
|
+
function timestamp2(value) {
|
|
405
2607
|
if (value === void 0) return void 0;
|
|
406
2608
|
const parsed = Number(value);
|
|
407
|
-
if (!Number.isSafeInteger(parsed) || parsed < 0) throw new
|
|
2609
|
+
if (!Number.isSafeInteger(parsed) || parsed < 0) throw new AdportError14("INVALID_INPUT", "linkedin: token expiration must be Unix milliseconds");
|
|
408
2610
|
return parsed;
|
|
409
2611
|
}
|
|
410
2612
|
function linkedInTokensData(tokens) {
|
|
@@ -413,10 +2615,10 @@ function linkedInTokensData(tokens) {
|
|
|
413
2615
|
async function resolveLinkedInCredentials(store) {
|
|
414
2616
|
const saved = await store.get("linkedin"), data = saved?.data;
|
|
415
2617
|
const complete = (d) => Boolean(d?.access_token || d?.refresh_token && d.client_id && d.client_secret);
|
|
416
|
-
const
|
|
417
|
-
if (!complete(
|
|
418
|
-
const credentials = { accessToken:
|
|
419
|
-
if (
|
|
2618
|
+
const source2 = complete(data) ? data : { access_token: process.env.LINKEDIN_ACCESS_TOKEN ?? "", refresh_token: process.env.LINKEDIN_REFRESH_TOKEN ?? "", client_id: process.env.LINKEDIN_CLIENT_ID ?? "", client_secret: process.env.LINKEDIN_CLIENT_SECRET ?? "", ...process.env.LINKEDIN_EXPIRES_AT ? { expires_at: process.env.LINKEDIN_EXPIRES_AT } : {}, ...process.env.LINKEDIN_REFRESH_EXPIRES_AT ? { refresh_expires_at: process.env.LINKEDIN_REFRESH_EXPIRES_AT } : {} };
|
|
2619
|
+
if (!complete(source2)) return void 0;
|
|
2620
|
+
const credentials = { accessToken: source2?.access_token || void 0, expiresAt: timestamp2(source2?.expires_at), refreshToken: source2?.refresh_token || void 0, refreshExpiresAt: timestamp2(source2?.refresh_expires_at), clientId: source2?.client_id || void 0, clientSecret: source2?.client_secret || void 0 };
|
|
2621
|
+
if (source2 === data) credentials.onTokens = async (tokens) => {
|
|
420
2622
|
const latest = await store.get("linkedin");
|
|
421
2623
|
if (latest) await store.set({ provider: "linkedin", source: latest.source, data: { ...latest.data, ...linkedInTokensData(tokens) } });
|
|
422
2624
|
};
|
|
@@ -431,6 +2633,7 @@ async function createLinkedInModule(store) {
|
|
|
431
2633
|
export {
|
|
432
2634
|
LINKEDIN_API_BASE,
|
|
433
2635
|
LINKEDIN_API_VERSION,
|
|
2636
|
+
LINKEDIN_CREATIVE_METADATA_VERSION,
|
|
434
2637
|
LINKEDIN_TOKEN_URL,
|
|
435
2638
|
LinkedInAdsClient,
|
|
436
2639
|
LinkedInAdsProvider,
|