@adport/provider-microsoft 0.7.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 +1096 -6
- package/dist/index.js +2703 -177
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -8,7 +8,8 @@ function hosts(sandbox) {
|
|
|
8
8
|
return {
|
|
9
9
|
campaign: `https://campaign.api${infix}.bingads.microsoft.com/CampaignManagement/v13`,
|
|
10
10
|
customer: `https://clientcenter.api${infix}.bingads.microsoft.com/CustomerManagement/v13`,
|
|
11
|
-
reporting: `https://reporting.api${infix}.bingads.microsoft.com/Reporting/v13
|
|
11
|
+
reporting: `https://reporting.api${infix}.bingads.microsoft.com/Reporting/v13`,
|
|
12
|
+
adinsight: `https://adinsight.api${infix}.bingads.microsoft.com/AdInsight/v13`
|
|
12
13
|
};
|
|
13
14
|
}
|
|
14
15
|
var MicrosoftAdsClient = class {
|
|
@@ -57,7 +58,7 @@ var MicrosoftAdsClient = class {
|
|
|
57
58
|
}
|
|
58
59
|
return this.accessToken.token;
|
|
59
60
|
}
|
|
60
|
-
async request(service, method, path, body, scope = {}) {
|
|
61
|
+
async request(service, method, path, body, scope = {}, options = {}) {
|
|
61
62
|
const token = await this.getAccessToken();
|
|
62
63
|
const headers = {
|
|
63
64
|
authorization: `Bearer ${token}`,
|
|
@@ -72,14 +73,23 @@ var MicrosoftAdsClient = class {
|
|
|
72
73
|
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
73
74
|
});
|
|
74
75
|
const raw = await response.text();
|
|
75
|
-
if (!response.ok) {
|
|
76
|
+
if (!response.ok || options.privatePayload && response.status !== 200) {
|
|
77
|
+
if (options.privatePayload) throw new AdportError("PROVIDER_ERROR", `microsoft: private request failed (HTTP ${response.status}); native response values omitted`);
|
|
76
78
|
throw new AdportError("PROVIDER_ERROR", formatMicrosoftError(response.status, raw), safeJson(raw));
|
|
77
79
|
}
|
|
80
|
+
if (options.privatePayload) {
|
|
81
|
+
try {
|
|
82
|
+
if (!raw.trim()) throw new Error("Empty receipt");
|
|
83
|
+
return JSON.parse(raw);
|
|
84
|
+
} catch {
|
|
85
|
+
throw new AdportError("PROVIDER_ERROR", "microsoft: private request returned an unrecognized JSON receipt; native values omitted");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
78
88
|
return raw ? JSON.parse(raw) : {};
|
|
79
89
|
}
|
|
80
90
|
/** Plain authorized download (report files); returns raw bytes. */
|
|
81
|
-
async download(
|
|
82
|
-
const response = await this.fetchImpl(
|
|
91
|
+
async download(url3) {
|
|
92
|
+
const response = await this.fetchImpl(url3, {});
|
|
83
93
|
if (!response.ok) {
|
|
84
94
|
throw new AdportError("PROVIDER_ERROR", `Microsoft report download failed (HTTP ${response.status})`);
|
|
85
95
|
}
|
|
@@ -93,17 +103,17 @@ function safeJson(raw) {
|
|
|
93
103
|
return raw;
|
|
94
104
|
}
|
|
95
105
|
}
|
|
96
|
-
function formatMicrosoftError(
|
|
106
|
+
function formatMicrosoftError(status2, raw) {
|
|
97
107
|
const parsed = safeJson(raw);
|
|
98
108
|
if (!parsed || typeof parsed !== "object" || !parsed.OperationErrors && !parsed.Errors && !parsed.BatchErrors) {
|
|
99
|
-
return `Microsoft Advertising API error (HTTP ${
|
|
109
|
+
return `Microsoft Advertising API error (HTTP ${status2})`;
|
|
100
110
|
}
|
|
101
111
|
const items = [...parsed.OperationErrors ?? [], ...parsed.BatchErrors ?? [], ...parsed.Errors ?? []];
|
|
102
112
|
const lines = items.map((e) => {
|
|
103
113
|
const where = e.Index !== void 0 ? ` [item ${e.Index}${e.FieldPath ? ` ${e.FieldPath}` : ""}]` : "";
|
|
104
114
|
return `${e.Code ?? "?"} ${e.ErrorCode ?? ""}: ${e.Message ?? e.Details ?? e.Detail ?? ""}${where}`;
|
|
105
115
|
});
|
|
106
|
-
let message = `Microsoft Advertising API error (HTTP ${
|
|
116
|
+
let message = `Microsoft Advertising API error (HTTP ${status2}, ${parsed.Type ?? "fault"}):
|
|
107
117
|
${lines.join("\n ")}`;
|
|
108
118
|
if (items.some((e) => e.Code === 105)) {
|
|
109
119
|
message += "\n Code 105 InvalidCredentials: check the developer token matches the environment (sandbox vs production).";
|
|
@@ -115,28 +125,31 @@ function formatMicrosoftError(status, raw) {
|
|
|
115
125
|
return message;
|
|
116
126
|
}
|
|
117
127
|
function formatPartialErrors(partialErrors) {
|
|
118
|
-
|
|
119
|
-
|
|
128
|
+
const errors = partialErrors?.filter((error) => error !== null) ?? [];
|
|
129
|
+
if (errors.length === 0) return void 0;
|
|
130
|
+
return errors.map((e) => `item ${e.Index ?? "?"}: ${e.Code ?? ""} ${e.ErrorCode ?? ""} ${e.Message ?? ""}${e.FieldPath ? ` (${e.FieldPath})` : ""}`).join("; ");
|
|
120
131
|
}
|
|
121
132
|
|
|
122
133
|
// src/provider.ts
|
|
123
134
|
import {
|
|
124
|
-
AdportError as
|
|
135
|
+
AdportError as AdportError17,
|
|
136
|
+
LocalMediaResolver as LocalMediaResolver2,
|
|
137
|
+
METRICS,
|
|
125
138
|
resolveDateRange
|
|
126
139
|
} from "@adport/core";
|
|
127
140
|
import { unzipSync } from "fflate";
|
|
128
141
|
|
|
129
142
|
// src/csv.ts
|
|
130
|
-
function parseCsv(
|
|
131
|
-
const
|
|
143
|
+
function parseCsv(text2) {
|
|
144
|
+
const rows3 = [];
|
|
132
145
|
let row = [];
|
|
133
146
|
let field = "";
|
|
134
147
|
let inQuotes = false;
|
|
135
|
-
for (let i = 0; i <
|
|
136
|
-
const char =
|
|
148
|
+
for (let i = 0; i < text2.length; i++) {
|
|
149
|
+
const char = text2[i];
|
|
137
150
|
if (inQuotes) {
|
|
138
151
|
if (char === '"') {
|
|
139
|
-
if (
|
|
152
|
+
if (text2[i + 1] === '"') {
|
|
140
153
|
field += '"';
|
|
141
154
|
i++;
|
|
142
155
|
} else {
|
|
@@ -153,10 +166,10 @@ function parseCsv(text) {
|
|
|
153
166
|
row.push(field);
|
|
154
167
|
field = "";
|
|
155
168
|
} else if (char === "\n" || char === "\r") {
|
|
156
|
-
if (char === "\r" &&
|
|
169
|
+
if (char === "\r" && text2[i + 1] === "\n") i++;
|
|
157
170
|
row.push(field);
|
|
158
171
|
field = "";
|
|
159
|
-
if (row.length > 1 || row[0] !== "")
|
|
172
|
+
if (row.length > 1 || row[0] !== "") rows3.push(row);
|
|
160
173
|
row = [];
|
|
161
174
|
} else {
|
|
162
175
|
field += char;
|
|
@@ -164,23 +177,2368 @@ function parseCsv(text) {
|
|
|
164
177
|
}
|
|
165
178
|
if (field !== "" || row.length > 0) {
|
|
166
179
|
row.push(field);
|
|
167
|
-
if (row.length > 1 || row[0] !== "")
|
|
180
|
+
if (row.length > 1 || row[0] !== "") rows3.push(row);
|
|
181
|
+
}
|
|
182
|
+
return rows3;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// src/children.ts
|
|
186
|
+
import { AdportError as AdportError2, creativeStatusAction } from "@adport/core";
|
|
187
|
+
var object = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
188
|
+
var objects = (value) => Array.isArray(value) ? value.filter((row) => row && typeof row === "object") : [];
|
|
189
|
+
var texts = (value) => objects(value).flatMap((link) => typeof object(link.Asset).Text === "string" ? [String(object(link.Asset).Text)] : []);
|
|
190
|
+
var MicrosoftChildService = class {
|
|
191
|
+
constructor(client, scope, campaign) {
|
|
192
|
+
this.client = client;
|
|
193
|
+
this.scope = scope;
|
|
194
|
+
this.campaign = campaign;
|
|
195
|
+
}
|
|
196
|
+
client;
|
|
197
|
+
scope;
|
|
198
|
+
campaign;
|
|
199
|
+
async request(account, path, body, method = "POST") {
|
|
200
|
+
const result = await this.client.request("campaign", method, path, body, await this.scope(account));
|
|
201
|
+
const partial = formatPartialErrors(result.PartialErrors);
|
|
202
|
+
if (partial) throw new AdportError2("PROVIDER_ERROR", `microsoft: ${path} partial errors \u2014 ${partial}. Check successful resource IDs before retrying.`, {
|
|
203
|
+
resourceIds: Object.entries(result).filter(([key]) => /Ids$/.test(key)).flatMap(([, value]) => Array.isArray(value) ? value.filter((id3) => id3 !== null).map(String) : []),
|
|
204
|
+
partialErrors: result.PartialErrors
|
|
205
|
+
});
|
|
206
|
+
return result;
|
|
207
|
+
}
|
|
208
|
+
async listGroups(input) {
|
|
209
|
+
await this.campaign(input.account_id, input.campaign_id);
|
|
210
|
+
const result = await this.request(input.account_id, "AdGroups/QueryByCampaignId", { CampaignId: input.campaign_id, ReturnAdditionalFields: "AdGroupType" });
|
|
211
|
+
return { rows: objects(result.AdGroups), truncated: false };
|
|
212
|
+
}
|
|
213
|
+
async group(input) {
|
|
214
|
+
await this.campaign(input.account_id, input.campaign_id);
|
|
215
|
+
const result = await this.request(input.account_id, "AdGroups/QueryByIds", { CampaignId: input.campaign_id, AdGroupIds: [input.ad_group_id], ReturnAdditionalFields: "AdGroupType" });
|
|
216
|
+
const group = objects(result.AdGroups).find((row) => String(row.Id) === input.ad_group_id);
|
|
217
|
+
if (!group) throw new AdportError2("INVALID_INPUT", "Microsoft ad group was not found in the selected campaign/account.");
|
|
218
|
+
return group;
|
|
219
|
+
}
|
|
220
|
+
async listKeywords(input) {
|
|
221
|
+
await this.group(input);
|
|
222
|
+
const result = await this.request(input.account_id, "Keywords/QueryByAdGroupId", { AdGroupId: input.ad_group_id, ReturnAdditionalFields: null });
|
|
223
|
+
return { rows: objects(result.Keywords), truncated: false };
|
|
224
|
+
}
|
|
225
|
+
async listAds(input) {
|
|
226
|
+
await this.group(input);
|
|
227
|
+
const result = await this.request(input.account_id, "Ads/QueryByAdGroupId", { AdGroupId: input.ad_group_id, AdTypes: input.ad_types, ReturnAdditionalFields: null });
|
|
228
|
+
const ads = objects(result.Ads);
|
|
229
|
+
return { ads: ads.slice(0, input.limit), truncated: ads.length > input.limit, creatives: ads.slice(0, input.limit).map((ad) => this.card(input, ad)) };
|
|
230
|
+
}
|
|
231
|
+
card(input, ad) {
|
|
232
|
+
const adId = String(ad.Id), headlines2 = texts(ad.Headlines), descriptions2 = texts(ad.Descriptions), args = { account_id: input.account_id, campaign_id: input.campaign_id, ad_group_id: input.ad_group_id, ad_id: adId };
|
|
233
|
+
if (!/^\d+$/.test(adId)) throw new AdportError2("PROVIDER_ERROR", "Microsoft returned an ad without a valid ID.");
|
|
234
|
+
const actions = ["Active", "Paused"].includes(String(ad.Status)) ? [creativeStatusAction("microsoft_set_ad_status", { ...args, ad_type: ad.Type }, String(ad.Status), ["Active", "Paused"])] : [];
|
|
235
|
+
if (ad.Type === "ResponsiveSearch") actions.push({
|
|
236
|
+
label: "Edit ad copy",
|
|
237
|
+
tool: "microsoft_update_responsive_search_ad",
|
|
238
|
+
arguments: args,
|
|
239
|
+
fields: [
|
|
240
|
+
{ key: "headlines", label: "Headlines (one per line)", type: "text_list", value: headlines2 },
|
|
241
|
+
{ key: "descriptions", label: "Descriptions (one per line)", type: "text_list", value: descriptions2 },
|
|
242
|
+
{ key: "final_urls", label: "Landing pages (one per line)", type: "url_list", value: Array.isArray(ad.FinalUrls) ? ad.FinalUrls.map(String) : [] }
|
|
243
|
+
]
|
|
244
|
+
});
|
|
245
|
+
const destinations = Array.isArray(ad.FinalUrls) ? ad.FinalUrls.map(String).filter((value) => {
|
|
246
|
+
try {
|
|
247
|
+
const url3 = new URL(value);
|
|
248
|
+
return ["http:", "https:"].includes(url3.protocol) && !url3.username && !url3.password;
|
|
249
|
+
} catch {
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
}) : [];
|
|
253
|
+
return {
|
|
254
|
+
id: adId,
|
|
255
|
+
provider: "microsoft",
|
|
256
|
+
account_id: input.account_id,
|
|
257
|
+
campaign_id: input.campaign_id,
|
|
258
|
+
ad_group_id: input.ad_group_id,
|
|
259
|
+
name: headlines2[0] || String(ad.Title ?? ad.TitlePart1 ?? `Ad ${adId}`),
|
|
260
|
+
type: String(ad.Type),
|
|
261
|
+
status: String(ad.Status),
|
|
262
|
+
headlines: headlines2,
|
|
263
|
+
descriptions: descriptions2,
|
|
264
|
+
landing_urls: destinations,
|
|
265
|
+
media: [],
|
|
266
|
+
actions
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
async ad(input, id3, type) {
|
|
270
|
+
await this.group(input);
|
|
271
|
+
const result = await this.request(input.account_id, "Ads/QueryByIds", { AdGroupId: input.ad_group_id, AdIds: [id3], AdTypes: [type], ReturnAdditionalFields: null });
|
|
272
|
+
const ad = objects(result.Ads).find((row) => String(row.Id) === id3 && row.Type === type);
|
|
273
|
+
if (!ad) throw new AdportError2("INVALID_INPUT", "Microsoft ad was not found with this type in the selected ad group/account.");
|
|
274
|
+
return ad;
|
|
275
|
+
}
|
|
276
|
+
async keywords(input, ids) {
|
|
277
|
+
await this.group(input);
|
|
278
|
+
const result = await this.request(input.account_id, "Keywords/QueryByIds", { AdGroupId: input.ad_group_id, KeywordIds: ids, ReturnAdditionalFields: null });
|
|
279
|
+
const rows3 = objects(result.Keywords);
|
|
280
|
+
if (ids.some((id3) => !rows3.some((row) => String(row.Id) === id3))) throw new AdportError2("INVALID_INPUT", "A keyword was not found in the selected ad group/account.");
|
|
281
|
+
return rows3;
|
|
282
|
+
}
|
|
283
|
+
async plan(op, guard) {
|
|
284
|
+
const p = op.payload, parent2 = { account_id: op.accountId, campaign_id: String(p.campaign_id), ad_group_id: String(p.ad_group_id) };
|
|
285
|
+
const mutate = (collection, body, changes, ids = [], coercions = []) => ({
|
|
286
|
+
summary: changes[0],
|
|
287
|
+
changes,
|
|
288
|
+
coercions,
|
|
289
|
+
budgetDeltas: [],
|
|
290
|
+
execute: async () => {
|
|
291
|
+
const method = op.kind === "create" ? "POST" : op.kind === "remove" ? "DELETE" : "PUT";
|
|
292
|
+
const result = await this.request(op.accountId, collection, body, method);
|
|
293
|
+
if (op.kind !== "create") return ids;
|
|
294
|
+
const values = result[`${collection === "AdGroups" ? "AdGroup" : collection === "Keywords" ? "Keyword" : "Ad"}Ids`];
|
|
295
|
+
const created = Array.isArray(values) ? values.filter((id3) => id3 !== null).map(String) : [];
|
|
296
|
+
if (created.length !== objects(body[collection]).length) throw new AdportError2("PROVIDER_ERROR", "Microsoft did not return an ID for every requested resource. Check creation status before retrying.", { resourceIds: created });
|
|
297
|
+
return created;
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
const creationStatus = (requested) => guard.forcePausedCreation ? "Paused" : requested ?? "Paused";
|
|
301
|
+
const creationCoercion = (requested) => guard.forcePausedCreation && requested === "Active" ? ["status coerced to Paused by policy (paused_creation)"] : [];
|
|
302
|
+
const assetLinks = (value, current = []) => value.map((text2, index) => {
|
|
303
|
+
const previous = objects(current)[index];
|
|
304
|
+
return { Asset: { Type: "TextAsset", Text: text2 }, ...previous?.PinnedField ? { PinnedField: previous.PinnedField } : {} };
|
|
305
|
+
});
|
|
306
|
+
switch (op.tool) {
|
|
307
|
+
case "microsoft_create_ad_group":
|
|
308
|
+
await this.campaign(op.accountId, String(p.campaign_id));
|
|
309
|
+
return mutate(
|
|
310
|
+
"AdGroups",
|
|
311
|
+
{ CampaignId: p.campaign_id, AdGroups: [{ Name: p.name, AdGroupType: "SearchStandard", Language: p.language, Status: creationStatus(p.status), ...p.cpc_bid !== void 0 ? { CpcBid: { Amount: p.cpc_bid } } : {} }] },
|
|
312
|
+
[`+ SearchStandard ad group "${p.name}" (${creationStatus(p.status)}), language=${p.language}`, ...p.cpc_bid !== void 0 ? [`CPC bid ${p.cpc_bid} whole currency units`] : []],
|
|
313
|
+
[],
|
|
314
|
+
creationCoercion(p.status)
|
|
315
|
+
);
|
|
316
|
+
case "microsoft_set_ad_group_status":
|
|
317
|
+
case "microsoft_update_ad_group": {
|
|
318
|
+
const current = await this.group(parent2), fields2 = op.tool === "microsoft_set_ad_group_status" ? { Status: p.status } : { ...p.name !== void 0 ? { Name: p.name } : {}, ...p.cpc_bid !== void 0 ? { CpcBid: { Amount: p.cpc_bid } } : {} };
|
|
319
|
+
return mutate("AdGroups", { CampaignId: p.campaign_id, AdGroups: [{ Id: p.ad_group_id, ...fields2 }] }, [`~ ad group ${p.ad_group_id}: ${JSON.stringify({ Name: current.Name, Status: current.Status, CpcBid: current.CpcBid })} \u2192 ${JSON.stringify(fields2)}`], [String(p.ad_group_id)]);
|
|
320
|
+
}
|
|
321
|
+
case "microsoft_create_responsive_search_ad": {
|
|
322
|
+
const group = await this.group(parent2);
|
|
323
|
+
if (group.AdGroupType !== "SearchStandard") throw new AdportError2("INVALID_INPUT", "Responsive search ads require a SearchStandard ad group.");
|
|
324
|
+
const fields2 = {
|
|
325
|
+
Type: "ResponsiveSearch",
|
|
326
|
+
Status: creationStatus(p.status),
|
|
327
|
+
Headlines: assetLinks(p.headlines),
|
|
328
|
+
Descriptions: assetLinks(p.descriptions),
|
|
329
|
+
FinalUrls: p.final_urls,
|
|
330
|
+
...p.path1 !== void 0 ? { Path1: p.path1 } : {},
|
|
331
|
+
...p.path2 !== void 0 ? { Path2: p.path2 } : {}
|
|
332
|
+
};
|
|
333
|
+
return mutate("Ads", { AdGroupId: p.ad_group_id, Ads: [fields2] }, [`+ responsive search ad ${JSON.stringify(fields2)}`], [], creationCoercion(p.status));
|
|
334
|
+
}
|
|
335
|
+
case "microsoft_update_responsive_search_ad":
|
|
336
|
+
case "microsoft_set_ad_status": {
|
|
337
|
+
const type = op.tool === "microsoft_set_ad_status" ? String(p.ad_type) : "ResponsiveSearch";
|
|
338
|
+
const current = await this.ad(parent2, String(p.ad_id), type);
|
|
339
|
+
const fields2 = { Id: p.ad_id, Type: type };
|
|
340
|
+
if (op.tool === "microsoft_set_ad_status") fields2.Status = p.status;
|
|
341
|
+
else {
|
|
342
|
+
if (p.headlines !== void 0) fields2.Headlines = assetLinks(p.headlines, current.Headlines);
|
|
343
|
+
if (p.descriptions !== void 0) fields2.Descriptions = assetLinks(p.descriptions, current.Descriptions);
|
|
344
|
+
if (p.final_urls !== void 0) fields2.FinalUrls = p.final_urls;
|
|
345
|
+
if (p.path1 !== void 0) fields2.Path1 = p.path1;
|
|
346
|
+
if (p.path2 !== void 0) fields2.Path2 = p.path2;
|
|
347
|
+
}
|
|
348
|
+
return mutate("Ads", { AdGroupId: p.ad_group_id, Ads: [fields2] }, [
|
|
349
|
+
`~ ad ${p.ad_id}: ${JSON.stringify(current)} \u2192 ${JSON.stringify(fields2)}`,
|
|
350
|
+
...op.tool === "microsoft_update_responsive_search_ad" ? [`Serving status remains ${current.Status}. Omitted content fields remain unchanged.`] : []
|
|
351
|
+
], [String(p.ad_id)]);
|
|
352
|
+
}
|
|
353
|
+
case "microsoft_add_keywords": {
|
|
354
|
+
await this.group(parent2);
|
|
355
|
+
const keywords2 = p.keywords.map((keyword2) => ({ Text: keyword2.text, MatchType: keyword2.match_type, Status: creationStatus(keyword2.status), ...keyword2.bid !== void 0 ? { Bid: { Amount: keyword2.bid } } : {} }));
|
|
356
|
+
return mutate("Keywords", { AdGroupId: p.ad_group_id, Keywords: keywords2 }, [`+ keywords ${JSON.stringify(keywords2)}`], [], guard.forcePausedCreation && p.keywords.some((keyword2) => keyword2.status === "Active") ? ["keyword statuses coerced to Paused by policy (paused_creation)"] : []);
|
|
357
|
+
}
|
|
358
|
+
case "microsoft_set_keyword_status":
|
|
359
|
+
case "microsoft_set_keyword_bid": {
|
|
360
|
+
const [current] = await this.keywords(parent2, [String(p.keyword_id)]);
|
|
361
|
+
const fields2 = op.tool === "microsoft_set_keyword_status" ? { Status: p.status } : { Bid: { Amount: p.bid } };
|
|
362
|
+
return mutate("Keywords", { AdGroupId: p.ad_group_id, Keywords: [{ Id: p.keyword_id, ...fields2 }] }, [`~ keyword ${p.keyword_id}: ${JSON.stringify(current)} \u2192 ${JSON.stringify(fields2)}`], [String(p.keyword_id)]);
|
|
363
|
+
}
|
|
364
|
+
case "microsoft_remove_keywords":
|
|
365
|
+
await this.keywords(parent2, p.keyword_ids);
|
|
366
|
+
return mutate("Keywords", { AdGroupId: p.ad_group_id, KeywordIds: p.keyword_ids }, [`- keywords ${p.keyword_ids.join(", ")}; cannot be undone`], p.keyword_ids);
|
|
367
|
+
default:
|
|
368
|
+
throw new AdportError2("PROVIDER_ERROR", `microsoft: unsupported write tool ${op.tool}`);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
// src/images.ts
|
|
374
|
+
import { AdportError as AdportError3, LocalMediaResolver, creativesOutput, defineTool, guardedWriteTool, mediaSourceFields } from "@adport/core";
|
|
375
|
+
import { z } from "zod";
|
|
376
|
+
var id = z.string().regex(/^[1-9]\d*$/);
|
|
377
|
+
var imageType = z.enum(["GenericImage", "Image16x9", "Image15x10", "Image4x3", "Image12x10", "Image1x1", "Image191x100", "Image4x1"]);
|
|
378
|
+
var upload = z.object({ ...mediaSourceFields, image_type: imageType.default("GenericImage"), alt_text: z.string().max(1e3).optional() }).refine((value) => Boolean(value.media_id) !== Boolean(value.file_path), "Choose media_id or file_path");
|
|
379
|
+
var image = z.object({ image_id: id });
|
|
380
|
+
var output = creativesOutput.extend({ images: z.array(z.record(z.string(), z.unknown())), next_page_index: z.number().int().nonnegative().optional() });
|
|
381
|
+
var MICROSOFT_IMAGE_WRITES = /* @__PURE__ */ new Set(["microsoft_upload_image", "microsoft_delete_image"]);
|
|
382
|
+
var rows = (value) => z.array(z.record(z.string(), z.unknown())).parse(value ?? []);
|
|
383
|
+
var nativeId = (value) => {
|
|
384
|
+
if (typeof value === "number" && (!Number.isSafeInteger(value) || value <= 0)) throw new AdportError3("PROVIDER_ERROR", "microsoft: unsafe native media ID");
|
|
385
|
+
const parsed = id.safeParse(typeof value === "number" ? String(value) : value);
|
|
386
|
+
if (!parsed.success) throw new AdportError3("PROVIDER_ERROR", "microsoft: invalid native media ID");
|
|
387
|
+
return parsed.data;
|
|
388
|
+
};
|
|
389
|
+
var MicrosoftImageService = class {
|
|
390
|
+
constructor(client, scope, media = new LocalMediaResolver()) {
|
|
391
|
+
this.client = client;
|
|
392
|
+
this.scope = scope;
|
|
393
|
+
this.media = media;
|
|
394
|
+
}
|
|
395
|
+
client;
|
|
396
|
+
scope;
|
|
397
|
+
media;
|
|
398
|
+
async request(account, path, body, method = "POST") {
|
|
399
|
+
id.parse(account);
|
|
400
|
+
const scope = await this.scope(account);
|
|
401
|
+
if (!scope.customerId || scope.customerAccountId !== account) throw new AdportError3("INVALID_INPUT", "microsoft: account ownership could not be verified");
|
|
402
|
+
const result = await this.client.request("campaign", method, path, body, scope);
|
|
403
|
+
const errors = formatPartialErrors(result.PartialErrors);
|
|
404
|
+
if (errors) throw new AdportError3("PROVIDER_ERROR", `microsoft: ${path}: ${errors}. Reconcile before retrying.`, { resourceIds: Array.isArray(result.MediaIds) ? result.MediaIds.filter((value) => value !== null).map(nativeId) : [], partialErrors: result.PartialErrors });
|
|
405
|
+
return result;
|
|
406
|
+
}
|
|
407
|
+
async page(account, pageIndex, pageSize) {
|
|
408
|
+
const result = await this.request(account, "MediaMetaData/QueryByAccountId", {
|
|
409
|
+
MediaEnabledEntities: "ImageAdExtension, ResponsiveAd",
|
|
410
|
+
PageInfo: { Index: pageIndex, Size: pageSize },
|
|
411
|
+
ReturnAdditionalFields: "Text"
|
|
412
|
+
});
|
|
413
|
+
if (!Object.hasOwn(result, "MediaMetaData")) throw new AdportError3("PROVIDER_ERROR", "microsoft: image-library metadata was not returned");
|
|
414
|
+
const images = rows(result.MediaMetaData);
|
|
415
|
+
if (images.length > pageSize || new Set(images.map((value) => nativeId(value.Id))).size !== images.length) throw new AdportError3("PROVIDER_ERROR", "microsoft: invalid image-library page");
|
|
416
|
+
return images;
|
|
417
|
+
}
|
|
418
|
+
async find(account, imageId) {
|
|
419
|
+
id.parse(imageId);
|
|
420
|
+
const seen = /* @__PURE__ */ new Set();
|
|
421
|
+
for (let page = 0; page < 5; page++) {
|
|
422
|
+
const values = await this.page(account, page, 1e3);
|
|
423
|
+
for (const value of values) {
|
|
424
|
+
const key = nativeId(value.Id);
|
|
425
|
+
if (seen.has(key)) throw new AdportError3("PROVIDER_ERROR", "microsoft: image-library pagination did not advance");
|
|
426
|
+
seen.add(key);
|
|
427
|
+
}
|
|
428
|
+
const found = values.find((value) => nativeId(value.Id) === imageId);
|
|
429
|
+
if (found) return found;
|
|
430
|
+
if (values.length < 1e3) return;
|
|
431
|
+
}
|
|
432
|
+
throw new AdportError3("PROVIDER_ERROR", "microsoft: cannot verify image ownership within the 5000-image library scan limit");
|
|
433
|
+
}
|
|
434
|
+
async owned(account, imageId) {
|
|
435
|
+
const result = await this.find(account, imageId);
|
|
436
|
+
if (!result) throw new AdportError3("INVALID_INPUT", "microsoft: image was not found in the selected account library");
|
|
437
|
+
return result;
|
|
438
|
+
}
|
|
439
|
+
gallery(account, images, truncated, nextPage) {
|
|
440
|
+
const creatives = images.map((value) => {
|
|
441
|
+
const imageId = nativeId(value.Id), alt = typeof value.Text === "string" ? value.Text : void 0;
|
|
442
|
+
const representations = rows(value.Representations);
|
|
443
|
+
const media = representations.flatMap((item) => {
|
|
444
|
+
if (typeof item.Url !== "string") return [];
|
|
445
|
+
try {
|
|
446
|
+
const url3 = new URL(item.Url);
|
|
447
|
+
if (url3.protocol === "https:" && !url3.username && !url3.password && url3.hostname === "www.bing.com") return [{ type: "image", url: item.Url, ...alt ? { alt } : {} }];
|
|
448
|
+
} catch {
|
|
449
|
+
}
|
|
450
|
+
return [];
|
|
451
|
+
});
|
|
452
|
+
return { id: imageId, account_id: account, provider: "microsoft", name: `Image ${imageId}`, type: String(value.MediaType ?? "IMAGE"), headlines: [], descriptions: alt ? [alt] : [], landing_urls: [], media, actions: [] };
|
|
453
|
+
});
|
|
454
|
+
return output.parse({ images, creatives, truncated, ...nextPage !== void 0 ? { next_page_index: nextPage } : {} });
|
|
455
|
+
}
|
|
456
|
+
async list(input) {
|
|
457
|
+
const images = await this.page(input.account_id, input.page_index, input.page_size);
|
|
458
|
+
const truncated = images.length === input.page_size;
|
|
459
|
+
return this.gallery(input.account_id, images, truncated, truncated ? input.page_index + 1 : void 0);
|
|
168
460
|
}
|
|
169
|
-
|
|
461
|
+
async get(input) {
|
|
462
|
+
return this.gallery(input.account_id, [await this.owned(input.account_id, input.image_id)], false);
|
|
463
|
+
}
|
|
464
|
+
async lookupMany(account, imageIds) {
|
|
465
|
+
const wanted = new Set(imageIds.map((value) => id.parse(value))), found = [], seen = /* @__PURE__ */ new Set();
|
|
466
|
+
for (let page = 0; wanted.size && page < 5; page++) {
|
|
467
|
+
const values = await this.page(account, page, 1e3);
|
|
468
|
+
for (const value of values) {
|
|
469
|
+
const key = nativeId(value.Id);
|
|
470
|
+
if (seen.has(key)) throw new AdportError3("PROVIDER_ERROR", "microsoft: image-library pagination did not advance");
|
|
471
|
+
seen.add(key);
|
|
472
|
+
if (wanted.delete(key)) found.push(value);
|
|
473
|
+
}
|
|
474
|
+
if (values.length < 1e3) break;
|
|
475
|
+
}
|
|
476
|
+
return { ...this.gallery(account, found, wanted.size > 0), missing_image_ids: [...wanted] };
|
|
477
|
+
}
|
|
478
|
+
async extensionUses(input) {
|
|
479
|
+
await this.owned(input.account_id, input.image_id);
|
|
480
|
+
const result = await this.request(input.account_id, "MediaAssociations/Query", { MediaEnabledEntities: "ImageAdExtension", MediaIds: [input.image_id] });
|
|
481
|
+
if (!Array.isArray(result.MediaAssociations) || result.MediaAssociations.length !== 1 || !Array.isArray(result.MediaAssociations[0])) throw new AdportError3("PROVIDER_ERROR", "microsoft: image-extension associations were not returned");
|
|
482
|
+
const associations = rows(result.MediaAssociations[0]);
|
|
483
|
+
for (const value of associations) {
|
|
484
|
+
nativeId(value.EntityId);
|
|
485
|
+
if (nativeId(value.MediaId) !== input.image_id || value.MediaEnabledEntity !== "ImageAdExtension") throw new AdportError3("PROVIDER_ERROR", "microsoft: image-extension association identity mismatch");
|
|
486
|
+
}
|
|
487
|
+
return { image_id: input.image_id, associations, coverage: "ImageAdExtension only; ResponsiveAd uses are not returned by this API", truncated: false };
|
|
488
|
+
}
|
|
489
|
+
async plan(op) {
|
|
490
|
+
id.parse(op.accountId);
|
|
491
|
+
const expectedKind = op.tool === "microsoft_upload_image" ? "create" : "remove";
|
|
492
|
+
if (op.provider !== "microsoft" || !MICROSOFT_IMAGE_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError3("INVALID_INPUT", "microsoft: image operation kind mismatch");
|
|
493
|
+
if (op.tool === "microsoft_upload_image") {
|
|
494
|
+
const input2 = upload.parse(op.payload);
|
|
495
|
+
const file = await this.media.read(input2, { maxBytes: 76800, contentTypes: ["image/png", "image/jpeg", "image/gif"] });
|
|
496
|
+
return { summary: `Upload Microsoft image ${file.name}`, changes: [`+ ${input2.image_type}; ${file.contentType}; ${file.bytes.byteLength} bytes; SHA-256 ${file.sha256}`, ...input2.alt_text !== void 0 ? [`Image alt text: ${JSON.stringify(input2.alt_text)}`] : [], "Creates an unattached image. Microsoft validates dimensions and rejects animation; PNG images are converted to JPEG."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
497
|
+
const result = await this.request(op.accountId, "Media", { AccountId: op.accountId, Media: [{ Type: "Image", MediaType: input2.image_type, ...input2.alt_text !== void 0 ? { Text: input2.alt_text } : {}, Data: Buffer.from(file.bytes).toString("base64") }] });
|
|
498
|
+
const created = Array.isArray(result.MediaIds) ? result.MediaIds.filter((value) => value !== null).map(nativeId) : [];
|
|
499
|
+
if (created.length !== 1) throw new AdportError3("PROVIDER_ERROR", "microsoft: image upload receipt mismatch; reconcile before retrying", { resourceIds: created });
|
|
500
|
+
let readback;
|
|
501
|
+
try {
|
|
502
|
+
readback = await this.owned(op.accountId, created[0]);
|
|
503
|
+
} catch {
|
|
504
|
+
throw new AdportError3("PROVIDER_ERROR", `microsoft: image ${created[0]} upload was accepted but library readback failed; reconcile before retrying`, { resourceIds: created });
|
|
505
|
+
}
|
|
506
|
+
if (input2.alt_text !== void 0 && readback.Text !== input2.alt_text) throw new AdportError3("PROVIDER_ERROR", "microsoft: uploaded image alt text was not confirmed; reconcile before retrying", { resourceIds: created });
|
|
507
|
+
return created;
|
|
508
|
+
} };
|
|
509
|
+
}
|
|
510
|
+
const input = image.parse(op.payload), current = await this.owned(op.accountId, input.image_id);
|
|
511
|
+
const uses = await this.extensionUses({ account_id: op.accountId, image_id: input.image_id });
|
|
512
|
+
if (uses.associations.length) throw new AdportError3("INVALID_INPUT", "microsoft: image is assigned to an image extension; remove the reference before deletion");
|
|
513
|
+
return { summary: `Delete Microsoft image ${input.image_id}`, changes: [`- ${input.image_id}; type ${String(current.MediaType)}; alt text ${JSON.stringify(current.Text ?? null)}`, "Permanent deletion. Microsoft atomically rejects images assigned to any image extension or responsive ad. The preflight association API covers image extensions only."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
514
|
+
await this.request(op.accountId, "Media", { AccountId: op.accountId, MediaIds: [input.image_id] }, "DELETE");
|
|
515
|
+
if (await this.find(op.accountId, input.image_id)) throw new AdportError3("PROVIDER_ERROR", "microsoft: image deletion was not confirmed; reconcile before retrying", { resourceIds: [input.image_id] });
|
|
516
|
+
return [input.image_id];
|
|
517
|
+
} };
|
|
518
|
+
}
|
|
519
|
+
};
|
|
520
|
+
function microsoftImageTools(provider) {
|
|
521
|
+
return [
|
|
522
|
+
defineTool({ name: "microsoft_images", namespace: "microsoft", description: "View account-library image metadata, alt text and native image previews. Native page indexes start at zero; a full page may have a continuation.", input: z.object({ account_id: id, page_index: z.number().int().nonnegative().max(1e5).default(0), page_size: z.number().int().positive().max(1e3).default(20) }), output, presentation: "creatives", pagination: { cursorInput: "page_index", cursorOutput: "next_page_index" }, annotations: { readOnly: true }, handler: (input) => provider.images.list(input) }),
|
|
523
|
+
defineTool({ name: "microsoft_get_library_image", namespace: "microsoft", description: "Read one image through the selected account library finder, including native alt text and previews. Ownership lookup is bounded to 5000 images.", input: z.object({ account_id: id, image_id: id }), output, presentation: "creatives", annotations: { readOnly: true }, handler: (input) => provider.images.get(input) }),
|
|
524
|
+
defineTool({ name: "microsoft_image_extension_associations", namespace: "microsoft", description: "Read image-extension references for an account-owned image. This API does not return responsive-ad references; an empty result does not prove global non-use.", input: z.object({ account_id: id, image_id: id }), output: z.object({ image_id: id, associations: z.array(z.record(z.string(), z.unknown())), coverage: z.string(), truncated: z.boolean() }), annotations: { readOnly: true }, handler: (input) => provider.images.extensionUses(input) }),
|
|
525
|
+
guardedWriteTool({ name: "microsoft_upload_image", namespace: "microsoft", provider: "microsoft", kind: "create", description: "Upload a SHA-256-bound static image as an unattached account asset. Hosted calls require project media_id. Native cap 76800 bytes; PNG converts to JPEG. Alt text is set at creation; no serving association is created.", payload: upload }),
|
|
526
|
+
guardedWriteTool({ name: "microsoft_delete_image", namespace: "microsoft", provider: "microsoft", kind: "remove", description: "Permanently delete an account-owned image only if Microsoft verifies it is unassigned. Preflight checks image-extension uses; native deletion also rejects responsive-ad assignments.", payload: image })
|
|
527
|
+
];
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// src/extensions.ts
|
|
531
|
+
import { AdportError as AdportError5, creativesOutput as creativesOutput2, defineTool as defineTool2, guardedWriteTool as guardedWriteTool2 } from "@adport/core";
|
|
532
|
+
import { z as z3 } from "zod";
|
|
533
|
+
|
|
534
|
+
// src/native.ts
|
|
535
|
+
import { AdportError as AdportError4 } from "@adport/core";
|
|
536
|
+
import { z as z2 } from "zod";
|
|
537
|
+
var microsoftId = z2.string().regex(/^[1-9]\d*$/);
|
|
538
|
+
var microsoftRows = (value) => z2.array(z2.record(z2.string(), z2.unknown())).parse(value ?? []);
|
|
539
|
+
var microsoftRow = (value) => z2.record(z2.string(), z2.unknown()).parse(value);
|
|
540
|
+
function microsoftNativeId(value) {
|
|
541
|
+
if (typeof value === "number" && (!Number.isSafeInteger(value) || value <= 0)) throw new AdportError4("PROVIDER_ERROR", "microsoft: unsafe native resource ID");
|
|
542
|
+
const parsed = microsoftId.safeParse(typeof value === "number" ? String(value) : value);
|
|
543
|
+
if (!parsed.success) throw new AdportError4("PROVIDER_ERROR", "microsoft: invalid native resource ID");
|
|
544
|
+
return parsed.data;
|
|
545
|
+
}
|
|
546
|
+
function compactErrors(errors) {
|
|
547
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
548
|
+
for (const value of errors) {
|
|
549
|
+
const error = microsoftRow(value), { PublisherCountry, ...base } = error;
|
|
550
|
+
if (typeof PublisherCountry !== "string") {
|
|
551
|
+
grouped.set(`item:${grouped.size}`, error);
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
const key = JSON.stringify(base), previous = grouped.get(key);
|
|
555
|
+
if (previous) previous.PublisherCountries = [.../* @__PURE__ */ new Set([...previous.PublisherCountries, PublisherCountry])];
|
|
556
|
+
else grouped.set(key, { ...base, PublisherCountries: [PublisherCountry] });
|
|
557
|
+
}
|
|
558
|
+
return [...grouped.values()];
|
|
559
|
+
}
|
|
560
|
+
var MicrosoftNativeService = class {
|
|
561
|
+
constructor(client, scope, lookupCampaign) {
|
|
562
|
+
this.client = client;
|
|
563
|
+
this.scope = scope;
|
|
564
|
+
this.lookupCampaign = lookupCampaign;
|
|
565
|
+
}
|
|
566
|
+
client;
|
|
567
|
+
scope;
|
|
568
|
+
lookupCampaign;
|
|
569
|
+
async accountScope(account, refresh = false) {
|
|
570
|
+
microsoftId.parse(account);
|
|
571
|
+
const scope = await this.scope(account, refresh);
|
|
572
|
+
if (!scope.customerId || scope.customerAccountId !== account) throw new AdportError4("INVALID_INPUT", "microsoft: selected account ownership could not be verified");
|
|
573
|
+
return scope;
|
|
574
|
+
}
|
|
575
|
+
async request(account, path, body, method = "POST", service = "campaign") {
|
|
576
|
+
const scope = await this.accountScope(account);
|
|
577
|
+
const result = await this.client.request(service, method, path, body, scope);
|
|
578
|
+
const errors = ["PartialErrors", "NestedPartialErrors"].flatMap((key) => {
|
|
579
|
+
if (result[key] === void 0 || result[key] === null) return [];
|
|
580
|
+
if (!Array.isArray(result[key])) throw new AdportError4("PROVIDER_ERROR", "microsoft: malformed native error receipt");
|
|
581
|
+
return result[key].filter((value) => value !== null);
|
|
582
|
+
});
|
|
583
|
+
if (errors.length) {
|
|
584
|
+
const negativeIds = Array.isArray(result.NegativeKeywordIds) ? result.NegativeKeywordIds.flatMap((group) => group && typeof group === "object" && Array.isArray(microsoftRow(group).Ids) ? [microsoftRow(group).Ids] : []) : [];
|
|
585
|
+
const ids = [result.CampaignCriterionIds, result.AdGroupCriterionIds, result.AdExtensionIdentities, result.BudgetIds, result.ConversionGoalIds, result.UetTags, result.AudienceIds, result.ExperimentIds, ...negativeIds].flatMap((value) => Array.isArray(value) ? value.flatMap((item) => {
|
|
586
|
+
const id3 = item && typeof item === "object" ? microsoftRow(item).Id : item;
|
|
587
|
+
return id3 === null || id3 === void 0 ? [] : [microsoftNativeId(id3)];
|
|
588
|
+
}) : []);
|
|
589
|
+
const compact = compactErrors(errors), summary2 = [...new Set(compact.map((value) => `${value.Code ?? "?"} ${value.ErrorCode ?? ""}: ${value.Message ?? "nested native error"}`))].slice(0, 5).join("; ");
|
|
590
|
+
throw new AdportError4("PROVIDER_ERROR", `microsoft: ${path} returned partial errors (${summary2}); reconcile successful resource IDs before retrying`, { resourceIds: ids, errors: compact, nativeErrorCount: errors.length });
|
|
591
|
+
}
|
|
592
|
+
return result;
|
|
593
|
+
}
|
|
594
|
+
async campaign(account, campaign) {
|
|
595
|
+
microsoftId.parse(account);
|
|
596
|
+
microsoftId.parse(campaign);
|
|
597
|
+
const result = microsoftRow(await this.lookupCampaign(account, campaign));
|
|
598
|
+
if (microsoftNativeId(result.Id) !== campaign) throw new AdportError4("INVALID_INPUT", "microsoft: campaign ownership mismatch");
|
|
599
|
+
return result;
|
|
600
|
+
}
|
|
601
|
+
};
|
|
602
|
+
|
|
603
|
+
// src/extensions.ts
|
|
604
|
+
var extensionType = z3.enum(["CalloutAdExtension", "SitelinkAdExtension", "StructuredSnippetAdExtension", "ImageAdExtension"]);
|
|
605
|
+
var url = z3.string().url().max(2048).refine((value) => {
|
|
606
|
+
const u = new URL(value);
|
|
607
|
+
return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password;
|
|
608
|
+
});
|
|
609
|
+
var urls = z3.array(url).min(1).max(10);
|
|
610
|
+
var sitelink = { display_text: z3.string().min(1).max(35), final_urls: urls, description1: z3.string().max(35).optional(), description2: z3.string().max(35).optional() };
|
|
611
|
+
var image2 = { alternative_text: z3.string().min(1).max(35), image_ids: z3.array(microsoftId).min(1).max(4), description: z3.string().max(100).optional(), final_urls: urls.optional() };
|
|
612
|
+
var content = z3.discriminatedUnion("extension_type", [
|
|
613
|
+
z3.object({ extension_type: z3.literal("CalloutAdExtension"), text: z3.string().min(1).max(25) }),
|
|
614
|
+
z3.object({ extension_type: z3.literal("SitelinkAdExtension"), ...sitelink }),
|
|
615
|
+
z3.object({ extension_type: z3.literal("StructuredSnippetAdExtension"), header: z3.string().min(1).max(100), values: z3.array(z3.string().min(1).max(25)).min(3).max(10) }),
|
|
616
|
+
z3.object({ extension_type: z3.literal("ImageAdExtension"), ...image2 })
|
|
617
|
+
]);
|
|
618
|
+
var fields = { text: "Text", display_text: "DisplayText", final_urls: "FinalUrls", description1: "Description1", description2: "Description2", header: "Header", values: "Values", alternative_text: "AlternativeText", image_ids: "ImageMediaIds", description: "Description" };
|
|
619
|
+
var labels = { Text: "Callout text", DisplayText: "Link text", FinalUrls: "Landing pages", Description1: "Description 1", Description2: "Description 2", Header: "Localized header", Values: "Snippet values", AlternativeText: "Alternative text", ImageMediaIds: "Source images", Description: "Internal description" };
|
|
620
|
+
var reviewValue = (value) => value === null || value === void 0 ? "\u2014" : typeof value === "string" ? value : JSON.stringify(value);
|
|
621
|
+
var reference = z3.object({ extension_id: microsoftId, extension_type: extensionType });
|
|
622
|
+
var versioned = reference.extend({ expected_version: z3.number().int().positive() });
|
|
623
|
+
var update = versioned.extend({
|
|
624
|
+
text: z3.string().min(1).max(25).optional(),
|
|
625
|
+
...z3.object(sitelink).partial().shape,
|
|
626
|
+
header: z3.string().min(1).max(100).optional(),
|
|
627
|
+
values: z3.array(z3.string().min(1).max(25)).min(3).max(10).optional(),
|
|
628
|
+
...z3.object(image2).partial().shape
|
|
629
|
+
}).superRefine((value, ctx) => {
|
|
630
|
+
const allowed = { CalloutAdExtension: ["text"], SitelinkAdExtension: Object.keys(sitelink), StructuredSnippetAdExtension: ["header", "values"], ImageAdExtension: Object.keys(image2) };
|
|
631
|
+
const supplied = Object.keys(fields).filter((key) => value[key] !== void 0);
|
|
632
|
+
if (!supplied.length || supplied.some((key) => !allowed[value.extension_type].includes(key))) ctx.addIssue({ code: "custom", message: "Supply content changes supported by this extension type" });
|
|
633
|
+
});
|
|
634
|
+
var target = z3.discriminatedUnion("type", [z3.object({ type: z3.literal("Account") }), z3.object({ type: z3.literal("Campaign"), campaign_id: microsoftId }), z3.object({ type: z3.literal("AdGroup"), campaign_id: microsoftId, ad_group_id: microsoftId })]);
|
|
635
|
+
var mutable = {
|
|
636
|
+
CalloutAdExtension: ["Text", "Scheduling"],
|
|
637
|
+
SitelinkAdExtension: ["DisplayText", "Description1", "Description2", "DestinationUrl", "DevicePreference", "Scheduling", "FinalUrls", "FinalMobileUrls", "FinalUrlSuffix", "TrackingUrlTemplate", "UrlCustomParameters"],
|
|
638
|
+
StructuredSnippetAdExtension: ["Header", "Values", "Scheduling"],
|
|
639
|
+
ImageAdExtension: ["AlternativeText", "Description", "DestinationUrl", "DisplayText", "FinalUrls", "FinalMobileUrls", "FinalUrlSuffix", "TrackingUrlTemplate", "UrlCustomParameters", "ImageMediaIds", "Images", "Layouts", "Scheduling"]
|
|
640
|
+
};
|
|
641
|
+
var allowedReadOnly = ["Id", "Version", "Type", "Status", "ForwardCompatibilityMap", "FinalAppUrls", "SourceType", "DevicePreference"];
|
|
642
|
+
var extensionOutput = creativesOutput2.extend({ extensions: z3.array(z3.record(z3.string(), z3.unknown())) });
|
|
643
|
+
var MICROSOFT_EXTENSION_WRITES = /* @__PURE__ */ new Set(["microsoft_create_ad_extension", "microsoft_update_ad_extension", "microsoft_delete_ad_extension", "microsoft_link_ad_extension", "microsoft_unlink_ad_extension"]);
|
|
644
|
+
var MicrosoftExtensionService = class extends MicrosoftNativeService {
|
|
645
|
+
constructor(client, scope, campaign, imageLookup) {
|
|
646
|
+
super(client, scope, campaign);
|
|
647
|
+
this.imageLookup = imageLookup;
|
|
648
|
+
}
|
|
649
|
+
imageLookup;
|
|
650
|
+
async getRaw(account, extensionId, type) {
|
|
651
|
+
const result = await this.request(account, "AdExtensions/QueryByIds", { AccountId: account, AdExtensionIds: [extensionId], AdExtensionType: type });
|
|
652
|
+
const values = microsoftRows(result.AdExtensions);
|
|
653
|
+
if (values.length !== 1 || microsoftNativeId(values[0].Id) !== extensionId || values[0].Type !== type) throw new AdportError5("INVALID_INPUT", "microsoft: extension was not found with this type in the selected account");
|
|
654
|
+
if (!Number.isSafeInteger(values[0].Version) || Number(values[0].Version) < 1) throw new AdportError5("PROVIDER_ERROR", "microsoft: extension version was not returned");
|
|
655
|
+
return values[0];
|
|
656
|
+
}
|
|
657
|
+
card(account, value) {
|
|
658
|
+
if (!Number.isSafeInteger(value.Version) || Number(value.Version) < 1) throw new AdportError5("PROVIDER_ERROR", "microsoft: extension version was not returned");
|
|
659
|
+
const type = extensionType.parse(value.Type), extensionId = microsoftNativeId(value.Id), args = { account_id: account, extension_id: extensionId, extension_type: type, expected_version: value.Version };
|
|
660
|
+
const text2 = (key) => typeof value[key] === "string" ? String(value[key]) : "";
|
|
661
|
+
const edit = { label: "Edit shared extension", tool: "microsoft_update_ad_extension", arguments: args, fields: [] };
|
|
662
|
+
if (type === "CalloutAdExtension") edit.fields = [{ key: "text", label: "Callout text", type: "text", value: text2("Text"), max_length: 25 }];
|
|
663
|
+
if (type === "SitelinkAdExtension") edit.fields = [{ key: "display_text", label: "Link text", type: "text", value: text2("DisplayText"), max_length: 35 }, { key: "description1", label: "Description 1", type: "text", value: text2("Description1"), max_length: 35 }, { key: "description2", label: "Description 2", type: "text", value: text2("Description2"), max_length: 35 }, { key: "final_urls", label: "Landing pages (one per line)", type: "url_list", value: Array.isArray(value.FinalUrls) ? value.FinalUrls.map(String) : [] }];
|
|
664
|
+
if (type === "StructuredSnippetAdExtension") edit.fields = [{ key: "header", label: "Localized header", type: "text", value: text2("Header") }, { key: "values", label: "Values (one per line)", type: "text_list", value: Array.isArray(value.Values) ? value.Values.map(String) : [] }];
|
|
665
|
+
if (type === "ImageAdExtension") edit.fields = [{ key: "alternative_text", label: "Extension alternative text", type: "text", value: text2("AlternativeText"), max_length: 35 }, { key: "description", label: "Internal description", type: "text", value: text2("Description"), max_length: 100 }, { key: "image_ids", label: "Account image IDs (one per line)", type: "text_list", value: this.imageIds(value) }];
|
|
666
|
+
return { id: extensionId, provider: "microsoft", account_id: account, type, name: text2("Text") || text2("DisplayText") || text2("Header") || text2("Description") || `Extension ${extensionId}`, status: typeof value.Status === "string" ? value.Status : void 0, headlines: [text2("Text") || text2("DisplayText") || text2("Header")].filter(Boolean), descriptions: [text2("Description1"), text2("Description2"), text2("AlternativeText"), ...Array.isArray(value.Values) ? value.Values.map(String) : []].filter(Boolean), landing_urls: Array.isArray(value.FinalUrls) ? value.FinalUrls.filter((item) => url.safeParse(item).success) : [], media: [], actions: [edit] };
|
|
667
|
+
}
|
|
668
|
+
imageIds(value) {
|
|
669
|
+
const ids = Array.isArray(value.ImageMediaIds) && value.ImageMediaIds.length ? value.ImageMediaIds.map(microsoftNativeId) : microsoftRows(value.Images).map((link) => microsoftNativeId(microsoftRow(link.Asset).Id));
|
|
670
|
+
return [...new Set(ids)];
|
|
671
|
+
}
|
|
672
|
+
async gallery(account, values, truncated, next) {
|
|
673
|
+
const creatives = values.map((value) => this.card(account, value));
|
|
674
|
+
const imageIds = [...new Set(values.filter((value) => value.Type === "ImageAdExtension").flatMap((value) => this.imageIds(value)))];
|
|
675
|
+
if (imageIds.length) {
|
|
676
|
+
const previews = await this.imageLookup(account, imageIds), media = new Map(previews.creatives.map((value) => [value.id, value.media]));
|
|
677
|
+
for (const [index, value] of values.entries()) if (value.Type === "ImageAdExtension") creatives[index].media = this.imageIds(value).flatMap((image3) => media.get(image3) ?? []).map((preview) => ({ ...preview, ...typeof value.AlternativeText === "string" ? { alt: value.AlternativeText } : {} }));
|
|
678
|
+
}
|
|
679
|
+
return extensionOutput.parse({ extensions: values, creatives, truncated, ...next ? { next_cursor: next } : {} });
|
|
680
|
+
}
|
|
681
|
+
async get(input) {
|
|
682
|
+
const value = await this.getRaw(input.account_id, input.extension_id, input.extension_type);
|
|
683
|
+
return this.gallery(input.account_id, [value], false);
|
|
684
|
+
}
|
|
685
|
+
async list(input) {
|
|
686
|
+
const result = await this.request(input.account_id, "AdExtensionIds/QueryByAccountId", { AccountId: input.account_id, AdExtensionType: input.extension_types.join(", "), AssociationType: null });
|
|
687
|
+
if (!Array.isArray(result.AdExtensionIds)) throw new AdportError5("PROVIDER_ERROR", "microsoft: account extension IDs were not returned");
|
|
688
|
+
const ids = result.AdExtensionIds.map(microsoftNativeId).sort((a, b) => BigInt(a) < BigInt(b) ? -1 : BigInt(a) > BigInt(b) ? 1 : 0);
|
|
689
|
+
if (new Set(ids).size !== ids.length) throw new AdportError5("PROVIDER_ERROR", "microsoft: duplicate native extension IDs");
|
|
690
|
+
const remaining = ids.filter((value) => !input.after_extension_id || BigInt(value) > BigInt(input.after_extension_id)), selected2 = remaining.slice(0, input.limit);
|
|
691
|
+
let values = [];
|
|
692
|
+
if (selected2.length) {
|
|
693
|
+
const detail = await this.request(input.account_id, "AdExtensions/QueryByIds", { AccountId: input.account_id, AdExtensionIds: selected2, AdExtensionType: input.extension_types.join(", ") });
|
|
694
|
+
values = microsoftRows(detail.AdExtensions);
|
|
695
|
+
if (values.length !== selected2.length || values.some((value, index) => microsoftNativeId(value.Id) !== selected2[index] || !input.extension_types.includes(extensionType.parse(value.Type)))) throw new AdportError5("PROVIDER_ERROR", "microsoft: extension page identity mismatch");
|
|
696
|
+
}
|
|
697
|
+
const truncated = remaining.length > selected2.length;
|
|
698
|
+
return this.gallery(input.account_id, values, truncated, truncated ? selected2.at(-1) : void 0);
|
|
699
|
+
}
|
|
700
|
+
async entity(account, value) {
|
|
701
|
+
if (value.type === "Account") return { entityId: account, paused: false };
|
|
702
|
+
const campaign = await this.campaign(account, value.campaign_id);
|
|
703
|
+
if (value.type === "Campaign") return { entityId: value.campaign_id, paused: campaign.Status === "Paused" };
|
|
704
|
+
const result = await this.request(account, "AdGroups/QueryByIds", { CampaignId: value.campaign_id, AdGroupIds: [value.ad_group_id] });
|
|
705
|
+
const groups2 = microsoftRows(result.AdGroups);
|
|
706
|
+
if (groups2.length !== 1 || microsoftNativeId(groups2[0].Id) !== value.ad_group_id) throw new AdportError5("INVALID_INPUT", "microsoft: ad group was not found in the selected campaign/account");
|
|
707
|
+
return { entityId: value.ad_group_id, paused: campaign.Status === "Paused" || groups2[0].Status === "Paused" };
|
|
708
|
+
}
|
|
709
|
+
async associations(input) {
|
|
710
|
+
const entity = await this.entity(input.account_id, input.target);
|
|
711
|
+
const result = await this.request(input.account_id, "AdExtensionsAssociations/Query", { AccountId: input.account_id, AdExtensionType: input.extension_type, AssociationType: input.target.type, EntityIds: [entity.entityId] });
|
|
712
|
+
const collections = microsoftRows(result.AdExtensionAssociationCollection);
|
|
713
|
+
if (collections.length !== 1) throw new AdportError5("PROVIDER_ERROR", "microsoft: extension associations were not returned");
|
|
714
|
+
const associations = microsoftRows(collections[0].AdExtensionAssociations);
|
|
715
|
+
for (const value of associations) if (microsoftNativeId(value.EntityId) !== entity.entityId || value.AssociationType !== input.target.type || microsoftRow(value.AdExtension).Type !== input.extension_type) throw new AdportError5("PROVIDER_ERROR", "microsoft: extension association identity mismatch");
|
|
716
|
+
return { associations, truncated: false };
|
|
717
|
+
}
|
|
718
|
+
nativeContent(value) {
|
|
719
|
+
const result = { Type: value.extension_type };
|
|
720
|
+
for (const [key, native] of Object.entries(fields)) if (value[key] !== void 0) result[native] = value[key];
|
|
721
|
+
if (result.Type === "SitelinkAdExtension") {
|
|
722
|
+
const first = String(result.Description1 ?? ""), second = String(result.Description2 ?? "");
|
|
723
|
+
if (Boolean(first) !== Boolean(second) || (first || second) && String(result.DisplayText).length > 25) throw new AdportError5("INVALID_INPUT", "microsoft: sitelink descriptions must be supplied together; links with descriptions have a 25-character text limit");
|
|
724
|
+
}
|
|
725
|
+
return result;
|
|
726
|
+
}
|
|
727
|
+
async plan(op, guard) {
|
|
728
|
+
const expectedKind = op.tool === "microsoft_create_ad_extension" || op.tool === "microsoft_link_ad_extension" ? "create" : op.tool === "microsoft_delete_ad_extension" || op.tool === "microsoft_unlink_ad_extension" ? "remove" : "update";
|
|
729
|
+
if (op.provider !== "microsoft" || !MICROSOFT_EXTENSION_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError5("INVALID_INPUT", "microsoft: extension operation kind mismatch");
|
|
730
|
+
if (op.tool === "microsoft_create_ad_extension") {
|
|
731
|
+
const input2 = content.parse(op.payload.content), value2 = this.nativeContent(input2);
|
|
732
|
+
await this.verifyImages(op.accountId, value2);
|
|
733
|
+
return { summary: `Create unattached Microsoft ${input2.extension_type}`, changes: [`+ ${JSON.stringify(value2)}`, "Extension status is natively Active; it cannot serve until associated. No association is created.", ...input2.extension_type === "ImageAdExtension" ? ["Microsoft validates placement crop dimensions: an accepted library image can still be too small for an extension. This preview is not server-validated."] : []], coercions: [], budgetDeltas: [], execute: async () => {
|
|
734
|
+
const result = await this.request(op.accountId, "AdExtensions", { AccountId: op.accountId, AdExtensions: [value2] });
|
|
735
|
+
const identities = microsoftRows(result.AdExtensionIdentities), created = identities.map((value3) => microsoftNativeId(value3.Id));
|
|
736
|
+
if (created.length !== 1) throw new AdportError5("PROVIDER_ERROR", "microsoft: extension creation receipt mismatch; reconcile before retrying", { resourceIds: created });
|
|
737
|
+
await this.confirm(op.accountId, created[0], input2.extension_type, value2);
|
|
738
|
+
return created;
|
|
739
|
+
} };
|
|
740
|
+
}
|
|
741
|
+
const input = versioned.parse(op.payload), current = await this.getRaw(op.accountId, input.extension_id, input.extension_type);
|
|
742
|
+
if (current.Version !== input.expected_version) throw new AdportError5("PENDING_MISMATCH", "microsoft: extension version changed; read it and request a fresh preview");
|
|
743
|
+
if (op.tool === "microsoft_update_ad_extension") {
|
|
744
|
+
const change2 = update.parse(op.payload), supplied = this.nativeContent(change2);
|
|
745
|
+
if (Object.keys(supplied).length === 1) throw new AdportError5("INVALID_INPUT", "microsoft: supply at least one extension content change");
|
|
746
|
+
const supported = mutable[input.extension_type];
|
|
747
|
+
if (Object.keys(current).some((key) => current[key] !== null && !supported.includes(key) && !allowedReadOnly.includes(key))) throw new AdportError5("INVALID_INPUT", "microsoft: extension contains unsupported fields; a safe full replacement cannot be built");
|
|
748
|
+
const value2 = { Type: input.extension_type, Id: input.extension_id, ...Object.fromEntries(supported.filter((key) => current[key] !== void 0).map((key) => [key, current[key]])), ...supplied };
|
|
749
|
+
if (supplied.ImageMediaIds && JSON.stringify(supplied.ImageMediaIds.slice().sort()) !== JSON.stringify(this.imageIds(current).sort())) delete value2.Images;
|
|
750
|
+
if (Array.isArray(value2.Images)) value2.Images = value2.Images.map((link) => {
|
|
751
|
+
const current2 = microsoftRow(link), asset = microsoftRow(current2.Asset);
|
|
752
|
+
const allowed = ["Id", "Type", "Name", "CropHeight", "CropWidth", "CropX", "CropY", "CroppingType", "SubType", "TargetHeight", "TargetWidth"];
|
|
753
|
+
if (Object.keys(asset).some((key) => asset[key] != null && !allowed.includes(key) && key !== "Excluded")) throw new AdportError5("INVALID_INPUT", "microsoft: unsupported image crop fields prevent a safe extension update");
|
|
754
|
+
return { Asset: Object.fromEntries(allowed.filter((key) => asset[key] !== void 0).map((key) => [key, asset[key]])), ...current2.PinnedField != null ? { PinnedField: current2.PinnedField } : {} };
|
|
755
|
+
});
|
|
756
|
+
await this.verifyImages(op.accountId, value2);
|
|
757
|
+
if (input.extension_type === "SitelinkAdExtension") this.nativeContent({ extension_type: input.extension_type, display_text: value2.DisplayText, description1: value2.Description1, description2: value2.Description2 });
|
|
758
|
+
const impact = "Every entity using this extension can change, including active ads. Existing scheduling, device preference and tracking fields are preserved. Native extension Version is read-only.";
|
|
759
|
+
const fieldChanges = Object.keys(supplied).filter((key) => key !== "Type").flatMap((key) => {
|
|
760
|
+
const before = key === "ImageMediaIds" ? this.imageIds(current) : current[key], after = supplied[key];
|
|
761
|
+
return JSON.stringify(before ?? null) === JSON.stringify(after ?? null) ? [] : [{ field: labels[key] ?? key, before: reviewValue(before), after: reviewValue(after) }];
|
|
762
|
+
});
|
|
763
|
+
return { summary: `Update shared Microsoft extension ${input.extension_id}`, changes: [`~ ${JSON.stringify(current)} \u2192 ${JSON.stringify(value2)}`, impact], fieldChanges, notes: [impact], coercions: [], budgetDeltas: [], execute: async () => {
|
|
764
|
+
await this.request(op.accountId, "AdExtensions", { AccountId: op.accountId, AdExtensions: [value2] }, "PUT");
|
|
765
|
+
await this.confirm(op.accountId, input.extension_id, input.extension_type, value2, input.expected_version);
|
|
766
|
+
return [input.extension_id];
|
|
767
|
+
} };
|
|
768
|
+
}
|
|
769
|
+
if (op.tool === "microsoft_delete_ad_extension") return { summary: `Delete shared Microsoft extension ${input.extension_id}`, changes: [`- ${JSON.stringify(current)}`, "Permanent deletion removes this shared extension and affects every associated entity. Uploaded source images remain in the media library."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
770
|
+
await this.request(op.accountId, "AdExtensions", { AccountId: op.accountId, AdExtensionIds: [input.extension_id] }, "DELETE");
|
|
771
|
+
const result = await this.request(op.accountId, "AdExtensionIds/QueryByAccountId", { AccountId: op.accountId, AdExtensionType: input.extension_type, AssociationType: null });
|
|
772
|
+
if (!Array.isArray(result.AdExtensionIds) || result.AdExtensionIds.map(microsoftNativeId).includes(input.extension_id)) throw new AdportError5("PROVIDER_ERROR", "microsoft: extension deletion was not confirmed; reconcile before retrying", { resourceIds: [input.extension_id] });
|
|
773
|
+
return [input.extension_id];
|
|
774
|
+
} };
|
|
775
|
+
const value = target.parse(op.payload.target), entity = await this.entity(op.accountId, value), linking = op.tool === "microsoft_link_ad_extension";
|
|
776
|
+
if (linking && guard.forcePausedCreation && !entity.paused) throw new AdportError5("POLICY_VIOLATION", "microsoft: extension associations cannot be paused; paused_creation requires a paused campaign or ad group target");
|
|
777
|
+
return { summary: `${linking ? "Associate" : "Remove"} Microsoft extension ${input.extension_id} ${linking ? "with" : "from"} ${value.type} ${entity.entityId}`, changes: [`${linking ? "+" : "-"} explicit association; extension ${input.extension_id}; ${value.type} ${entity.entityId}`, "Associations have no pause state. No campaign/ad group status is changed; other associations are preserved."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
778
|
+
await this.request(op.accountId, linking ? "AdExtensionsAssociations/Set" : "AdExtensionsAssociations", { AccountId: op.accountId, AdExtensionIdToEntityIdAssociations: [{ AdExtensionId: input.extension_id, EntityId: entity.entityId }], AssociationType: value.type }, linking ? "POST" : "DELETE");
|
|
779
|
+
const readback = await this.associations({ account_id: op.accountId, target: value, extension_type: input.extension_type });
|
|
780
|
+
const exists = readback.associations.some((value2) => microsoftNativeId(microsoftRow(value2.AdExtension).Id) === input.extension_id);
|
|
781
|
+
if (exists !== linking) throw new AdportError5("PROVIDER_ERROR", "microsoft: extension association change was not confirmed; reconcile before retrying", { resourceIds: [input.extension_id] });
|
|
782
|
+
return [input.extension_id];
|
|
783
|
+
} };
|
|
784
|
+
}
|
|
785
|
+
async confirm(account, extension, type, expected, previousVersion) {
|
|
786
|
+
try {
|
|
787
|
+
const actual = await this.getRaw(account, extension, type);
|
|
788
|
+
if (previousVersion !== void 0 && Number(actual.Version) <= previousVersion) throw new Error("Version did not advance");
|
|
789
|
+
for (const key of Object.keys(expected).filter((key2) => !["Id", "Type", "ImageMediaIds", "Images"].includes(key2))) {
|
|
790
|
+
if (JSON.stringify(actual[key] ?? null) !== JSON.stringify(expected[key] ?? null)) throw new Error(`Readback mismatch: ${key}`);
|
|
791
|
+
}
|
|
792
|
+
if (type === "ImageAdExtension" && JSON.stringify(this.imageIds(actual).sort()) !== JSON.stringify(this.imageIds(expected).sort())) throw new Error("Image references were not confirmed");
|
|
793
|
+
} catch {
|
|
794
|
+
throw new AdportError5("PROVIDER_ERROR", `microsoft: extension ${extension} mutation was accepted but content readback was not confirmed; reconcile before retrying`, { resourceIds: [extension] });
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
async verifyImages(account, value) {
|
|
798
|
+
if (value.Type !== "ImageAdExtension") return;
|
|
799
|
+
const ids = this.imageIds(value);
|
|
800
|
+
if (!ids.length || (await this.imageLookup(account, ids)).missing_image_ids.length) throw new AdportError5("INVALID_INPUT", "microsoft: image references could not be verified in the selected account library");
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
function microsoftExtensionTools(provider) {
|
|
804
|
+
return [
|
|
805
|
+
defineTool2({ name: "microsoft_ad_extensions", namespace: "microsoft", description: "View account-owned callout, sitelink, structured-snippet and image extensions, including native versions and shared-content edit actions. Continue with next_cursor as after_extension_id.", input: z3.object({ account_id: microsoftId, extension_types: z3.array(extensionType).min(1).max(4).default([...extensionType.options]), after_extension_id: microsoftId.optional(), limit: z3.number().int().positive().max(100).default(20) }), output: extensionOutput, presentation: "creatives", pagination: { cursorInput: "after_extension_id" }, annotations: { readOnly: true }, handler: (input) => provider.extensions.list(input) }),
|
|
806
|
+
defineTool2({ name: "microsoft_get_ad_extension", namespace: "microsoft", description: "Read one extension by exact ID and type in the selected account, including the native version required for edits.", input: reference.extend({ account_id: microsoftId }), output: extensionOutput, presentation: "creatives", annotations: { readOnly: true }, handler: (input) => provider.extensions.get(input) }),
|
|
807
|
+
defineTool2({ name: "microsoft_ad_extension_associations", namespace: "microsoft", description: "Read direct extension associations for an account, campaign or verified ad group. Native editorial status is preserved; inherited associations are not combined.", input: z3.object({ account_id: microsoftId, target, extension_type: extensionType }), output: z3.object({ associations: z3.array(z3.record(z3.string(), z3.unknown())), truncated: z3.boolean() }), annotations: { readOnly: true }, handler: (input) => provider.extensions.associations(input) }),
|
|
808
|
+
guardedWriteTool2({ name: "microsoft_create_ad_extension", namespace: "microsoft", provider: "microsoft", kind: "create", description: "Create an unattached callout, sitelink, structured-snippet or image extension. Native status is Active but no serving association is created. Uses full native content readback.", payload: z3.object({ content }) }),
|
|
809
|
+
guardedWriteTool2({ name: "microsoft_update_ad_extension", namespace: "microsoft", provider: "microsoft", kind: "update", description: "Edit supplied shared extension content with expected_version. Preserves omitted mutable fields and scheduling; all associated entities can change. Image alt text here belongs to the extension, not the source media.", payload: update }),
|
|
810
|
+
guardedWriteTool2({ name: "microsoft_delete_ad_extension", namespace: "microsoft", provider: "microsoft", kind: "remove", description: "Permanently delete an account-owned shared extension and its associations. Requires its latest native version. Source images remain in the account library.", payload: versioned }),
|
|
811
|
+
guardedWriteTool2({ name: "microsoft_link_ad_extension", namespace: "microsoft", provider: "microsoft", kind: "create", description: "Associate a version-verified extension with one owned entity. Associations cannot be paused; default paused_creation requires a paused parent campaign or ad group. Account-wide associations are blocked under that policy.", payload: versioned.extend({ target }) }),
|
|
812
|
+
guardedWriteTool2({ name: "microsoft_unlink_ad_extension", namespace: "microsoft", provider: "microsoft", kind: "remove", description: "Remove one explicit extension association, preserving its source extension and other associations. Does not alter inherited associations or serving statuses.", payload: versioned.extend({ target }) })
|
|
813
|
+
];
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// src/targeting.ts
|
|
817
|
+
import { AdportError as AdportError6, defineTool as defineTool3, guardedWriteTool as guardedWriteTool3 } from "@adport/core";
|
|
818
|
+
import { z as z5 } from "zod";
|
|
819
|
+
|
|
820
|
+
// src/targeting-schemas.ts
|
|
821
|
+
import { z as z4 } from "zod";
|
|
822
|
+
var criterionType = z4.enum(["Age", "Gender", "Device", "DayTime", "Location", "LocationIntent", "Radius"]);
|
|
823
|
+
var bidType = criterionType.exclude(["LocationIntent"]);
|
|
824
|
+
var adjustment = z4.number().int().min(-90).max(900);
|
|
825
|
+
var deviceAdjustment = z4.number().int().min(-100).max(900);
|
|
826
|
+
var minute = z4.enum(["Zero", "Fifteen", "Thirty", "FortyFive"]);
|
|
827
|
+
var intent = z4.enum(["PeopleIn", "PeopleInOrSearchingForOrViewingPages"]);
|
|
828
|
+
var target2 = z4.discriminatedUnion("type", [
|
|
829
|
+
z4.object({ type: z4.literal("Age"), age_range: z4.enum(["EighteenToTwentyFour", "TwentyFiveToThirtyFour", "ThirtyFiveToFourtyNine", "FiftyToSixtyFour", "SixtyFiveAndAbove", "ThirtyFiveToFiftyFour", "FiftyFiveAndAbove", "Unknown"]), bid_adjustment_percent: adjustment.default(0) }).strict(),
|
|
830
|
+
z4.object({ type: z4.literal("Gender"), gender: z4.enum(["Male", "Female"]), bid_adjustment_percent: adjustment.default(0) }).strict(),
|
|
831
|
+
z4.object({ type: z4.literal("Device"), device_name: z4.enum(["Computers", "Smartphones", "Tablets"]), bid_adjustment_percent: deviceAdjustment.default(0) }).strict(),
|
|
832
|
+
z4.object({ type: z4.literal("DayTime"), day: z4.enum(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]), from_hour: z4.number().int().min(0).max(23), from_minute: minute, to_hour: z4.number().int().min(0).max(24), to_minute: minute, bid_adjustment_percent: adjustment.default(0) }).strict(),
|
|
833
|
+
z4.object({ type: z4.literal("Location"), location_id: microsoftId, exclude: z4.boolean().default(false), bid_adjustment_percent: adjustment.optional() }).strict(),
|
|
834
|
+
z4.object({ type: z4.literal("LocationIntent"), intent_option: intent }).strict(),
|
|
835
|
+
z4.object({ type: z4.literal("Radius"), latitude: z4.number().min(-85).max(85), longitude: z4.number().min(-180).max(180), radius: z4.number().int().positive().max(800), radius_unit: z4.enum(["Miles", "Kilometers"]), name: z4.string().max(50).optional(), bid_adjustment_percent: adjustment.default(0) }).strict()
|
|
836
|
+
]);
|
|
837
|
+
var minutes = { Zero: 0, Fifteen: 15, Thirty: 30, FortyFive: 45 };
|
|
838
|
+
function validateTargetBatch(value, ctx) {
|
|
839
|
+
const devices = value.targets.filter((value2) => value2.type === "Device");
|
|
840
|
+
if (devices.length && (devices.length !== 3 || new Set(devices.map((value2) => value2.device_name)).size !== 3 || devices.every((value2) => value2.bid_adjustment_percent === -100))) ctx.addIssue({ code: "custom", message: "Add all three distinct device types together, leaving at least one device included" });
|
|
841
|
+
for (const item of value.targets) {
|
|
842
|
+
if (item.type === "Location" && item.exclude && item.bid_adjustment_percent !== void 0) ctx.addIssue({ code: "custom", message: "Excluded locations cannot have a bid adjustment" });
|
|
843
|
+
if (item.type === "Radius" && item.radius_unit === "Miles" && item.radius > 500) ctx.addIssue({ code: "custom", message: "Radius in miles cannot exceed 500" });
|
|
844
|
+
if (item.type === "DayTime" && (item.to_hour === 24 && item.to_minute !== "Zero" || item.from_hour * 60 + minutes[item.from_minute] >= item.to_hour * 60 + minutes[item.to_minute])) ctx.addIssue({ code: "custom", message: "DayTime must end after its start within one day; hour 24 requires minute Zero" });
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
var add = z4.object({ campaign_id: microsoftId, targets: z4.array(target2).min(1).max(100) }).superRefine(validateTargetBatch);
|
|
848
|
+
var reference2 = z4.object({ campaign_id: microsoftId, criterion_id: microsoftId, criterion_type: criterionType });
|
|
849
|
+
var remove = z4.object({ campaign_id: microsoftId, criterion_type: criterionType.exclude(["LocationIntent"]), criterion_ids: z4.array(microsoftId).min(1).max(100).refine((value) => new Set(value).size === value.length, "Criterion IDs must be unique") });
|
|
850
|
+
var bid = reference2.extend({ criterion_type: bidType, bid_adjustment_percent: deviceAdjustment, expected_current_percent: z4.number() }).superRefine((value, ctx) => {
|
|
851
|
+
if (value.criterion_type !== "Device" && value.bid_adjustment_percent < -90) ctx.addIssue({ code: "custom", message: "Only devices support a bid adjustment below -90 percent" });
|
|
852
|
+
});
|
|
853
|
+
var intentUpdate = z4.object({ campaign_id: microsoftId, criterion_id: microsoftId, intent_option: intent, expected_current_intent: intent });
|
|
854
|
+
function nativeTarget(parent2, input) {
|
|
855
|
+
const criterion = { Type: `${input.type}Criterion` };
|
|
856
|
+
if (input.type === "Age") criterion.AgeRange = input.age_range;
|
|
857
|
+
if (input.type === "Gender") criterion.GenderType = input.gender;
|
|
858
|
+
if (input.type === "Device") criterion.DeviceName = input.device_name;
|
|
859
|
+
if (input.type === "DayTime") Object.assign(criterion, { Day: input.day, FromHour: input.from_hour, FromMinute: input.from_minute, ToHour: input.to_hour, ToMinute: input.to_minute });
|
|
860
|
+
if (input.type === "Location") criterion.LocationId = input.location_id;
|
|
861
|
+
if (input.type === "LocationIntent") criterion.IntentOption = input.intent_option;
|
|
862
|
+
if (input.type === "Radius") Object.assign(criterion, { LatitudeDegrees: input.latitude, LongitudeDegrees: input.longitude, Radius: String(input.radius), RadiusUnit: input.radius_unit, ...input.name !== void 0 ? { Name: input.name } : {} });
|
|
863
|
+
const excluded = input.type === "Location" && input.exclude;
|
|
864
|
+
return { ...parent2, Type: excluded ? `Negative${"AdGroupId" in parent2 ? "AdGroup" : "Campaign"}Criterion` : `Biddable${"AdGroupId" in parent2 ? "AdGroup" : "Campaign"}Criterion`, Criterion: criterion, ...!excluded && input.type !== "LocationIntent" ? { CriterionBid: { Type: "BidMultiplier", Multiplier: input.bid_adjustment_percent ?? 0 } } : {} };
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// src/targeting.ts
|
|
868
|
+
var MICROSOFT_TARGETING_WRITES = /* @__PURE__ */ new Set(["microsoft_add_campaign_targets", "microsoft_set_campaign_target_bid", "microsoft_set_campaign_location_intent", "microsoft_remove_campaign_targets"]);
|
|
869
|
+
var MicrosoftTargetingService = class extends MicrosoftNativeService {
|
|
870
|
+
subtype(value) {
|
|
871
|
+
return criterionType.parse(String(microsoftRow(value.Criterion).Type).replace(/Criterion$/, ""));
|
|
872
|
+
}
|
|
873
|
+
key(type, criterion) {
|
|
874
|
+
const keys = { Age: ["AgeRange"], Gender: ["GenderType"], Device: ["DeviceName"], DayTime: ["Day", "FromHour", "FromMinute", "ToHour", "ToMinute"], Location: ["LocationId"], LocationIntent: [], Radius: ["LatitudeDegrees", "LongitudeDegrees", "Radius", "RadiusUnit"] };
|
|
875
|
+
return JSON.stringify(keys[type].map((key) => String(criterion[key] ?? "")));
|
|
876
|
+
}
|
|
877
|
+
async confirm(criterion, change2, check) {
|
|
878
|
+
try {
|
|
879
|
+
if (await check()) return;
|
|
880
|
+
} catch {
|
|
881
|
+
}
|
|
882
|
+
throw new AdportError6("PROVIDER_ERROR", `microsoft: ${change2} was not confirmed; reconcile before retrying`, { resourceIds: Array.isArray(criterion) ? criterion : [criterion] });
|
|
883
|
+
}
|
|
884
|
+
async query(account, campaign, type) {
|
|
885
|
+
const result = await this.request(account, "CampaignCriterions/QueryByIds", { CampaignId: campaign, CampaignCriterionIds: null, CriterionType: type });
|
|
886
|
+
if (!Object.hasOwn(result, "CampaignCriterions")) throw new AdportError6("PROVIDER_ERROR", "microsoft: campaign targeting was not returned");
|
|
887
|
+
const values = microsoftRows(result.CampaignCriterions);
|
|
888
|
+
if (values.some((value) => microsoftNativeId(value.CampaignId) !== campaign || this.subtype(value) !== type || !["BiddableCampaignCriterion", "NegativeCampaignCriterion"].includes(String(value.Type)))) throw new AdportError6("PROVIDER_ERROR", "microsoft: campaign target identity mismatch");
|
|
889
|
+
if (new Set(values.map((value) => microsoftNativeId(value.Id))).size !== values.length) throw new AdportError6("PROVIDER_ERROR", "microsoft: duplicate campaign criterion IDs");
|
|
890
|
+
return values;
|
|
891
|
+
}
|
|
892
|
+
async list(input) {
|
|
893
|
+
await this.campaign(input.account_id, input.campaign_id);
|
|
894
|
+
return { rows: await this.query(input.account_id, input.campaign_id, input.criterion_type), truncated: false };
|
|
895
|
+
}
|
|
896
|
+
async owned(account, input) {
|
|
897
|
+
await this.campaign(account, input.campaign_id);
|
|
898
|
+
const result = (await this.query(account, input.campaign_id, input.criterion_type)).find((value) => microsoftNativeId(value.Id) === input.criterion_id);
|
|
899
|
+
if (!result) throw new AdportError6("INVALID_INPUT", "microsoft: target was not found with this type in the selected campaign/account");
|
|
900
|
+
return result;
|
|
901
|
+
}
|
|
902
|
+
async geoFile(input) {
|
|
903
|
+
const result = await this.request(input.account_id, "GeoLocationsFileUrl/Query", { Version: "2.0", LanguageLocale: input.language_locale });
|
|
904
|
+
return z5.object({ FileUrl: z5.string().url(), FileUrlExpiryTimeUtc: z5.string(), LastModifiedTimeUtc: z5.string() }).parse(result);
|
|
905
|
+
}
|
|
906
|
+
async plan(op, guard) {
|
|
907
|
+
const expectedKind = op.tool === "microsoft_add_campaign_targets" ? "create" : op.tool === "microsoft_remove_campaign_targets" ? "remove" : "update";
|
|
908
|
+
if (op.provider !== "microsoft" || !MICROSOFT_TARGETING_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError6("INVALID_INPUT", "microsoft: targeting operation kind mismatch");
|
|
909
|
+
if (op.tool === "microsoft_add_campaign_targets") {
|
|
910
|
+
const input2 = add.parse(op.payload), campaign = await this.campaign(op.accountId, input2.campaign_id), values = input2.targets.map((value) => nativeTarget({ CampaignId: input2.campaign_id }, value));
|
|
911
|
+
if (guard.forcePausedCreation && campaign.Status !== "Paused") throw new AdportError6("POLICY_VIOLATION", "microsoft: campaign targets are natively Active and cannot be paused; paused_creation requires a paused campaign");
|
|
912
|
+
const seen = /* @__PURE__ */ new Map();
|
|
913
|
+
for (const [index, value] of values.entries()) {
|
|
914
|
+
const type = input2.targets[index].type;
|
|
915
|
+
if (!seen.has(type)) seen.set(type, new Set((await this.query(op.accountId, input2.campaign_id, type)).map((value2) => this.key(type, microsoftRow(value2.Criterion)))));
|
|
916
|
+
const key = this.key(type, microsoftRow(value.Criterion));
|
|
917
|
+
if (seen.get(type).has(key)) throw new AdportError6("INVALID_INPUT", "microsoft: this campaign target already exists; use its explicit bid/intent edit or remove it first");
|
|
918
|
+
seen.get(type).add(key);
|
|
919
|
+
}
|
|
920
|
+
return { summary: `Add ${values.length} Microsoft campaign target(s)`, changes: [`+ ${JSON.stringify(values)}`, `Campaign ${input2.campaign_id} remains ${campaign.Status}. Targets have native Active status; no parent status changes. Bid adjustments are whole percentages, not multipliers.`, "Location IDs must be current in the geographical file; Microsoft rejects deprecated targets. Schedule timezone follows the native AdScheduleUseSearcherTimeZone flag: searcher or account time. The deprecated campaign TimeZone is not authoritative."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
921
|
+
const result = await this.request(op.accountId, "CampaignCriterions", { CampaignCriterions: values, CriterionType: "Targets" });
|
|
922
|
+
const created = Array.isArray(result.CampaignCriterionIds) ? result.CampaignCriterionIds.filter((value) => value !== null).map(microsoftNativeId) : [];
|
|
923
|
+
if (created.length !== values.length || new Set(created).size !== created.length) throw new AdportError6("PROVIDER_ERROR", "microsoft: target creation receipt mismatch; reconcile before retrying", { resourceIds: created });
|
|
924
|
+
try {
|
|
925
|
+
const byType = /* @__PURE__ */ new Map();
|
|
926
|
+
for (const [index, expected] of values.entries()) {
|
|
927
|
+
const type = input2.targets[index].type;
|
|
928
|
+
if (!byType.has(type)) byType.set(type, await this.query(op.accountId, input2.campaign_id, type));
|
|
929
|
+
const actual = byType.get(type).find((value) => microsoftNativeId(value.Id) === created[index]);
|
|
930
|
+
if (!actual || actual.Type !== expected.Type) throw new Error("Created target missing");
|
|
931
|
+
const actualCriterion = microsoftRow(actual.Criterion);
|
|
932
|
+
for (const [key, value] of Object.entries(microsoftRow(expected.Criterion))) if (key !== "Type" && (key === "LocationId" ? microsoftNativeId(actualCriterion[key]) !== value : actualCriterion[key] !== value)) throw new Error("Created target content mismatch");
|
|
933
|
+
if (expected.CriterionBid && microsoftRow(actual.CriterionBid).Multiplier !== microsoftRow(expected.CriterionBid).Multiplier) throw new Error("Created target bid mismatch");
|
|
934
|
+
}
|
|
935
|
+
} catch {
|
|
936
|
+
throw new AdportError6("PROVIDER_ERROR", "microsoft: targets were accepted but native readback was not confirmed; reconcile before retrying", { resourceIds: created });
|
|
937
|
+
}
|
|
938
|
+
return created;
|
|
939
|
+
} };
|
|
940
|
+
}
|
|
941
|
+
if (op.tool === "microsoft_set_campaign_target_bid") {
|
|
942
|
+
const input2 = bid.parse(op.payload), current2 = await this.owned(op.accountId, input2);
|
|
943
|
+
if (current2.Type !== "BiddableCampaignCriterion" || microsoftRow(current2.CriterionBid).Type !== "BidMultiplier") throw new AdportError6("INVALID_INPUT", "microsoft: only biddable campaign targets with BidMultiplier support this edit");
|
|
944
|
+
if (microsoftRow(current2.CriterionBid).Multiplier !== input2.expected_current_percent) throw new AdportError6("PENDING_MISMATCH", "microsoft: target bid changed; request a fresh preview");
|
|
945
|
+
const value = { CampaignId: input2.campaign_id, Id: input2.criterion_id, Type: "BiddableCampaignCriterion", CriterionBid: { Type: "BidMultiplier", Multiplier: input2.bid_adjustment_percent } };
|
|
946
|
+
return { summary: `Set Microsoft ${input2.criterion_type} target bid adjustment`, changes: [`~ ${input2.criterion_id}: ${input2.expected_current_percent}% \u2192 ${input2.bid_adjustment_percent}%`, "Changes the percentage adjustment, preserving the criterion and campaign serving status. Automated bidding may use this as a signal rather than a direct override."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
947
|
+
await this.request(op.accountId, "CampaignCriterions", { CampaignCriterions: [value], CriterionType: "Targets" }, "PUT");
|
|
948
|
+
await this.confirm(input2.criterion_id, "target bid update", async () => microsoftRow((await this.owned(op.accountId, input2)).CriterionBid).Multiplier === input2.bid_adjustment_percent);
|
|
949
|
+
return [input2.criterion_id];
|
|
950
|
+
} };
|
|
951
|
+
}
|
|
952
|
+
if (op.tool === "microsoft_set_campaign_location_intent") {
|
|
953
|
+
const input2 = intentUpdate.parse(op.payload), reference7 = { ...input2, criterion_type: "LocationIntent" }, current2 = await this.owned(op.accountId, reference7);
|
|
954
|
+
if (current2.Type !== "BiddableCampaignCriterion" || microsoftRow(current2.Criterion).IntentOption !== input2.expected_current_intent) throw new AdportError6("PENDING_MISMATCH", "microsoft: location intent changed; request a fresh preview");
|
|
955
|
+
const value = { CampaignId: input2.campaign_id, Id: input2.criterion_id, Type: "BiddableCampaignCriterion", Criterion: { Type: "LocationIntentCriterion", IntentOption: input2.intent_option } };
|
|
956
|
+
return { summary: "Update Microsoft campaign location intent", changes: [`~ ${input2.criterion_id}: ${input2.expected_current_intent} \u2192 ${input2.intent_option}`, "No bid is sent: Microsoft ignores bid multipliers for location intent. Campaign status is preserved."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
957
|
+
await this.request(op.accountId, "CampaignCriterions", { CampaignCriterions: [value], CriterionType: "Targets" }, "PUT");
|
|
958
|
+
await this.confirm(input2.criterion_id, "location intent update", async () => microsoftRow((await this.owned(op.accountId, reference7)).Criterion).IntentOption === input2.intent_option);
|
|
959
|
+
return [input2.criterion_id];
|
|
960
|
+
} };
|
|
961
|
+
}
|
|
962
|
+
const input = remove.parse(op.payload);
|
|
963
|
+
await this.campaign(op.accountId, input.campaign_id);
|
|
964
|
+
const current = await this.query(op.accountId, input.campaign_id, input.criterion_type), selected2 = input.criterion_ids.map((id3) => current.find((value) => microsoftNativeId(value.Id) === id3));
|
|
965
|
+
if (selected2.some((value) => !value)) throw new AdportError6("INVALID_INPUT", "microsoft: a target was not found with this type in the selected campaign/account");
|
|
966
|
+
if (input.criterion_type === "Device" && (input.criterion_ids.length !== 3 || current.length !== 3 || !["Computers", "Smartphones", "Tablets"].every((name5) => current.some((value) => microsoftRow(value.Criterion).DeviceName === name5)))) throw new AdportError6("INVALID_INPUT", "microsoft: remove all three device criterion IDs together (Computers, Smartphones, Tablets)");
|
|
967
|
+
return { summary: `Remove ${input.criterion_ids.length} Microsoft ${input.criterion_type} campaign target(s)`, changes: [`- ${JSON.stringify(selected2)}`, "Removing a target or exclusion can broaden or narrow delivery for this campaign. Other criterion IDs and parent serving status are preserved."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
968
|
+
await this.request(op.accountId, "CampaignCriterions", { CampaignId: input.campaign_id, CampaignCriterionIds: input.criterion_ids, CriterionType: "Targets" }, "DELETE");
|
|
969
|
+
await this.confirm(input.criterion_ids, "target removal", async () => !(await this.query(op.accountId, input.campaign_id, input.criterion_type)).some((value) => input.criterion_ids.includes(microsoftNativeId(value.Id)) && value.Status !== "Deleted"));
|
|
970
|
+
return input.criterion_ids;
|
|
971
|
+
} };
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
function microsoftTargetingTools(provider) {
|
|
975
|
+
return [
|
|
976
|
+
defineTool3({ name: "microsoft_campaign_targets", namespace: "microsoft", description: "Read one concrete campaign targeting subtype with verified campaign/account ownership. Native criterion and percent bid adjustments are preserved. Targets is a mutation selector and cannot be used for reads.", input: z5.object({ account_id: microsoftId, campaign_id: microsoftId, criterion_type: criterionType }), output: z5.object({ rows: z5.array(z5.record(z5.string(), z5.unknown())), truncated: z5.boolean() }), annotations: { readOnly: true }, handler: (input) => provider.targeting.list(input) }),
|
|
977
|
+
defineTool3({ name: "microsoft_geo_locations_file", namespace: "microsoft", description: "Get the native geographical-location file URL, server expiration and modification time. Use current non-deprecated location IDs for targeting; returns metadata without downloading or caching the file.", input: z5.object({ account_id: microsoftId, language_locale: z5.enum(["zh-Hant", "en", "fr", "de", "it", "ja-JP", "pt-BR", "es"]).default("en") }), annotations: { readOnly: true }, handler: (input) => provider.targeting.geoFile(input) }),
|
|
978
|
+
guardedWriteTool3({ name: "microsoft_add_campaign_targets", namespace: "microsoft", provider: "microsoft", kind: "create", description: "Add age, gender, device, day/time, location, location-intent or radius targets; locations can be excluded. Native targets are Active; default paused_creation requires a paused campaign. Device creation requires all three device types together. Bids are integer percent adjustments.", payload: add }),
|
|
979
|
+
guardedWriteTool3({ name: "microsoft_set_campaign_target_bid", namespace: "microsoft", provider: "microsoft", kind: "update", description: "Change a biddable target percentage adjustment with an expected current value. Device range -100..900; other supported targets -90..900. Excluded locations and location-intent criteria do not accept bids.", payload: bid }),
|
|
980
|
+
guardedWriteTool3({ name: "microsoft_set_campaign_location_intent", namespace: "microsoft", provider: "microsoft", kind: "update", description: "Change campaign location intent with an expected current value. PeopleInOrSearchingForOrViewingPages restores the API default; this criterion cannot be deleted. Preserves status and omits the inapplicable bid multiplier.", payload: intentUpdate }),
|
|
981
|
+
guardedWriteTool3({ name: "microsoft_remove_campaign_targets", namespace: "microsoft", provider: "microsoft", kind: "remove", description: "Remove exact owned criterion IDs of one subtype. Devices require all three IDs together. Location intent cannot be deleted; use its edit tool instead. Other targets remain; removing restrictions can broaden delivery. Confirms native disappearance.", payload: remove })
|
|
982
|
+
];
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
// src/negative-keywords.ts
|
|
986
|
+
import { AdportError as AdportError7, defineTool as defineTool4, guardedWriteTool as guardedWriteTool4 } from "@adport/core";
|
|
987
|
+
import { z as z6 } from "zod";
|
|
988
|
+
var target4 = z6.discriminatedUnion("type", [z6.object({ type: z6.literal("Campaign"), campaign_id: microsoftId }), z6.object({ type: z6.literal("AdGroup"), campaign_id: microsoftId, ad_group_id: microsoftId })]);
|
|
989
|
+
var keyword = z6.object({ text: z6.string().min(1).max(100).refine((value) => value.trim().length > 0, "Keyword text cannot be blank"), match_type: z6.enum(["Exact", "Phrase"]) });
|
|
990
|
+
var add2 = z6.object({ target: target4, keywords: z6.array(keyword).min(1).max(1e3) }).refine((value) => new Set(value.keywords.map((value2) => JSON.stringify([value2.text, value2.match_type]))).size === value.keywords.length, "Negative keywords must be unique");
|
|
991
|
+
var remove2 = z6.object({ target: target4, keyword_ids: z6.array(microsoftId).min(1).max(1e3).refine((value) => new Set(value).size === value.length, "Keyword IDs must be unique") });
|
|
992
|
+
var MICROSOFT_NEGATIVE_KEYWORD_WRITES = /* @__PURE__ */ new Set(["microsoft_add_negative_keywords", "microsoft_remove_negative_keywords"]);
|
|
993
|
+
var MicrosoftNegativeKeywordService = class extends MicrosoftNativeService {
|
|
994
|
+
async entity(account, value) {
|
|
995
|
+
await this.campaign(account, value.campaign_id);
|
|
996
|
+
if (value.type === "Campaign") return { EntityId: value.campaign_id, EntityType: "Campaign", ParentEntityId: null };
|
|
997
|
+
const result = await this.request(account, "AdGroups/QueryByIds", { CampaignId: value.campaign_id, AdGroupIds: [value.ad_group_id] });
|
|
998
|
+
const groups2 = microsoftRows(result.AdGroups);
|
|
999
|
+
if (groups2.length !== 1 || microsoftNativeId(groups2[0].Id) !== value.ad_group_id) throw new AdportError7("INVALID_INPUT", "microsoft: ad group was not found in the selected campaign/account");
|
|
1000
|
+
return { EntityId: value.ad_group_id, EntityType: "AdGroup", ParentEntityId: value.campaign_id };
|
|
1001
|
+
}
|
|
1002
|
+
async query(account, entity) {
|
|
1003
|
+
const result = await this.request(account, "NegativeKeywords/QueryByEntityIds", { EntityIds: [entity.EntityId], EntityType: entity.EntityType, ParentEntityId: entity.ParentEntityId });
|
|
1004
|
+
const collections = microsoftRows(result.EntityNegativeKeywords);
|
|
1005
|
+
if (collections.length !== 1 || microsoftNativeId(collections[0].EntityId) !== entity.EntityId || collections[0].EntityType !== entity.EntityType || !Object.hasOwn(collections[0], "NegativeKeywords")) throw new AdportError7("PROVIDER_ERROR", "microsoft: negative-keyword entity identity mismatch");
|
|
1006
|
+
const values = microsoftRows(collections[0].NegativeKeywords);
|
|
1007
|
+
if (values.length > 2e4 || new Set(values.map((value) => microsoftNativeId(value.Id))).size !== values.length || values.some((value) => !keyword.safeParse({ text: value.Text, match_type: value.MatchType }).success)) throw new AdportError7("PROVIDER_ERROR", "microsoft: invalid native negative-keyword list");
|
|
1008
|
+
return values;
|
|
1009
|
+
}
|
|
1010
|
+
async list(input) {
|
|
1011
|
+
const entity = await this.entity(input.account_id, input.target), values = await this.query(input.account_id, entity);
|
|
1012
|
+
const remaining = values.filter((value) => !input.after_keyword_id || BigInt(microsoftNativeId(value.Id)) > BigInt(input.after_keyword_id)).sort((a, b) => BigInt(microsoftNativeId(a.Id)) < BigInt(microsoftNativeId(b.Id)) ? -1 : BigInt(microsoftNativeId(a.Id)) > BigInt(microsoftNativeId(b.Id)) ? 1 : 0);
|
|
1013
|
+
const page = remaining.slice(0, input.limit), truncated = remaining.length > page.length;
|
|
1014
|
+
return { rows: page, truncated, ...truncated ? { next_cursor: microsoftNativeId(page.at(-1).Id) } : {} };
|
|
1015
|
+
}
|
|
1016
|
+
async plan(op) {
|
|
1017
|
+
if (op.provider !== "microsoft" || !MICROSOFT_NEGATIVE_KEYWORD_WRITES.has(op.tool) || op.kind !== (op.tool === "microsoft_add_negative_keywords" ? "create" : "remove")) throw new AdportError7("INVALID_INPUT", "microsoft: negative-keyword operation kind mismatch");
|
|
1018
|
+
const input = op.tool === "microsoft_add_negative_keywords" ? add2.parse(op.payload) : remove2.parse(op.payload), entity = await this.entity(op.accountId, input.target), current = await this.query(op.accountId, entity);
|
|
1019
|
+
if ("keywords" in input) {
|
|
1020
|
+
const existing = new Set(current.map((value) => JSON.stringify([value.Text, value.MatchType])));
|
|
1021
|
+
if (input.keywords.some((value) => existing.has(JSON.stringify([value.text, value.match_type])))) throw new AdportError7("INVALID_INPUT", "microsoft: an exact negative-keyword entry already exists; do not replay the create operation");
|
|
1022
|
+
if (current.length + input.keywords.length > 2e4) throw new AdportError7("INVALID_INPUT", "microsoft: this request exceeds the native 20000 direct-negative-keyword limit");
|
|
1023
|
+
const values = input.keywords.map((value) => ({ Text: value.text, MatchType: value.match_type }));
|
|
1024
|
+
return { summary: `Add ${values.length} Microsoft ${entity.EntityType} negative keyword(s)`, changes: [`+ exclusions ${JSON.stringify(values)} in ${entity.EntityType} ${entity.EntityId}`, "Appends direct exclusions. Native negative keywords have no individual serving status; parent status is preserved. Shared and inherited exclusions are separate."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
1025
|
+
const result = await this.request(op.accountId, "EntityNegativeKeywords", { EntityNegativeKeywords: [{ EntityId: entity.EntityId, EntityType: entity.EntityType, NegativeKeywords: values }] });
|
|
1026
|
+
const groups2 = microsoftRows(result.NegativeKeywordIds), ids = groups2.length === 1 && Array.isArray(groups2[0].Ids) ? groups2[0].Ids.filter((value) => value !== null).map(microsoftNativeId) : [];
|
|
1027
|
+
if (ids.length !== values.length || new Set(ids).size !== ids.length || ids.some((id3) => current.some((value) => microsoftNativeId(value.Id) === id3))) throw new AdportError7("PROVIDER_ERROR", "microsoft: negative-keyword creation receipt mismatch; reconcile before retrying", { resourceIds: ids });
|
|
1028
|
+
try {
|
|
1029
|
+
const actual = await this.query(op.accountId, entity);
|
|
1030
|
+
if (ids.some((id3, index) => !actual.some((value) => microsoftNativeId(value.Id) === id3 && value.Text === values[index].Text && value.MatchType === values[index].MatchType))) throw new Error("Created exclusion was not confirmed");
|
|
1031
|
+
} catch {
|
|
1032
|
+
throw new AdportError7("PROVIDER_ERROR", "microsoft: negative keywords were accepted but content readback was not confirmed; reconcile before retrying", { resourceIds: ids });
|
|
1033
|
+
}
|
|
1034
|
+
return ids;
|
|
1035
|
+
} };
|
|
1036
|
+
}
|
|
1037
|
+
const selected2 = input.keyword_ids.map((id3) => current.find((value) => microsoftNativeId(value.Id) === id3));
|
|
1038
|
+
if (selected2.some((value) => !value)) throw new AdportError7("INVALID_INPUT", "microsoft: a negative keyword was not found in the selected entity/account");
|
|
1039
|
+
return { summary: `Remove ${selected2.length} Microsoft ${entity.EntityType} negative keyword(s)`, changes: [`- direct exclusions ${JSON.stringify(selected2)}`, "Removing exclusions can broaden delivery. Other direct, inherited and shared-list exclusions and parent serving statuses are preserved."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
1040
|
+
await this.request(op.accountId, "EntityNegativeKeywords", { EntityNegativeKeywords: [{ EntityId: entity.EntityId, EntityType: entity.EntityType, NegativeKeywords: input.keyword_ids.map((Id) => ({ Id })) }] }, "DELETE");
|
|
1041
|
+
try {
|
|
1042
|
+
if ((await this.query(op.accountId, entity)).some((value) => input.keyword_ids.includes(microsoftNativeId(value.Id)))) throw new Error("Deleted exclusion remains");
|
|
1043
|
+
} catch {
|
|
1044
|
+
throw new AdportError7("PROVIDER_ERROR", "microsoft: negative-keyword removal was not confirmed; reconcile before retrying", { resourceIds: input.keyword_ids });
|
|
1045
|
+
}
|
|
1046
|
+
return input.keyword_ids;
|
|
1047
|
+
} };
|
|
1048
|
+
}
|
|
1049
|
+
};
|
|
1050
|
+
function microsoftNegativeKeywordTools(provider) {
|
|
1051
|
+
return [
|
|
1052
|
+
defineTool4({ name: "microsoft_negative_keywords", namespace: "microsoft", description: "Read direct campaign or ad-group negative keywords after verifying the full account/parent hierarchy. Shared-list and inherited exclusions are separate. Continue with next_cursor as after_keyword_id.", input: z6.object({ account_id: microsoftId, target: target4, after_keyword_id: microsoftId.optional(), limit: z6.number().int().positive().max(1e3).default(100) }), output: z6.object({ rows: z6.array(z6.record(z6.string(), z6.unknown())), truncated: z6.boolean(), next_cursor: microsoftId.optional() }), pagination: { cursorInput: "after_keyword_id" }, annotations: { readOnly: true }, handler: (input) => provider.negativeKeywords.list(input) }),
|
|
1053
|
+
guardedWriteTool4({ name: "microsoft_add_negative_keywords", namespace: "microsoft", provider: "microsoft", kind: "create", description: "Append up to 1000 direct Exact/Phrase exclusions to an owned campaign or ad group. Native negative keywords have no pause state and only restrict delivery; parent status is preserved. Verifies every created ID and its text/match type.", payload: add2 }),
|
|
1054
|
+
guardedWriteTool4({ name: "microsoft_remove_negative_keywords", namespace: "microsoft", provider: "microsoft", kind: "remove", description: "Remove exact owned direct exclusion IDs. This can broaden delivery. Text and match type are immutable: add and confirm a replacement before removing its predecessor. Shared and inherited exclusions are separate.", payload: remove2 })
|
|
1055
|
+
];
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
// src/budgets.ts
|
|
1059
|
+
import { createHash } from "crypto";
|
|
1060
|
+
import { AdportError as AdportError8, defineTool as defineTool5, guardedWriteTool as guardedWriteTool5 } from "@adport/core";
|
|
1061
|
+
import { z as z7 } from "zod";
|
|
1062
|
+
var hash = z7.string().regex(/^[a-f0-9]{64}$/);
|
|
1063
|
+
var name = z7.string().min(1).max(255).refine((value) => value.trim().length > 0, "Name cannot be blank");
|
|
1064
|
+
var amount = z7.number().positive().refine((value) => Number.isSafeInteger(Math.round(value * 1e6)) && Math.abs(value * 1e6 - Math.round(value * 1e6)) < 1e-6, "Amount must fit safe integer micros with at most six decimal places");
|
|
1065
|
+
var create = z7.object({ name, amount });
|
|
1066
|
+
var selected = z7.object({ budget_id: microsoftId, expected_snapshot_hash: hash });
|
|
1067
|
+
var update2 = selected.extend({ name: name.optional(), amount: amount.optional() }).refine((value) => value.name !== void 0 || value.amount !== void 0, "Supply a name or amount");
|
|
1068
|
+
var assign = z7.object({ campaign_id: microsoftId, budget_id: microsoftId, expected_campaign_hash: hash, expected_budget_hash: hash });
|
|
1069
|
+
var unassign = z7.object({ campaign_id: microsoftId, daily_budget: amount, expected_campaign_hash: hash });
|
|
1070
|
+
var budgetSchema = z7.object({ Id: microsoftId, Name: z7.string(), Amount: z7.number().positive(), BudgetType: z7.string(), AssociationCount: z7.number().int().nonnegative() });
|
|
1071
|
+
var memberSchema = z7.object({ Id: microsoftId, Name: z7.string(), Status: z7.string(), CampaignType: z7.string(), SubType: z7.string().nullable(), ExperimentId: microsoftId.nullable() });
|
|
1072
|
+
var viewSchema = z7.object({ budget: budgetSchema, currency: z7.string().optional(), members: z7.array(memberSchema), membership_complete: z7.boolean(), snapshot_hash: hash });
|
|
1073
|
+
var contextSchema = z7.object({ campaign: memberSchema, budget_id: microsoftId.nullable(), effective_daily_amount: z7.number().positive(), budget_type: z7.string(), currency: z7.string().optional(), shared_budget: viewSchema.optional(), snapshot_hash: hash });
|
|
1074
|
+
var digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
1075
|
+
var micros = (value) => {
|
|
1076
|
+
const result = Math.round(value * 1e6);
|
|
1077
|
+
if (!Number.isSafeInteger(result) || result <= 0) throw new AdportError8("PROVIDER_ERROR", "microsoft: native budget amount cannot be represented safely in micros");
|
|
1078
|
+
return result;
|
|
1079
|
+
};
|
|
1080
|
+
var sharedId = (value) => value === null || value === void 0 || value === "0" || value === 0 ? null : microsoftNativeId(value);
|
|
1081
|
+
var member = (value) => memberSchema.parse({ Id: microsoftNativeId(value.Id), Name: value.Name, Status: value.Status, CampaignType: value.CampaignType, SubType: value.SubType ?? null, ExperimentId: sharedId(value.ExperimentId) });
|
|
1082
|
+
var order = (a, b) => BigInt(a.Id) < BigInt(b.Id) ? -1 : BigInt(a.Id) > BigInt(b.Id) ? 1 : 0;
|
|
1083
|
+
var notes = ["Snapshot checks detect changed amounts and campaign membership before sending the write. Microsoft has no atomic compare-and-set for these operations; concurrent changes can still occur.", "Campaign status is preserved. Shared budgets are account-scoped; the amount is one daily pool, not an amount multiplied by its campaign count."];
|
|
1084
|
+
var MICROSOFT_BUDGET_WRITES = /* @__PURE__ */ new Set(["microsoft_create_shared_budget", "microsoft_update_shared_budget", "microsoft_delete_shared_budget", "microsoft_assign_shared_budget", "microsoft_unassign_shared_budget"]);
|
|
1085
|
+
var MicrosoftBudgetService = class extends MicrosoftNativeService {
|
|
1086
|
+
constructor(client, scope, lookupCampaign, campaigns, currency2) {
|
|
1087
|
+
super(client, scope, lookupCampaign);
|
|
1088
|
+
this.campaigns = campaigns;
|
|
1089
|
+
this.currency = currency2;
|
|
1090
|
+
}
|
|
1091
|
+
campaigns;
|
|
1092
|
+
currency;
|
|
1093
|
+
async inventory(account) {
|
|
1094
|
+
const result = await this.request(account, "Budgets/QueryByIds", { BudgetIds: null });
|
|
1095
|
+
const budgets = microsoftRows(result.Budgets).map((value) => budgetSchema.parse({ ...value, Id: microsoftNativeId(value.Id) }));
|
|
1096
|
+
if (new Set(budgets.map((value) => value.Id)).size !== budgets.length) throw new AdportError8("PROVIDER_ERROR", "microsoft: duplicate budget IDs in native inventory");
|
|
1097
|
+
budgets.forEach((value) => micros(value.Amount));
|
|
1098
|
+
const campaigns = microsoftRows(await this.campaigns(account));
|
|
1099
|
+
if (new Set(campaigns.map((value) => microsoftNativeId(value.Id))).size !== campaigns.length) throw new AdportError8("PROVIDER_ERROR", "microsoft: duplicate campaign IDs in native inventory");
|
|
1100
|
+
const currency2 = await this.currency(account);
|
|
1101
|
+
return { budgets, campaigns, ...currency2 ? { currency: currency2 } : {} };
|
|
1102
|
+
}
|
|
1103
|
+
view(account, budgetId, inventory) {
|
|
1104
|
+
const budget = inventory.budgets.find((value2) => value2.Id === budgetId);
|
|
1105
|
+
if (!budget) throw new AdportError8("INVALID_INPUT", "microsoft: shared budget was not found in the selected account");
|
|
1106
|
+
const members = inventory.campaigns.filter((value2) => sharedId(value2.BudgetId) === budgetId).map(member).sort(order);
|
|
1107
|
+
const value = { budget, ...inventory.currency ? { currency: inventory.currency } : {}, members, membership_complete: members.length === budget.AssociationCount };
|
|
1108
|
+
return { ...value, snapshot_hash: digest({ account, ...value }) };
|
|
1109
|
+
}
|
|
1110
|
+
context(account, campaignId, inventory) {
|
|
1111
|
+
const current = inventory.campaigns.find((value2) => microsoftNativeId(value2.Id) === campaignId);
|
|
1112
|
+
if (!current) throw new AdportError8("INVALID_INPUT", "microsoft: campaign was not found in the selected account");
|
|
1113
|
+
const campaign = member(current), budget_id = sharedId(current.BudgetId), shared_budget = budget_id ? this.view(account, budget_id, inventory) : void 0;
|
|
1114
|
+
const effective_daily_amount = shared_budget?.budget.Amount ?? amount.parse(current.DailyBudget);
|
|
1115
|
+
micros(effective_daily_amount);
|
|
1116
|
+
const value = { campaign, budget_id, effective_daily_amount, budget_type: z7.string().parse(shared_budget?.budget.BudgetType ?? current.BudgetType), ...inventory.currency ? { currency: inventory.currency } : {}, ...shared_budget ? { shared_budget } : {} };
|
|
1117
|
+
return { ...value, snapshot_hash: digest({ account, ...value }) };
|
|
1118
|
+
}
|
|
1119
|
+
async list(input) {
|
|
1120
|
+
const inventory = await this.inventory(input.account_id), remaining = inventory.budgets.filter((value) => !input.after_budget_id || BigInt(value.Id) > BigInt(input.after_budget_id)).sort(order), page = remaining.slice(0, input.limit), truncated = remaining.length > page.length;
|
|
1121
|
+
return { rows: page.map((value) => this.view(input.account_id, value.Id, inventory)), truncated, ...truncated ? { next_cursor: page.at(-1).Id } : {} };
|
|
1122
|
+
}
|
|
1123
|
+
async get(account, budgetId) {
|
|
1124
|
+
microsoftId.parse(budgetId);
|
|
1125
|
+
return this.view(account, budgetId, await this.inventory(account));
|
|
1126
|
+
}
|
|
1127
|
+
async campaignBudget(account, campaignId) {
|
|
1128
|
+
microsoftId.parse(campaignId);
|
|
1129
|
+
return this.context(account, campaignId, await this.inventory(account));
|
|
1130
|
+
}
|
|
1131
|
+
complete(value) {
|
|
1132
|
+
if (!value.membership_complete) throw new AdportError8("INVALID_INPUT", "microsoft: campaign membership does not match native AssociationCount; refresh and reconcile all campaign types before writing");
|
|
1133
|
+
if (value.budget.BudgetType !== "DailyBudgetStandard") throw new AdportError8("INVALID_INPUT", "microsoft: only native DailyBudgetStandard shared budgets can be changed");
|
|
1134
|
+
}
|
|
1135
|
+
expected(actual, expected) {
|
|
1136
|
+
if (actual !== expected) throw new AdportError8("INVALID_INPUT", "microsoft: budget or campaign snapshot changed; read fresh context and request a new preview");
|
|
1137
|
+
}
|
|
1138
|
+
eligible(value) {
|
|
1139
|
+
if (value.CampaignType === "PerformanceMax" || value.SubType === "ShoppingSmartAds" || value.ExperimentId) throw new AdportError8("INVALID_INPUT", "microsoft: Performance Max, Smart Shopping and experiment campaigns cannot be assigned or directly detached with shared-budget tools");
|
|
1140
|
+
if (!["Active", "Paused", "BudgetPaused"].includes(value.Status)) throw new AdportError8("INVALID_INPUT", "microsoft: campaign serving status is not recognized for a budget change");
|
|
1141
|
+
}
|
|
1142
|
+
async verify(account, ids, test) {
|
|
1143
|
+
try {
|
|
1144
|
+
if (!test(await this.inventory(account))) throw new Error("Native readback mismatch");
|
|
1145
|
+
} catch {
|
|
1146
|
+
throw new AdportError8("PROVIDER_ERROR", "microsoft: budget write was accepted but readback was not confirmed; reconcile these resource IDs before retrying", { resourceIds: ids });
|
|
1147
|
+
}
|
|
1148
|
+
return ids;
|
|
1149
|
+
}
|
|
1150
|
+
async plan(op) {
|
|
1151
|
+
const kinds = { microsoft_create_shared_budget: "create", microsoft_update_shared_budget: "update", microsoft_delete_shared_budget: "remove", microsoft_assign_shared_budget: "update", microsoft_unassign_shared_budget: "update" };
|
|
1152
|
+
if (op.provider !== "microsoft" || !MICROSOFT_BUDGET_WRITES.has(op.tool) || op.kind !== kinds[op.tool]) throw new AdportError8("INVALID_INPUT", "microsoft: shared-budget operation kind mismatch");
|
|
1153
|
+
const input = op.tool === "microsoft_create_shared_budget" ? create.parse(op.payload) : op.tool === "microsoft_update_shared_budget" ? update2.parse(op.payload) : op.tool === "microsoft_delete_shared_budget" ? selected.parse(op.payload) : op.tool === "microsoft_assign_shared_budget" ? assign.parse(op.payload) : unassign.parse(op.payload);
|
|
1154
|
+
const account = op.accountId, inventory = await this.inventory(account);
|
|
1155
|
+
const delta = (target6, from, to) => ({ target: target6, ...inventory.currency ? { currency: inventory.currency } : {}, fromMicros: from === 0 ? 0 : micros(from), toMicros: micros(to) });
|
|
1156
|
+
const unique = (value2, except) => {
|
|
1157
|
+
if (inventory.budgets.some((budget) => budget.Id !== except && budget.Name.toLowerCase() === value2.toLowerCase())) throw new AdportError8("INVALID_INPUT", "microsoft: shared-budget name already exists in this account");
|
|
1158
|
+
};
|
|
1159
|
+
if (op.tool === "microsoft_create_shared_budget" && "name" in input && "amount" in input) {
|
|
1160
|
+
const value2 = create.parse(input);
|
|
1161
|
+
unique(value2.name);
|
|
1162
|
+
return { summary: `Create Microsoft shared daily budget "${value2.name}"`, changes: [`+ unattached shared budget ${JSON.stringify(value2)}`, "No campaigns are assigned by this operation."], fieldChanges: [{ field: "Name", before: "(new)", after: value2.name }], notes, coercions: [], budgetDeltas: [delta(`new shared budget "${value2.name}" daily pool`, 0, value2.amount)], execute: async () => {
|
|
1163
|
+
const result = await this.request(account, "Budgets", { Budgets: [{ Name: value2.name, Amount: value2.amount, BudgetType: "DailyBudgetStandard" }] });
|
|
1164
|
+
const ids = Array.isArray(result.BudgetIds) ? result.BudgetIds.filter((value3) => value3 !== null).map(microsoftNativeId) : [];
|
|
1165
|
+
if (ids.length !== 1 || inventory.budgets.some((value3) => value3.Id === ids[0])) throw new AdportError8("PROVIDER_ERROR", "microsoft: budget creation receipt mismatch; reconcile before retrying", { resourceIds: ids });
|
|
1166
|
+
return this.verify(account, ids, (actual) => {
|
|
1167
|
+
const view3 = this.view(account, ids[0], actual);
|
|
1168
|
+
return view3.budget.Name === value2.name && view3.budget.Amount === value2.amount && view3.budget.BudgetType === "DailyBudgetStandard" && view3.membership_complete && !view3.members.length;
|
|
1169
|
+
});
|
|
1170
|
+
} };
|
|
1171
|
+
}
|
|
1172
|
+
if (op.tool === "microsoft_update_shared_budget" || op.tool === "microsoft_delete_shared_budget") {
|
|
1173
|
+
const value2 = selected.parse(input), current2 = this.view(account, value2.budget_id, inventory);
|
|
1174
|
+
this.complete(current2);
|
|
1175
|
+
this.expected(current2.snapshot_hash, value2.expected_snapshot_hash);
|
|
1176
|
+
if (op.tool === "microsoft_delete_shared_budget") {
|
|
1177
|
+
if (current2.members.length) throw new AdportError8("INVALID_INPUT", "microsoft: detach all campaigns before deleting a shared budget");
|
|
1178
|
+
return { summary: `Delete unused Microsoft shared budget "${current2.budget.Name}"`, changes: [`- shared budget ${current2.budget.Id}; native AssociationCount and discovered membership are both zero`], notes, coercions: [], budgetDeltas: [], execute: async () => {
|
|
1179
|
+
await this.request(account, "Budgets", { BudgetIds: [current2.budget.Id] }, "DELETE");
|
|
1180
|
+
return this.verify(account, [current2.budget.Id], (actual) => !actual.budgets.some((value3) => value3.Id === current2.budget.Id));
|
|
1181
|
+
} };
|
|
1182
|
+
}
|
|
1183
|
+
const edit = update2.parse(input);
|
|
1184
|
+
if (edit.name !== void 0) unique(edit.name, current2.budget.Id);
|
|
1185
|
+
const fields2 = { ...edit.name !== void 0 && edit.name !== current2.budget.Name ? { Name: edit.name } : {}, ...edit.amount !== void 0 && edit.amount !== current2.budget.Amount ? { Amount: edit.amount } : {} };
|
|
1186
|
+
if (!Object.keys(fields2).length) throw new AdportError8("INVALID_INPUT", "microsoft: shared-budget update has no changes");
|
|
1187
|
+
const fieldChanges = Object.entries(fields2).map(([field, after]) => ({ field, before: String(current2.budget[field]), after: String(after) }));
|
|
1188
|
+
return { summary: `Update Microsoft shared budget "${current2.budget.Name}" (${current2.members.length} campaign(s))`, changes: [`~ shared budget ${current2.budget.Id} ${JSON.stringify(fields2)}`, `Affected campaigns: ${JSON.stringify(current2.members)}`], fieldChanges, notes: [...notes, `Affected campaigns: ${current2.members.map((value3) => `${value3.Id} ${value3.Name} (${value3.Status})`).join("; ") || "(none)"}`], coercions: [], budgetDeltas: fields2.Amount !== void 0 ? [delta(`shared budget ${current2.budget.Id} daily pool`, current2.budget.Amount, fields2.Amount)] : [], execute: async () => {
|
|
1189
|
+
await this.request(account, "Budgets", { Budgets: [{ Id: current2.budget.Id, ...fields2 }] }, "PUT");
|
|
1190
|
+
return this.verify(account, [current2.budget.Id], (actual) => {
|
|
1191
|
+
const after = this.view(account, current2.budget.Id, actual);
|
|
1192
|
+
return after.membership_complete && JSON.stringify(after.members) === JSON.stringify(current2.members) && Object.entries(fields2).every(([key, value3]) => after.budget[key] === value3);
|
|
1193
|
+
});
|
|
1194
|
+
} };
|
|
1195
|
+
}
|
|
1196
|
+
if (op.tool === "microsoft_assign_shared_budget") {
|
|
1197
|
+
const value2 = assign.parse(input), current2 = this.context(account, value2.campaign_id, inventory), destination = this.view(account, value2.budget_id, inventory);
|
|
1198
|
+
this.eligible(current2.campaign);
|
|
1199
|
+
this.complete(destination);
|
|
1200
|
+
if (current2.shared_budget) this.complete(current2.shared_budget);
|
|
1201
|
+
this.expected(current2.snapshot_hash, value2.expected_campaign_hash);
|
|
1202
|
+
this.expected(destination.snapshot_hash, value2.expected_budget_hash);
|
|
1203
|
+
if (current2.budget_id === value2.budget_id) throw new AdportError8("INVALID_INPUT", "microsoft: campaign already uses this shared budget");
|
|
1204
|
+
return { summary: `Assign Microsoft campaign "${current2.campaign.Name}" to shared budget "${destination.budget.Name}"`, changes: [`~ campaign ${value2.campaign_id} BudgetId ${current2.budget_id ?? "(individual)"} \u2192 ${value2.budget_id}`, `Source members before assignment: ${JSON.stringify(current2.shared_budget?.members ?? [current2.campaign])}`, `Destination members before assignment: ${JSON.stringify(destination.members)}`, "Policy compares the campaign\u2019s current effective daily limit with the destination pool amount. Pool membership changes can redistribute spend among its campaigns."], fieldChanges: [{ field: "Budget", before: current2.budget_id ?? "(individual)", after: value2.budget_id }], notes: [...notes, `Source campaigns: ${(current2.shared_budget?.members ?? [current2.campaign]).map((value3) => `${value3.Id} ${value3.Name} (${value3.Status})`).join("; ")}`, `Destination campaigns: ${destination.members.map((value3) => `${value3.Id} ${value3.Name} (${value3.Status})`).join("; ") || "(none)"}`], coercions: [], budgetDeltas: [delta(`campaign ${value2.campaign_id} effective daily budget`, current2.effective_daily_amount, destination.budget.Amount)], execute: async () => {
|
|
1205
|
+
await this.request(account, "Campaigns", { AccountId: account, Campaigns: [{ Id: value2.campaign_id, BudgetId: value2.budget_id }] }, "PUT");
|
|
1206
|
+
return this.verify(account, [value2.campaign_id, value2.budget_id], (actual) => {
|
|
1207
|
+
const after = this.context(account, value2.campaign_id, actual), target6 = this.view(account, value2.budget_id, actual);
|
|
1208
|
+
return after.budget_id === value2.budget_id && after.campaign.Status === current2.campaign.Status && target6.membership_complete && target6.budget.Amount === destination.budget.Amount && JSON.stringify(target6.members) === JSON.stringify([...destination.members, current2.campaign].sort(order)) && (!current2.budget_id || this.view(account, current2.budget_id, actual).membership_complete);
|
|
1209
|
+
});
|
|
1210
|
+
} };
|
|
1211
|
+
}
|
|
1212
|
+
const value = unassign.parse(input), current = this.context(account, value.campaign_id, inventory);
|
|
1213
|
+
this.eligible(current.campaign);
|
|
1214
|
+
this.expected(current.snapshot_hash, value.expected_campaign_hash);
|
|
1215
|
+
if (!current.shared_budget) throw new AdportError8("INVALID_INPUT", "microsoft: campaign is not using a shared budget");
|
|
1216
|
+
this.complete(current.shared_budget);
|
|
1217
|
+
return { summary: `Detach Microsoft campaign "${current.campaign.Name}" to its own daily budget`, changes: [`~ campaign ${value.campaign_id} BudgetId ${current.budget_id} \u2192 0; DailyBudget \u2192 ${value.daily_budget}; BudgetType \u2192 DailyBudgetStandard`, "The remaining shared pool amount is preserved. Detaching adds an independent daily allocation alongside that pool."], fieldChanges: [{ field: "Budget", before: current.budget_id, after: "(individual DailyBudgetStandard)" }], notes, coercions: [], budgetDeltas: [delta(`campaign ${value.campaign_id} effective daily budget`, current.effective_daily_amount, value.daily_budget)], execute: async () => {
|
|
1218
|
+
await this.request(account, "Campaigns", { AccountId: account, Campaigns: [{ Id: value.campaign_id, BudgetId: "0", DailyBudget: value.daily_budget, BudgetType: "DailyBudgetStandard" }] }, "PUT");
|
|
1219
|
+
return this.verify(account, [value.campaign_id, current.budget_id], (actual) => {
|
|
1220
|
+
const after = this.context(account, value.campaign_id, actual), previous = this.view(account, current.budget_id, actual);
|
|
1221
|
+
return after.budget_id === null && after.effective_daily_amount === value.daily_budget && after.campaign.Status === current.campaign.Status && previous.membership_complete && previous.budget.Amount === current.shared_budget.budget.Amount && JSON.stringify(previous.members) === JSON.stringify(current.shared_budget.members.filter((value2) => value2.Id !== current.campaign.Id));
|
|
1222
|
+
});
|
|
1223
|
+
} };
|
|
1224
|
+
}
|
|
1225
|
+
};
|
|
1226
|
+
function microsoftBudgetTools(provider) {
|
|
1227
|
+
return [
|
|
1228
|
+
defineTool5({ name: "microsoft_shared_budgets", namespace: "microsoft", description: "List native daily pools with all-type campaign membership, completeness and snapshot hashes. Continue next_cursor as after_budget_id.", input: z7.object({ account_id: microsoftId, after_budget_id: microsoftId.optional(), limit: z7.number().int().positive().max(100).default(50) }), output: z7.object({ rows: z7.array(viewSchema), truncated: z7.boolean(), next_cursor: microsoftId.optional() }), pagination: { cursorInput: "after_budget_id" }, annotations: { readOnly: true }, handler: (input) => provider.budgets.list(input) }),
|
|
1229
|
+
defineTool5({ name: "microsoft_get_shared_budget", namespace: "microsoft", description: "Read an owned daily pool, its campaign members and snapshot_hash for update, assignment or deletion. Writes reject incomplete membership.", input: z7.object({ account_id: microsoftId, budget_id: microsoftId }), output: viewSchema, annotations: { readOnly: true }, handler: (input) => provider.budgets.get(input.account_id, input.budget_id) }),
|
|
1230
|
+
defineTool5({ name: "microsoft_campaign_budget", namespace: "microsoft", description: "Read an owned campaign\u2019s effective daily limit, individual/shared budget, members and snapshot_hash. Use this hash as expected_campaign_hash when assigning or detaching.", input: z7.object({ account_id: microsoftId, campaign_id: microsoftId }), output: contextSchema, annotations: { readOnly: true }, handler: (input) => provider.budgets.campaignBudget(input.account_id, input.campaign_id) }),
|
|
1231
|
+
guardedWriteTool5({ name: "microsoft_create_shared_budget", namespace: "microsoft", provider: "microsoft", kind: "create", description: "Create an unattached DailyBudgetStandard pool in account currency. Checks its amount in policy micros. Does not assign or activate campaigns.", payload: create }),
|
|
1232
|
+
guardedWriteTool5({ name: "microsoft_update_shared_budget", namespace: "microsoft", provider: "microsoft", kind: "update", description: "Rename or change one shared daily pool after binding its amount and all campaign members/statuses with expected_snapshot_hash. Monetary caps apply once to the pool; no atomic native compare-and-set.", payload: update2 }),
|
|
1233
|
+
guardedWriteTool5({ name: "microsoft_delete_shared_budget", namespace: "microsoft", provider: "microsoft", kind: "remove", destructive: true, description: "Permanently delete an owned unused shared budget. Requires matching snapshot and both native and discovered campaign counts zero; verifies disappearance.", payload: selected }),
|
|
1234
|
+
guardedWriteTool5({ name: "microsoft_assign_shared_budget", namespace: "microsoft", provider: "microsoft", kind: "update", description: "Assign a campaign to an owned daily pool using campaign and destination snapshot hashes. Compares current effective limit with the pool amount for policy; preserves status. Excludes Performance Max, Smart Shopping and experiments.", payload: assign }),
|
|
1235
|
+
guardedWriteTool5({ name: "microsoft_unassign_shared_budget", namespace: "microsoft", provider: "microsoft", kind: "update", description: "Detach to an explicit individual DailyBudgetStandard budget in account currency. Requires campaign snapshot, preserves status and remaining pool amount, and checks monetary policy. Excludes experiment campaigns.", payload: unassign })
|
|
1236
|
+
];
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
// src/planning.ts
|
|
1240
|
+
import { AdportError as AdportError9, defineTool as defineTool6 } from "@adport/core";
|
|
1241
|
+
import { z as z8 } from "zod";
|
|
1242
|
+
var text = z8.string().min(1).max(100).refine((value) => value.trim().length > 0, "Keyword cannot be blank");
|
|
1243
|
+
var keywords = z8.array(text).min(1).max(200);
|
|
1244
|
+
var date = z8.iso.date();
|
|
1245
|
+
var dateRange = z8.object({ start: date, end: date }).refine((value) => value.start <= value.end, "Start date must not follow end date");
|
|
1246
|
+
var targeting = z8.object({ account_id: microsoftId, language: z8.enum(["English", "French", "German"]), location_ids: z8.array(microsoftId).min(1).max(2e3).refine((value) => new Set(value).size === value.length, "Location IDs must be unique"), network: z8.enum(["OwnedAndOperatedAndSyndicatedSearch", "OwnedAndOperatedOnly"]).default("OwnedAndOperatedAndSyndicatedSearch") });
|
|
1247
|
+
var baseIdeas = targeting.extend({ date_range: dateRange.optional(), limit: z8.number().int().positive().max(3e3).default(100) });
|
|
1248
|
+
var ideas = baseIdeas.extend({ keywords: keywords.optional(), url: z8.url().refine((value) => {
|
|
1249
|
+
const url3 = new URL(value);
|
|
1250
|
+
return url3.protocol === "https:" && !url3.username && !url3.password;
|
|
1251
|
+
}, "Use an HTTPS URL without credentials").optional(), category_id: microsoftId.optional() }).refine((value) => value.keywords !== void 0 || value.url !== void 0 || value.category_id !== void 0, "Supply keyword, URL or category seeds");
|
|
1252
|
+
var historical = baseIdeas.extend({ keywords });
|
|
1253
|
+
var traffic = targeting.extend({ keywords: z8.array(z8.object({ text, match_type: z8.enum(["Phrase", "Broad"]), max_cpc: z8.number().positive().optional() })).min(1).max(1e3), max_cpc: z8.number().positive(), daily_budget: z8.number().positive().optional(), negative_keywords: z8.array(z8.object({ text, match_type: z8.enum(["Exact", "Phrase"]) })).max(1e3).optional() });
|
|
1254
|
+
var ideasOutput = z8.object({ rows: z8.array(z8.record(z8.string(), z8.unknown())), truncated: z8.boolean(), returned_count: z8.number().int().nonnegative(), native_result_count: z8.number().int().nonnegative(), currency: z8.string().optional(), date_range: dateRange.optional(), notes: z8.array(z8.string()) });
|
|
1255
|
+
var parts = (value) => {
|
|
1256
|
+
const [Year, Month, Day] = value.split("-").map(Number);
|
|
1257
|
+
return { Year, Month, Day };
|
|
1258
|
+
};
|
|
1259
|
+
function criteria(input) {
|
|
1260
|
+
return [{ Type: "LanguageCriterion", Language: input.language }, { Type: "NetworkCriterion", Network: input.network }, ...input.location_ids.map((LocationId) => ({ Type: "LocationCriterion", LocationId }))];
|
|
1261
|
+
}
|
|
1262
|
+
var MicrosoftPlanningService = class extends MicrosoftNativeService {
|
|
1263
|
+
constructor(client, scope, lookupCampaign, currency2) {
|
|
1264
|
+
super(client, scope, lookupCampaign);
|
|
1265
|
+
this.currency = currency2;
|
|
1266
|
+
}
|
|
1267
|
+
currency;
|
|
1268
|
+
async keywordIdeas(input, expand) {
|
|
1269
|
+
const value = expand ? ideas.parse(input) : historical.parse(input);
|
|
1270
|
+
const parameters = [{ Type: "LanguageSearchParameter", Languages: [{ Type: "LanguageCriterion", Language: value.language }] }, { Type: "LocationSearchParameter", Locations: value.location_ids.map((LocationId) => ({ Type: "LocationCriterion", LocationId })) }, { Type: "NetworkSearchParameter", Network: { Type: "NetworkCriterion", Network: value.network } }];
|
|
1271
|
+
if (value.keywords) parameters.push({ Type: "QuerySearchParameter", Queries: value.keywords });
|
|
1272
|
+
if ("url" in value && value.url) parameters.push({ Type: "UrlSearchParameter", Url: value.url });
|
|
1273
|
+
if ("category_id" in value && value.category_id) parameters.push({ Type: "CategorySearchParameter", CategoryId: value.category_id });
|
|
1274
|
+
if (value.date_range) parameters.push({ Type: "DateRangeSearchParameter", StartDate: parts(value.date_range.start), EndDate: parts(value.date_range.end) });
|
|
1275
|
+
const result = await this.request(value.account_id, "KeywordIdeas/Query", { ExpandIdeas: expand, IdeaAttributes: ["Keyword", "Competition", "MonthlySearchCounts", "SuggestedBid", "AdImpressionShare", "Relevance", "Source", "AdGroupId", "AdGroupName"], SearchParameters: parameters }, "POST", "adinsight");
|
|
1276
|
+
if (!Object.hasOwn(result, "KeywordIdeas")) throw new AdportError9("PROVIDER_ERROR", "microsoft: keyword-idea response did not contain the native result envelope");
|
|
1277
|
+
const values = microsoftRows(result.KeywordIdeas);
|
|
1278
|
+
const currency2 = this.currency(value.account_id);
|
|
1279
|
+
const page = values.slice(0, value.limit);
|
|
1280
|
+
return { rows: page, truncated: values.length > page.length, returned_count: page.length, native_result_count: values.length, ...currency2 ? { currency: currency2 } : {}, ...value.date_range ? { date_range: value.date_range } : {}, notes: ["returned_count is the number of rows displayed here. native_result_count is the native response size before the requested limit. Native results are currently capped at 3000 with no continuation cursor; neither count proves the full search universe.", "MonthlySearchCounts is newest-first. Without an explicit date range, its exact calendar months cannot be identified; the latest month may lag by up to 72 hours.", "Suggested bids are estimates in account currency, not observed campaign performance. Missing native metrics remain missing; native numeric zero is preserved without inferring availability.", "Negative AdGroupId values identify suggested planning groups; they are not existing campaign ad-group IDs."] };
|
|
1281
|
+
}
|
|
1282
|
+
async trafficEstimates(input) {
|
|
1283
|
+
const value = traffic.parse(input);
|
|
1284
|
+
const estimator = { AdGroupEstimators: [{ KeywordEstimators: value.keywords.map((value2) => ({ Keyword: { Text: value2.text, MatchType: value2.match_type }, ...value2.max_cpc !== void 0 ? { MaxCpc: value2.max_cpc } : {} })), MaxCpc: value.max_cpc }], Criteria: criteria(value), ...value.daily_budget !== void 0 ? { DailyBudget: value.daily_budget } : {}, ...value.negative_keywords !== void 0 ? { NegativeKeywords: value.negative_keywords.map((value2) => ({ Text: value2.text, MatchType: value2.match_type })) } : {} };
|
|
1285
|
+
const result = await this.request(value.account_id, "KeywordTrafficEstimates/Query", { CampaignEstimators: [estimator] }, "POST", "adinsight");
|
|
1286
|
+
if (!Object.hasOwn(result, "CampaignEstimates")) throw new AdportError9("PROVIDER_ERROR", "microsoft: traffic-estimate response did not contain the native result envelope");
|
|
1287
|
+
const currency2 = this.currency(value.account_id);
|
|
1288
|
+
return { rows: microsoftRows(result.CampaignEstimates), estimate_period: "week", deprecated_metrics: ["AveragePosition"], ...currency2 ? { currency: currency2 } : {}, notes: ["Clicks, impressions and total cost are estimated per week. The optional DailyBudget input is a daily filter, not the estimate period.", "AveragePosition is deprecated and native values have been fixed at zero since 2021-03-31; it is not a valid position estimate.", "These are hypothetical traffic estimates in account currency, not a forecast guarantee or observed performance. No campaigns, ads or keywords are created or edited.", "CampaignId and AdGroupId are reserved by this API and are intentionally omitted. Only Phrase and Broad keyword estimates are supported."] };
|
|
1289
|
+
}
|
|
1290
|
+
};
|
|
1291
|
+
function microsoftPlanningTools(provider) {
|
|
1292
|
+
return [
|
|
1293
|
+
defineTool6({ name: "microsoft_keyword_ideas", namespace: "microsoft", description: "Read Ad Insight keyword ideas from keyword, HTTPS URL or native category seeds. Requires language and location IDs; suggested bids use account currency. Native cap 3000, no pagination; monthly counts newest-first and undated unless date_range supplied.", input: ideas, output: ideasOutput, annotations: { readOnly: true }, handler: (input) => provider.planning.keywordIdeas(input, true) }),
|
|
1294
|
+
defineTool6({ name: "microsoft_keyword_historical_metrics", namespace: "microsoft", description: "Read native keyword attributes without expanding seeds: demand history, competition and estimated bids. Monthly counts newest-first; missing values remain unavailable. Exact month labels require explicit date_range.", input: historical, output: ideasOutput, annotations: { readOnly: true }, handler: (input) => provider.planning.keywordIdeas(input, false) }),
|
|
1295
|
+
defineTool6({ name: "microsoft_keyword_traffic_estimates", namespace: "microsoft", description: "Estimate hypothetical weekly Phrase/Broad keyword traffic from bids, language, locations and network, optionally daily budget and exclusions. Read-only; no campaign changes. Cost/bids use account currency. AveragePosition is deprecated and always zero.", input: traffic, output: z8.object({ rows: z8.array(z8.record(z8.string(), z8.unknown())), estimate_period: z8.literal("week"), deprecated_metrics: z8.array(z8.string()), currency: z8.string().optional(), notes: z8.array(z8.string()) }), annotations: { readOnly: true }, handler: (input) => provider.planning.trafficEstimates(input) })
|
|
1296
|
+
];
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
// src/conversions.ts
|
|
1300
|
+
import { createHash as createHash2 } from "crypto";
|
|
1301
|
+
import { AdportError as AdportError10, defineTool as defineTool7, guardedWriteTool as guardedWriteTool6 } from "@adport/core";
|
|
1302
|
+
import { z as z9 } from "zod";
|
|
1303
|
+
var goalType = z9.enum(["AppDownload", "AppInstall", "Duration", "Event", "InStoreTransaction", "OfflineConversion", "PagesViewedPerVisit", "Url"]);
|
|
1304
|
+
var supportedType = z9.enum(["Url", "Event", "OfflineConversion"]);
|
|
1305
|
+
var standardTypes = ["AppDownload", "AppInstall", "Duration", "Event", "OfflineConversion", "PagesViewedPerVisit", "Url"];
|
|
1306
|
+
var name2 = z9.string().min(1).max(100).refine((value) => value.trim().length > 0, "Name cannot be blank");
|
|
1307
|
+
var category = z9.enum(["AddToCart", "BeginCheckout", "BookAppointment", "Contact", "GetDirections", "Other", "OutboundClick", "PageView", "Purchase", "RequestQuote", "Signup", "SubmitLeadForm", "Subscribe"]);
|
|
1308
|
+
var expression = z9.object({ operator: z9.enum(["BeginsWith", "Contains", "Equals", "RegularExpression"]), text: z9.string().min(1).max(100) });
|
|
1309
|
+
var event = z9.object({ action: expression.optional(), category: expression.optional(), label: expression.optional(), value: z9.object({ operator: z9.enum(["Equals", "GreaterThan", "LessThan"]), amount: z9.number() }).optional() }).refine((value) => Object.values(value).some((value2) => value2 !== void 0), "At least one complete event condition is required");
|
|
1310
|
+
var url2 = z9.object({ operator: expression.shape.operator, expression: z9.string().min(1).max(1e3) });
|
|
1311
|
+
var revenue = z9.discriminatedUnion("type", [z9.object({ type: z9.literal("NoValue") }), z9.object({ type: z9.literal("FixedValue"), value: z9.number().nonnegative(), currency: z9.string().regex(/^[A-Z]{3}$/).optional() }), z9.object({ type: z9.literal("VariableValue"), value: z9.number().nonnegative().optional(), currency: z9.string().regex(/^[A-Z]{3}$/).optional() })]);
|
|
1312
|
+
var common = z9.object({ name: name2, goal_category: category, status: z9.enum(["Active", "Paused"]).default("Paused"), exclude_from_bidding: z9.boolean().default(true), count_type: z9.enum(["All", "Unique"]).default("All"), conversion_window_minutes: z9.number().int().min(1).max(129600).default(43200), revenue: revenue.default({ type: "NoValue" }), expected_auto_tagging_enabled: z9.boolean() });
|
|
1313
|
+
var create2 = z9.object({ goal: z9.discriminatedUnion("type", [common.extend({ type: z9.literal("OfflineConversion"), is_externally_attributed: z9.boolean().default(false) }), common.extend({ type: z9.literal("Url"), tag_id: microsoftId, url_rule: url2 }), common.extend({ type: z9.literal("Event"), tag_id: microsoftId, event_conditions: event })]) });
|
|
1314
|
+
var update3 = z9.object({ goal_id: microsoftId, goal_type: supportedType, expected_snapshot_hash: z9.string().regex(/^[a-f0-9]{64}$/), name: name2.optional(), goal_category: category.optional(), status: z9.enum(["Active", "Paused"]).optional(), exclude_from_bidding: z9.boolean().optional(), count_type: z9.enum(["All", "Unique"]).optional(), conversion_window_minutes: z9.number().int().min(1).max(129600).optional(), revenue: revenue.optional(), is_externally_attributed: z9.boolean().optional(), url_rule: url2.optional(), event_conditions: event.optional() }).refine((value) => Object.entries(value).some(([key, value2]) => !["goal_id", "goal_type", "expected_snapshot_hash"].includes(key) && value2 !== void 0), "Supply an editable field");
|
|
1315
|
+
var createTag = z9.object({ name: name2, description: z9.string().min(1).max(1e3).optional(), expected_customer_id: microsoftId.describe("native_customer_id from microsoft_linked_uet_tags") });
|
|
1316
|
+
var view = z9.object({ account_id: microsoftId, goal: z9.record(z9.string(), z9.unknown()), auto_tagging_enabled: z9.boolean().describe("MSCLKIDAutoTaggingEnabled on the selected account, separate from the goal Scope"), auto_tagging_scope: z9.literal("Account"), snapshot_hash: z9.string().regex(/^[a-f0-9]{64}$/) });
|
|
1317
|
+
var additional = "GoalCategory, IsExternallyAttributed, IsAutoGoal, IsEnhancedConversionsEnabled, ViewThroughConversionWindowInMinutes, AttributionModelType, ApplicationDownloadGoal";
|
|
1318
|
+
var pairs = [["ActionExpression", "ActionOperator", "action"], ["CategoryExpression", "CategoryOperator", "category"], ["LabelExpression", "LabelOperator", "label"], ["Value", "ValueOperator", "value"]];
|
|
1319
|
+
var notes2 = ["Microsoft automatically enables MSCLKIDAutoTaggingEnabled when adding or updating this goal, including paused goals. This tool does not install a UET tag or send conversion events.", "Account scope is fixed. Native Deleted status is internal-only; no permanent goal-deletion operation is exposed. Use Paused to stop tracking.", "Goal snapshots detect changed configuration before submission; Microsoft provides no atomic compare-and-set. Conversion settings can affect reporting and automated bidding."];
|
|
1320
|
+
function canonical(value) {
|
|
1321
|
+
return Array.isArray(value) ? value.map(canonical) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value2]) => [key, canonical(value2)])) : value;
|
|
1322
|
+
}
|
|
1323
|
+
var wireRevenue = (value) => ({ Type: value.type, ..."value" in value && value.value !== void 0 ? { Value: value.value } : {}, ..."currency" in value && value.currency ? { CurrencyCode: value.currency } : {} });
|
|
1324
|
+
function eventFields(value) {
|
|
1325
|
+
const fields2 = {};
|
|
1326
|
+
for (const [field, operator, key] of pairs) {
|
|
1327
|
+
const condition = value[key];
|
|
1328
|
+
fields2[field] = condition ? "text" in condition ? condition.text : condition.amount : null;
|
|
1329
|
+
fields2[operator] = condition?.operator ?? null;
|
|
1330
|
+
}
|
|
1331
|
+
return fields2;
|
|
1332
|
+
}
|
|
1333
|
+
function matches(actual, fields2) {
|
|
1334
|
+
return Object.entries(fields2).every(([key, value]) => value === null ? actual[key] === null || actual[key] === void 0 : value && typeof value === "object" && !Array.isArray(value) ? actual[key] && typeof actual[key] === "object" && matches(actual[key], value) : String(actual[key]) === String(value));
|
|
1335
|
+
}
|
|
1336
|
+
var MICROSOFT_CONVERSION_WRITES = /* @__PURE__ */ new Set(["microsoft_create_conversion_goal", "microsoft_update_conversion_goal", "microsoft_create_uet_tag"]);
|
|
1337
|
+
var MicrosoftConversionService = class extends MicrosoftNativeService {
|
|
1338
|
+
async autoTagging(account) {
|
|
1339
|
+
const result = await this.request(account, "AccountProperties/Query", { AccountPropertyNames: ["MSCLKIDAutoTaggingEnabled"] });
|
|
1340
|
+
const properties = microsoftRows(result.AccountProperties).filter((value) => value.Name === "MSCLKIDAutoTaggingEnabled");
|
|
1341
|
+
if (properties.length !== 1 || !["true", "false"].includes(String(properties[0].Value))) throw new AdportError10("PROVIDER_ERROR", "microsoft: native click-ID auto-tagging state is unavailable");
|
|
1342
|
+
return String(properties[0].Value) === "true";
|
|
1343
|
+
}
|
|
1344
|
+
async query(account, types) {
|
|
1345
|
+
const result = await this.request(account, "ConversionGoals/QueryByIds", { ConversionGoalIds: null, ConversionGoalTypes: types.join(", "), ReturnAdditionalFields: additional });
|
|
1346
|
+
if (!Object.hasOwn(result, "ConversionGoals")) throw new AdportError10("PROVIDER_ERROR", "microsoft: conversion goals response envelope is missing");
|
|
1347
|
+
const values = microsoftRows(result.ConversionGoals);
|
|
1348
|
+
if (new Set(values.map((value) => microsoftNativeId(value.Id))).size !== values.length || values.some((value) => !types.includes(goalType.parse(value.Type)))) throw new AdportError10("PROVIDER_ERROR", "microsoft: conversion-goal native identities or types mismatch");
|
|
1349
|
+
return values;
|
|
1350
|
+
}
|
|
1351
|
+
snapshot(account, goal, enabled) {
|
|
1352
|
+
const { TrackingStatus: _tracking, ...configuration } = goal;
|
|
1353
|
+
return { account_id: account, goal, auto_tagging_enabled: enabled, auto_tagging_scope: "Account", snapshot_hash: createHash2("sha256").update(JSON.stringify(canonical({ account, configuration, enabled }))).digest("hex") };
|
|
1354
|
+
}
|
|
1355
|
+
async list(input) {
|
|
1356
|
+
const values = await this.query(input.account_id, input.goal_types), enabled = await this.autoTagging(input.account_id), remaining = values.filter((value) => !input.after_goal_id || BigInt(microsoftNativeId(value.Id)) > BigInt(input.after_goal_id)).sort((a, b) => BigInt(microsoftNativeId(a.Id)) < BigInt(microsoftNativeId(b.Id)) ? -1 : 1), page = remaining.slice(0, input.limit), truncated = remaining.length > page.length;
|
|
1357
|
+
return { account_id: input.account_id, rows: page.map((value) => this.snapshot(input.account_id, value, enabled)), auto_tagging_enabled: enabled, auto_tagging_scope: "Account", truncated, ...truncated ? { next_cursor: microsoftNativeId(page.at(-1).Id) } : {} };
|
|
1358
|
+
}
|
|
1359
|
+
async get(account, goalId2, type) {
|
|
1360
|
+
microsoftId.parse(goalId2);
|
|
1361
|
+
const values = await this.query(account, [type]), enabled = await this.autoTagging(account), current = values.find((value) => microsoftNativeId(value.Id) === goalId2);
|
|
1362
|
+
if (!current) throw new AdportError10("INVALID_INPUT", "microsoft: conversion goal was not found for the selected account/type");
|
|
1363
|
+
return this.snapshot(account, current, enabled);
|
|
1364
|
+
}
|
|
1365
|
+
async linkedTags(input) {
|
|
1366
|
+
const scope = await this.accountScope(input.account_id, true);
|
|
1367
|
+
const goals = await this.query(input.account_id, [...standardTypes]), links = /* @__PURE__ */ new Map();
|
|
1368
|
+
for (const goal of goals) {
|
|
1369
|
+
if (goal.TagId === null || goal.TagId === void 0 || goal.TagId === "0" || goal.TagId === 0) continue;
|
|
1370
|
+
const tag = microsoftNativeId(goal.TagId);
|
|
1371
|
+
links.set(tag, [...links.get(tag) ?? [], microsoftNativeId(goal.Id)]);
|
|
1372
|
+
}
|
|
1373
|
+
const ids = [...links.keys()].filter((value) => !input.after_tag_id || BigInt(value) > BigInt(input.after_tag_id)).sort((a, b) => BigInt(a) < BigInt(b) ? -1 : 1), page = ids.slice(0, input.limit), truncated = ids.length > page.length;
|
|
1374
|
+
if (!page.length) return { native_customer_id: scope.customerId, rows: [], truncated: false };
|
|
1375
|
+
const result = await this.request(input.account_id, "UetTags/QueryByIds", { TagIds: page }), tags = microsoftRows(result.UetTags);
|
|
1376
|
+
if (tags.length !== page.length || new Set(tags.map((value) => microsoftNativeId(value.Id))).size !== page.length || tags.some((value) => !page.includes(microsoftNativeId(value.Id)))) throw new AdportError10("PROVIDER_ERROR", "microsoft: linked UET tag readback does not match the selected account\u2019s goal references");
|
|
1377
|
+
return { native_customer_id: scope.customerId, rows: tags.sort((a, b) => page.indexOf(microsoftNativeId(a.Id)) - page.indexOf(microsoftNativeId(b.Id))).map((tag) => ({ tag: { ...Object.fromEntries(["Name", "Description", "TrackingStatus", "TrackingScript", "TrackingNoScript"].filter((key) => Object.hasOwn(tag, key)).map((key) => [key, tag[key]])), Id: microsoftNativeId(tag.Id) }, goal_ids: links.get(microsoftNativeId(tag.Id)), native_scope: "Customer" })), truncated, ...truncated ? { next_cursor: page.at(-1) } : {} };
|
|
1378
|
+
}
|
|
1379
|
+
async tag(account, tagId) {
|
|
1380
|
+
const result = await this.request(account, "UetTags/QueryByIds", { TagIds: [tagId] });
|
|
1381
|
+
const values = microsoftRows(result.UetTags);
|
|
1382
|
+
if (values.length !== 1 || microsoftNativeId(values[0].Id) !== tagId) throw new AdportError10("INVALID_INPUT", "microsoft: UET tag is unavailable in the selected native customer/account context");
|
|
1383
|
+
}
|
|
1384
|
+
async verify(account, goalId2, type, expected) {
|
|
1385
|
+
try {
|
|
1386
|
+
const current = await this.get(account, goalId2, type);
|
|
1387
|
+
if (current.goal.Scope !== "Account" || !current.auto_tagging_enabled || !matches(current.goal, expected)) throw new Error("Goal readback mismatch");
|
|
1388
|
+
} catch {
|
|
1389
|
+
throw new AdportError10("PROVIDER_ERROR", "microsoft: conversion-goal write was accepted but readback was not confirmed; reconcile before retrying", { resourceIds: [goalId2] });
|
|
1390
|
+
}
|
|
1391
|
+
return [goalId2];
|
|
1392
|
+
}
|
|
1393
|
+
async plan(op, guard) {
|
|
1394
|
+
if (op.provider !== "microsoft" || !MICROSOFT_CONVERSION_WRITES.has(op.tool) || op.kind !== (op.tool === "microsoft_update_conversion_goal" ? "update" : "create")) throw new AdportError10("INVALID_INPUT", "microsoft: conversion-goal operation kind mismatch");
|
|
1395
|
+
const account = op.accountId;
|
|
1396
|
+
if (op.tool === "microsoft_create_uet_tag") {
|
|
1397
|
+
const value2 = createTag.parse(op.payload), scope = await this.accountScope(account, true), fields3 = { Name: value2.name, ...value2.description ? { Description: value2.description } : {} };
|
|
1398
|
+
if (scope.customerId !== value2.expected_customer_id) throw new AdportError10("INVALID_INPUT", "microsoft: parent customer changed; read fresh linked-tag context and request a new preview");
|
|
1399
|
+
return { summary: `Create Microsoft UET tag "${value2.name}"`, changes: [`+ uninstalled UET tag in native customer ${scope.customerId} library ${JSON.stringify(fields3)}`], fieldChanges: [{ field: "Name", before: "(new)", after: value2.name }, { field: "Resource scope", before: "(new)", after: "Customer" }], notes: [`UET tags belong to native customer ${scope.customerId}'s shared library. The new tag is uninstalled and creates no serving campaign, tracking event or account-share update.`, "Native tags have no pause state. Associate its ID with a paused account-scoped conversion goal, then use microsoft_linked_uet_tags to read its tracking code. Installation is a separate action.", "This tool creates a new tag only. Customer-wide tag edits, sharing and permanent deletion are not exposed."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
1400
|
+
const result = await this.request(account, "UetTags", { UetTags: [fields3] }), created = microsoftRows(result.UetTags), ids = created.map((value3) => microsoftNativeId(value3.Id));
|
|
1401
|
+
if (created.length !== 1 || !matches(created[0], fields3)) throw new AdportError10("PROVIDER_ERROR", "microsoft: UET creation receipt mismatch; reconcile before retrying", { resourceIds: ids });
|
|
1402
|
+
try {
|
|
1403
|
+
const actual = microsoftRows((await this.request(account, "UetTags/QueryByIds", { TagIds: ids })).UetTags);
|
|
1404
|
+
if (actual.length !== 1 || microsoftNativeId(actual[0].Id) !== ids[0] || !matches(actual[0], fields3)) throw new Error("UET readback mismatch");
|
|
1405
|
+
} catch {
|
|
1406
|
+
throw new AdportError10("PROVIDER_ERROR", "microsoft: UET tag was accepted but readback was not confirmed; reconcile before retrying", { resourceIds: ids });
|
|
1407
|
+
}
|
|
1408
|
+
return ids;
|
|
1409
|
+
} };
|
|
1410
|
+
}
|
|
1411
|
+
if (op.tool === "microsoft_create_conversion_goal") {
|
|
1412
|
+
const value2 = create2.parse(op.payload).goal, enabled = await this.autoTagging(account);
|
|
1413
|
+
if (value2.expected_auto_tagging_enabled !== enabled) throw new AdportError10("INVALID_INPUT", "microsoft: auto-tagging state changed; read fresh conversion context before previewing");
|
|
1414
|
+
const existing = await this.query(account, [...standardTypes]);
|
|
1415
|
+
if (existing.some((goal) => typeof goal.Name === "string" && goal.Name.toLowerCase() === value2.name.toLowerCase())) throw new AdportError10("INVALID_INPUT", "microsoft: conversion goal name already exists; do not replay creation");
|
|
1416
|
+
if ("tag_id" in value2) await this.tag(account, value2.tag_id);
|
|
1417
|
+
const status2 = guard.forcePausedCreation ? "Paused" : value2.status;
|
|
1418
|
+
const fields3 = { Type: value2.type, Scope: "Account", Name: value2.name, Status: status2, GoalCategory: value2.goal_category, ExcludeFromBidding: value2.exclude_from_bidding, CountType: value2.count_type, ConversionWindowInMinutes: value2.conversion_window_minutes, Revenue: wireRevenue(value2.revenue), ...value2.type === "OfflineConversion" ? { IsExternallyAttributed: value2.is_externally_attributed } : { TagId: value2.tag_id }, ...value2.type === "Url" ? { UrlExpression: value2.url_rule.expression, UrlOperator: value2.url_rule.operator } : value2.type === "Event" ? eventFields(value2.event_conditions) : {} };
|
|
1419
|
+
return { summary: `Create Microsoft ${value2.type} goal "${value2.name}"`, changes: [`+ account-scoped conversion goal ${JSON.stringify(fields3)}`, `MSCLKIDAutoTaggingEnabled ${enabled} \u2192 true (native side effect)`], fieldChanges: [{ field: "Name", before: "(new)", after: value2.name }, { field: "Status", before: "(new)", after: status2 }, { field: "MSCLKIDAutoTaggingEnabled", before: String(enabled), after: "true" }], notes: notes2, coercions: status2 !== value2.status ? ["Status coerced to Paused by policy (paused_creation)"] : [], budgetDeltas: [], execute: async () => {
|
|
1420
|
+
const result = await this.request(account, "ConversionGoals", { ConversionGoals: [fields3] });
|
|
1421
|
+
const ids = Array.isArray(result.ConversionGoalIds) ? result.ConversionGoalIds.filter((value3) => value3 !== null).map(microsoftNativeId) : [];
|
|
1422
|
+
if (ids.length !== 1 || existing.some((goal) => microsoftNativeId(goal.Id) === ids[0])) throw new AdportError10("PROVIDER_ERROR", "microsoft: conversion-goal creation receipt mismatch; reconcile before retrying", { resourceIds: ids });
|
|
1423
|
+
return this.verify(account, ids[0], value2.type, fields3);
|
|
1424
|
+
} };
|
|
1425
|
+
}
|
|
1426
|
+
const value = update3.parse(op.payload), current = await this.get(account, value.goal_id, value.goal_type);
|
|
1427
|
+
if (current.goal.Scope !== "Account") throw new AdportError10("INVALID_INPUT", "microsoft: customer-wide conversion goals require authorization covering every affected account; single-account tools cannot mutate them");
|
|
1428
|
+
if (current.snapshot_hash !== value.expected_snapshot_hash) throw new AdportError10("INVALID_INPUT", "microsoft: conversion-goal snapshot changed; read fresh context and request a new preview");
|
|
1429
|
+
if (value.url_rule && value.goal_type !== "Url" || value.event_conditions && value.goal_type !== "Event" || value.is_externally_attributed !== void 0 && value.goal_type !== "OfflineConversion") throw new AdportError10("INVALID_INPUT", "microsoft: conversion-goal subtype fields mismatch");
|
|
1430
|
+
const fields2 = {};
|
|
1431
|
+
for (const [key, field] of [["name", "Name"], ["goal_category", "GoalCategory"], ["status", "Status"], ["exclude_from_bidding", "ExcludeFromBidding"], ["count_type", "CountType"], ["conversion_window_minutes", "ConversionWindowInMinutes"], ["is_externally_attributed", "IsExternallyAttributed"]]) if (value[key] !== void 0 && value[key] !== current.goal[field]) fields2[field] = value[key];
|
|
1432
|
+
if (value.revenue) fields2.Revenue = wireRevenue(value.revenue);
|
|
1433
|
+
if (value.url_rule) Object.assign(fields2, { UrlExpression: value.url_rule.expression, UrlOperator: value.url_rule.operator });
|
|
1434
|
+
if (value.event_conditions) Object.assign(fields2, eventFields(value.event_conditions));
|
|
1435
|
+
const changed = Object.entries(fields2).filter(([key, value2]) => !matches(current.goal, { [key]: value2 }));
|
|
1436
|
+
if (!changed.length) throw new AdportError10("INVALID_INPUT", "microsoft: conversion-goal update has no changes");
|
|
1437
|
+
if (value.goal_type === "Event" && !value.event_conditions) for (const [expression2, operator] of pairs) {
|
|
1438
|
+
const expressionValue = current.goal[expression2], operatorValue = current.goal[operator];
|
|
1439
|
+
if ((expressionValue === null || expressionValue === void 0) !== (operatorValue === null || operatorValue === void 0)) throw new AdportError10("INVALID_INPUT", "microsoft: existing event condition is incomplete; refusing a partial update");
|
|
1440
|
+
fields2[expression2] = expressionValue ?? null;
|
|
1441
|
+
fields2[operator] = operatorValue ?? null;
|
|
1442
|
+
}
|
|
1443
|
+
const fieldChanges = changed.map(([field, after]) => ({ field, before: JSON.stringify(current.goal[field] ?? null), after: JSON.stringify(after) }));
|
|
1444
|
+
return { summary: `Update Microsoft ${value.goal_type} goal "${String(current.goal.Name)}"`, changes: [`~ goal ${value.goal_id} ${JSON.stringify(fields2)}`, `MSCLKIDAutoTaggingEnabled ${current.auto_tagging_enabled} \u2192 true (native side effect)`], fieldChanges: [...fieldChanges, { field: "MSCLKIDAutoTaggingEnabled", before: String(current.auto_tagging_enabled), after: "true" }], notes: notes2, coercions: [], budgetDeltas: [], execute: async () => {
|
|
1445
|
+
await this.request(account, "ConversionGoals", { ConversionGoals: [{ Id: value.goal_id, Type: value.goal_type, ...fields2 }] }, "PUT");
|
|
1446
|
+
return this.verify(account, value.goal_id, value.goal_type, { ...fields2, Status: fields2.Status ?? current.goal.Status });
|
|
1447
|
+
} };
|
|
1448
|
+
}
|
|
1449
|
+
};
|
|
1450
|
+
function microsoftConversionTools(provider) {
|
|
1451
|
+
return [
|
|
1452
|
+
defineTool7({ name: "microsoft_linked_uet_tags", namespace: "microsoft", description: "Read current native_customer_id plus UET metadata/code only for tags referenced by selected-account goals. Tags are customer-scoped; the entire library and sharing graph are not exposed. Continue next_cursor as after_tag_id.", input: z9.object({ account_id: microsoftId, after_tag_id: microsoftId.optional(), limit: z9.number().int().positive().max(100).default(50) }), output: z9.object({ native_customer_id: microsoftId, rows: z9.array(z9.object({ tag: z9.record(z9.string(), z9.unknown()), goal_ids: z9.array(microsoftId), native_scope: z9.literal("Customer") })), truncated: z9.boolean(), next_cursor: microsoftId.optional() }), pagination: { cursorInput: "after_tag_id" }, annotations: { readOnly: true }, handler: (input) => provider.conversions.linkedTags(input) }),
|
|
1453
|
+
guardedWriteTool6({ name: "microsoft_create_uet_tag", namespace: "microsoft", provider: "microsoft", kind: "create", description: "Create one uninstalled UET tag in the selected account\u2019s native customer library. Requires expected_customer_id from linked-tag reads; rechecks current parent ownership. Returns its ID for paused goal setup. No installation or event sending; tags have no pause state.", payload: createTag }),
|
|
1454
|
+
defineTool7({ name: "microsoft_conversion_goals", namespace: "microsoft", description: "Read account-associated native goals, tracking state, configuration hashes and account-level click-ID auto-tagging. Default excludes pilot-only InStoreTransaction, whose inclusion can reject the entire query. Continue next_cursor as after_goal_id.", input: z9.object({ account_id: microsoftId, goal_types: z9.array(goalType).min(1).refine((value) => new Set(value).size === value.length, "Goal types must be unique").default([...standardTypes]), after_goal_id: microsoftId.optional(), limit: z9.number().int().positive().max(1e3).default(100) }), output: z9.object({ account_id: microsoftId, rows: z9.array(view), auto_tagging_enabled: z9.boolean(), auto_tagging_scope: z9.literal("Account"), truncated: z9.boolean(), next_cursor: microsoftId.optional() }), pagination: { cursorInput: "after_goal_id" }, annotations: { readOnly: true }, handler: (input) => provider.conversions.list(input) }),
|
|
1455
|
+
defineTool7({ name: "microsoft_get_conversion_goal", namespace: "microsoft", description: "Read one account-associated native goal and snapshot_hash. TrackingStatus is system-owned and excluded from the configuration hash. Customer-scoped goals cannot be edited through single-account tools.", input: z9.object({ account_id: microsoftId, goal_id: microsoftId, goal_type: goalType }), output: view, annotations: { readOnly: true }, handler: (input) => provider.conversions.get(input.account_id, input.goal_id, input.goal_type) }),
|
|
1456
|
+
guardedWriteTool6({ name: "microsoft_create_conversion_goal", namespace: "microsoft", provider: "microsoft", kind: "create", description: "Create an account-scoped URL, Event or OfflineConversion goal. Defaults Paused and excluded from bidding. Native add automatically enables click-ID auto-tagging; supply its expected state from conversion-goal reads. Does not install tracking or send events. Goals cannot be permanently deleted through this API.", payload: create2 }),
|
|
1457
|
+
guardedWriteTool6({ name: "microsoft_update_conversion_goal", namespace: "microsoft", provider: "microsoft", kind: "update", description: "Edit an Account-scoped URL/Event/Offline goal with expected_snapshot_hash. Preserves omitted event criteria, status and other optional settings. Native update enables click-ID auto-tagging. Event conditions, when supplied, replace the full condition set. Use Paused to stop tracking; Deleted is internal-only.", payload: update3 })
|
|
1458
|
+
];
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
// src/audiences.ts
|
|
1462
|
+
import { createHash as createHash3 } from "crypto";
|
|
1463
|
+
import { AdportError as AdportError11, defineTool as defineTool8, guardedWriteTool as guardedWriteTool7 } from "@adport/core";
|
|
1464
|
+
import { z as z10 } from "zod";
|
|
1465
|
+
var microsoftAudienceType = z10.enum(["RemarketingList", "Custom", "InMarket", "Product", "SimilarRemarketingList", "CombinedList", "CustomerList", "ImpressionBasedRemarketingList", "CustomSegment"]);
|
|
1466
|
+
var audienceType = microsoftAudienceType;
|
|
1467
|
+
var standardTypes2 = audienceType.options.filter((value) => value !== "CustomSegment");
|
|
1468
|
+
var name3 = z10.string().min(1).max(128).refine((value) => value.trim().length > 0, "Name cannot be blank");
|
|
1469
|
+
var description = z10.string().max(1024);
|
|
1470
|
+
var hash2 = z10.string().regex(/^[a-f0-9]{64}$/);
|
|
1471
|
+
var stringOperator = z10.enum(["Equals", "Contains", "BeginsWith", "EndsWith", "NotEquals", "DoesNotContain", "DoesNotBeginWith", "DoesNotEndWith"]);
|
|
1472
|
+
var numberOperator = z10.enum(["Equals", "GreaterThan", "LessThan", "GreaterThanEqualTo", "LessThanEqualTo", "NotEquals"]);
|
|
1473
|
+
var groups = z10.array(z10.object({ items: z10.array(z10.object({ operand: z10.enum(["Url", "ReferrerUrl"]), operator: stringOperator, value: z10.string().min(1) })).min(1).max(100) })).min(1).max(100);
|
|
1474
|
+
var eventExpression = z10.object({ operator: stringOperator, text: z10.string().min(1) });
|
|
1475
|
+
var rule = z10.discriminatedUnion("type", [
|
|
1476
|
+
z10.object({ type: z10.literal("PageVisitors"), normal_form: z10.enum(["Conjunctive", "Disjunctive"]).default("Disjunctive"), groups }),
|
|
1477
|
+
z10.object({ type: z10.literal("PageVisitorsWhoVisitedAnotherPage"), groups, another_groups: groups }),
|
|
1478
|
+
z10.object({ type: z10.literal("PageVisitorsWhoDidNotVisitAnotherPage"), include_groups: groups, exclude_groups: groups }),
|
|
1479
|
+
z10.object({ type: z10.literal("CustomEvents"), action: eventExpression.optional(), category: eventExpression.optional(), label: eventExpression.optional(), value: z10.object({ operator: numberOperator, amount: z10.number().int().positive() }).optional() }).refine((value) => Object.values(value).some((value2) => value2 !== void 0 && value2 !== "CustomEvents"), "At least one complete event condition is required")
|
|
1480
|
+
]);
|
|
1481
|
+
var create3 = z10.object({ name: name3, description: description.optional(), membership_duration_days: z10.number().int().min(1).max(180).default(30), tag_id: microsoftId, rule });
|
|
1482
|
+
var reference4 = z10.object({ audience_id: microsoftId, expected_snapshot_hash: hash2 });
|
|
1483
|
+
var update4 = reference4.extend({ name: name3.optional(), description: description.optional(), membership_duration_days: z10.number().int().min(1).max(180).optional(), tag_id: microsoftId.optional(), rule: rule.optional() }).refine((value) => Object.entries(value).some(([key, value2]) => !["audience_id", "expected_snapshot_hash"].includes(key) && value2 !== void 0), "Supply an editable field");
|
|
1484
|
+
var view2 = z10.object({ account_id: microsoftId, audience: z10.record(z10.string(), z10.unknown()), shared: z10.boolean(), snapshot_hash: hash2 });
|
|
1485
|
+
var notes3 = ["Remarketing lists have no independent pause state. Creation is account-scoped and unattached; it does not install UET, send events or upload customer records.", "Omitted rules and tag settings are preserved. Supplying a rule replaces its entire condition set. Conjunctive means OR within each group, AND across groups; Disjunctive means AND within each group, OR across groups.", "Audience changes can affect existing targeting and exclusions in the selected account. Configuration hashes detect drift before submission; Microsoft has no atomic compare-and-set. Customer scope and sharing changes are not exposed."];
|
|
1486
|
+
function canonical2(value) {
|
|
1487
|
+
return Array.isArray(value) ? value.map(canonical2) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value2]) => [key, canonical2(value2)])) : value;
|
|
1488
|
+
}
|
|
1489
|
+
function matches2(actual, expected) {
|
|
1490
|
+
if (expected === null || expected === void 0) return actual === null || actual === void 0;
|
|
1491
|
+
if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((value, index) => matches2(actual[index], value));
|
|
1492
|
+
if (typeof expected === "object") {
|
|
1493
|
+
if (actual === null || typeof actual !== "object") return false;
|
|
1494
|
+
if (expected.Type === "CustomEvents") {
|
|
1495
|
+
for (const field of ["Action", "Category", "Label", "Value"]) if (!Object.hasOwn(expected, field) && ![void 0, null, "None"].includes(actual[`${field}Operator`])) return false;
|
|
1496
|
+
}
|
|
1497
|
+
return Object.entries(expected).every(([key, value]) => matches2(actual[key], value));
|
|
1498
|
+
}
|
|
1499
|
+
return String(actual) === String(expected);
|
|
1500
|
+
}
|
|
1501
|
+
var nativeGroups = (value) => value.map((group) => ({ Items: group.items.map((item) => ({ Type: "String", Operand: item.operand, Operator: item.operator, Value: item.value })) }));
|
|
1502
|
+
function nativeRule(value) {
|
|
1503
|
+
if (value.type === "PageVisitors") return { Type: value.type, NormalForm: value.normal_form, RuleItemGroups: nativeGroups(value.groups) };
|
|
1504
|
+
if (value.type === "PageVisitorsWhoVisitedAnotherPage") return { Type: value.type, RuleItemGroups: nativeGroups(value.groups), AnotherRuleItemGroups: nativeGroups(value.another_groups) };
|
|
1505
|
+
if (value.type === "PageVisitorsWhoDidNotVisitAnotherPage") return { Type: value.type, IncludeRuleItemGroups: nativeGroups(value.include_groups), ExcludeRuleItemGroups: nativeGroups(value.exclude_groups) };
|
|
1506
|
+
const result = { Type: value.type };
|
|
1507
|
+
for (const [key, field] of [["action", "Action"], ["category", "Category"], ["label", "Label"], ["value", "Value"]]) {
|
|
1508
|
+
const condition = value[key];
|
|
1509
|
+
if (condition) {
|
|
1510
|
+
result[field] = "text" in condition ? condition.text : condition.amount;
|
|
1511
|
+
result[`${field}Operator`] = condition.operator;
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
return result;
|
|
1515
|
+
}
|
|
1516
|
+
var MICROSOFT_AUDIENCE_WRITES = /* @__PURE__ */ new Set(["microsoft_create_remarketing_list", "microsoft_update_remarketing_list", "microsoft_delete_remarketing_list"]);
|
|
1517
|
+
var MicrosoftAudienceService = class extends MicrosoftNativeService {
|
|
1518
|
+
constructor(...args) {
|
|
1519
|
+
const [client, scope, campaign, campaigns] = args;
|
|
1520
|
+
super(client, scope, campaign);
|
|
1521
|
+
this.campaigns = campaigns;
|
|
1522
|
+
}
|
|
1523
|
+
campaigns;
|
|
1524
|
+
async query(account, types, ids = null) {
|
|
1525
|
+
const result = await this.request(account, "Audiences/QueryByIds", { AudienceIds: ids, Type: types.join(", "), ReturnAdditionalFields: "NormalForm, NumberRuleItem, ImpressionBasedRemarketingList, CampaignIdsAdGroupIds" });
|
|
1526
|
+
if (!Object.hasOwn(result, "Audiences")) throw new AdportError11("PROVIDER_ERROR", "microsoft: native audience response envelope is missing");
|
|
1527
|
+
const values = microsoftRows(result.Audiences);
|
|
1528
|
+
if (new Set(values.map((value) => microsoftNativeId(value.Id))).size !== values.length || values.some((value) => !types.includes(audienceType.parse(value.Type)))) throw new AdportError11("PROVIDER_ERROR", "microsoft: native audience identities or types mismatch");
|
|
1529
|
+
return values;
|
|
1530
|
+
}
|
|
1531
|
+
shared(value) {
|
|
1532
|
+
return value.CustomerShare !== null && value.CustomerShare !== void 0 && microsoftRows(microsoftRow(value.CustomerShare).CustomerAccountShares).length > 0;
|
|
1533
|
+
}
|
|
1534
|
+
snapshot(account, value) {
|
|
1535
|
+
const { SearchSize: _search, AudienceNetworkSize: _network, SupportedCampaignTypes: _supported, ...configuration } = value;
|
|
1536
|
+
const { CustomerShare: _sharing, ...audience } = value;
|
|
1537
|
+
return { account_id: account, audience, shared: this.shared(value), snapshot_hash: createHash3("sha256").update(JSON.stringify(canonical2({ account, configuration }))).digest("hex") };
|
|
1538
|
+
}
|
|
1539
|
+
async list(input) {
|
|
1540
|
+
const values = (await this.query(input.account_id, input.audience_types)).filter((value) => !input.after_audience_id || BigInt(microsoftNativeId(value.Id)) > BigInt(input.after_audience_id)).sort((a, b) => BigInt(microsoftNativeId(a.Id)) < BigInt(microsoftNativeId(b.Id)) ? -1 : 1), page = values.slice(0, input.limit), truncated = values.length > page.length;
|
|
1541
|
+
return { rows: page.map((value) => this.snapshot(input.account_id, value)), truncated, ...truncated ? { next_cursor: microsoftNativeId(page.at(-1).Id) } : {} };
|
|
1542
|
+
}
|
|
1543
|
+
async find(account, audience, type) {
|
|
1544
|
+
const found = (await this.query(account, [type], [audience])).find((value) => microsoftNativeId(value.Id) === audience);
|
|
1545
|
+
if (!found) throw new AdportError11("INVALID_INPUT", "microsoft: audience was not found for the selected account/type");
|
|
1546
|
+
return found;
|
|
1547
|
+
}
|
|
1548
|
+
async get(account, audience, type) {
|
|
1549
|
+
microsoftId.parse(audience);
|
|
1550
|
+
return this.snapshot(account, await this.find(account, audience, type));
|
|
1551
|
+
}
|
|
1552
|
+
async owned(account, audience) {
|
|
1553
|
+
await this.accountScope(account, true);
|
|
1554
|
+
const current = await this.find(account, audience, "RemarketingList");
|
|
1555
|
+
if (current.Scope !== "Account" || microsoftNativeId(current.ParentId) !== account || this.shared(current)) throw new AdportError11("INVALID_INPUT", "microsoft: remarketing mutations require an unshared Account-scoped list owned by the selected account");
|
|
1556
|
+
return current;
|
|
1557
|
+
}
|
|
1558
|
+
async tag(account, tag) {
|
|
1559
|
+
const result = await this.request(account, "UetTags/QueryByIds", { TagIds: [tag] }), values = microsoftRows(result.UetTags);
|
|
1560
|
+
if (values.length !== 1 || microsoftNativeId(values[0].Id) !== tag) throw new AdportError11("INVALID_INPUT", "microsoft: UET tag is unavailable in the selected customer/account context");
|
|
1561
|
+
}
|
|
1562
|
+
async usage(account, audience) {
|
|
1563
|
+
await this.owned(account, audience);
|
|
1564
|
+
const lists = await this.query(account, ["SimilarRemarketingList", "CombinedList"]), derivedLists = lists.filter((value) => value.Type === "SimilarRemarketingList" && String(value.SourceId) === audience);
|
|
1565
|
+
if (derivedLists.some((value) => value.Scope !== "Account" || microsoftNativeId(value.ParentId) !== account || this.shared(value))) throw new AdportError11("INVALID_INPUT", "microsoft: a derived similar audience has wider or unverifiable ownership/sharing; single-account deletion use check is incomplete");
|
|
1566
|
+
const derived = derivedLists.map((value) => microsoftNativeId(value.Id)), ids = [audience, ...derived];
|
|
1567
|
+
const combined = lists.filter((value) => value.Type === "CombinedList" && microsoftRows(value.CombinationRules).some((rule2) => Array.isArray(rule2.AudienceIds) && rule2.AudienceIds.some((value2) => ids.includes(microsoftNativeId(value2))))).map((value) => microsoftNativeId(value.Id));
|
|
1568
|
+
const groupsResult = await this.request(account, "AudienceGroups/QueryByIds", { AudienceGroupIds: null });
|
|
1569
|
+
if (!Object.hasOwn(groupsResult, "AudienceGroups")) throw new AdportError11("PROVIDER_ERROR", "microsoft: audience-signal inventory is unavailable; deletion use check is incomplete");
|
|
1570
|
+
const signals = microsoftRows(groupsResult.AudienceGroups);
|
|
1571
|
+
if (signals.length >= 100) throw new AdportError11("PROVIDER_ERROR", "microsoft: audience-signal inventory reached the documented result boundary; deletion use check is incomplete");
|
|
1572
|
+
const signalIds = signals.filter((value) => microsoftRows(value.Dimensions).some((dimension) => dimension.Type === "Audience" && microsoftRows(dimension.Audiences).some((value2) => ids.includes(microsoftNativeId(value2.Id))))).map((value) => microsoftNativeId(value.Id));
|
|
1573
|
+
const campaigns = microsoftRows(await this.campaigns(account)), associations = [];
|
|
1574
|
+
if (campaigns.length > 200) throw new AdportError11("INVALID_INPUT", "microsoft: audience use check exceeds 200 campaigns; no deletion was submitted");
|
|
1575
|
+
let groupCount = 0;
|
|
1576
|
+
for (const campaign of campaigns) {
|
|
1577
|
+
if (!["Search", "Audience", "DynamicSearchAds", "Shopping", "PerformanceMax"].includes(String(campaign.CampaignType))) throw new AdportError11("INVALID_INPUT", "microsoft: audience use check encountered an unsupported campaign type; no deletion was submitted");
|
|
1578
|
+
const campaignId = microsoftNativeId(campaign.Id);
|
|
1579
|
+
let groups2 = [];
|
|
1580
|
+
if (campaign.CampaignType !== "PerformanceMax") {
|
|
1581
|
+
const result = await this.request(account, "AdGroups/QueryByCampaignId", { CampaignId: campaignId });
|
|
1582
|
+
if (!Object.hasOwn(result, "AdGroups")) throw new AdportError11("PROVIDER_ERROR", "microsoft: ad-group inventory is unavailable; audience use check is incomplete");
|
|
1583
|
+
groups2 = microsoftRows(result.AdGroups);
|
|
1584
|
+
}
|
|
1585
|
+
groupCount += groups2.length;
|
|
1586
|
+
if (groupCount > 2e3) throw new AdportError11("INVALID_INPUT", "microsoft: audience use check exceeds 2000 ad groups; no deletion was submitted");
|
|
1587
|
+
for (const type of ["RemarketingList", ...derived.length ? ["SimilarRemarketingList"] : []]) {
|
|
1588
|
+
for (const group of [void 0, ...groups2]) {
|
|
1589
|
+
const prefix2 = group ? "AdGroup" : "Campaign", parentId = group ? microsoftNativeId(group.Id) : campaignId;
|
|
1590
|
+
const result = await this.request(account, `${prefix2}Criterions/QueryByIds`, { [`${prefix2}Id`]: parentId, [`${prefix2}CriterionIds`]: null, CriterionType: type });
|
|
1591
|
+
if (!Object.hasOwn(result, `${prefix2}Criterions`)) throw new AdportError11("PROVIDER_ERROR", "microsoft: audience association response is unavailable; use check is incomplete");
|
|
1592
|
+
for (const criterion of microsoftRows(result[`${prefix2}Criterions`])) {
|
|
1593
|
+
if (microsoftNativeId(criterion[`${prefix2}Id`]) !== parentId || !["AudienceCriterion", "Audience"].includes(String(microsoftRow(criterion.Criterion).Type)) || microsoftRow(criterion.Criterion).AudienceType !== type) throw new AdportError11("PROVIDER_ERROR", "microsoft: audience association ownership/type mismatch");
|
|
1594
|
+
if (ids.includes(microsoftNativeId(microsoftRow(criterion.Criterion).AudienceId)) && criterion.Status !== "Deleted") associations.push({ campaign_id: campaignId, ...group ? { ad_group_id: parentId } : {}, criterion });
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
return { audience_id: audience, derived_audience_ids: derived, associations, combined_list_ids: combined, audience_signal_ids: signalIds, campaigns_scanned: campaigns.length, ad_groups_scanned: groupCount, complete: true };
|
|
1600
|
+
}
|
|
1601
|
+
async confirm(account, audience, expected) {
|
|
1602
|
+
try {
|
|
1603
|
+
const actual = await this.owned(account, audience);
|
|
1604
|
+
if (!matches2(actual, expected)) throw new Error("Audience readback mismatch");
|
|
1605
|
+
} catch {
|
|
1606
|
+
throw new AdportError11("PROVIDER_ERROR", "microsoft: audience write was accepted but readback was not confirmed; reconcile before retrying", { resourceIds: [audience] });
|
|
1607
|
+
}
|
|
1608
|
+
return [audience];
|
|
1609
|
+
}
|
|
1610
|
+
async plan(op) {
|
|
1611
|
+
const expectedKind = op.tool === "microsoft_create_remarketing_list" ? "create" : op.tool === "microsoft_delete_remarketing_list" ? "remove" : "update";
|
|
1612
|
+
if (op.provider !== "microsoft" || !MICROSOFT_AUDIENCE_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError11("INVALID_INPUT", "microsoft: audience operation kind mismatch");
|
|
1613
|
+
const account = op.accountId;
|
|
1614
|
+
if (op.tool === "microsoft_create_remarketing_list") {
|
|
1615
|
+
const input2 = create3.parse(op.payload);
|
|
1616
|
+
await this.accountScope(account, true);
|
|
1617
|
+
await this.tag(account, input2.tag_id);
|
|
1618
|
+
if ((await this.query(account, ["RemarketingList"])).some((value2) => String(value2.Name).toLowerCase() === input2.name.toLowerCase())) throw new AdportError11("INVALID_INPUT", "microsoft: a remarketing list with this name already exists");
|
|
1619
|
+
const fields3 = { Type: "RemarketingList", Scope: "Account", ParentId: account, Name: input2.name, MembershipDuration: input2.membership_duration_days, TagId: input2.tag_id, Rule: nativeRule(input2.rule), ...input2.description !== void 0 ? { Description: input2.description } : {} };
|
|
1620
|
+
return { summary: `Create Microsoft remarketing list "${input2.name}"`, changes: [`+ ${JSON.stringify(fields3)}`], notes: notes3, coercions: [], budgetDeltas: [], fieldChanges: [{ field: "Name", before: "(new)", after: input2.name }, { field: "Scope", before: "(new)", after: "Account" }, { field: "Rule", before: "(new)", after: JSON.stringify(fields3.Rule) }], execute: async () => {
|
|
1621
|
+
const result = await this.request(account, "Audiences", { Audiences: [fields3] }), ids = Array.isArray(result.AudienceIds) ? result.AudienceIds.filter((value2) => value2 !== null).map(microsoftNativeId) : [];
|
|
1622
|
+
if (ids.length !== 1) throw new AdportError11("PROVIDER_ERROR", "microsoft: audience creation receipt mismatch; reconcile before retrying", { resourceIds: ids });
|
|
1623
|
+
return this.confirm(account, ids[0], fields3);
|
|
1624
|
+
} };
|
|
1625
|
+
}
|
|
1626
|
+
const input = (op.kind === "remove" ? reference4 : update4).parse(op.payload), current = await this.owned(account, input.audience_id);
|
|
1627
|
+
if (this.snapshot(account, current).snapshot_hash !== input.expected_snapshot_hash) throw new AdportError11("PENDING_MISMATCH", "microsoft: audience configuration snapshot changed; request a fresh preview");
|
|
1628
|
+
if (op.kind === "remove") {
|
|
1629
|
+
const usage = await this.usage(account, input.audience_id);
|
|
1630
|
+
if (usage.associations.length || usage.combined_list_ids.length || usage.audience_signal_ids.length) throw new AdportError11("INVALID_INPUT", "microsoft: audience or derived similar audience is referenced; remove its targeting, combined-list and signal references before deleting");
|
|
1631
|
+
return { summary: `Delete Microsoft remarketing list ${input.audience_id}`, changes: [`- ${JSON.stringify(this.snapshot(account, current).audience)}`, `Also deletes derived similar lists: ${JSON.stringify(usage.derived_audience_ids)}. No campaign/ad-group, combined-list or audience-signal references were found in the bounded account scan.`], notes: ["Deletion is permanent. Use checks are repeated before submission; native concurrent association changes cannot be locked."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
1632
|
+
await this.request(account, "Audiences", { AudienceIds: [input.audience_id] }, "DELETE");
|
|
1633
|
+
try {
|
|
1634
|
+
const remaining = await this.query(account, ["RemarketingList", "SimilarRemarketingList"]);
|
|
1635
|
+
if (remaining.some((value2) => [input.audience_id, ...usage.derived_audience_ids].includes(microsoftNativeId(value2.Id)))) throw new Error("Audience still present");
|
|
1636
|
+
} catch {
|
|
1637
|
+
throw new AdportError11("PROVIDER_ERROR", "microsoft: audience deletion readback was not confirmed; reconcile before retrying", { resourceIds: [input.audience_id, ...usage.derived_audience_ids] });
|
|
1638
|
+
}
|
|
1639
|
+
return [input.audience_id, ...usage.derived_audience_ids];
|
|
1640
|
+
} };
|
|
1641
|
+
}
|
|
1642
|
+
const value = update4.parse(input), fields2 = { Id: value.audience_id, Type: "RemarketingList" };
|
|
1643
|
+
for (const [key, field] of [["name", "Name"], ["description", "Description"], ["membership_duration_days", "MembershipDuration"], ["tag_id", "TagId"]]) if (value[key] !== void 0) fields2[field] = value[key];
|
|
1644
|
+
if (value.tag_id) await this.tag(account, value.tag_id);
|
|
1645
|
+
if (value.rule) fields2.Rule = nativeRule(value.rule);
|
|
1646
|
+
const expected = Object.fromEntries(Object.entries({ ...current, ...fields2 }).filter(([key]) => !["CustomerShare", "SearchSize", "AudienceNetworkSize", "SupportedCampaignTypes"].includes(key)));
|
|
1647
|
+
return { summary: `Update Microsoft remarketing list ${value.audience_id}`, changes: [`~ ${JSON.stringify(fields2)}`], fieldChanges: Object.entries(fields2).filter(([key]) => !["Id", "Type"].includes(key)).map(([field, value2]) => ({ field, before: typeof current[field] === "object" ? JSON.stringify(current[field]) : String(current[field] ?? "(unset)"), after: typeof value2 === "object" ? JSON.stringify(value2) : String(value2) })), notes: notes3, coercions: [], budgetDeltas: [], execute: async () => {
|
|
1648
|
+
await this.request(account, "Audiences", { Audiences: [fields2] }, "PUT");
|
|
1649
|
+
return this.confirm(account, value.audience_id, expected);
|
|
1650
|
+
} };
|
|
1651
|
+
}
|
|
1652
|
+
};
|
|
1653
|
+
function microsoftAudienceTools(provider) {
|
|
1654
|
+
return [
|
|
1655
|
+
defineTool8({ name: "microsoft_audiences", namespace: "microsoft", description: "Read account-associated native audiences with configuration hashes. Preserves unavailable sizes. Sharing graphs are omitted; shared is reported. System-generated visitor/converter/Smart lists are not supported by this API. CustomSegment is opt-in; reserved AIPrompt is excluded. Continue next_cursor as after_audience_id.", input: z10.object({ account_id: microsoftId, audience_types: z10.array(audienceType).min(1).refine((value) => new Set(value).size === value.length, "Audience types must be unique").default(standardTypes2), after_audience_id: microsoftId.optional(), limit: z10.number().int().positive().max(1e3).default(100) }), output: z10.object({ rows: z10.array(view2), truncated: z10.boolean(), next_cursor: microsoftId.optional() }), pagination: { cursorInput: "after_audience_id" }, annotations: { readOnly: true }, handler: (input) => provider.audiences.list(input) }),
|
|
1656
|
+
defineTool8({ name: "microsoft_get_audience", namespace: "microsoft", description: "Read one account-associated native audience and snapshot_hash. Customer-scoped or shared lists are readable but cannot be changed by single-account remarketing tools. System-owned sizes are excluded from the hash.", input: z10.object({ account_id: microsoftId, audience_id: microsoftId, audience_type: audienceType }), output: view2, annotations: { readOnly: true }, handler: (input) => provider.audiences.get(input.account_id, input.audience_id, input.audience_type) }),
|
|
1657
|
+
defineTool8({ name: "microsoft_audience_usage", namespace: "microsoft", description: "Check an owned unshared Account remarketing list and its derived similar lists for campaign/ad-group criteria, combined-list and audience-signal references. Bounded to 200 campaigns, 2000 ad groups and fewer than 100 signals; incomplete/unsupported scans fail closed.", input: z10.object({ account_id: microsoftId, audience_id: microsoftId }), annotations: { readOnly: true }, handler: (input) => provider.audiences.usage(input.account_id, input.audience_id) }),
|
|
1658
|
+
guardedWriteTool7({ name: "microsoft_create_remarketing_list", namespace: "microsoft", provider: "microsoft", kind: "create", description: "Create one unattached Account-scoped remarketing list using an available UET tag and PageVisitors, visited-another-page, excluded-page or CustomEvents rule. No pause state, installation, event sending or customer-record upload. Membership is 1..180 days.", payload: create3 }),
|
|
1659
|
+
guardedWriteTool7({ name: "microsoft_update_remarketing_list", namespace: "microsoft", provider: "microsoft", kind: "update", description: "Edit an owned unshared Account remarketing list with expected_snapshot_hash. Preserves omitted rule/tag/settings; supplying rule replaces its entire condition set. Scope/parent/sharing are immutable here. Existing audience targeting and exclusions can be affected.", payload: update4 }),
|
|
1660
|
+
guardedWriteTool7({ name: "microsoft_delete_remarketing_list", namespace: "microsoft", provider: "microsoft", kind: "remove", destructive: true, description: "Permanently delete an owned unshared Account remarketing list and its derived similar lists. Requires expected_snapshot_hash and a complete bounded scan with no targeting, combined-list or signal references. Confirms disappearance; never retries an uncertain deletion.", payload: reference4 })
|
|
1661
|
+
];
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
// src/audience-targeting.ts
|
|
1665
|
+
import { createHash as createHash4 } from "crypto";
|
|
1666
|
+
import { AdportError as AdportError12, defineTool as defineTool9, guardedWriteTool as guardedWriteTool8 } from "@adport/core";
|
|
1667
|
+
import { z as z11 } from "zod";
|
|
1668
|
+
var audienceType2 = microsoftAudienceType.exclude(["CustomSegment"]);
|
|
1669
|
+
var selectors = { Custom: "CustomAudience", InMarket: "InMarketAudience", Product: "ProductAudience", RemarketingList: "RemarketingList", SimilarRemarketingList: "SimilarRemarketingList", CombinedList: "CombinedList", CustomerList: "CustomerList", ImpressionBasedRemarketingList: "ImpressionBasedRemarketingList" };
|
|
1670
|
+
var target5 = z11.discriminatedUnion("type", [z11.object({ type: z11.literal("Campaign"), campaign_id: microsoftId }), z11.object({ type: z11.literal("AdGroup"), campaign_id: microsoftId, ad_group_id: microsoftId })]);
|
|
1671
|
+
var hash3 = z11.string().regex(/^[a-f0-9]{64}$/);
|
|
1672
|
+
var adjustment2 = z11.number().int().min(-90).max(900);
|
|
1673
|
+
var add3 = z11.object({ target: target5, audience_id: microsoftId, audience_type: audienceType2, expected_audience_snapshot_hash: hash3, exclude: z11.boolean().default(false), bid_adjustment_percent: adjustment2.optional(), expected_target_and_bid: z11.boolean().optional() }).superRefine((value, ctx) => {
|
|
1674
|
+
if (value.exclude && (value.bid_adjustment_percent !== void 0 || value.expected_target_and_bid !== void 0)) ctx.addIssue({ code: "custom", message: "Exclusions have no bid adjustment and are independent of positive target mode" });
|
|
1675
|
+
if (!value.exclude && value.expected_target_and_bid === void 0) ctx.addIssue({ code: "custom", message: "Positive associations require expected_target_and_bid from microsoft_audience_targets" });
|
|
1676
|
+
});
|
|
1677
|
+
var reference5 = z11.object({ target: target5, audience_type: audienceType2, criterion_id: microsoftId, expected_snapshot_hash: hash3 });
|
|
1678
|
+
var bid2 = reference5.extend({ bid_adjustment_percent: adjustment2 });
|
|
1679
|
+
var mode = z11.object({ target: target5, expected_context_hash: hash3, target_and_bid: z11.boolean() });
|
|
1680
|
+
var context = z11.object({ account_id: microsoftId, target: target5, campaign_status: z11.string(), ad_group_status: z11.string().optional(), target_and_bid: z11.boolean(), audience_target_option: z11.enum(["TargetAndBid", "BidOnly"]), context_hash: hash3 });
|
|
1681
|
+
function canonical3(value) {
|
|
1682
|
+
return Array.isArray(value) ? value.map(canonical3) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value2]) => [key, canonical3(value2)])) : value;
|
|
1683
|
+
}
|
|
1684
|
+
var digest2 = (value) => createHash4("sha256").update(JSON.stringify(canonical3(value))).digest("hex");
|
|
1685
|
+
var prefix = (value) => value.type;
|
|
1686
|
+
var entityId = (value) => value.type === "Campaign" ? value.campaign_id : value.ad_group_id;
|
|
1687
|
+
var isTargetSetting = (value) => ["Target", "TargetSetting"].includes(String(value.Type));
|
|
1688
|
+
var orderedDetails = (value) => [...value].sort((a, b) => String(a.CriterionTypeGroup).localeCompare(String(b.CriterionTypeGroup)));
|
|
1689
|
+
var notices = ["Audience criteria have native Active status, without an independent pause. Default paused_creation requires an effectively paused parent for new associations.", "Positive audiences can be associated at campaign or ad-group level, but not both within one campaign. Exclusions can exist at both levels and Microsoft applies their union.", "TargetAndBid restricts positive audience delivery; BidOnly adjusts bids without adding that restriction. Exclusions apply regardless. Automated bidding can treat bid percentages as signals. Snapshots detect changes before submission; Microsoft has no atomic compare-and-set."];
|
|
1690
|
+
var MICROSOFT_AUDIENCE_TARGETING_WRITES = /* @__PURE__ */ new Set(["microsoft_add_audience_target", "microsoft_set_audience_target_bid", "microsoft_remove_audience_target", "microsoft_set_audience_target_mode"]);
|
|
1691
|
+
var MicrosoftAudienceTargetingService = class extends MicrosoftNativeService {
|
|
1692
|
+
constructor(...args) {
|
|
1693
|
+
const [client, scope, campaign, source] = args;
|
|
1694
|
+
super(client, scope, campaign);
|
|
1695
|
+
this.source = source;
|
|
1696
|
+
}
|
|
1697
|
+
source;
|
|
1698
|
+
async entity(account, value, refresh = false) {
|
|
1699
|
+
await this.accountScope(account, refresh);
|
|
1700
|
+
const known = await this.campaign(account, value.campaign_id);
|
|
1701
|
+
const result = await this.request(account, "Campaigns/QueryByIds", { AccountId: account, CampaignIds: [value.campaign_id], CampaignType: known.CampaignType, ReturnAdditionalFields: "TargetSetting" }), campaigns = microsoftRows(result.Campaigns);
|
|
1702
|
+
if (campaigns.length !== 1 || microsoftNativeId(campaigns[0].Id) !== value.campaign_id || campaigns[0].CampaignType !== known.CampaignType || typeof campaigns[0].Status !== "string") throw new AdportError12("PROVIDER_ERROR", "microsoft: audience target campaign context is unavailable or mismatched");
|
|
1703
|
+
const campaign = campaigns[0];
|
|
1704
|
+
let group;
|
|
1705
|
+
if (value.type === "AdGroup") {
|
|
1706
|
+
if (campaign.CampaignType === "PerformanceMax") throw new AdportError12("INVALID_INPUT", "microsoft: Performance Max audiences use campaign exclusions or asset-group signals, not ordinary ad-group criteria");
|
|
1707
|
+
const groups2 = microsoftRows((await this.request(account, "AdGroups/QueryByIds", { CampaignId: value.campaign_id, AdGroupIds: [value.ad_group_id], ReturnAdditionalFields: "AdGroupType" })).AdGroups);
|
|
1708
|
+
if (groups2.length !== 1 || microsoftNativeId(groups2[0].Id) !== value.ad_group_id || typeof groups2[0].Status !== "string") throw new AdportError12("INVALID_INPUT", "microsoft: ad group was not found in the selected campaign/account");
|
|
1709
|
+
group = groups2[0];
|
|
1710
|
+
}
|
|
1711
|
+
const entity = group ?? campaign, settings = microsoftRows(entity.Settings), targetSettings = settings.filter(isTargetSetting);
|
|
1712
|
+
if (targetSettings.length > 1) throw new AdportError12("PROVIDER_ERROR", "microsoft: duplicate target settings in the selected entity");
|
|
1713
|
+
const details = orderedDetails(microsoftRows(targetSettings[0]?.Details));
|
|
1714
|
+
if (details.some((value2) => typeof value2.CriterionTypeGroup !== "string" || typeof value2.TargetAndBid !== "boolean") || new Set(details.map((value2) => value2.CriterionTypeGroup)).size !== details.length) throw new AdportError12("PROVIDER_ERROR", "microsoft: target-setting details are incomplete or duplicated");
|
|
1715
|
+
const targetAndBid = details.find((value2) => value2.CriterionTypeGroup === "Audience")?.TargetAndBid === true;
|
|
1716
|
+
const visible = { account_id: account, target: value, campaign_status: campaign.Status, ...group ? { ad_group_status: String(group.Status) } : {}, target_and_bid: targetAndBid, audience_target_option: targetAndBid ? "TargetAndBid" : "BidOnly" };
|
|
1717
|
+
return { campaign, group, entity, settings, targetSettings, details, context: { ...visible, context_hash: digest2({ ...visible, targetSettings }) } };
|
|
1718
|
+
}
|
|
1719
|
+
async query(account, value, type) {
|
|
1720
|
+
const kind2 = prefix(value), result = await this.request(account, `${kind2}Criterions/QueryByIds`, { [`${kind2}Id`]: entityId(value), [`${kind2}CriterionIds`]: null, CriterionType: selectors[type] });
|
|
1721
|
+
if (!Object.hasOwn(result, `${kind2}Criterions`)) throw new AdportError12("PROVIDER_ERROR", "microsoft: audience criterion response envelope is missing");
|
|
1722
|
+
const values = microsoftRows(result[`${kind2}Criterions`]);
|
|
1723
|
+
if (new Set(values.map((value2) => microsoftNativeId(value2.Id))).size !== values.length || values.some((criterion) => microsoftNativeId(criterion[`${kind2}Id`]) !== entityId(value) || ![`Biddable${kind2}Criterion`, `Negative${kind2}Criterion`].includes(String(criterion.Type)) || !["Audience", "AudienceCriterion"].includes(String(microsoftRow(criterion.Criterion).Type)) || microsoftRow(criterion.Criterion).AudienceType !== type)) throw new AdportError12("PROVIDER_ERROR", "microsoft: native audience criterion ownership or type mismatch");
|
|
1724
|
+
return values.filter((value2) => value2.Status !== "Deleted");
|
|
1725
|
+
}
|
|
1726
|
+
snapshot(value, contextHash) {
|
|
1727
|
+
return digest2({ contextHash, value });
|
|
1728
|
+
}
|
|
1729
|
+
async list(input) {
|
|
1730
|
+
const current = await this.entity(input.account_id, input.target), values = (await this.query(input.account_id, input.target, input.audience_type)).filter((value) => !input.after_criterion_id || BigInt(microsoftNativeId(value.Id)) > BigInt(input.after_criterion_id)).sort((a, b) => BigInt(microsoftNativeId(a.Id)) < BigInt(microsoftNativeId(b.Id)) ? -1 : 1), page = values.slice(0, input.limit), truncated = values.length > page.length;
|
|
1731
|
+
return { context: current.context, rows: page.map((value) => ({ criterion: value, snapshot_hash: this.snapshot(value, current.context.context_hash) })), truncated, ...truncated ? { next_cursor: microsoftNativeId(page.at(-1).Id) } : {} };
|
|
1732
|
+
}
|
|
1733
|
+
async all(account, value) {
|
|
1734
|
+
const results = [];
|
|
1735
|
+
for (let i = 0; i < audienceType2.options.length; i += 4) results.push(...(await Promise.all(audienceType2.options.slice(i, i + 4).map((type) => this.query(account, value, type)))).flat());
|
|
1736
|
+
return results;
|
|
1737
|
+
}
|
|
1738
|
+
async exclusive(account, value) {
|
|
1739
|
+
let opposite;
|
|
1740
|
+
if (value.type === "AdGroup") opposite = [{ type: "Campaign", campaign_id: value.campaign_id }];
|
|
1741
|
+
else {
|
|
1742
|
+
const result = await this.request(account, "AdGroups/QueryByCampaignId", { CampaignId: value.campaign_id });
|
|
1743
|
+
if (!Object.hasOwn(result, "AdGroups")) throw new AdportError12("PROVIDER_ERROR", "microsoft: opposite-level audience check lacks the ad-group inventory");
|
|
1744
|
+
const groups2 = microsoftRows(result.AdGroups);
|
|
1745
|
+
if (groups2.length > 50 || new Set(groups2.map((value2) => microsoftNativeId(value2.Id))).size !== groups2.length) throw new AdportError12("INVALID_INPUT", "microsoft: opposite-level audience check exceeds 50 ad groups or contains duplicate IDs; no association submitted");
|
|
1746
|
+
opposite = groups2.map((group) => ({ type: "AdGroup", campaign_id: value.campaign_id, ad_group_id: microsoftNativeId(group.Id) }));
|
|
1747
|
+
}
|
|
1748
|
+
for (const entity of opposite) if ((await this.all(account, entity)).some((value2) => String(value2.Type).startsWith("Biddable"))) throw new AdportError12("INVALID_INPUT", "microsoft: positive audience targets already exist at the opposite campaign/ad-group level; remove them before changing levels");
|
|
1749
|
+
}
|
|
1750
|
+
async confirm(ids, check) {
|
|
1751
|
+
try {
|
|
1752
|
+
if (await check()) return ids;
|
|
1753
|
+
} catch {
|
|
1754
|
+
}
|
|
1755
|
+
throw new AdportError12("PROVIDER_ERROR", "microsoft: audience targeting write was accepted but readback was not confirmed; reconcile before retrying", { resourceIds: ids });
|
|
1756
|
+
}
|
|
1757
|
+
async plan(op, guard) {
|
|
1758
|
+
const expectedKind = op.tool === "microsoft_add_audience_target" ? "create" : op.tool === "microsoft_remove_audience_target" ? "remove" : "update";
|
|
1759
|
+
if (op.provider !== "microsoft" || !MICROSOFT_AUDIENCE_TARGETING_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError12("INVALID_INPUT", "microsoft: audience targeting operation kind mismatch");
|
|
1760
|
+
const account = op.accountId;
|
|
1761
|
+
if (op.tool === "microsoft_set_audience_target_mode") {
|
|
1762
|
+
const input2 = mode.parse(op.payload), current2 = await this.entity(account, input2.target, true);
|
|
1763
|
+
if (current2.campaign.CampaignType === "PerformanceMax") throw new AdportError12("INVALID_INPUT", "microsoft: Performance Max does not support TargetSetting; use campaign exclusions or asset-group signals");
|
|
1764
|
+
if (current2.context.context_hash !== input2.expected_context_hash) throw new AdportError12("PENDING_MISMATCH", "microsoft: audience parent context changed; request a fresh preview");
|
|
1765
|
+
if (current2.targetSettings.some((setting) => Object.entries(setting).some(([key, value]) => !["Type", "Details"].includes(key) && value !== null && value !== void 0))) throw new AdportError12("INVALID_INPUT", "microsoft: an unsupported target-setting property prevents a safe replacement");
|
|
1766
|
+
const details = orderedDetails([...current2.details.filter((value) => value.CriterionTypeGroup !== "Audience"), ...input2.target_and_bid ? [{ CriterionTypeGroup: "Audience", TargetAndBid: true }] : []]), fields2 = { Id: entityId(input2.target), Settings: [{ Type: "TargetSetting", Details: details.length ? details : null }] };
|
|
1767
|
+
const body = input2.target.type === "Campaign" ? { AccountId: account, Campaigns: [fields2] } : { CampaignId: input2.target.campaign_id, AdGroups: [fields2] };
|
|
1768
|
+
return { summary: `Set Microsoft ${input2.target.type} "${String(current2.entity.Name ?? entityId(input2.target))}" audience delivery option`, changes: [`~ ${JSON.stringify(fields2)}`, "Applies to every positive audience on this entity. Other target groups and other settings are preserved; exclusions and serving status are unchanged."], fieldChanges: [{ field: "Audience delivery option", before: current2.context.audience_target_option, after: input2.target_and_bid ? "TargetAndBid" : "BidOnly" }], notes: notices, coercions: [], budgetDeltas: [], execute: async () => {
|
|
1769
|
+
await this.request(account, input2.target.type === "Campaign" ? "Campaigns" : "AdGroups", body, "PUT");
|
|
1770
|
+
return this.confirm([entityId(input2.target)], async () => {
|
|
1771
|
+
const after = await this.entity(account, input2.target);
|
|
1772
|
+
return after.context.target_and_bid === input2.target_and_bid && digest2(after.details.filter((value) => value.CriterionTypeGroup !== "Audience")) === digest2(current2.details.filter((value) => value.CriterionTypeGroup !== "Audience")) && digest2(after.settings.filter((value) => !isTargetSetting(value))) === digest2(current2.settings.filter((value) => !isTargetSetting(value))) && after.context.campaign_status === current2.context.campaign_status && after.context.ad_group_status === current2.context.ad_group_status;
|
|
1773
|
+
});
|
|
1774
|
+
} };
|
|
1775
|
+
}
|
|
1776
|
+
if (op.tool === "microsoft_add_audience_target") {
|
|
1777
|
+
const input2 = add3.parse(op.payload), current2 = await this.entity(account, input2.target, true), source = await this.source(account, input2.audience_id, input2.audience_type);
|
|
1778
|
+
if (source.snapshot_hash !== input2.expected_audience_snapshot_hash) throw new AdportError12("PENDING_MISMATCH", "microsoft: audience definition changed; read its current snapshot and request a fresh preview");
|
|
1779
|
+
if (current2.campaign.CampaignType === "PerformanceMax" && !input2.exclude) throw new AdportError12("INVALID_INPUT", "microsoft: Performance Max audience criteria support exclusions only; positive audiences use asset-group signals");
|
|
1780
|
+
if (guard.forcePausedCreation && current2.campaign.Status !== "Paused" && current2.group?.Status !== "Paused") throw new AdportError12("POLICY_VIOLATION", "microsoft: audience criteria are natively Active; paused_creation requires a paused campaign or ad group");
|
|
1781
|
+
if (!input2.exclude && current2.context.target_and_bid !== input2.expected_target_and_bid) throw new AdportError12("PENDING_MISMATCH", "microsoft: audience target mode changed; request a fresh preview");
|
|
1782
|
+
if ((await this.query(account, input2.target, input2.audience_type)).some((value) => microsoftNativeId(microsoftRow(value.Criterion).AudienceId) === input2.audience_id)) throw new AdportError12("INVALID_INPUT", "microsoft: this audience is already associated or excluded at the selected level");
|
|
1783
|
+
if (!input2.exclude) await this.exclusive(account, input2.target);
|
|
1784
|
+
const kind3 = prefix(input2.target), percent = input2.bid_adjustment_percent ?? 0, fields2 = { [`${kind3}Id`]: entityId(input2.target), Type: `${input2.exclude ? "Negative" : "Biddable"}${kind3}Criterion`, Criterion: { Type: "AudienceCriterion", AudienceId: input2.audience_id }, ...!input2.exclude ? { CriterionBid: { Type: "BidMultiplier", Multiplier: percent } } : {} };
|
|
1785
|
+
return { summary: `${input2.exclude ? "Exclude" : "Associate"} Microsoft audience "${String(source.audience.Name ?? input2.audience_id)}"`, changes: [`+ ${JSON.stringify(fields2)}`, `Parent audience delivery option remains ${current2.context.audience_target_option}. No source-definition, target-mode or parent-status changes.`], fieldChanges: [{ field: "Audience", before: "(unattached)", after: `${String(source.audience.Name ?? "")} (${input2.audience_id})` }, { field: "Parent", before: "(unattached)", after: `${input2.target.type} ${String(current2.entity.Name ?? "")} (${entityId(input2.target)})` }, { field: "Association", before: "(none)", after: input2.exclude ? "Exclude" : `${current2.context.audience_target_option}, bid adjustment ${percent}%` }], notes: notices, coercions: [], budgetDeltas: [], execute: async () => {
|
|
1786
|
+
const result = await this.request(account, `${kind3}Criterions`, { [`${kind3}Criterions`]: [fields2], CriterionType: "Audience" }), ids = Array.isArray(result[`${kind3}CriterionIds`]) ? result[`${kind3}CriterionIds`].filter((value) => value !== null).map(microsoftNativeId) : [];
|
|
1787
|
+
if (ids.length !== 1) throw new AdportError12("PROVIDER_ERROR", "microsoft: audience criterion receipt mismatch; reconcile before retrying", { resourceIds: ids });
|
|
1788
|
+
return this.confirm(ids, async () => {
|
|
1789
|
+
const actual = (await this.query(account, input2.target, input2.audience_type)).find((value) => microsoftNativeId(value.Id) === ids[0]);
|
|
1790
|
+
return !!actual && actual.Type === fields2.Type && microsoftNativeId(microsoftRow(actual.Criterion).AudienceId) === input2.audience_id && (input2.exclude || microsoftRow(actual.CriterionBid).Type === "BidMultiplier" && microsoftRow(actual.CriterionBid).Multiplier === percent);
|
|
1791
|
+
});
|
|
1792
|
+
} };
|
|
1793
|
+
}
|
|
1794
|
+
const input = (op.tool === "microsoft_set_audience_target_bid" ? bid2 : reference5).parse(op.payload), current = await this.entity(account, input.target, true), criterion = (await this.query(account, input.target, input.audience_type)).find((value) => microsoftNativeId(value.Id) === input.criterion_id);
|
|
1795
|
+
if (!criterion) throw new AdportError12("INVALID_INPUT", "microsoft: audience criterion was not found in the selected entity/account/type");
|
|
1796
|
+
if (this.snapshot(criterion, current.context.context_hash) !== input.expected_snapshot_hash) throw new AdportError12("PENDING_MISMATCH", "microsoft: audience criterion or parent context changed; request a fresh preview");
|
|
1797
|
+
const kind2 = prefix(input.target);
|
|
1798
|
+
if (op.tool === "microsoft_set_audience_target_bid") {
|
|
1799
|
+
const value = bid2.parse(input);
|
|
1800
|
+
if (criterion.Type !== `Biddable${kind2}Criterion` || microsoftRow(criterion.CriterionBid).Type !== "BidMultiplier") throw new AdportError12("INVALID_INPUT", "microsoft: only biddable audience criteria with BidMultiplier accept a bid edit");
|
|
1801
|
+
const fields2 = { [`${kind2}Id`]: entityId(input.target), Id: input.criterion_id, Type: `Biddable${kind2}Criterion`, CriterionBid: { Type: "BidMultiplier", Multiplier: value.bid_adjustment_percent } };
|
|
1802
|
+
return { summary: `Set Microsoft audience ${microsoftNativeId(microsoftRow(criterion.Criterion).AudienceId)} bid adjustment on ${kind2} "${String(current.entity.Name ?? entityId(input.target))}"`, changes: [`~ ${JSON.stringify(fields2)}`], fieldChanges: [{ field: "Bid adjustment", before: `${microsoftRow(criterion.CriterionBid).Multiplier}%`, after: `${value.bid_adjustment_percent}%` }], notes: notices, coercions: [], budgetDeltas: [], execute: async () => {
|
|
1803
|
+
await this.request(account, `${kind2}Criterions`, { [`${kind2}Criterions`]: [fields2], CriterionType: "Audience" }, "PUT");
|
|
1804
|
+
return this.confirm([input.criterion_id], async () => {
|
|
1805
|
+
const actual = (await this.query(account, input.target, input.audience_type)).find((value2) => microsoftNativeId(value2.Id) === input.criterion_id);
|
|
1806
|
+
return !!actual && actual.Type === criterion.Type && digest2(actual.Criterion) === digest2(criterion.Criterion) && microsoftRow(actual.CriterionBid).Multiplier === value.bid_adjustment_percent;
|
|
1807
|
+
});
|
|
1808
|
+
} };
|
|
1809
|
+
}
|
|
1810
|
+
return { summary: `Remove Microsoft audience association from ${kind2} "${String(current.entity.Name ?? entityId(input.target))}"`, changes: [`- ${JSON.stringify(criterion)}`, "Removing a positive association or an exclusion can change delivery. Parent target mode, status and other criterion IDs are preserved."], fieldChanges: [{ field: "Audience association", before: `${String(criterion.Type).startsWith("Negative") ? "Exclude" : "Positive"} audience ${microsoftNativeId(microsoftRow(criterion.Criterion).AudienceId)} (criterion ${input.criterion_id})`, after: "Removed" }], notes: notices, coercions: [], budgetDeltas: [], execute: async () => {
|
|
1811
|
+
await this.request(account, `${kind2}Criterions`, { [`${kind2}Id`]: entityId(input.target), [`${kind2}CriterionIds`]: [input.criterion_id], CriterionType: "Audience" }, "DELETE");
|
|
1812
|
+
return this.confirm([input.criterion_id], async () => !(await this.query(account, input.target, input.audience_type)).some((value) => microsoftNativeId(value.Id) === input.criterion_id));
|
|
1813
|
+
} };
|
|
1814
|
+
}
|
|
1815
|
+
};
|
|
1816
|
+
function microsoftAudienceTargetingTools(provider) {
|
|
1817
|
+
return [
|
|
1818
|
+
defineTool9({ name: "microsoft_audience_targets", namespace: "microsoft", description: "Read campaign or ad-group audience associations/exclusions of one concrete audience type. Returns native criteria, snapshots and verified parent target-mode/status context. Campaign TargetSetting is explicitly requested. Continue next_cursor as after_criterion_id.", input: z11.object({ account_id: microsoftId, target: target5, audience_type: audienceType2, after_criterion_id: microsoftId.optional(), limit: z11.number().int().positive().max(1e3).default(100) }), output: z11.object({ context, rows: z11.array(z11.object({ criterion: z11.record(z11.string(), z11.unknown()), snapshot_hash: hash3 })), truncated: z11.boolean(), next_cursor: microsoftId.optional() }), pagination: { cursorInput: "after_criterion_id" }, annotations: { readOnly: true }, handler: (input) => provider.audienceTargeting.list(input) }),
|
|
1819
|
+
guardedWriteTool8({ name: "microsoft_add_audience_target", namespace: "microsoft", provider: "microsoft", kind: "create", description: "Associate or exclude an account-available audience with expected_audience_snapshot_hash. Positive criteria require expected_target_and_bid from target reads and a complete opposite-level check, bounded to 50 ad groups. Preserves parent mode/status; native Active criteria require an effectively paused parent under paused_creation. Performance Max supports campaign exclusions only.", payload: add3 }),
|
|
1820
|
+
guardedWriteTool8({ name: "microsoft_set_audience_target_bid", namespace: "microsoft", provider: "microsoft", kind: "update", description: "Edit an owned positive audience criterion percentage adjustment (-90..900, integer) with expected_snapshot_hash. Preserves audience identity, delivery mode and parent status. Exclusions do not accept bids.", payload: bid2 }),
|
|
1821
|
+
guardedWriteTool8({ name: "microsoft_remove_audience_target", namespace: "microsoft", provider: "microsoft", kind: "remove", description: "Remove an exact owned audience association/exclusion with expected_snapshot_hash. This can broaden or narrow delivery; preserves target mode and other criteria. Confirms disappearance before reporting success.", payload: reference5 }),
|
|
1822
|
+
guardedWriteTool8({ name: "microsoft_set_audience_target_mode", namespace: "microsoft", provider: "microsoft", kind: "update", description: "Set TargetAndBid (restrict positive audience delivery) or BidOnly (bid adjustment without that restriction) with expected_context_hash from target reads. Preserves all other target-setting details and other settings; affects all positive audiences on that entity. Performance Max uses signals and exclusions instead.", payload: mode })
|
|
1823
|
+
];
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
// src/offline-reports.ts
|
|
1827
|
+
import { AdportError as AdportError13, defineTool as defineTool10 } from "@adport/core";
|
|
1828
|
+
import { z as z12 } from "zod";
|
|
1829
|
+
var range = z12.object({ start_utc: z12.iso.datetime(), end_utc: z12.iso.datetime() }).refine((value) => {
|
|
1830
|
+
const span = Date.parse(value.end_utc) - Date.parse(value.start_utc);
|
|
1831
|
+
return span >= 0 && span <= 7 * 864e5;
|
|
1832
|
+
}, "Use an ordered UTC interval of at most seven days");
|
|
1833
|
+
var accountInput = z12.object({ account_id: microsoftId, date_range: range });
|
|
1834
|
+
var channels = z12.enum(["CampaignManagementAPI", "BulkAPI", "WebUpload", "Unknown"]);
|
|
1835
|
+
var goalInput = accountInput.extend({ goal_ids: z12.array(microsoftId).min(1).max(20).refine((value) => new Set(value).size === value.length, "Goal IDs must be unique"), upload_channels: z12.array(channels).min(1).refine((value) => new Set(value).size === value.length && (!value.includes("Unknown") || value.length === 1), "Use unique channels; Unknown cannot be combined with other channels").optional() });
|
|
1836
|
+
var count = z12.union([z12.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), z12.string().regex(/^\d+$/)]);
|
|
1837
|
+
var rate = z12.union([z12.number().min(0).max(1), z12.string().regex(/^(?:0(?:\.\d+)?|1(?:\.0+)?)$/)]);
|
|
1838
|
+
var optionalCount = count.nullable().optional();
|
|
1839
|
+
var alert = z12.object({ Count: optionalCount, UnattributedReason: z12.string().nullable().optional() });
|
|
1840
|
+
var goalId = z12.preprocess(microsoftNativeId, microsoftId);
|
|
1841
|
+
var day = z12.object({ GoalId: goalId, UploadDate: z12.string(), SuccessCount: optionalCount, UnattributedCount: optionalCount, SuccessRate: rate.nullable().optional(), Alerts: z12.array(alert).nullable().optional() });
|
|
1842
|
+
var summary = z12.object({ GoalId: goalId, ConversionName: z12.string().nullable().optional(), OverallSuccessCount: optionalCount, OverallUnattributedCount: optionalCount, OverallSuccessRate: rate.nullable().optional(), OverallAlerts: z12.array(alert).nullable().optional(), DailySummaries: z12.array(day).nullable().optional() });
|
|
1843
|
+
var daily = z12.object({ UploadDate: z12.string(), SuccessCount: optionalCount, FailureCount: optionalCount, FileUrlExpiryTimeUtc: z12.string().nullable().optional(), file_available: z12.boolean() });
|
|
1844
|
+
var partialError = z12.object({ index: z12.number().int().nonnegative().optional(), goal_id: microsoftId.optional(), code: z12.number().int().optional(), error_code: z12.string().optional() });
|
|
1845
|
+
var accountOutput = z12.object({ account_id: microsoftId, date_range: range, rows: z12.array(daily), notes: z12.array(z12.string()) });
|
|
1846
|
+
var goalOutput = z12.object({ account_id: microsoftId, date_range: range, rows: z12.array(summary), errors: z12.array(partialError), not_returned_goal_ids: z12.array(microsoftId), notes: z12.array(z12.string()) });
|
|
1847
|
+
var notes4 = ["Read-only upload diagnostics, not campaign performance or proof of incremental attribution. Counts preserve native strings and missing values; success rates are ratios, not percentages.", "Input boundaries are UTC. Native UploadDate values are preserved; Microsoft documents DailySummary.UploadDate as local time. No conversion events are submitted."];
|
|
1848
|
+
var MicrosoftOfflineReportService = class extends MicrosoftNativeService {
|
|
1849
|
+
async daily(input) {
|
|
1850
|
+
const result = await this.request(input.account_id, "OfflineConversionReports/Query", { StartDateUtc: input.date_range.start_utc, EndDateUtc: input.date_range.end_utc });
|
|
1851
|
+
if (!Object.hasOwn(result, "DailySummaries")) throw new AdportError13("PROVIDER_ERROR", "microsoft: offline upload report envelope is missing");
|
|
1852
|
+
const values = microsoftRows(result.DailySummaries).map((value) => {
|
|
1853
|
+
if (!Object.hasOwn(value, "SuccessCount") && !Object.hasOwn(value, "FailureCount")) throw new AdportError13("PROVIDER_ERROR", "microsoft: offline report lacks aggregate counts; event-level records are not exposed by this tool");
|
|
1854
|
+
return daily.parse({ ...value, file_available: typeof value.FileUrl === "string" && value.FileUrl.length > 0 });
|
|
1855
|
+
});
|
|
1856
|
+
return accountOutput.parse({ account_id: input.account_id, date_range: input.date_range, rows: values, notes: [...notes4, "Signed FileUrl values and pilot event/customer fields are omitted. This tool does not download raw conversion files."] });
|
|
1857
|
+
}
|
|
1858
|
+
async goals(input) {
|
|
1859
|
+
const available = microsoftRows((await this.request(input.account_id, "ConversionGoals/QueryByIds", { ConversionGoalIds: input.goal_ids, ConversionGoalTypes: "OfflineConversion" })).ConversionGoals);
|
|
1860
|
+
if (available.length !== input.goal_ids.length || new Set(available.map((value) => microsoftNativeId(value.Id))).size !== available.length || available.some((value) => value.Type !== "OfflineConversion" || !input.goal_ids.includes(microsoftNativeId(value.Id)))) throw new AdportError13("INVALID_INPUT", "microsoft: requested offline goals are not all available in the selected account");
|
|
1861
|
+
const scope = await this.accountScope(input.account_id);
|
|
1862
|
+
const result = await this.client.request("campaign", "POST", "OfflineConversionReport/QueryByGoalIds", { StartDateUtc: input.date_range.start_utc, EndDateUtc: input.date_range.end_utc, GoalIds: input.goal_ids, UploadChannelFilter: input.upload_channels?.join(", ") ?? null }, scope);
|
|
1863
|
+
if (!Object.hasOwn(result, "OfflineGoalConversionSummaries") || result.NestedPartialErrors !== void 0 && result.NestedPartialErrors !== null && (!Array.isArray(result.NestedPartialErrors) || result.NestedPartialErrors.some(Boolean))) throw new AdportError13("PROVIDER_ERROR", "microsoft: offline goal report envelope is missing or contains unsupported nested errors");
|
|
1864
|
+
const values = microsoftRows(result.OfflineGoalConversionSummaries).map((value) => summary.parse(value));
|
|
1865
|
+
if (new Set(values.map((value) => value.GoalId)).size !== values.length || values.some((value) => !input.goal_ids.includes(value.GoalId) || value.DailySummaries?.some((day2) => day2.GoalId !== value.GoalId))) throw new AdportError13("PROVIDER_ERROR", "microsoft: offline report returned an unexpected or duplicate goal identity");
|
|
1866
|
+
const errors = z12.array(z12.record(z12.string(), z12.unknown()).nullable()).parse(result.PartialErrors ?? []).filter((value) => value !== null).map((value) => {
|
|
1867
|
+
if (value.Index !== void 0 && value.Index !== null && (!Number.isInteger(value.Index) || Number(value.Index) < 0 || Number(value.Index) >= input.goal_ids.length)) throw new AdportError13("PROVIDER_ERROR", "microsoft: offline report error index is outside the requested goals");
|
|
1868
|
+
if (typeof value.Code !== "number" && typeof value.ErrorCode !== "string") throw new AdportError13("PROVIDER_ERROR", "microsoft: malformed offline report partial error");
|
|
1869
|
+
const index = typeof value.Index === "number" ? value.Index : void 0;
|
|
1870
|
+
return partialError.parse({ ...index !== void 0 ? { index, goal_id: input.goal_ids[index] } : {}, ...value.Code !== void 0 ? { code: value.Code } : {}, ...value.ErrorCode !== void 0 ? { error_code: value.ErrorCode } : {} });
|
|
1871
|
+
});
|
|
1872
|
+
return goalOutput.parse({ account_id: input.account_id, date_range: input.date_range, rows: values, errors, not_returned_goal_ids: input.goal_ids.filter((goal) => !values.some((value) => value.GoalId === goal)), notes: [...notes4, "Missing summaries and per-goal errors are explicit; absence does not mean zero conversions. Error messages, details and event/customer fields are omitted."] });
|
|
1873
|
+
}
|
|
1874
|
+
};
|
|
1875
|
+
function microsoftOfflineReportTools(provider) {
|
|
1876
|
+
return [
|
|
1877
|
+
defineTool10({ name: "microsoft_offline_conversion_reports", namespace: "microsoft", description: "Read daily offline-conversion upload success/failure counts in an explicit UTC interval (tool bound: seven days). Preserves native dates/counts; omits signed file URLs and pilot event/customer records. Downloads and event ingestion are separate workflows.", input: accountInput, output: accountOutput, annotations: { readOnly: true }, handler: (input) => provider.offlineReports.daily(input) }),
|
|
1878
|
+
defineTool10({ name: "microsoft_offline_conversion_goal_report", namespace: "microsoft", description: "Read offline conversion attribution diagnostics for up to 20 unique account-available OfflineConversion goals and at most seven days in UTC. Native channel flags are optional CSV filters. Returns aggregate/daily ratios and counts, explicit per-goal errors and missing summaries; never infers zero for missing data.", input: goalInput, output: goalOutput, annotations: { readOnly: true }, handler: (input) => provider.offlineReports.goals(input) })
|
|
1879
|
+
];
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
// src/offline-conversions.ts
|
|
1883
|
+
import { createHash as createHash5 } from "crypto";
|
|
1884
|
+
import { AdportError as AdportError14, guardedWriteTool as guardedWriteTool9 } from "@adport/core";
|
|
1885
|
+
|
|
1886
|
+
// src/offline-conversion-schemas.ts
|
|
1887
|
+
import { z as z13 } from "zod";
|
|
1888
|
+
var offlineTime = z13.iso.datetime().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,7})?Z$/, "Use a UTC timestamp with seconds and at most seven fractional digits");
|
|
1889
|
+
var hash4 = z13.string().regex(/^[a-f0-9]{64}$/);
|
|
1890
|
+
var identifier = z13.string().min(1).max(512).regex(/^[^\s\x00-\x1f\x7f]+$/);
|
|
1891
|
+
var currency = z13.string().regex(/^[A-Z]{3}$/);
|
|
1892
|
+
var identity = z13.object({
|
|
1893
|
+
microsoft_click_id: identifier.optional(),
|
|
1894
|
+
hashed_email_address: hash4.optional(),
|
|
1895
|
+
hashed_phone_number: hash4.optional(),
|
|
1896
|
+
conversion_time: offlineTime
|
|
1897
|
+
}).strict();
|
|
1898
|
+
var identified = (value) => !!(value.microsoft_click_id || value.hashed_email_address || value.hashed_phone_number);
|
|
1899
|
+
var offlineConversion = identity.extend({
|
|
1900
|
+
conversion_value: z13.number().finite().optional(),
|
|
1901
|
+
conversion_currency_code: currency.optional(),
|
|
1902
|
+
external_attribution_credit: z13.number().finite().gt(0).max(1).optional(),
|
|
1903
|
+
external_attribution_model: z13.string().min(1).max(512).optional()
|
|
1904
|
+
}).strict().refine(identified, "Supply a Microsoft click ID or an already hashed email/phone identifier");
|
|
1905
|
+
var adjustment3 = identity.extend({ adjustment_time: offlineTime });
|
|
1906
|
+
var offlineAdjustment = z13.discriminatedUnion("adjustment_type", [
|
|
1907
|
+
adjustment3.extend({ adjustment_type: z13.literal("Restate"), adjustment_value: z13.number().finite(), adjustment_currency_code: currency }).strict(),
|
|
1908
|
+
adjustment3.extend({ adjustment_type: z13.literal("Retract") }).strict()
|
|
1909
|
+
]).refine(identified, "Supply the original Microsoft click ID or already hashed email/phone identifiers");
|
|
1910
|
+
var binding = z13.object({
|
|
1911
|
+
goal_id: microsoftId,
|
|
1912
|
+
expected_goal_hash: hash4,
|
|
1913
|
+
acknowledge_measurement_effects: z13.literal(true)
|
|
1914
|
+
}).strict();
|
|
1915
|
+
var offlineUpload = binding.extend({ conversions: z13.array(offlineConversion).min(1).max(1e3) }).strict();
|
|
1916
|
+
var offlineAdjustments = binding.extend({ adjustments: z13.array(offlineAdjustment).min(1).max(1e3) }).strict();
|
|
1917
|
+
function offlineTimeTicks(value) {
|
|
1918
|
+
const [whole, fraction = ""] = value.slice(0, -1).split(".");
|
|
1919
|
+
return BigInt(Date.parse(`${whole}Z`)) * 10000n + BigInt(fraction.padEnd(7, "0"));
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
// src/offline-conversions.ts
|
|
1923
|
+
var MICROSOFT_OFFLINE_CONVERSION_WRITES = /* @__PURE__ */ new Set(["microsoft_upload_offline_conversions", "microsoft_upload_offline_conversion_adjustments"]);
|
|
1924
|
+
var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1925
|
+
var canonical4 = (value) => Array.isArray(value) ? value.map(canonical4) : record(value) ? Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical4(item)])) : value;
|
|
1926
|
+
var digest3 = (value) => createHash5("sha256").update(JSON.stringify(canonical4(value))).digest("hex");
|
|
1927
|
+
var wireFields = { microsoft_click_id: "MicrosoftClickId", hashed_email_address: "HashedEmailAddress", hashed_phone_number: "HashedPhoneNumber", conversion_time: "ConversionTime", conversion_value: "ConversionValue", conversion_currency_code: "ConversionCurrencyCode", external_attribution_credit: "ExternalAttributionCredit", external_attribution_model: "ExternalAttributionModel", adjustment_time: "AdjustmentTime", adjustment_type: "AdjustmentType", adjustment_value: "AdjustmentValue", adjustment_currency_code: "AdjustmentCurrencyCode" };
|
|
1928
|
+
var notes5 = [
|
|
1929
|
+
"This is a local preview. Microsoft has no dry run for offline imports or adjustments; no event is sent until apply.",
|
|
1930
|
+
"Events and adjustments can affect measured revenue, conversion counts and automated bidding. This tool preserves goal configuration, account auto-tagging, campaign status and budgets.",
|
|
1931
|
+
"Wait two hours after creating a goal. Receipt acceptance does not prove matching, attribution or reporting; reporting can take six hours. Click time and conversion-window eligibility cannot be checked from these inputs.",
|
|
1932
|
+
"Native deduplication retains the first original conversion for the same goal/click/time. Use a restatement or retraction to change a prior conversion. No global Adport event ledger or per-event readback is available.",
|
|
1933
|
+
"Approval is single-attempt. Failed or unknown rows are never retried automatically; reconcile batch SHA-256, original row indexes and aggregate upload diagnostics before requesting another preview.",
|
|
1934
|
+
"Private identifiers are omitted from previews, receipts and audit summaries. Full arguments are stored in the private pending approval; the agent applies them without copying them into the widget."
|
|
1935
|
+
];
|
|
1936
|
+
function outcome(value, count2) {
|
|
1937
|
+
const errors = [];
|
|
1938
|
+
let unmapped = 0, verified = record(value) && Object.keys(value).every((key) => key === "PartialErrors");
|
|
1939
|
+
const partial = record(value) ? value.PartialErrors : void 0;
|
|
1940
|
+
if (partial !== void 0 && partial !== null && !Array.isArray(partial)) verified = false;
|
|
1941
|
+
if (Array.isArray(partial)) {
|
|
1942
|
+
if (partial.length > 2e4) {
|
|
1943
|
+
verified = false;
|
|
1944
|
+
unmapped++;
|
|
1945
|
+
}
|
|
1946
|
+
for (const item of partial.slice(0, 2e4)) {
|
|
1947
|
+
if (item === null) continue;
|
|
1948
|
+
if (!record(item) || !Number.isInteger(item.Index) || Number(item.Index) < 0 || Number(item.Index) >= count2 || !Number.isSafeInteger(item.Code) || Number(item.Code) <= 0) {
|
|
1949
|
+
unmapped++;
|
|
1950
|
+
continue;
|
|
1951
|
+
}
|
|
1952
|
+
errors.push({ index: Number(item.Index), code: Number(item.Code) });
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
const failed = new Set(errors.map((error) => error.index));
|
|
1956
|
+
const rows3 = Array.from({ length: count2 }, (_, index) => ({ index, status: failed.has(index) ? "FAILED" : verified && !unmapped ? "ACCEPTED" : "UNKNOWN" }));
|
|
1957
|
+
return { receipt_verified: verified && !unmapped, accepted_count: rows3.filter((row) => row.status === "ACCEPTED").length, failed_count: failed.size, unknown_count: rows3.filter((row) => row.status === "UNKNOWN").length, rows: rows3, errors, unmapped_error_count: unmapped };
|
|
1958
|
+
}
|
|
1959
|
+
var MicrosoftOfflineConversionService = class extends MicrosoftNativeService {
|
|
1960
|
+
constructor(client, scope, campaign, conversions) {
|
|
1961
|
+
super(client, scope, campaign);
|
|
1962
|
+
this.conversions = conversions;
|
|
1963
|
+
}
|
|
1964
|
+
conversions;
|
|
1965
|
+
async plan(op) {
|
|
1966
|
+
const adjusting = op.tool === "microsoft_upload_offline_conversion_adjustments";
|
|
1967
|
+
if (op.provider !== "microsoft" || !MICROSOFT_OFFLINE_CONVERSION_WRITES.has(op.tool) || op.kind !== (adjusting ? "update" : "create")) throw new AdportError14("INVALID_INPUT", "microsoft: offline conversion operation provider/kind mismatch");
|
|
1968
|
+
const input = adjusting ? offlineAdjustments.parse(op.payload) : offlineUpload.parse(op.payload);
|
|
1969
|
+
const scope = await this.accountScope(op.accountId, true), current = await this.conversions.get(op.accountId, input.goal_id, "OfflineConversion");
|
|
1970
|
+
if (current.snapshot_hash !== input.expected_goal_hash) throw new AdportError14("PENDING_MISMATCH", "microsoft: offline goal or auto-tagging configuration changed; read it and preview again");
|
|
1971
|
+
const goal = current.goal;
|
|
1972
|
+
if (goal.Type !== "OfflineConversion" || !["Account", "Customer"].includes(String(goal.Scope)) || !["Active", "Paused"].includes(String(goal.Status)) || typeof goal.Name !== "string" || !goal.Name.trim()) throw new AdportError14("INVALID_INPUT", "microsoft: an available Account/Customer offline goal with a concrete name and status is required");
|
|
1973
|
+
const source = "conversions" in input ? input.conversions : input.adjustments;
|
|
1974
|
+
const now = BigInt(Date.now()) * 10000n, maxAge = 90n * 86400n * 10000000n, identities = /* @__PURE__ */ new Set();
|
|
1975
|
+
for (const row of source) {
|
|
1976
|
+
const time = offlineTimeTicks(String(row.conversion_time));
|
|
1977
|
+
if (time > now || time < now - maxAge) throw new AdportError14("INVALID_INPUT", "microsoft: original conversion times must be in UTC within the last90days and not in the future");
|
|
1978
|
+
if (adjusting && (offlineTimeTicks(String(row.adjustment_time)) < time || offlineTimeTicks(String(row.adjustment_time)) > now)) throw new AdportError14("INVALID_INPUT", "microsoft: adjustment time must be at/after the original conversion and not in the future");
|
|
1979
|
+
if ((row.hashed_email_address || row.hashed_phone_number) && goal.IsEnhancedConversionsEnabled !== true) throw new AdportError14("INVALID_INPUT", "microsoft: hashed identifiers require an already enabled enhanced-conversion goal; no setting or terms are changed");
|
|
1980
|
+
if ((row.external_attribution_credit !== void 0 || row.external_attribution_model !== void 0) && goal.IsExternallyAttributed !== true) throw new AdportError14("INVALID_INPUT", "microsoft: external attribution fields require a verified externally attributed goal");
|
|
1981
|
+
const identity3 = digest3({ time: time.toString(), ...row.microsoft_click_id ? { click: row.microsoft_click_id } : { email: row.hashed_email_address, phone: row.hashed_phone_number } });
|
|
1982
|
+
if (identities.has(identity3)) throw new AdportError14("INVALID_INPUT", "microsoft: duplicate original conversion identities in this batch; submit at most one operation per original identity");
|
|
1983
|
+
identities.add(identity3);
|
|
1984
|
+
}
|
|
1985
|
+
const bodyRows = source.map((row) => ({ ConversionName: goal.Name, ...Object.fromEntries(Object.entries(row).map(([key, value]) => [wireFields[key], value])) }));
|
|
1986
|
+
const path = adjusting ? "OfflineConversionAdjustments/Apply" : "OfflineConversions/Apply";
|
|
1987
|
+
const body = { [adjusting ? "OfflineConversionAdjustments" : "OfflineConversions"]: bodyRows };
|
|
1988
|
+
const batchHash = digest3({ account: op.accountId, path, body }), count2 = source.length;
|
|
1989
|
+
const valueRanges = /* @__PURE__ */ new Map();
|
|
1990
|
+
for (const row of source) {
|
|
1991
|
+
const value = adjusting ? row.adjustment_value : row.conversion_value;
|
|
1992
|
+
if (typeof value !== "number") continue;
|
|
1993
|
+
const currency2 = String((adjusting ? row.adjustment_currency_code : row.conversion_currency_code) ?? "(goal default)"), previous = valueRanges.get(currency2);
|
|
1994
|
+
valueRanges.set(currency2, { currency: currency2, records: (previous?.records ?? 0) + 1, minimum: Math.min(previous?.minimum ?? value, value), maximum: Math.max(previous?.maximum ?? value, value) });
|
|
1995
|
+
}
|
|
1996
|
+
const changes = [`${count2} ${adjusting ? "adjustments" : "conversions"} for offline goal ${input.goal_id}.`, `Approved native batch SHA-256: ${batchHash}.`, adjusting ? "Restatements replace recorded values; retractions remove previously recorded conversions. Original conversion time identifies the record; adjustment time records the adjustment." : "Omitted conversion value and currency use the goal revenue defaults. Values are whole currency units, not budget micros."];
|
|
1997
|
+
const notices3 = [...notes5, ...goal.Status === "Paused" ? ["This goal is Paused. It stays paused; receipt acceptance does not imply that these records will be counted."] : [], ...record(goal.Revenue) && goal.Revenue.Type === "NoValue" ? ["Goal revenue is NoValue; supplying monetary values does not change the goal into a revenue-tracking goal."] : [], ...!current.auto_tagging_enabled ? ["Click-ID auto-tagging is disabled and remains disabled. An uploaded click ID must already identify a real native click."] : []];
|
|
1998
|
+
let details, warnings = [];
|
|
1999
|
+
return {
|
|
2000
|
+
summary: `${adjusting ? "Adjust" : "Import"} ${count2} Microsoft offline conversion${count2 === 1 ? "" : "s"} \xB7 batch ${batchHash}`,
|
|
2001
|
+
changes,
|
|
2002
|
+
notes: notices3,
|
|
2003
|
+
coercions: [],
|
|
2004
|
+
budgetDeltas: [],
|
|
2005
|
+
review: { provider: "microsoft", accountId: op.accountId, kind: op.kind, title: adjusting ? "Adjust offline conversions" : "Import offline conversions", fields: [
|
|
2006
|
+
{ label: "Goal", after: `${goal.Name} [${input.goal_id}]` },
|
|
2007
|
+
{ label: "Goal scope", after: goal.Scope },
|
|
2008
|
+
{ label: "Goal status", after: goal.Status },
|
|
2009
|
+
{ label: "Records", after: count2 },
|
|
2010
|
+
{ label: "Identifier matching", after: { click_ids: source.filter((row) => row.microsoft_click_id).length, hashed_emails: source.filter((row) => row.hashed_email_address).length, hashed_phones: source.filter((row) => row.hashed_phone_number).length } },
|
|
2011
|
+
...adjusting ? [{ label: "Adjustments", after: { restatements: source.filter((row) => row.adjustment_type === "Restate").length, retractions: source.filter((row) => row.adjustment_type === "Retract").length } }] : [{ label: "Goal revenue defaults", after: goal.Revenue ?? "Not reported" }],
|
|
2012
|
+
{ label: "Explicit value ranges (whole currency units)", after: [...valueRanges.values()] },
|
|
2013
|
+
{ label: "Batch SHA-256", after: batchHash }
|
|
2014
|
+
], notices: notices3 },
|
|
2015
|
+
resultDetails: () => details,
|
|
2016
|
+
resultWarnings: () => warnings,
|
|
2017
|
+
execute: async () => {
|
|
2018
|
+
let result;
|
|
2019
|
+
try {
|
|
2020
|
+
result = await this.client.request("campaign", "POST", path, body, scope, { privatePayload: true });
|
|
2021
|
+
} catch {
|
|
2022
|
+
throw new AdportError14("PROVIDER_ERROR", "microsoft: offline batch outcome is unknown; private native response details were omitted. Reconcile upload diagnostics before another preview. No request was retried.", { batch_sha256: batchHash, target_goal_id: input.goal_id, record_count: count2, ...outcome(null, count2), processed: false });
|
|
2023
|
+
}
|
|
2024
|
+
const receipt = outcome(result, count2);
|
|
2025
|
+
details = { status: receipt.accepted_count ? "ACCEPTED_FOR_PROCESSING" : "PARTIAL_OR_UNCONFIRMED", receipt_status: receipt.accepted_count === count2 ? "ALL_ACCEPTED" : receipt.unknown_count ? "UNCONFIRMED" : "PARTIAL", processed: false, account_id: op.accountId, target_goal_id: input.goal_id, batch_sha256: batchHash, record_count: count2, ...receipt, next_tool: "microsoft_offline_conversion_goal_report" };
|
|
2026
|
+
if (!receipt.accepted_count) throw new AdportError14("PROVIDER_ERROR", "microsoft: no offline records were confirmed accepted. Reconcile the returned row outcomes and native upload diagnostics; no automatic retry.", details);
|
|
2027
|
+
if (receipt.accepted_count < count2) warnings = [`Microsoft accepted ${receipt.accepted_count} of ${count2} rows for processing; ${receipt.failed_count} failed and ${receipt.unknown_count} remain unknown. Acceptance is not attribution. Inspect original row indexes before a new upload.`];
|
|
2028
|
+
return [input.goal_id];
|
|
2029
|
+
}
|
|
2030
|
+
};
|
|
2031
|
+
}
|
|
2032
|
+
};
|
|
2033
|
+
function microsoftOfflineConversionTools(_provider) {
|
|
2034
|
+
const catalog = { category: "measurement", exposure: "specialist" };
|
|
2035
|
+
return [
|
|
2036
|
+
guardedWriteTool9({ name: "microsoft_upload_offline_conversions", namespace: "microsoft", provider: "microsoft", catalog, kind: "create", sensitiveInputs: ["conversions"], description: "Import 1\u20131,000 offline conversions into an existing goal with expected_goal_hash. Local preview sends no events; apply returns sparse indexed failures and acceptance for processing, not attribution. Uses the current exact goal name, preserves its configuration and never retries. Already hashed identifiers require enhanced conversions to be enabled.", payload: offlineUpload }),
|
|
2037
|
+
guardedWriteTool9({ name: "microsoft_upload_offline_conversion_adjustments", namespace: "microsoft", provider: "microsoft", catalog, kind: "update", sensitiveInputs: ["adjustments"], description: "Restate or retract 1\u20131,000 previously imported offline conversions with expected_goal_hash. Original conversion_time identifies each record; adjustment_time records the adjustment. Local preview sends nothing. Returns indexed failures and processing acceptance; no automatic retry or per-event readback.", payload: offlineAdjustments })
|
|
2038
|
+
];
|
|
2039
|
+
}
|
|
2040
|
+
|
|
2041
|
+
// src/general-targeting.ts
|
|
2042
|
+
import { createHash as createHash6 } from "crypto";
|
|
2043
|
+
import { z as z15 } from "zod";
|
|
2044
|
+
import { AdportError as AdportError15, defineTool as defineTool11, guardedWriteTool as guardedWriteTool10 } from "@adport/core";
|
|
2045
|
+
|
|
2046
|
+
// src/general-targeting-schemas.ts
|
|
2047
|
+
import { z as z14 } from "zod";
|
|
2048
|
+
var targetSelection = z14.discriminatedUnion("type", [z14.object({ type: z14.literal("Campaign"), campaign_id: microsoftId }).strict(), z14.object({ type: z14.literal("AdGroup"), campaign_id: microsoftId, ad_group_id: microsoftId }).strict()]);
|
|
2049
|
+
var hash5 = z14.string().regex(/^[a-f0-9]{64}$/);
|
|
2050
|
+
var targetingRead = z14.object({ account_id: microsoftId, target: targetSelection, criterion_types: z14.array(criterionType).min(1).max(7).refine((values) => new Set(values).size === values.length, "Use unique types").default([...criterionType.options]), page_size: z14.number().int().min(1).max(200).default(50), cursor: z14.string().max(2048).optional() }).strict();
|
|
2051
|
+
var change = z14.discriminatedUnion("action", [
|
|
2052
|
+
z14.object({ action: z14.literal("add"), targets: z14.array(target2).min(1).max(1e3) }).strict().superRefine(validateTargetBatch),
|
|
2053
|
+
z14.object({ action: z14.literal("set_bid"), criterion_id: microsoftId, criterion_type: bidType, bid_adjustment_percent: deviceAdjustment }).strict().refine((value) => value.criterion_type === "Device" || value.bid_adjustment_percent >= -90, "Only devices support adjustments below -90 percent"),
|
|
2054
|
+
z14.object({ action: z14.literal("remove"), criterion_ids: z14.array(microsoftId).min(1).max(1e3).refine((values) => new Set(values).size === values.length, "Use unique IDs") }).strict(),
|
|
2055
|
+
z14.object({ action: z14.literal("set_location_intent"), criterion_id: microsoftId, intent_option: intent }).strict(),
|
|
2056
|
+
z14.object({ action: z14.literal("set_schedule_clock"), use_searcher_time_zone: z14.boolean() }).strict()
|
|
2057
|
+
]);
|
|
2058
|
+
var targetingWrite = z14.object({ target: targetSelection, expected_context_hash: hash5, acknowledge_delivery_effects: z14.literal(true), change }).strict();
|
|
2059
|
+
|
|
2060
|
+
// src/general-targeting.ts
|
|
2061
|
+
var BOUND = 2e4;
|
|
2062
|
+
var canonical5 = (value) => Array.isArray(value) ? value.map(canonical5) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical5(item)])) : value;
|
|
2063
|
+
var digest4 = (value) => createHash6("sha256").update(JSON.stringify(canonical5(value)) ?? "undefined").digest("hex");
|
|
2064
|
+
var same = (a, b) => digest4(a) === digest4(b);
|
|
2065
|
+
var pick = (value, fields2) => Object.fromEntries(fields2.filter((field) => Object.hasOwn(value, field)).map((field) => [field, value[field]]));
|
|
2066
|
+
var optionalRow = (value) => value === void 0 || value === null ? {} : microsoftRow(value);
|
|
2067
|
+
var kind = (value) => criterionType.parse(String(microsoftRow(value.Criterion).Type).replace(/Criterion$/, ""));
|
|
2068
|
+
var entityId2 = (target6) => target6.type === "Campaign" ? target6.campaign_id : target6.ad_group_id;
|
|
2069
|
+
var geo = (value) => ["Location", "Radius"].includes(kind(value));
|
|
2070
|
+
function title(value) {
|
|
2071
|
+
const data = microsoftRow(value.Criterion), type = kind(value), text2 = (field) => data[field] === void 0 || data[field] === null ? "Not reported" : String(data[field]);
|
|
2072
|
+
if (type === "Device") return text2("DeviceName");
|
|
2073
|
+
if (type === "Location") return `Location ${text2("LocationId")}`;
|
|
2074
|
+
if (type === "Radius") return `${data.Name || "Radius"} \xB7 ${text2("Radius")} ${text2("RadiusUnit")} \xB7 ${text2("LatitudeDegrees")}, ${text2("LongitudeDegrees")}`;
|
|
2075
|
+
if (type === "Age") return text2("AgeRange").replace(/([a-z])([A-Z])/g, "$1 $2");
|
|
2076
|
+
if (type === "Gender") return text2("GenderType");
|
|
2077
|
+
if (type === "LocationIntent") return text2("IntentOption").replace(/([a-z])([A-Z])/g, "$1 $2");
|
|
2078
|
+
const time = (end) => {
|
|
2079
|
+
const hour = data[end ? "ToHour" : "FromHour"], minute2 = data[end ? "ToMinute" : "FromMinute"];
|
|
2080
|
+
return typeof hour === "number" && typeof minute2 === "string" && Object.hasOwn(minutes, minute2) ? `${String(hour).padStart(2, "0")}:${String(minutes[minute2]).padStart(2, "0")}` : "Not reported";
|
|
2081
|
+
};
|
|
2082
|
+
return `${text2("Day")} ${time(false)}\u2013${time(true)}`;
|
|
2083
|
+
}
|
|
2084
|
+
var identity2 = (value) => {
|
|
2085
|
+
const fields2 = { Age: ["AgeRange"], Gender: ["GenderType"], Device: ["DeviceName"], DayTime: ["Day", "FromHour", "FromMinute", "ToHour", "ToMinute"], Location: ["LocationId"], LocationIntent: [], Radius: ["LatitudeDegrees", "LongitudeDegrees", "Radius", "RadiusUnit"] };
|
|
2086
|
+
const criterion = microsoftRow(value.Criterion);
|
|
2087
|
+
return digest4({ type: kind(value), fields: fields2[kind(value)].map((field) => String(criterion[field] ?? "")) });
|
|
2088
|
+
};
|
|
2089
|
+
var notices2 = ["Ad-group criteria override campaign criteria of the same type. Locations, negative locations and radii form one geo family: any ad-group geo criterion disables inheritance of ALL campaign geo criteria. Location intent alone does not change the geo source.", "Device and schedule criteria override rather than combine with campaign settings. Removing the last ad-group criterion can restore inherited targeting; adding the first can broaden or narrow delivery.", "BidMultiplier carries whole percentage points, not a ratio or currency micros. Automated bidding can treat it as a signal. Location intent has no bid. Criteria have native Active status without an independent pause.", "A configuration hash detects observed changes before submission, not concurrent changes during a native request. Reads and preservation checks cover these seven criterion families and selected parent/account configuration, not every native targeting feature."];
|
|
2090
|
+
var MICROSOFT_GENERAL_TARGETING_WRITES = /* @__PURE__ */ new Set(["microsoft_update_targeting"]);
|
|
2091
|
+
var MicrosoftGeneralTargetingService = class extends MicrosoftNativeService {
|
|
2092
|
+
async query(account, target6, type) {
|
|
2093
|
+
const prefix2 = target6.type, result = await this.request(account, `${prefix2}Criterions/QueryByIds`, { [`${prefix2}Id`]: entityId2(target6), [`${prefix2}CriterionIds`]: null, CriterionType: type });
|
|
2094
|
+
if (!Object.hasOwn(result, `${prefix2}Criterions`)) throw new AdportError15("PROVIDER_ERROR", "microsoft: complete target criteria were not returned");
|
|
2095
|
+
const values = microsoftRows(result[`${prefix2}Criterions`]);
|
|
2096
|
+
if (values.length > BOUND || new Set(values.map((value) => microsoftNativeId(value.Id))).size !== values.length || values.some((value) => microsoftNativeId(value[`${prefix2}Id`]) !== entityId2(target6) || kind(value) !== type || ![`Biddable${prefix2}Criterion`, `Negative${prefix2}Criterion`].includes(String(value.Type)))) throw new AdportError15("PROVIDER_ERROR", "microsoft: targeting response identity, scope or safety bound mismatch");
|
|
2097
|
+
return values.filter((value) => value.Status !== "Deleted");
|
|
2098
|
+
}
|
|
2099
|
+
async all(account, target6) {
|
|
2100
|
+
const values = [];
|
|
2101
|
+
for (let i = 0; i < criterionType.options.length; i += 3) values.push(...(await Promise.all(criterionType.options.slice(i, i + 3).map((type) => this.query(account, target6, type)))).flat());
|
|
2102
|
+
if (values.length > BOUND || new Set(values.map((value) => microsoftNativeId(value.Id))).size !== values.length) throw new AdportError15("PROVIDER_ERROR", "microsoft: targeting snapshot exceeds its bound or contains duplicate IDs");
|
|
2103
|
+
return values.sort((a, b) => BigInt(microsoftNativeId(a.Id)) < BigInt(microsoftNativeId(b.Id)) ? -1 : 1);
|
|
2104
|
+
}
|
|
2105
|
+
async context(account, target6) {
|
|
2106
|
+
const scope = await this.accountScope(account, true), known = await this.campaign(account, target6.campaign_id);
|
|
2107
|
+
const accountResult = await this.request(account, "Account/Query", { AccountId: account }, "POST", "customer"), nativeAccount = microsoftRow(accountResult.Account);
|
|
2108
|
+
if (microsoftNativeId(nativeAccount.Id) !== account || microsoftNativeId(nativeAccount.ParentCustomerId) !== scope.customerId) throw new AdportError15("PROVIDER_ERROR", "microsoft: account/timezone ownership could not be verified");
|
|
2109
|
+
const accountContext = pick(nativeAccount, ["Id", "ParentCustomerId", "CurrencyCode", "TimeZone", "AccountLifeCycleStatus"]);
|
|
2110
|
+
const parents = microsoftRows((await this.request(account, "Campaigns/QueryByIds", { AccountId: account, CampaignIds: [target6.campaign_id], CampaignType: known.CampaignType, ReturnAdditionalFields: "TargetSetting, AdScheduleUseSearcherTimeZone" })).Campaigns);
|
|
2111
|
+
if (parents.length !== 1 || microsoftNativeId(parents[0].Id) !== target6.campaign_id || parents[0].CampaignType !== known.CampaignType || !["Active", "Paused"].includes(String(parents[0].Status))) throw new AdportError15("INVALID_INPUT", "microsoft: campaign context is unavailable or mismatched");
|
|
2112
|
+
const campaign = pick(parents[0], ["Id", "Name", "Status", "CampaignType", "SubType", "DailyBudget", "BudgetType", "BudgetId", "BiddingScheme", "ExperimentId", "Settings", "AdScheduleUseSearcherTimeZone"]);
|
|
2113
|
+
let group;
|
|
2114
|
+
if (target6.type === "AdGroup") {
|
|
2115
|
+
if (campaign.CampaignType === "PerformanceMax") throw new AdportError15("INVALID_INPUT", "microsoft: Performance Max has asset groups, not ordinary ad-group targeting");
|
|
2116
|
+
const groups2 = microsoftRows((await this.request(account, "AdGroups/QueryByIds", { CampaignId: target6.campaign_id, AdGroupIds: [target6.ad_group_id], ReturnAdditionalFields: "AdGroupType, AdScheduleUseSearcherTimeZone" })).AdGroups);
|
|
2117
|
+
if (groups2.length !== 1 || microsoftNativeId(groups2[0].Id) !== target6.ad_group_id || !["Active", "Paused"].includes(String(groups2[0].Status))) throw new AdportError15("INVALID_INPUT", "microsoft: ad group was not found in the selected campaign/account");
|
|
2118
|
+
group = pick(groups2[0], ["Id", "Name", "Status", "AdGroupType", "Language", "CpcBid", "CpmBid", "CpvBid", "BiddingScheme", "StartDate", "EndDate", "Settings", "AdScheduleUseSearcherTimeZone"]);
|
|
2119
|
+
}
|
|
2120
|
+
const campaignCriteria = await this.all(account, { type: "Campaign", campaign_id: target6.campaign_id }), ownCriteria = target6.type === "AdGroup" ? await this.all(account, target6) : campaignCriteria;
|
|
2121
|
+
const data = { account_id: account, target: target6, account: accountContext, campaign, group, campaignCriteria, ownCriteria };
|
|
2122
|
+
return { ...data, context_hash: digest4(data) };
|
|
2123
|
+
}
|
|
2124
|
+
inherited(context2, own = context2.ownCriteria) {
|
|
2125
|
+
return Object.fromEntries(criterionType.options.map((type) => {
|
|
2126
|
+
const useOwn = context2.target.type === "Campaign" || (["Location", "Radius", "LocationIntent"].includes(type) ? own.some(geo) : own.some((value) => kind(value) === type));
|
|
2127
|
+
const source = useOwn ? context2.target.type : "Campaign", selected2 = useOwn ? own : context2.campaignCriteria;
|
|
2128
|
+
return [type, { source, criterion_count: selected2.filter((value) => kind(value) === type).length }];
|
|
2129
|
+
}));
|
|
2130
|
+
}
|
|
2131
|
+
clock(context2, own = context2.ownCriteria) {
|
|
2132
|
+
const source = this.inherited(context2, own).DayTime.source, parent2 = source === "AdGroup" ? context2.group : context2.campaign, flag = parent2.AdScheduleUseSearcherTimeZone;
|
|
2133
|
+
return { source, use_searcher_time_zone: typeof flag === "boolean" ? flag : null, timezone: flag === true ? "Searcher local time" : flag === false ? context2.account.TimeZone ?? "Account time zone not reported" : "Schedule clock not reported" };
|
|
2134
|
+
}
|
|
2135
|
+
geography(context2, own = context2.ownCriteria) {
|
|
2136
|
+
const source = this.inherited(context2, own).Location.source, selected2 = source === context2.target.type ? own : context2.campaignCriteria, included = selected2.filter((value) => kind(value) === "Location" && String(value.Type).startsWith("Biddable")), excluded = selected2.filter((value) => kind(value) === "Location" && String(value.Type).startsWith("Negative")), radii = selected2.filter((value) => kind(value) === "Radius");
|
|
2137
|
+
return { source, included_location_count: included.length, excluded_location_count: excluded.length, radius_count: radii.length, included_location_ids: included.slice(0, 20).map((value) => microsoftRow(value.Criterion).LocationId), ids_truncated: included.length > 20, ...!included.length && !radii.length ? { reach: "No positive location/radius restriction; exclusions and native campaign eligibility still apply." } : {} };
|
|
2138
|
+
}
|
|
2139
|
+
async list(raw) {
|
|
2140
|
+
const input = targetingRead.parse(raw), context2 = await this.context(input.account_id, input.target), types = [...input.criterion_types].sort(), visible = [...context2.ownCriteria.map((criterion) => ({ source: input.target.type, criterion })), ...input.target.type === "AdGroup" ? context2.campaignCriteria.map((criterion) => ({ source: "Campaign", criterion })) : []].filter((value) => input.criterion_types.includes(kind(value.criterion)));
|
|
2141
|
+
let offset = 0;
|
|
2142
|
+
if (input.cursor) try {
|
|
2143
|
+
const cursor = z15.object({ account: z15.string(), target: targetSelection, hash: z15.string(), types: z15.array(z15.string()), size: z15.number().int().positive(), offset: z15.number().int().positive() }).strict().parse(JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")));
|
|
2144
|
+
if (cursor.account !== input.account_id || !same(cursor.target, input.target) || cursor.hash !== context2.context_hash || !same(cursor.types, types) || cursor.size !== input.page_size || cursor.offset >= visible.length || cursor.offset % cursor.size) throw new Error("Selection changed");
|
|
2145
|
+
offset = cursor.offset;
|
|
2146
|
+
} catch {
|
|
2147
|
+
throw new AdportError15("PENDING_MISMATCH", "microsoft: targeting continuation is stale or belongs to another selection; refresh the first page");
|
|
2148
|
+
}
|
|
2149
|
+
const inheritance = this.inherited(context2), page = visible.slice(offset, offset + input.page_size), end = offset + page.length;
|
|
2150
|
+
return {
|
|
2151
|
+
account_id: input.account_id,
|
|
2152
|
+
target: input.target,
|
|
2153
|
+
context_hash: context2.context_hash,
|
|
2154
|
+
account: context2.account,
|
|
2155
|
+
campaign: context2.campaign,
|
|
2156
|
+
ad_group: context2.group,
|
|
2157
|
+
inheritance,
|
|
2158
|
+
schedule_clock: this.clock(context2),
|
|
2159
|
+
total_criteria: visible.length,
|
|
2160
|
+
criteria: page,
|
|
2161
|
+
records: page.map(({ source, criterion }) => {
|
|
2162
|
+
const type = kind(criterion), bid3 = optionalRow(criterion.CriterionBid).Multiplier, selected2 = inheritance[type].source === source, hasGeo = inheritance.Location.criterion_count + inheritance.Radius.criterion_count > 0;
|
|
2163
|
+
return { id: `${source}:${microsoftNativeId(criterion.Id)}`, criterion_id: microsoftNativeId(criterion.Id), kind: type, name: title(criterion), source, effective: selected2 && (type !== "LocationIntent" || hasGeo), status: criterion.Status ?? "Not reported", bid_adjustment: typeof bid3 === "number" ? `${bid3}%${type === "Device" && bid3 === -100 ? " \xB7 device excluded" : ""}` : type === "LocationIntent" || String(criterion.Type).startsWith("Negative") ? "Not applicable" : "Not reported" };
|
|
2164
|
+
}),
|
|
2165
|
+
truncated: end < visible.length,
|
|
2166
|
+
...end < visible.length ? { next_cursor: Buffer.from(JSON.stringify({ account: input.account_id, target: input.target, hash: context2.context_hash, types, size: input.page_size, offset: end })).toString("base64url") } : {},
|
|
2167
|
+
notes: [...notices2, "Both owned and campaign criteria are shown. Effective identifies the selected source, not eligibility or delivery; false marks overridden/inapplicable rows. Intent without geographic criteria is inapplicable. Only owned IDs can be edited at the selected scope."]
|
|
2168
|
+
};
|
|
2169
|
+
}
|
|
2170
|
+
async plan(op, guard) {
|
|
2171
|
+
if (op.tool !== "microsoft_update_targeting" || op.provider !== "microsoft" || op.kind !== "update") throw new AdportError15("INVALID_INPUT", "microsoft: scoped targeting operation provider/kind mismatch");
|
|
2172
|
+
const input = targetingWrite.parse(op.payload), before = await this.context(op.accountId, input.target), change2 = input.change, prefix2 = input.target.type, parentKey = `${prefix2}Id`, selectedParent = before.group ?? before.campaign;
|
|
2173
|
+
if (before.context_hash !== input.expected_context_hash) throw new AdportError15("PENDING_MISMATCH", "microsoft: targeting, inheritance or parent/account configuration changed; read and preview again");
|
|
2174
|
+
let method = "PUT", path = `${prefix2}Criterions`, body = {}, creates = [], removed = [], updated, clock;
|
|
2175
|
+
const selected2 = (id3) => {
|
|
2176
|
+
const found = before.ownCriteria.find((value) => microsoftNativeId(value.Id) === id3);
|
|
2177
|
+
if (!found) throw new AdportError15("INVALID_INPUT", "microsoft: criterion is not owned by the selected entity; inherited criterion IDs cannot be edited here");
|
|
2178
|
+
return found;
|
|
2179
|
+
};
|
|
2180
|
+
if (change2.action === "add") {
|
|
2181
|
+
if (guard.forcePausedCreation && before.campaign.Status !== "Paused" && before.group?.Status !== "Paused") throw new AdportError15("POLICY_VIOLATION", "microsoft: new targets are natively Active; paused_creation requires an effectively paused parent");
|
|
2182
|
+
creates = change2.targets.map((value) => nativeTarget({ [parentKey]: entityId2(input.target) }, value));
|
|
2183
|
+
const seen = new Set(before.ownCriteria.map(identity2));
|
|
2184
|
+
for (const value of creates) {
|
|
2185
|
+
if (seen.has(identity2(value))) throw new AdportError15("INVALID_INPUT", "microsoft: target already exists or is duplicated in this request; use an explicit edit");
|
|
2186
|
+
seen.add(identity2(value));
|
|
2187
|
+
}
|
|
2188
|
+
method = "POST";
|
|
2189
|
+
body = { [`${prefix2}Criterions`]: creates, CriterionType: "Targets" };
|
|
2190
|
+
} else if (change2.action === "remove") {
|
|
2191
|
+
removed = change2.criterion_ids;
|
|
2192
|
+
const values = removed.map(selected2);
|
|
2193
|
+
if (values.some((value) => kind(value) === "LocationIntent")) throw new AdportError15("INVALID_INPUT", "microsoft: location intent cannot be deleted; restore its default with set_location_intent");
|
|
2194
|
+
if (values.some((value) => kind(value) === "Device") && before.ownCriteria.some((value) => kind(value) === "Device" && !removed.includes(microsoftNativeId(value.Id)))) throw new AdportError15("INVALID_INPUT", "microsoft: remove the complete device set together");
|
|
2195
|
+
method = "DELETE";
|
|
2196
|
+
body = { [parentKey]: entityId2(input.target), [`${prefix2}CriterionIds`]: removed, CriterionType: "Targets" };
|
|
2197
|
+
} else if (change2.action === "set_schedule_clock") {
|
|
2198
|
+
if (selectedParent.AdScheduleUseSearcherTimeZone === change2.use_searcher_time_zone) throw new AdportError15("INVALID_INPUT", "microsoft: schedule clock already has this value");
|
|
2199
|
+
clock = change2.use_searcher_time_zone;
|
|
2200
|
+
path = prefix2 === "Campaign" ? "Campaigns" : "AdGroups";
|
|
2201
|
+
body = { [prefix2 === "Campaign" ? "AccountId" : "CampaignId"]: prefix2 === "Campaign" ? op.accountId : input.target.campaign_id, [path]: [{ Id: entityId2(input.target), AdScheduleUseSearcherTimeZone: clock }] };
|
|
2202
|
+
} else {
|
|
2203
|
+
const current = selected2(change2.criterion_id), type = kind(current);
|
|
2204
|
+
if (current.Type !== `Biddable${prefix2}Criterion`) throw new AdportError15("INVALID_INPUT", "microsoft: excluded targets cannot have a bid or intent edit");
|
|
2205
|
+
updated = { ...current };
|
|
2206
|
+
if (change2.action === "set_bid") {
|
|
2207
|
+
const bid3 = optionalRow(current.CriterionBid);
|
|
2208
|
+
if (type !== change2.criterion_type || bid3.Type !== "BidMultiplier" || typeof bid3.Multiplier !== "number" || !Number.isFinite(bid3.Multiplier)) throw new AdportError15("INVALID_INPUT", "microsoft: owned biddable criterion with a verified native percentage is required");
|
|
2209
|
+
if (bid3.Multiplier === change2.bid_adjustment_percent) throw new AdportError15("INVALID_INPUT", "microsoft: bid adjustment is unchanged");
|
|
2210
|
+
updated.CriterionBid = { Type: "BidMultiplier", Multiplier: change2.bid_adjustment_percent };
|
|
2211
|
+
body = { [`${prefix2}Criterions`]: [{ [parentKey]: entityId2(input.target), Id: change2.criterion_id, Type: current.Type, CriterionBid: updated.CriterionBid }], CriterionType: "Targets" };
|
|
2212
|
+
} else {
|
|
2213
|
+
if (type !== "LocationIntent") throw new AdportError15("INVALID_INPUT", "microsoft: location intent requires its exact criterion ID");
|
|
2214
|
+
if (microsoftRow(current.Criterion).IntentOption === change2.intent_option) throw new AdportError15("INVALID_INPUT", "microsoft: location intent is unchanged");
|
|
2215
|
+
updated.Criterion = { ...microsoftRow(current.Criterion), IntentOption: change2.intent_option };
|
|
2216
|
+
body = { [`${prefix2}Criterions`]: [{ [parentKey]: entityId2(input.target), Id: change2.criterion_id, Type: current.Type, Criterion: updated.Criterion }], CriterionType: "Targets" };
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
const afterOwn = [...before.ownCriteria.filter((value) => !removed.includes(microsoftNativeId(value.Id))).map((value) => updated && microsoftNativeId(updated.Id) === microsoftNativeId(value.Id) ? updated : value), ...creates];
|
|
2220
|
+
const touched = /* @__PURE__ */ new Set([...creates.map(kind), ...before.ownCriteria.filter((value) => removed.includes(microsoftNativeId(value.Id))).map(kind), ...updated ? [kind(updated)] : []]);
|
|
2221
|
+
this.validateResultingCriteria(afterOwn, touched);
|
|
2222
|
+
const touchesSchedule = clock !== void 0 || creates.some((value) => kind(value) === "DayTime") || before.ownCriteria.some((value) => removed.includes(microsoftNativeId(value.Id)) && kind(value) === "DayTime");
|
|
2223
|
+
if (touchesSchedule && (clock ?? selectedParent.AdScheduleUseSearcherTimeZone) !== true && (typeof (clock ?? selectedParent.AdScheduleUseSearcherTimeZone) !== "boolean" || typeof before.account.TimeZone !== "string" || !before.account.TimeZone)) throw new AdportError15("INVALID_INPUT", "microsoft: schedule clock/account time zone is not verified; set an explicit clock and read fresh context");
|
|
2224
|
+
const projected = { ...before, campaign: { ...before.campaign, ...prefix2 === "Campaign" && clock !== void 0 ? { AdScheduleUseSearcherTimeZone: clock } : {} }, group: before.group ? { ...before.group, ...prefix2 === "AdGroup" && clock !== void 0 ? { AdScheduleUseSearcherTimeZone: clock } : {} } : void 0 };
|
|
2225
|
+
const effectiveBefore = this.inherited(before), effectiveAfter = this.inherited(before, afterOwn), fields2 = [{ label: "Campaign", after: `${before.campaign.Name ?? "Not reported"} [${input.target.campaign_id}]` }, ...before.group ? [{ label: "Ad group", after: `${before.group.Name ?? "Not reported"} [${entityId2(input.target)}]` }] : [], { label: "Scope", after: input.target }, { label: "Campaign status", after: before.campaign.Status }, ...before.group ? [{ label: "Ad group status", after: before.group.Status }] : [], { label: "Change", after: change2 }, { label: "Effective targeting", before: effectiveBefore, after: effectiveAfter }, { label: "Geographic reach", before: this.geography(before), after: this.geography(before, afterOwn) }, { label: "Schedule clock", before: this.clock(before), after: this.clock(projected, afterOwn) }, ...clock !== void 0 ? [{ label: "Use searcher timezone", before: selectedParent.AdScheduleUseSearcherTimeZone ?? "Not reported", after: clock }] : []];
|
|
2226
|
+
let details;
|
|
2227
|
+
const known = /* @__PURE__ */ new Set([...removed, ...updated ? [microsoftNativeId(updated.Id)] : [], ...clock !== void 0 ? [entityId2(input.target)] : []]);
|
|
2228
|
+
return {
|
|
2229
|
+
summary: `Update Microsoft ${prefix2} targeting \xB7 ${change2.action}`,
|
|
2230
|
+
changes: [`${method} ${path}; only approved target fields are submitted.`, `${creates.length} additions, ${removed.length} removals, ${updated ? 1 : 0} criterion updates.`, "Other returned criteria and parent statuses/budgets/settings are preserved. Immutable schedule intervals require separate reviewed remove/add operations; pause delivery before a multi-step replacement."],
|
|
2231
|
+
coercions: [],
|
|
2232
|
+
budgetDeltas: [],
|
|
2233
|
+
notes: notices2,
|
|
2234
|
+
review: { provider: "microsoft", accountId: op.accountId, kind: "update", title: "Update targeting", fields: fields2, notices: notices2 },
|
|
2235
|
+
resultDetails: () => details,
|
|
2236
|
+
execute: async () => {
|
|
2237
|
+
try {
|
|
2238
|
+
const result = await this.request(op.accountId, path, body, method), acknowledged = result[`${prefix2}CriterionIds`];
|
|
2239
|
+
if (Array.isArray(acknowledged)) for (const id3 of acknowledged) try {
|
|
2240
|
+
known.add(microsoftNativeId(id3));
|
|
2241
|
+
} catch {
|
|
2242
|
+
}
|
|
2243
|
+
const createdIds = method === "POST" ? rowsOfIds(acknowledged) : [];
|
|
2244
|
+
if (method === "POST" && (createdIds.length !== creates.length || new Set(createdIds).size !== createdIds.length || createdIds.some((id3) => before.ownCriteria.some((value) => microsoftNativeId(value.Id) === id3)))) throw new Error("Creation receipt mismatch");
|
|
2245
|
+
const after = await this.context(op.accountId, input.target), expectedCampaign = { ...before.campaign, ...prefix2 === "Campaign" && clock !== void 0 ? { AdScheduleUseSearcherTimeZone: clock } : {} }, expectedGroup = before.group ? { ...before.group, ...prefix2 === "AdGroup" && clock !== void 0 ? { AdScheduleUseSearcherTimeZone: clock } : {} } : void 0;
|
|
2246
|
+
if (!same(after.account, before.account) || !same(after.campaign, expectedCampaign) || !same(after.group, expectedGroup) || prefix2 === "AdGroup" && !same(after.campaignCriteria, before.campaignCriteria)) throw new Error("Parent preservation mismatch");
|
|
2247
|
+
const expectedIds = /* @__PURE__ */ new Set([...before.ownCriteria.filter((value) => !removed.includes(microsoftNativeId(value.Id))).map((value) => microsoftNativeId(value.Id)), ...createdIds]);
|
|
2248
|
+
if (after.ownCriteria.length !== expectedIds.size || after.ownCriteria.some((value) => !expectedIds.has(microsoftNativeId(value.Id)))) throw new Error("Criterion inventory mismatch");
|
|
2249
|
+
for (const previous of before.ownCriteria) {
|
|
2250
|
+
if (removed.includes(microsoftNativeId(previous.Id))) continue;
|
|
2251
|
+
const observed = after.ownCriteria.find((value) => microsoftNativeId(value.Id) === microsoftNativeId(previous.Id)), expected = updated && microsoftNativeId(updated.Id) === microsoftNativeId(previous.Id) ? updated : previous;
|
|
2252
|
+
if (!same(observed, expected)) throw new Error("Criterion preservation mismatch");
|
|
2253
|
+
}
|
|
2254
|
+
for (let i = 0; i < creates.length; i++) {
|
|
2255
|
+
const observed = after.ownCriteria.find((value) => microsoftNativeId(value.Id) === createdIds[i]);
|
|
2256
|
+
if (!observed || !contains(observed, creates[i])) throw new Error("Created criterion mismatch");
|
|
2257
|
+
}
|
|
2258
|
+
details = { snapshot_hash: after.context_hash, created_criterion_ids: createdIds, removed_criterion_ids: removed, updated_criterion_ids: updated ? [microsoftNativeId(updated.Id)] : [], independent_readback_verified: true, inheritance: this.inherited(after), schedule_clock: this.clock(after) };
|
|
2259
|
+
return [...known];
|
|
2260
|
+
} catch (error) {
|
|
2261
|
+
if (error instanceof AdportError15 && error.details && typeof error.details === "object" && Array.isArray(error.details.resourceIds)) for (const id3 of error.details.resourceIds) try {
|
|
2262
|
+
known.add(microsoftNativeId(id3));
|
|
2263
|
+
} catch {
|
|
2264
|
+
}
|
|
2265
|
+
throw new AdportError15("PROVIDER_ERROR", "microsoft: targeting outcome was not confirmed. Reconcile known IDs and current configuration before another mutation; no write was retried.", { resourceIds: [...known] });
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
};
|
|
2269
|
+
}
|
|
2270
|
+
validateResultingCriteria(values, touched) {
|
|
2271
|
+
const devices = values.filter((value) => kind(value) === "Device");
|
|
2272
|
+
if (touched.has("Device") && devices.length && (devices.length !== 3 || !["Computers", "Smartphones", "Tablets"].every((name5) => devices.some((value) => microsoftRow(value.Criterion).DeviceName === name5)) || devices.some((value) => !String(value.Type).startsWith("Biddable") || optionalRow(value.CriterionBid).Type !== "BidMultiplier" || typeof optionalRow(value.CriterionBid).Multiplier !== "number") || devices.every((value) => optionalRow(value.CriterionBid).Multiplier === -100))) throw new AdportError15("INVALID_INPUT", "microsoft: targeting requires a complete supported three-device set with at least one device included");
|
|
2273
|
+
const schedule = values.filter((value) => kind(value) === "DayTime").map((value) => microsoftRow(value.Criterion));
|
|
2274
|
+
if (touched.has("DayTime") && schedule.length > 49) throw new AdportError15("INVALID_INPUT", "microsoft: maximum49weekly schedules");
|
|
2275
|
+
const number = (value, end) => {
|
|
2276
|
+
const hour = value[end ? "ToHour" : "FromHour"], minute2 = value[end ? "ToMinute" : "FromMinute"];
|
|
2277
|
+
if (typeof hour !== "number" || !Number.isInteger(hour) || typeof minute2 !== "string" || !Object.hasOwn(minutes, minute2)) throw new AdportError15("PROVIDER_ERROR", "microsoft: native schedule interval is incomplete");
|
|
2278
|
+
return hour * 60 + minutes[minute2];
|
|
2279
|
+
};
|
|
2280
|
+
if (touched.has("DayTime")) for (const day2 of new Set(schedule.map((value) => value.Day))) {
|
|
2281
|
+
const entries = schedule.filter((value) => value.Day === day2).sort((a, b) => number(a, false) - number(b, false));
|
|
2282
|
+
if (entries.length > 7 || entries.some((value, index) => number(value, true) <= number(value, false) || index > 0 && number(value, false) < number(entries[index - 1], true))) throw new AdportError15("INVALID_INPUT", "microsoft: schedules must not overlap or exceed seven per day");
|
|
2283
|
+
}
|
|
2284
|
+
if (touched.has("Location") && values.filter((value) => kind(value) === "Location").length > 1e4) throw new AdportError15("INVALID_INPUT", "microsoft: combined included/excluded locations exceed10000");
|
|
2285
|
+
}
|
|
2286
|
+
};
|
|
2287
|
+
function rowsOfIds(value) {
|
|
2288
|
+
if (!Array.isArray(value)) return [];
|
|
2289
|
+
return value.map(microsoftNativeId);
|
|
2290
|
+
}
|
|
2291
|
+
function contains(actual, expected) {
|
|
2292
|
+
return Object.entries(expected).every(([key, value]) => value && typeof value === "object" && !Array.isArray(value) ? actual[key] && typeof actual[key] === "object" && contains(microsoftRow(actual[key]), microsoftRow(value)) : key === "Type" ? String(actual[key]).replace(/Criterion$/, "") === String(value).replace(/Criterion$/, "") : String(actual[key]) === String(value));
|
|
2293
|
+
}
|
|
2294
|
+
function microsoftGeneralTargetingTools(provider) {
|
|
2295
|
+
const catalog = { category: "audiences", exposure: "specialist" };
|
|
2296
|
+
return [
|
|
2297
|
+
defineTool11({ name: "microsoft_targeting_context", namespace: "microsoft", catalog, description: "Read owned and inherited campaign/ad-group general targets, effective sources, schedule clock and context_hash. Seven concrete types, complete bounded context and stable paging; bid values are percentages. This is not audience targeting or every native targeting family.", input: targetingRead, presentation: "records", pagination: { cursorInput: "cursor" }, annotations: { readOnly: true }, handler: (input) => provider.generalTargeting.list(input) }),
|
|
2298
|
+
guardedWriteTool10({ name: "microsoft_update_targeting", namespace: "microsoft", provider: "microsoft", catalog, kind: "update", description: "Edit scoped targeting with expected_context_hash and delivery-effects acknowledgement. One native add, remove, bid, location-intent or schedule-clock operation per approval. Preserves unmentioned criteria/status/budgets; checks inheritance, full devices and schedule limits. New criteria require an effectively paused parent under paused_creation.", payload: targetingWrite })
|
|
2299
|
+
];
|
|
2300
|
+
}
|
|
2301
|
+
|
|
2302
|
+
// src/experiments.ts
|
|
2303
|
+
import { createHash as createHash7 } from "crypto";
|
|
2304
|
+
import { AdportError as AdportError16, defineTool as defineTool12, guardedWriteTool as guardedWriteTool11 } from "@adport/core";
|
|
2305
|
+
import { z as z16 } from "zod";
|
|
2306
|
+
var hash6 = z16.string().regex(/^[a-f0-9]{64}$/);
|
|
2307
|
+
var name4 = z16.string().min(1).max(128).refine((value) => value.trim().length > 0, "Name cannot be blank");
|
|
2308
|
+
var date2 = z16.iso.date();
|
|
2309
|
+
var split = z16.number().int().min(1).max(99);
|
|
2310
|
+
var create4 = z16.object({ base_campaign_id: microsoftId, expected_base_context_hash: hash6, name: name4, start_date: date2, end_date: date2.optional(), traffic_split_percent: split, experiment_type: z16.enum(["TrafficBased", "CookieBased"]).default("TrafficBased") }).refine((value) => !value.end_date || value.start_date <= value.end_date, "End date must be on or after start date");
|
|
2311
|
+
var reference6 = z16.object({ experiment_id: microsoftId, expected_snapshot_hash: hash6 });
|
|
2312
|
+
var update5 = reference6.extend({ name: name4.optional(), start_date: date2.optional(), end_date: date2.nullable().optional(), traffic_split_percent: split.optional() }).refine((value) => ["name", "start_date", "end_date", "traffic_split_percent"].some((key) => value[key] !== void 0), "Supply an editable experiment field");
|
|
2313
|
+
var additional2 = "ExperimentSubType, ExperimentArms, ExperimentCampaignType";
|
|
2314
|
+
var notes6 = ["Microsoft copies eligible base-campaign settings and child entities into an experiment campaign. Expired ad groups, legacy ad formats and some legacy keyword/audience settings are not copied; native copy diagnostics can report omissions.", "The experiment campaign inherits the base budget, BudgetType, status and timezone. TrafficSplitPercent divides the existing base budget/traffic; the branch is not an additional independent daily pool. Pause or change budget through the base campaign.", "Dates are calendar dates in the base campaign timezone; end dates are inclusive. Setup is asynchronous. A returned experiment ID or Creating status does not prove the campaign copy is ready.", "Snapshots cover the experiment and parent/branch campaign configuration plus the visible active experiment inventory, not every child entity. Microsoft provides no atomic compare-and-set; external changes can race submission."];
|
|
2315
|
+
var contextSchema2 = z16.object({ account_id: microsoftId, base_campaign: z16.record(z16.string(), z16.unknown()), active_experiments: z16.array(z16.record(z16.string(), z16.unknown())), currency: z16.string().optional(), snapshot_hash: hash6 });
|
|
2316
|
+
var viewSchema2 = z16.object({ account_id: microsoftId, experiment: z16.record(z16.string(), z16.unknown()), base_context: contextSchema2, experiment_campaign: z16.record(z16.string(), z16.unknown()).optional(), snapshot_hash: hash6, notes: z16.array(z16.string()) });
|
|
2317
|
+
function canonical6(value) {
|
|
2318
|
+
return Array.isArray(value) ? value.map(canonical6) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value2]) => [key, canonical6(value2)])) : value;
|
|
2319
|
+
}
|
|
2320
|
+
var digest5 = (value) => createHash7("sha256").update(JSON.stringify(canonical6(value))).digest("hex");
|
|
2321
|
+
var optionalId = (value) => value === null || value === void 0 || value === "0" || value === 0 ? void 0 : microsoftNativeId(value);
|
|
2322
|
+
function nativeDate(value) {
|
|
2323
|
+
const [Year, Month, Day] = value.split("-").map(Number);
|
|
2324
|
+
return { Day, Month, Year };
|
|
2325
|
+
}
|
|
2326
|
+
function calendarDate(value) {
|
|
2327
|
+
if (value === void 0 || value === null) return void 0;
|
|
2328
|
+
const row = z16.object({ Year: z16.number().int(), Month: z16.number().int(), Day: z16.number().int() }).parse(value);
|
|
2329
|
+
if (row.Year === 0 && row.Month === 0 && row.Day === 0) return void 0;
|
|
2330
|
+
return date2.parse(`${String(row.Year).padStart(4, "0")}-${String(row.Month).padStart(2, "0")}-${String(row.Day).padStart(2, "0")}`);
|
|
2331
|
+
}
|
|
2332
|
+
var micros2 = (value) => {
|
|
2333
|
+
if (typeof value !== "number" || value <= 0 || !Number.isSafeInteger(Math.round(value * 1e6)) || Math.abs(value * 1e6 - Math.round(value * 1e6)) > 1e-6) throw new AdportError16("PROVIDER_ERROR", "microsoft: base campaign daily budget cannot be represented safely in micros");
|
|
2334
|
+
return Math.round(value * 1e6);
|
|
2335
|
+
};
|
|
2336
|
+
var MICROSOFT_EXPERIMENT_WRITES = /* @__PURE__ */ new Set(["microsoft_create_experiment", "microsoft_update_experiment", "microsoft_end_experiment", "microsoft_delete_experiment"]);
|
|
2337
|
+
var MicrosoftExperimentService = class extends MicrosoftNativeService {
|
|
2338
|
+
constructor(...args) {
|
|
2339
|
+
const [client, scope, campaign, campaigns, currency2] = args;
|
|
2340
|
+
super(client, scope, campaign);
|
|
2341
|
+
this.campaigns = campaigns;
|
|
2342
|
+
this.currency = currency2;
|
|
2343
|
+
}
|
|
2344
|
+
campaigns;
|
|
2345
|
+
currency;
|
|
2346
|
+
async query(account, ids) {
|
|
2347
|
+
const result = await this.request(account, "Experiments/QueryByIds", { ExperimentIds: ids, ReturnAdditionalFields: additional2 });
|
|
2348
|
+
if (!Object.hasOwn(result, "Experiments") || result.Experiments !== null && !Array.isArray(result.Experiments)) throw new AdportError16("PROVIDER_ERROR", "microsoft: experiment response envelope is missing or malformed");
|
|
2349
|
+
const values = microsoftRows(result.Experiments?.filter((value) => value !== null));
|
|
2350
|
+
if (new Set(values.map((value) => microsoftNativeId(value.Id))).size !== values.length || values.some((value) => ids && !ids.includes(microsoftNativeId(value.Id)))) throw new AdportError16("PROVIDER_ERROR", "microsoft: duplicate or unexpected experiment identities");
|
|
2351
|
+
return values;
|
|
2352
|
+
}
|
|
2353
|
+
async campaignById(account, campaignId, type) {
|
|
2354
|
+
const result = await this.request(account, "Campaigns/QueryByIds", { AccountId: account, CampaignIds: [campaignId], CampaignType: type, ReturnAdditionalFields: "TargetSetting" });
|
|
2355
|
+
if (!Object.hasOwn(result, "Campaigns") || result.Campaigns !== null && !Array.isArray(result.Campaigns)) throw new AdportError16("PROVIDER_ERROR", "microsoft: experiment campaign response envelope is missing");
|
|
2356
|
+
const campaigns = microsoftRows(result.Campaigns?.filter((value) => value !== null));
|
|
2357
|
+
if (campaigns.length > 1 || campaigns.some((value) => microsoftNativeId(value.Id) !== campaignId || value.CampaignType !== type)) throw new AdportError16("PROVIDER_ERROR", "microsoft: experiment campaign identity/type mismatch");
|
|
2358
|
+
return campaigns[0];
|
|
2359
|
+
}
|
|
2360
|
+
async base(account, campaignId, refresh = false) {
|
|
2361
|
+
await this.accountScope(account, refresh);
|
|
2362
|
+
const known = await this.campaign(account, campaignId), base = await this.campaignById(account, campaignId, known.CampaignType);
|
|
2363
|
+
if (!base || typeof base.Name !== "string" || typeof base.Status !== "string" || typeof base.TimeZone !== "string") throw new AdportError16("PROVIDER_ERROR", "microsoft: base campaign configuration is incomplete");
|
|
2364
|
+
const active = (await this.query(account, null)).filter((value) => microsoftNativeId(value.BaseCampaignId) === campaignId).sort((a, b) => BigInt(microsoftNativeId(a.Id)) < BigInt(microsoftNativeId(b.Id)) ? -1 : 1), currency2 = await this.currency(account);
|
|
2365
|
+
const visible = { account_id: account, base_campaign: base, active_experiments: active, ...currency2 ? { currency: currency2 } : {} };
|
|
2366
|
+
return { ...visible, snapshot_hash: digest5(visible) };
|
|
2367
|
+
}
|
|
2368
|
+
async list(input) {
|
|
2369
|
+
const remaining = (await this.query(input.account_id, null)).filter((value) => !input.after_experiment_id || BigInt(microsoftNativeId(value.Id)) > BigInt(input.after_experiment_id)).sort((a, b) => BigInt(microsoftNativeId(a.Id)) < BigInt(microsoftNativeId(b.Id)) ? -1 : 1), page = remaining.slice(0, input.limit), truncated = remaining.length > page.length;
|
|
2370
|
+
return { rows: page, truncated, ...truncated ? { next_cursor: microsoftNativeId(page.at(-1).Id) } : {}, visibility: "Native active inventory only; use microsoft_get_experiment for an exact known historical ID.", notes: notes6 };
|
|
2371
|
+
}
|
|
2372
|
+
async get(account, experimentId, refresh = false) {
|
|
2373
|
+
await this.accountScope(account, refresh);
|
|
2374
|
+
const values = await this.query(account, [experimentId]), experiment = values[0];
|
|
2375
|
+
if (!experiment) throw new AdportError16("INVALID_INPUT", "microsoft: experiment was not found in the selected account");
|
|
2376
|
+
const context2 = await this.base(account, microsoftNativeId(experiment.BaseCampaignId)), branchId = optionalId(experiment.ExperimentCampaignId), branch = branchId ? await this.campaignById(account, branchId, context2.base_campaign.CampaignType) : void 0;
|
|
2377
|
+
if (branchId && (!branch || optionalId(branch.ExperimentId) !== experimentId)) throw new AdportError16("PROVIDER_ERROR", "microsoft: experiment campaign ownership could not be verified");
|
|
2378
|
+
const visible = { account_id: account, experiment, base_context: context2, ...branch ? { experiment_campaign: branch } : {} };
|
|
2379
|
+
return { ...visible, snapshot_hash: digest5(visible), notes: notes6 };
|
|
2380
|
+
}
|
|
2381
|
+
eligible(context2) {
|
|
2382
|
+
const base = context2.base_campaign;
|
|
2383
|
+
if (!["Audience", "Search", "Shopping", "PerformanceMax"].includes(String(base.CampaignType)) || optionalId(base.ExperimentId) || !Object.hasOwn(base, "ExperimentId") || optionalId(base.BudgetId) || base.SubType !== void 0 && base.SubType !== null && base.SubType !== "" || microsoftRows(base.Settings).some((value) => /dynamicsearch/i.test(String(value.Type)))) throw new AdportError16("INVALID_INPUT", "microsoft: experiments require a verified non-experiment base without shared budgets, Dynamic Search Ads, mixed or other specialized subtypes");
|
|
2384
|
+
if (base.BudgetType !== "DailyBudgetStandard") throw new AdportError16("INVALID_INPUT", "microsoft: experiment base must use DailyBudgetStandard");
|
|
2385
|
+
micros2(base.DailyBudget);
|
|
2386
|
+
}
|
|
2387
|
+
budget(context2) {
|
|
2388
|
+
const value = micros2(context2.base_campaign.DailyBudget);
|
|
2389
|
+
return [{ target: `base campaign ${microsoftNativeId(context2.base_campaign.Id)} inherited total daily pool (split, not additional)`, ...context2.currency ? { currency: context2.currency } : {}, fromMicros: value, toMicros: value }];
|
|
2390
|
+
}
|
|
2391
|
+
async unique(account, value, exceptExperiment, exceptCampaign) {
|
|
2392
|
+
const campaigns = microsoftRows(await this.campaigns(account)), experiments = await this.query(account, null);
|
|
2393
|
+
if (campaigns.some((row) => microsoftNativeId(row.Id) !== exceptCampaign && typeof row.Name === "string" && row.Name.toLowerCase() === value.toLowerCase()) || experiments.some((row) => microsoftNativeId(row.Id) !== exceptExperiment && typeof row.Name === "string" && row.Name.toLowerCase() === value.toLowerCase())) throw new AdportError16("INVALID_INPUT", "microsoft: experiment name conflicts with a visible campaign or experiment");
|
|
2394
|
+
}
|
|
2395
|
+
interval(context2, start, end, except) {
|
|
2396
|
+
if (context2.active_experiments.some((value) => {
|
|
2397
|
+
if (microsoftNativeId(value.Id) === except) return false;
|
|
2398
|
+
const from = calendarDate(value.StartDate), to = calendarDate(value.EndDate) ?? "9999-12-31";
|
|
2399
|
+
return !from || start <= to && from <= (end ?? "9999-12-31");
|
|
2400
|
+
})) throw new AdportError16("INVALID_INPUT", "microsoft: experiment date range overlaps the visible active inventory or an existing range is unverifiable");
|
|
2401
|
+
}
|
|
2402
|
+
async confirmed(ids, verify) {
|
|
2403
|
+
try {
|
|
2404
|
+
if (!await verify()) throw new Error("Native readback mismatch");
|
|
2405
|
+
} catch {
|
|
2406
|
+
throw new AdportError16("PROVIDER_ERROR", "microsoft: experiment write was accepted but its readback is unconfirmed; reconcile these IDs before retrying", { resourceIds: ids });
|
|
2407
|
+
}
|
|
2408
|
+
return ids;
|
|
2409
|
+
}
|
|
2410
|
+
async removedAfterDelete(account, kind2, targetId, campaignType) {
|
|
2411
|
+
const experiment = kind2 === "experiment", collection = experiment ? "Experiments" : "Campaigns";
|
|
2412
|
+
const result = await this.client.request("campaign", "POST", `${collection}/QueryByIds`, experiment ? { ExperimentIds: [targetId], ReturnAdditionalFields: additional2 } : { AccountId: account, CampaignIds: [targetId], CampaignType: campaignType, ReturnAdditionalFields: "TargetSetting" }, await this.accountScope(account));
|
|
2413
|
+
const values = result[collection];
|
|
2414
|
+
if (!Array.isArray(values) || values.length > 1 || result.NestedPartialErrors !== void 0 && result.NestedPartialErrors !== null && (!Array.isArray(result.NestedPartialErrors) || result.NestedPartialErrors.some(Boolean))) return false;
|
|
2415
|
+
const errors = z16.array(z16.record(z16.string(), z16.unknown()).nullable()).parse(result.PartialErrors ?? []).filter((value) => value !== null);
|
|
2416
|
+
if (!errors.length) return values.every((value) => value === null || microsoftNativeId(value.Id) === targetId && value[experiment ? "ExperimentStatus" : "Status"] === "Deleted");
|
|
2417
|
+
return values.length === 1 && values[0] === null && errors.length === 1 && errors[0].Index === 0 && errors[0].Code === (experiment ? 6110 : 1120) && errors[0].ErrorCode === (experiment ? "ExperimentIdInvalid" : "CampaignServiceInvalidCampaignStatus");
|
|
2418
|
+
}
|
|
2419
|
+
async plan(op, guard) {
|
|
2420
|
+
const kinds = { microsoft_create_experiment: "create", microsoft_update_experiment: "update", microsoft_end_experiment: "update", microsoft_delete_experiment: "remove" };
|
|
2421
|
+
if (op.provider !== "microsoft" || !MICROSOFT_EXPERIMENT_WRITES.has(op.tool) || op.kind !== kinds[op.tool]) throw new AdportError16("INVALID_INPUT", "microsoft: experiment operation kind mismatch");
|
|
2422
|
+
const account = op.accountId;
|
|
2423
|
+
if (op.tool === "microsoft_create_experiment") {
|
|
2424
|
+
const input2 = create4.parse(op.payload), context3 = await this.base(account, input2.base_campaign_id, true);
|
|
2425
|
+
this.eligible(context3);
|
|
2426
|
+
if (context3.snapshot_hash !== input2.expected_base_context_hash) throw new AdportError16("PENDING_MISMATCH", "microsoft: experiment base context changed; read fresh context and request a new preview");
|
|
2427
|
+
if (guard.forcePausedCreation && context3.base_campaign.Status !== "Paused") throw new AdportError16("POLICY_VIOLATION", "microsoft: experiment campaign status is inherited; paused_creation requires a currently Paused base campaign");
|
|
2428
|
+
await this.unique(account, input2.name);
|
|
2429
|
+
const start = input2.start_date;
|
|
2430
|
+
if (context3.active_experiments.length >= 10) throw new AdportError16("INVALID_INPUT", "microsoft: visible experiment inventory has reached the native ten-experiment limit for this base");
|
|
2431
|
+
this.interval(context3, start, input2.end_date);
|
|
2432
|
+
const fields3 = { BaseCampaignId: input2.base_campaign_id, Name: input2.name, StartDate: nativeDate(start), ...input2.end_date ? { EndDate: nativeDate(input2.end_date) } : {}, TrafficSplitPercent: input2.traffic_split_percent, ExperimentType: input2.experiment_type, ExperimentStatus: "Active" };
|
|
2433
|
+
return { summary: `Create Microsoft experiment "${input2.name}" from "${String(context3.base_campaign.Name)}"`, changes: [`+ ${JSON.stringify(fields3)}`, `Creates an asynchronous campaign copy inheriting base ${context3.base_campaign.Status} status, ${context3.base_campaign.DailyBudget} daily budget and ${context3.base_campaign.TimeZone} timezone. Required native Active setup input transitions to Creating; it is not an independent branch activation.`, "Existing total base daily allocation is split, not increased. Native name/history and experiment limits remain authoritative."], fieldChanges: [{ field: "Experiment", before: "(new)", after: input2.name }, { field: "Base campaign", before: "(none)", after: `${String(context3.base_campaign.Name)} (${input2.base_campaign_id})` }, { field: "Experiment traffic/budget share", before: "0%", after: `${input2.traffic_split_percent}% of existing base pool` }, { field: "Inherited serving status", before: String(context3.base_campaign.Status), after: String(context3.base_campaign.Status) }], notes: notes6, coercions: [], budgetDeltas: this.budget(context3), execute: async () => {
|
|
2434
|
+
const result = await this.request(account, "Experiments", { Experiments: [fields3] }), ids = z16.array(z16.unknown()).parse(result.ExperimentIds).filter((value) => value !== null).map(microsoftNativeId);
|
|
2435
|
+
if (ids.length !== 1) throw new AdportError16("PROVIDER_ERROR", "microsoft: experiment creation receipt mismatch; reconcile before retrying", { resourceIds: ids });
|
|
2436
|
+
return this.confirmed(ids, async () => {
|
|
2437
|
+
const after = await this.get(account, ids[0]);
|
|
2438
|
+
return microsoftNativeId(after.experiment.BaseCampaignId) === input2.base_campaign_id && after.experiment.Name === input2.name && ["Creating", "Active", "Paused", "Scheduled"].includes(String(after.experiment.ExperimentStatus)) && (!guard.forcePausedCreation || after.base_context.base_campaign.Status === "Paused" && (!after.experiment_campaign || after.experiment_campaign.Status === "Paused"));
|
|
2439
|
+
});
|
|
2440
|
+
} };
|
|
2441
|
+
}
|
|
2442
|
+
const input = (op.tool === "microsoft_update_experiment" ? update5 : reference6).parse(op.payload), current = await this.get(account, input.experiment_id, true), experiment = current.experiment, context2 = current.base_context, status2 = String(experiment.ExperimentStatus);
|
|
2443
|
+
if (input.expected_snapshot_hash !== current.snapshot_hash) throw new AdportError16("PENDING_MISMATCH", "microsoft: experiment or coupled campaign context changed; request a fresh preview");
|
|
2444
|
+
if (["Promoting", "Graduating"].includes(status2)) throw new AdportError16("INVALID_INPUT", "microsoft: reconcile the in-progress experiment transition before another mutation");
|
|
2445
|
+
if (op.tool === "microsoft_delete_experiment") {
|
|
2446
|
+
const branchId = optionalId(experiment.ExperimentCampaignId), baseId = microsoftNativeId(experiment.BaseCampaignId);
|
|
2447
|
+
return { summary: `Delete Microsoft experiment "${String(experiment.Name)}" and its campaign copy`, changes: [`- experiment ${input.experiment_id}${branchId ? ` and experiment campaign ${branchId}` : " (no experiment campaign ID returned yet)"}`, "Native deletion is coupled to the experiment campaign. The base campaign is preserved."], fieldChanges: [{ field: "Experiment and campaign copy", before: `${String(experiment.Name)} (${input.experiment_id})`, after: "Deleted together" }], notes: notes6, coercions: [], budgetDeltas: [], execute: async () => {
|
|
2448
|
+
await this.request(account, "Experiments", { ExperimentIds: [input.experiment_id] }, "DELETE");
|
|
2449
|
+
return this.confirmed([input.experiment_id, ...branchId ? [branchId] : []], async () => {
|
|
2450
|
+
if (!await this.removedAfterDelete(account, "experiment", input.experiment_id) || branchId && !await this.removedAfterDelete(account, "campaign", branchId, context2.base_campaign.CampaignType)) return false;
|
|
2451
|
+
const base = await this.campaignById(account, baseId, context2.base_campaign.CampaignType), active = await this.query(account, null), campaigns = microsoftRows(await this.campaigns(account));
|
|
2452
|
+
return !!base && base.Status === context2.base_campaign.Status && base.DailyBudget === context2.base_campaign.DailyBudget && !active.some((value) => microsoftNativeId(value.Id) === input.experiment_id) && !campaigns.some((value) => value.Status !== "Deleted" && (microsoftNativeId(value.Id) === branchId || optionalId(value.ExperimentId) === input.experiment_id));
|
|
2453
|
+
});
|
|
2454
|
+
} };
|
|
2455
|
+
}
|
|
2456
|
+
if (!["Active", "Paused", "Scheduled", "Ended"].includes(status2)) throw new AdportError16("INVALID_INPUT", "microsoft: experiment is not in a supported settled state for this edit");
|
|
2457
|
+
let fields2, fieldChanges;
|
|
2458
|
+
if (op.tool === "microsoft_end_experiment") {
|
|
2459
|
+
if (status2 === "Ended") throw new AdportError16("INVALID_INPUT", "microsoft: experiment is already ended");
|
|
2460
|
+
fields2 = { Id: input.experiment_id, ExperimentStatus: "Ended" };
|
|
2461
|
+
fieldChanges = [{ field: "Experiment status", before: status2, after: "Ended (cannot restart)" }];
|
|
2462
|
+
} else {
|
|
2463
|
+
const edit = update5.parse(input);
|
|
2464
|
+
if (status2 === "Ended") throw new AdportError16("INVALID_INPUT", "microsoft: ended experiments cannot be edited; deletion is a separate operation");
|
|
2465
|
+
if ((edit.start_date !== void 0 || edit.traffic_split_percent !== void 0) && status2 !== "Scheduled") throw new AdportError16("INVALID_INPUT", "microsoft: start-date and split edits require native Scheduled status; Paused does not prove the experiment never started");
|
|
2466
|
+
const from = edit.start_date ?? calendarDate(experiment.StartDate), to = edit.end_date === null ? void 0 : edit.end_date ?? calendarDate(experiment.EndDate);
|
|
2467
|
+
if (!from || to && from > to) throw new AdportError16("INVALID_INPUT", "microsoft: experiment date interval is invalid or unavailable");
|
|
2468
|
+
if (edit.start_date !== void 0 || edit.end_date !== void 0) this.interval(context2, from, to, input.experiment_id);
|
|
2469
|
+
if (edit.name !== void 0) await this.unique(account, edit.name, input.experiment_id, optionalId(experiment.ExperimentCampaignId));
|
|
2470
|
+
fields2 = { Id: input.experiment_id, ...edit.name !== void 0 ? { Name: edit.name } : {}, ...edit.start_date !== void 0 ? { StartDate: nativeDate(edit.start_date) } : {}, ...edit.end_date !== void 0 ? { EndDate: edit.end_date === null ? { Day: 0, Month: 0, Year: 0 } : nativeDate(edit.end_date) } : {}, ...edit.traffic_split_percent !== void 0 ? { TrafficSplitPercent: edit.traffic_split_percent } : {} };
|
|
2471
|
+
fieldChanges = Object.entries(fields2).filter(([key]) => key !== "Id").map(([field, value]) => ({ field, before: JSON.stringify(experiment[field] ?? null), after: JSON.stringify(value) }));
|
|
2472
|
+
}
|
|
2473
|
+
return { summary: `${op.tool === "microsoft_end_experiment" ? "End" : "Update"} Microsoft experiment "${String(experiment.Name)}"`, changes: [`~ ${JSON.stringify(fields2)}`, "Names are coupled to the experiment campaign; other branch settings, base status and the inherited total budget are preserved. Ending is irreversible and pauses the experiment campaign."], fieldChanges, notes: notes6, coercions: [], budgetDeltas: this.budget(context2), execute: async () => {
|
|
2474
|
+
await this.request(account, "Experiments", { Experiments: [fields2] }, "PUT");
|
|
2475
|
+
return this.confirmed([input.experiment_id], async () => {
|
|
2476
|
+
const after = await this.get(account, input.experiment_id);
|
|
2477
|
+
return Object.entries(fields2).filter(([key]) => key !== "Id").every(([key, value]) => key === "EndDate" ? calendarDate(after.experiment.EndDate) === calendarDate(value) : key === "StartDate" ? calendarDate(after.experiment.StartDate) === calendarDate(value) : after.experiment[key] === value) && after.base_context.base_campaign.Status === context2.base_campaign.Status && after.base_context.base_campaign.DailyBudget === context2.base_campaign.DailyBudget && (op.tool !== "microsoft_end_experiment" || !after.experiment_campaign || after.experiment_campaign.Status === "Paused");
|
|
2478
|
+
});
|
|
2479
|
+
} };
|
|
2480
|
+
}
|
|
2481
|
+
};
|
|
2482
|
+
function microsoftExperimentTools(provider) {
|
|
2483
|
+
return [
|
|
2484
|
+
defineTool12({ name: "microsoft_experiments", namespace: "microsoft", description: "Read native active experiments only; this inventory does not establish absence of historical experiments. Use get for an exact known ID. Continue next_cursor as after_experiment_id.", input: z16.object({ account_id: microsoftId, after_experiment_id: microsoftId.optional(), limit: z16.number().int().positive().max(1e3).default(100) }), output: z16.object({ rows: z16.array(z16.record(z16.string(), z16.unknown())), truncated: z16.boolean(), next_cursor: microsoftId.optional(), visibility: z16.string(), notes: z16.array(z16.string()) }), pagination: { cursorInput: "after_experiment_id" }, annotations: { readOnly: true }, handler: (input) => provider.experiments.list(input) }),
|
|
2485
|
+
defineTool12({ name: "microsoft_experiment_base_context", namespace: "microsoft", description: "Read an owned base campaign, its native active experiments, currency and snapshot_hash for creation. Budgets/status/timezone are inherited by experiment copies. Snapshot covers campaign configuration and visible active inventory, not every child entity.", input: z16.object({ account_id: microsoftId, base_campaign_id: microsoftId }), output: contextSchema2, annotations: { readOnly: true }, handler: (input) => provider.experiments.base(input.account_id, input.base_campaign_id) }),
|
|
2486
|
+
defineTool12({ name: "microsoft_get_experiment", namespace: "microsoft", description: "Read an exact known experiment, verified base/experiment campaign ownership, native setup state and coupled snapshot_hash. Creating is asynchronous acceptance, not readiness.", input: z16.object({ account_id: microsoftId, experiment_id: microsoftId }), output: viewSchema2, annotations: { readOnly: true }, handler: (input) => provider.experiments.get(input.account_id, input.experiment_id) }),
|
|
2487
|
+
guardedWriteTool11({ name: "microsoft_create_experiment", namespace: "microsoft", provider: "microsoft", kind: "create", description: "Create a native campaign-copy experiment with expected_base_context_hash. Paused creation requires a currently Paused base; native Active setup input becomes Creating. Dates use base timezone. Splits existing daily budget/traffic rather than adding a pool. Shared-budget, DSA, mixed/specialized or experiment bases are rejected. Setup is asynchronous.", payload: create4 }),
|
|
2488
|
+
guardedWriteTool11({ name: "microsoft_update_experiment", namespace: "microsoft", provider: "microsoft", kind: "update", description: "Edit experiment name or calendar schedule with expected_snapshot_hash. Name changes rename the campaign copy. Native Scheduled status is required before changing start/split; Paused alone is insufficient. end_date:null clears expiry with the native zero Date. No promotion or graduation.", payload: update5 }),
|
|
2489
|
+
guardedWriteTool11({ name: "microsoft_end_experiment", namespace: "microsoft", provider: "microsoft", kind: "update", description: "End an owned settled experiment early with expected_snapshot_hash. This cannot be restarted and pauses its campaign copy; the base campaign is preserved. Pausing temporarily is instead coupled to pausing the base campaign.", payload: reference6 }),
|
|
2490
|
+
guardedWriteTool11({ name: "microsoft_delete_experiment", namespace: "microsoft", provider: "microsoft", kind: "remove", description: "Delete an exact owned experiment and its coupled campaign copy with expected_snapshot_hash; preserve the base. Confirms disappearance before success. Do not retry accepted-but-unconfirmed receipts without reconciling their IDs.", payload: reference6 })
|
|
2491
|
+
];
|
|
170
2492
|
}
|
|
171
2493
|
|
|
172
2494
|
// src/provider.ts
|
|
173
2495
|
var UNITS_TO_MICROS = 1e6;
|
|
2496
|
+
var MICROSOFT_CAMPAIGN_TYPES = "App, Audience, DynamicSearchAds, Hotel, ObjectiveBased, PerformanceMax, Search, Shopping";
|
|
174
2497
|
var MicrosoftAdsProvider = class {
|
|
175
|
-
constructor(client, options = {}) {
|
|
2498
|
+
constructor(client, options = {}, media = new LocalMediaResolver2()) {
|
|
176
2499
|
this.client = client;
|
|
177
2500
|
this.options = options;
|
|
2501
|
+
this.children = new MicrosoftChildService(client, (account) => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign));
|
|
2502
|
+
this.images = new MicrosoftImageService(client, (account) => this.scopeFor(account), media);
|
|
2503
|
+
this.extensions = new MicrosoftExtensionService(client, (account) => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign), (account, ids) => this.images.lookupMany(account, ids));
|
|
2504
|
+
this.targeting = new MicrosoftTargetingService(client, (account) => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign));
|
|
2505
|
+
this.generalTargeting = new MicrosoftGeneralTargetingService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign));
|
|
2506
|
+
this.negativeKeywords = new MicrosoftNegativeKeywordService(client, (account) => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign));
|
|
2507
|
+
this.budgets = new MicrosoftBudgetService(client, (account) => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign), (account) => this.listCampaigns(account), async (account) => {
|
|
2508
|
+
await this.scopeFor(account);
|
|
2509
|
+
return this.currencies.get(account);
|
|
2510
|
+
});
|
|
2511
|
+
this.planning = new MicrosoftPlanningService(client, (account) => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign), (account) => this.currencies.get(account));
|
|
2512
|
+
this.conversions = new MicrosoftConversionService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign));
|
|
2513
|
+
this.audiences = new MicrosoftAudienceService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign), (account) => this.listCampaigns(account));
|
|
2514
|
+
this.audienceTargeting = new MicrosoftAudienceTargetingService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign), (account, audience, type) => this.audiences.get(account, audience, type));
|
|
2515
|
+
this.offlineReports = new MicrosoftOfflineReportService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign));
|
|
2516
|
+
this.offlineConversions = new MicrosoftOfflineConversionService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign), this.conversions);
|
|
2517
|
+
this.experiments = new MicrosoftExperimentService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign), (account) => this.listCampaigns(account), async (account) => {
|
|
2518
|
+
await this.scopeFor(account);
|
|
2519
|
+
return this.currencies.get(account);
|
|
2520
|
+
});
|
|
178
2521
|
}
|
|
179
2522
|
client;
|
|
180
2523
|
options;
|
|
181
2524
|
id = "microsoft";
|
|
182
2525
|
/** accountId → parent customer id, learned from SearchAccounts. */
|
|
183
2526
|
customerIds = /* @__PURE__ */ new Map();
|
|
2527
|
+
currencies = /* @__PURE__ */ new Map();
|
|
2528
|
+
children;
|
|
2529
|
+
images;
|
|
2530
|
+
extensions;
|
|
2531
|
+
targeting;
|
|
2532
|
+
generalTargeting;
|
|
2533
|
+
negativeKeywords;
|
|
2534
|
+
budgets;
|
|
2535
|
+
planning;
|
|
2536
|
+
conversions;
|
|
2537
|
+
audiences;
|
|
2538
|
+
audienceTargeting;
|
|
2539
|
+
offlineReports;
|
|
2540
|
+
offlineConversions;
|
|
2541
|
+
experiments;
|
|
184
2542
|
capabilities() {
|
|
185
2543
|
return { serverDryRun: false };
|
|
186
2544
|
}
|
|
@@ -201,7 +2559,7 @@ var MicrosoftAdsProvider = class {
|
|
|
201
2559
|
);
|
|
202
2560
|
const userId = user.User?.Id;
|
|
203
2561
|
if (userId === void 0) {
|
|
204
|
-
throw new
|
|
2562
|
+
throw new AdportError17("PROVIDER_ERROR", "microsoft: GetUser returned no user id");
|
|
205
2563
|
}
|
|
206
2564
|
const search = await this.client.request("customer", "POST", "Accounts/Search", {
|
|
207
2565
|
Predicates: [{ Field: "UserId", Operator: "Equals", Value: String(userId) }],
|
|
@@ -209,6 +2567,7 @@ var MicrosoftAdsProvider = class {
|
|
|
209
2567
|
});
|
|
210
2568
|
const accounts = search.Accounts ?? [];
|
|
211
2569
|
for (const account of accounts) {
|
|
2570
|
+
if (account.CurrencyCode) this.currencies.set(String(account.Id), account.CurrencyCode);
|
|
212
2571
|
if (account.ParentCustomerId !== void 0) {
|
|
213
2572
|
this.customerIds.set(String(account.Id), String(account.ParentCustomerId));
|
|
214
2573
|
}
|
|
@@ -221,8 +2580,12 @@ var MicrosoftAdsProvider = class {
|
|
|
221
2580
|
status: a.AccountLifeCycleStatus
|
|
222
2581
|
}));
|
|
223
2582
|
}
|
|
224
|
-
async scopeFor(accountId) {
|
|
225
|
-
if (
|
|
2583
|
+
async scopeFor(accountId, refresh = false) {
|
|
2584
|
+
if (refresh) {
|
|
2585
|
+
this.customerIds.delete(accountId);
|
|
2586
|
+
this.currencies.delete(accountId);
|
|
2587
|
+
}
|
|
2588
|
+
if (refresh || !this.customerIds.has(accountId)) await this.listAccounts();
|
|
226
2589
|
return { customerId: this.customerIds.get(accountId), customerAccountId: accountId };
|
|
227
2590
|
}
|
|
228
2591
|
async listCampaigns(accountId) {
|
|
@@ -231,7 +2594,7 @@ var MicrosoftAdsProvider = class {
|
|
|
231
2594
|
"campaign",
|
|
232
2595
|
"POST",
|
|
233
2596
|
"Campaigns/QueryByAccountId",
|
|
234
|
-
{ AccountId: accountId, ReturnAdditionalFields: null },
|
|
2597
|
+
{ AccountId: accountId, CampaignType: MICROSOFT_CAMPAIGN_TYPES, ReturnAdditionalFields: null },
|
|
235
2598
|
scope
|
|
236
2599
|
);
|
|
237
2600
|
return data.Campaigns ?? [];
|
|
@@ -243,27 +2606,42 @@ var MicrosoftAdsProvider = class {
|
|
|
243
2606
|
return this.client.request(input.service, "POST", path, input.body ?? {}, scope);
|
|
244
2607
|
}
|
|
245
2608
|
async report(query) {
|
|
246
|
-
|
|
247
|
-
throw new AdportError2("INVALID_INPUT", "microsoft: report supports campaign and account levels in v0");
|
|
248
|
-
}
|
|
249
|
-
const range = resolveDateRange(query.dateRange);
|
|
2609
|
+
const range2 = resolveDateRange(query.dateRange);
|
|
250
2610
|
const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);
|
|
251
|
-
const
|
|
2611
|
+
const rows3 = [];
|
|
252
2612
|
for (const accountId of accountIds) {
|
|
253
|
-
const providerRows = await this.
|
|
2613
|
+
const providerRows = await this.performanceReport(accountId, range2.start, range2.end, query.level === "account" ? { ...query, level: "campaign", metrics: [...METRICS] } : query);
|
|
254
2614
|
if (query.level === "account") {
|
|
255
|
-
if (providerRows.length > 0)
|
|
2615
|
+
if (providerRows.length > 0) {
|
|
2616
|
+
const aggregate = aggregateAccountRows(providerRows, this.id, accountId);
|
|
2617
|
+
aggregate.metrics = Object.fromEntries(query.metrics.filter((metric) => aggregate.metrics[metric] !== void 0).map((metric) => [metric, aggregate.metrics[metric]]));
|
|
2618
|
+
rows3.push(aggregate);
|
|
2619
|
+
}
|
|
256
2620
|
} else {
|
|
257
|
-
|
|
2621
|
+
rows3.push(...providerRows);
|
|
258
2622
|
}
|
|
259
2623
|
}
|
|
260
|
-
|
|
2624
|
+
const limit = query.limit ?? 1e3;
|
|
2625
|
+
return { rows: rows3.slice(0, limit), truncated: rows3.length > limit };
|
|
261
2626
|
}
|
|
262
|
-
async
|
|
2627
|
+
async performanceReport(accountId, start, end, query) {
|
|
2628
|
+
const selection = query.level === "ad_group" ? { type: "AdGroupPerformanceReportRequest", columns: ["AdGroupId", "AdGroupName", "Status"] } : query.level === "ad" ? { type: "AdPerformanceReportRequest", columns: ["AdId", "AdTitle", "AdStatus"] } : { type: "CampaignPerformanceReportRequest", columns: ["CampaignId", "CampaignName", "CampaignStatus"] };
|
|
2629
|
+
const bytes = await this.reportCsv(accountId, start, end, selection.type, [...selection.columns, "Spend", "Impressions", "Clicks", "Conversions", "Revenue"]);
|
|
2630
|
+
return bytes ? this.parseReport(bytes, accountId, query) : [];
|
|
2631
|
+
}
|
|
2632
|
+
async nativeReport(input) {
|
|
2633
|
+
const range2 = resolveDateRange(input.date_range);
|
|
2634
|
+
const type = input.kind === "keyword" ? "KeywordPerformanceReportRequest" : "SearchQueryPerformanceReportRequest";
|
|
2635
|
+
const columns = input.kind === "keyword" ? ["CampaignId", "AdGroupId", "KeywordId", "Keyword", "BidMatchType"] : ["CampaignId", "AdGroupId", "AdId", "KeywordId", "Keyword", "SearchQuery"];
|
|
2636
|
+
const bytes = await this.reportCsv(input.account_id, range2.start, range2.end, type, [...columns, "Spend", "Impressions", "Clicks", "Conversions", "Revenue"]);
|
|
2637
|
+
const records = bytes ? this.reportObjects(bytes) : [];
|
|
2638
|
+
return { rows: records.slice(0, input.limit), truncated: records.length > input.limit, report_type: type };
|
|
2639
|
+
}
|
|
2640
|
+
async reportCsv(accountId, start, end, type, columns) {
|
|
263
2641
|
const scope = await this.scopeFor(accountId);
|
|
264
2642
|
const toDate = (iso) => {
|
|
265
|
-
const [year, month,
|
|
266
|
-
return { Day:
|
|
2643
|
+
const [year, month, day2] = iso.split("-").map(Number);
|
|
2644
|
+
return { Day: day2, Month: month, Year: year };
|
|
267
2645
|
};
|
|
268
2646
|
const submit = await this.client.request(
|
|
269
2647
|
"reporting",
|
|
@@ -271,7 +2649,7 @@ var MicrosoftAdsProvider = class {
|
|
|
271
2649
|
"GenerateReport/Submit",
|
|
272
2650
|
{
|
|
273
2651
|
ReportRequest: {
|
|
274
|
-
Type:
|
|
2652
|
+
Type: type,
|
|
275
2653
|
Format: "Csv",
|
|
276
2654
|
FormatVersion: "2.0",
|
|
277
2655
|
ReportName: "adport campaign report",
|
|
@@ -280,7 +2658,7 @@ var MicrosoftAdsProvider = class {
|
|
|
280
2658
|
ExcludeColumnHeaders: false,
|
|
281
2659
|
ReturnOnlyCompleteData: false,
|
|
282
2660
|
Aggregation: "Summary",
|
|
283
|
-
Columns:
|
|
2661
|
+
Columns: columns,
|
|
284
2662
|
Scope: { AccountIds: [accountId] },
|
|
285
2663
|
Time: { CustomDateRangeStart: toDate(start), CustomDateRangeEnd: toDate(end) }
|
|
286
2664
|
}
|
|
@@ -288,75 +2666,59 @@ var MicrosoftAdsProvider = class {
|
|
|
288
2666
|
scope
|
|
289
2667
|
);
|
|
290
2668
|
if (!submit.ReportRequestId) {
|
|
291
|
-
throw new
|
|
2669
|
+
throw new AdportError17("PROVIDER_ERROR", "microsoft: SubmitGenerateReport returned no ReportRequestId");
|
|
292
2670
|
}
|
|
293
2671
|
const maxAttempts = this.options.pollMaxAttempts ?? 30;
|
|
294
2672
|
const interval = this.options.pollIntervalMs ?? 5e3;
|
|
295
2673
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
296
2674
|
const poll = await this.client.request("reporting", "POST", "GenerateReport/Poll", { ReportRequestId: submit.ReportRequestId }, scope);
|
|
297
|
-
const
|
|
298
|
-
if (
|
|
299
|
-
throw new
|
|
2675
|
+
const status2 = poll.ReportRequestStatus?.Status;
|
|
2676
|
+
if (status2 === "Error") {
|
|
2677
|
+
throw new AdportError17("PROVIDER_ERROR", "microsoft: report generation failed (Status: Error)");
|
|
300
2678
|
}
|
|
301
|
-
if (
|
|
302
|
-
const
|
|
303
|
-
if (!
|
|
304
|
-
return this.
|
|
2679
|
+
if (status2 === "Success") {
|
|
2680
|
+
const url3 = poll.ReportRequestStatus?.ReportDownloadUrl;
|
|
2681
|
+
if (!url3) return void 0;
|
|
2682
|
+
return this.client.download(url3);
|
|
305
2683
|
}
|
|
306
2684
|
await new Promise((resolve) => setTimeout(resolve, interval));
|
|
307
2685
|
}
|
|
308
|
-
throw new
|
|
2686
|
+
throw new AdportError17("PROVIDER_ERROR", `microsoft: report not ready after ${maxAttempts} polls`);
|
|
309
2687
|
}
|
|
310
|
-
|
|
2688
|
+
reportObjects(zipBytes) {
|
|
311
2689
|
const files = unzipSync(zipBytes);
|
|
312
|
-
const
|
|
313
|
-
if (!
|
|
314
|
-
const
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
const
|
|
321
|
-
const
|
|
322
|
-
return
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
const impressions = Number(value("Impressions") || 0);
|
|
326
|
-
const clicks = Number(value("Clicks") || 0);
|
|
327
|
-
const conversions = Number(value("Conversions") || 0);
|
|
328
|
-
const revenue = Number(value("Revenue") || 0);
|
|
329
|
-
const all = {
|
|
330
|
-
spend: round2(spend),
|
|
331
|
-
impressions,
|
|
332
|
-
clicks,
|
|
333
|
-
conversions,
|
|
334
|
-
conversion_value: round2(revenue),
|
|
335
|
-
ctr: impressions > 0 ? round2(clicks / impressions * 100) : 0,
|
|
336
|
-
cpc: clicks > 0 ? round2(spend / clicks) : 0,
|
|
337
|
-
cpm: impressions > 0 ? round2(spend / impressions * 1e3) : 0,
|
|
338
|
-
cpa: conversions > 0 ? round2(spend / conversions) : 0,
|
|
339
|
-
roas: spend > 0 ? round2(revenue / spend) : 0
|
|
2690
|
+
const selected2 = Object.entries(files).find(([name5]) => name5.toLowerCase().endsWith(".csv"))?.[1] ?? Object.values(files)[0];
|
|
2691
|
+
if (!selected2) return [];
|
|
2692
|
+
const rows3 = parseCsv(new TextDecoder().decode(selected2).replace(/^\uFEFF/, ""));
|
|
2693
|
+
const header = rows3[0];
|
|
2694
|
+
return header ? rows3.slice(1).map((row) => Object.fromEntries(header.map((key, index) => [key, row[index] ?? ""]))) : [];
|
|
2695
|
+
}
|
|
2696
|
+
parseReport(zipBytes, accountId, query) {
|
|
2697
|
+
return this.reportObjects(zipBytes).map((row) => {
|
|
2698
|
+
const numeric = (key) => {
|
|
2699
|
+
const text2 = row[key]?.trim();
|
|
2700
|
+
if (!text2) return void 0;
|
|
2701
|
+
const number = Number(text2);
|
|
2702
|
+
return Number.isFinite(number) ? number : void 0;
|
|
340
2703
|
};
|
|
341
|
-
|
|
2704
|
+
const metrics = performanceMetrics({ spend: numeric("Spend"), impressions: numeric("Impressions"), clicks: numeric("Clicks"), conversions: numeric("Conversions"), conversion_value: numeric("Revenue") });
|
|
2705
|
+
const identity3 = query.level === "ad_group" ? ["AdGroupId", "AdGroupName", "Status"] : query.level === "ad" ? ["AdId", "AdTitle", "AdStatus"] : ["CampaignId", "CampaignName", "CampaignStatus"];
|
|
2706
|
+
return {
|
|
342
2707
|
provider: this.id,
|
|
343
2708
|
accountId,
|
|
344
|
-
entity: {
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
status: value("CampaignStatus") || void 0
|
|
349
|
-
},
|
|
350
|
-
metrics: Object.fromEntries(query.metrics.map((m) => [m, all[m]]))
|
|
351
|
-
});
|
|
352
|
-
}
|
|
353
|
-
return out;
|
|
2709
|
+
entity: { level: query.level, id: row[identity3[0]] ?? "", name: row[identity3[1]] ?? "", status: row[identity3[2]] || void 0 },
|
|
2710
|
+
metrics: Object.fromEntries(query.metrics.filter((metric) => metrics[metric] !== void 0).map((metric) => [metric, metrics[metric]]))
|
|
2711
|
+
};
|
|
2712
|
+
});
|
|
354
2713
|
}
|
|
355
2714
|
async previewWrite(op, guard) {
|
|
356
2715
|
const plan = await this.plan(op, guard);
|
|
357
2716
|
return {
|
|
358
2717
|
summary: plan.summary,
|
|
359
2718
|
changes: plan.changes,
|
|
2719
|
+
...plan.fieldChanges ? { fieldChanges: plan.fieldChanges } : {},
|
|
2720
|
+
...plan.notes ? { notes: plan.notes } : {},
|
|
2721
|
+
...plan.review ? { review: plan.review } : {},
|
|
360
2722
|
coercions: plan.coercions,
|
|
361
2723
|
budgetDeltas: plan.budgetDeltas,
|
|
362
2724
|
serverValidated: false
|
|
@@ -365,9 +2727,20 @@ var MicrosoftAdsProvider = class {
|
|
|
365
2727
|
async applyWrite(op, guard) {
|
|
366
2728
|
const plan = await this.plan(op, guard);
|
|
367
2729
|
const resourceIds = await plan.execute();
|
|
368
|
-
return { applied: true, resourceIds };
|
|
2730
|
+
return { applied: true, resourceIds, ...plan.resultDetails ? { details: plan.resultDetails() } : {}, ...plan.resultWarnings ? { warnings: plan.resultWarnings() } : {} };
|
|
369
2731
|
}
|
|
370
2732
|
async plan(op, guard) {
|
|
2733
|
+
if (MICROSOFT_IMAGE_WRITES.has(op.tool)) return this.images.plan(op);
|
|
2734
|
+
if (MICROSOFT_EXTENSION_WRITES.has(op.tool)) return this.extensions.plan(op, guard);
|
|
2735
|
+
if (MICROSOFT_TARGETING_WRITES.has(op.tool)) return this.targeting.plan(op, guard);
|
|
2736
|
+
if (MICROSOFT_GENERAL_TARGETING_WRITES.has(op.tool)) return this.generalTargeting.plan(op, guard);
|
|
2737
|
+
if (MICROSOFT_NEGATIVE_KEYWORD_WRITES.has(op.tool)) return this.negativeKeywords.plan(op);
|
|
2738
|
+
if (MICROSOFT_BUDGET_WRITES.has(op.tool)) return this.budgets.plan(op);
|
|
2739
|
+
if (MICROSOFT_CONVERSION_WRITES.has(op.tool)) return this.conversions.plan(op, guard);
|
|
2740
|
+
if (MICROSOFT_OFFLINE_CONVERSION_WRITES.has(op.tool)) return this.offlineConversions.plan(op);
|
|
2741
|
+
if (MICROSOFT_AUDIENCE_WRITES.has(op.tool)) return this.audiences.plan(op);
|
|
2742
|
+
if (MICROSOFT_AUDIENCE_TARGETING_WRITES.has(op.tool)) return this.audienceTargeting.plan(op, guard);
|
|
2743
|
+
if (MICROSOFT_EXPERIMENT_WRITES.has(op.tool)) return this.experiments.plan(op, guard);
|
|
371
2744
|
const payload = op.payload;
|
|
372
2745
|
switch (op.tool) {
|
|
373
2746
|
case "microsoft_create_campaign":
|
|
@@ -383,15 +2756,31 @@ var MicrosoftAdsProvider = class {
|
|
|
383
2756
|
case "microsoft_api_delete":
|
|
384
2757
|
return this.planApiDelete(op.accountId, payload);
|
|
385
2758
|
default:
|
|
386
|
-
|
|
2759
|
+
return this.children.plan(op, guard);
|
|
387
2760
|
}
|
|
388
2761
|
}
|
|
389
2762
|
async planApiCreate(accountId, payload, guard) {
|
|
390
2763
|
const resource = validateMicrosoftResource(payload.resource);
|
|
2764
|
+
requireTypedMutationTool(resource, payload.body);
|
|
391
2765
|
const body = structuredClone(payload.body);
|
|
392
2766
|
validateMicrosoftAccountScope(body, accountId);
|
|
393
2767
|
const coercions = [];
|
|
394
|
-
if (guard.forcePausedCreation)
|
|
2768
|
+
if (guard.forcePausedCreation) {
|
|
2769
|
+
const collection = resource.toLowerCase();
|
|
2770
|
+
if (["campaigns", "adgroups", "ads", "keywords"].includes(collection)) {
|
|
2771
|
+
const keys = Object.keys(body).filter((key) => key.toLowerCase() === collection);
|
|
2772
|
+
if (!keys.length || keys.some((key) => !Array.isArray(body[key]))) throw new AdportError17("INVALID_INPUT", `microsoft: ${resource} creation needs its native collection array so paused_creation can be enforced`);
|
|
2773
|
+
for (const key of keys) for (const [index, item] of body[key].entries()) {
|
|
2774
|
+
if (!isRecord(item)) throw new AdportError17("INVALID_INPUT", `microsoft: ${resource} creation needs resource objects`);
|
|
2775
|
+
const statuses = Object.keys(item).filter((key2) => key2.toLowerCase() === "status");
|
|
2776
|
+
if (statuses.length === 1 && statuses[0] === "Status" && item.Status === "Paused") continue;
|
|
2777
|
+
for (const status2 of statuses) delete item[status2];
|
|
2778
|
+
item.Status = "Paused";
|
|
2779
|
+
coercions.push(`body.${key}[${index}].Status coerced to Paused by policy (paused_creation)`);
|
|
2780
|
+
}
|
|
2781
|
+
}
|
|
2782
|
+
coerceMicrosoftCreatedStatuses(body, coercions);
|
|
2783
|
+
}
|
|
395
2784
|
return {
|
|
396
2785
|
summary: `Create Microsoft Advertising ${resource} resource(s)`,
|
|
397
2786
|
changes: [`+ POST /${resource} ${JSON.stringify(body)}`],
|
|
@@ -402,9 +2791,10 @@ var MicrosoftAdsProvider = class {
|
|
|
402
2791
|
}
|
|
403
2792
|
async planApiUpdate(accountId, payload) {
|
|
404
2793
|
const resource = validateMicrosoftResource(payload.resource);
|
|
2794
|
+
requireTypedMutationTool(resource, payload.body);
|
|
405
2795
|
validateMicrosoftAccountScope(payload.body, accountId);
|
|
406
2796
|
if (containsMicrosoftBudget(payload.body)) {
|
|
407
|
-
throw new
|
|
2797
|
+
throw new AdportError17("INVALID_INPUT", "microsoft: budget updates require microsoft_set_budget for policy checks");
|
|
408
2798
|
}
|
|
409
2799
|
return {
|
|
410
2800
|
summary: `Update Microsoft Advertising ${resource} resource(s)`,
|
|
@@ -416,6 +2806,7 @@ var MicrosoftAdsProvider = class {
|
|
|
416
2806
|
}
|
|
417
2807
|
async planApiDelete(accountId, payload) {
|
|
418
2808
|
const resource = validateMicrosoftResource(payload.resource);
|
|
2809
|
+
requireTypedMutationTool(resource, payload.body);
|
|
419
2810
|
validateMicrosoftAccountScope(payload.body, accountId);
|
|
420
2811
|
return {
|
|
421
2812
|
summary: `Permanently delete Microsoft Advertising ${resource} resource(s)`,
|
|
@@ -429,14 +2820,14 @@ var MicrosoftAdsProvider = class {
|
|
|
429
2820
|
const scope = await this.scopeFor(accountId);
|
|
430
2821
|
const result = await this.client.request("campaign", method, resource, body, scope);
|
|
431
2822
|
const partial = formatPartialErrors(result.PartialErrors);
|
|
432
|
-
if (partial) throw new
|
|
2823
|
+
if (partial) throw new AdportError17("PROVIDER_ERROR", `microsoft: ${resource} partial errors \u2014 ${partial}`);
|
|
433
2824
|
return extractMicrosoftIds(result);
|
|
434
2825
|
}
|
|
435
2826
|
async planCreateCampaign(accountId, payload, guard) {
|
|
436
2827
|
const coercions = [];
|
|
437
|
-
let
|
|
438
|
-
if (guard.forcePausedCreation &&
|
|
439
|
-
|
|
2828
|
+
let status2 = payload.status ?? "Paused";
|
|
2829
|
+
if (guard.forcePausedCreation && status2 === "Active") {
|
|
2830
|
+
status2 = "Paused";
|
|
440
2831
|
coercions.push("status coerced to Paused by policy (paused_creation)");
|
|
441
2832
|
}
|
|
442
2833
|
const campaign = {
|
|
@@ -445,11 +2836,11 @@ var MicrosoftAdsProvider = class {
|
|
|
445
2836
|
DailyBudget: payload.daily_budget,
|
|
446
2837
|
BudgetType: "DailyBudgetStandard",
|
|
447
2838
|
TimeZone: payload.time_zone ?? "PacificTimeUSCanadaTijuana",
|
|
448
|
-
Status:
|
|
2839
|
+
Status: status2
|
|
449
2840
|
};
|
|
450
2841
|
return {
|
|
451
|
-
summary: `Create Microsoft Advertising campaign "${payload.name}" (${
|
|
452
|
-
changes: [`+ campaign "${payload.name}" type=Search daily_budget=${payload.daily_budget} status=${
|
|
2842
|
+
summary: `Create Microsoft Advertising campaign "${payload.name}" (${status2}), daily budget ${payload.daily_budget}`,
|
|
2843
|
+
changes: [`+ campaign "${payload.name}" type=Search daily_budget=${payload.daily_budget} status=${status2}`],
|
|
453
2844
|
coercions,
|
|
454
2845
|
budgetDeltas: [
|
|
455
2846
|
{ target: `new campaign "${payload.name}" daily budget`, toMicros: payload.daily_budget * UNITS_TO_MICROS }
|
|
@@ -458,8 +2849,8 @@ var MicrosoftAdsProvider = class {
|
|
|
458
2849
|
const scope = await this.scopeFor(accountId);
|
|
459
2850
|
const result = await this.client.request("campaign", "POST", "Campaigns", { AccountId: accountId, Campaigns: [campaign] }, scope);
|
|
460
2851
|
const partial = formatPartialErrors(result.PartialErrors);
|
|
461
|
-
if (partial) throw new
|
|
462
|
-
return (result.CampaignIds ?? []).filter((
|
|
2852
|
+
if (partial) throw new AdportError17("PROVIDER_ERROR", `microsoft: AddCampaigns partial errors \u2014 ${partial}`);
|
|
2853
|
+
return (result.CampaignIds ?? []).filter((id3) => id3 !== null).map(String);
|
|
463
2854
|
}
|
|
464
2855
|
};
|
|
465
2856
|
}
|
|
@@ -467,21 +2858,23 @@ var MicrosoftAdsProvider = class {
|
|
|
467
2858
|
const campaigns = await this.listCampaigns(accountId);
|
|
468
2859
|
const campaign = campaigns.find((c) => String(c.Id) === campaignId);
|
|
469
2860
|
if (!campaign) {
|
|
470
|
-
throw new
|
|
2861
|
+
throw new AdportError17("PROVIDER_ERROR", `microsoft: campaign ${campaignId} not found in account ${accountId}`);
|
|
471
2862
|
}
|
|
472
2863
|
return campaign;
|
|
473
2864
|
}
|
|
474
|
-
async updateCampaign(accountId,
|
|
2865
|
+
async updateCampaign(accountId, fields2) {
|
|
475
2866
|
const scope = await this.scopeFor(accountId);
|
|
476
|
-
const result = await this.client.request("campaign", "PUT", "Campaigns", { AccountId: accountId, Campaigns: [
|
|
2867
|
+
const result = await this.client.request("campaign", "PUT", "Campaigns", { AccountId: accountId, Campaigns: [fields2] }, scope);
|
|
477
2868
|
const partial = formatPartialErrors(result.PartialErrors);
|
|
478
|
-
if (partial) throw new
|
|
2869
|
+
if (partial) throw new AdportError17("PROVIDER_ERROR", `microsoft: UpdateCampaigns partial errors \u2014 ${partial}`);
|
|
479
2870
|
}
|
|
480
2871
|
async planSetStatus(accountId, payload) {
|
|
481
2872
|
const current = await this.lookupCampaign(accountId, payload.campaign_id);
|
|
2873
|
+
if (current.ExperimentId && String(current.ExperimentId) !== "0") throw new AdportError17("INVALID_INPUT", "microsoft: experiment campaign status is inherited; change the base campaign status instead");
|
|
482
2874
|
return {
|
|
483
2875
|
summary: `Set Microsoft campaign "${current.Name}" status ${current.Status} \u2192 ${payload.status}`,
|
|
484
2876
|
changes: [`~ campaign ${payload.campaign_id} Status ${current.Status} \u2192 ${payload.status}`],
|
|
2877
|
+
notes: ["Related active or scheduled campaign-copy experiments follow the base serving status. Completed experiments cannot be restarted by unpausing the base."],
|
|
485
2878
|
coercions: [],
|
|
486
2879
|
budgetDeltas: [],
|
|
487
2880
|
execute: async () => {
|
|
@@ -492,8 +2885,9 @@ var MicrosoftAdsProvider = class {
|
|
|
492
2885
|
}
|
|
493
2886
|
async planSetBudget(accountId, payload) {
|
|
494
2887
|
const current = await this.lookupCampaign(accountId, payload.campaign_id);
|
|
2888
|
+
if (current.ExperimentId && String(current.ExperimentId) !== "0") throw new AdportError17("INVALID_INPUT", "microsoft: experiment campaign budget is inherited; change the base campaign budget instead");
|
|
495
2889
|
if (current.BudgetId && Number(current.BudgetId) > 0) {
|
|
496
|
-
throw new
|
|
2890
|
+
throw new AdportError17(
|
|
497
2891
|
"PROVIDER_ERROR",
|
|
498
2892
|
`microsoft: campaign "${current.Name}" uses a SHARED budget (BudgetId ${current.BudgetId}) \u2014 its DailyBudget cannot be changed per-campaign (CampaignServiceCannotUpdateSharedBudget).`
|
|
499
2893
|
);
|
|
@@ -501,6 +2895,7 @@ var MicrosoftAdsProvider = class {
|
|
|
501
2895
|
return {
|
|
502
2896
|
summary: `Change Microsoft campaign "${current.Name}" daily budget ${current.DailyBudget ?? "(unset)"} \u2192 ${payload.daily_budget}`,
|
|
503
2897
|
changes: [`~ campaign ${payload.campaign_id} DailyBudget ${current.DailyBudget ?? "(unset)"} \u2192 ${payload.daily_budget}`],
|
|
2898
|
+
notes: ["For related campaign-copy experiments, this changes the base total daily allocation before its traffic/budget split. The experiment campaign inherits that budget rather than receiving an additional independent pool."],
|
|
504
2899
|
coercions: [],
|
|
505
2900
|
budgetDeltas: [
|
|
506
2901
|
{
|
|
@@ -516,52 +2911,69 @@ var MicrosoftAdsProvider = class {
|
|
|
516
2911
|
};
|
|
517
2912
|
}
|
|
518
2913
|
};
|
|
519
|
-
function
|
|
520
|
-
const
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
return { provider, accountId, entity: { level: "account", id: accountId, name: accountId }, metrics };
|
|
2914
|
+
function performanceMetrics(base) {
|
|
2915
|
+
const ratio = (numerator, denominator, scale = 1) => numerator === void 0 || denominator === void 0 ? void 0 : denominator > 0 ? round2(numerator / denominator * scale) : 0;
|
|
2916
|
+
return Object.fromEntries(Object.entries({
|
|
2917
|
+
...base,
|
|
2918
|
+
ctr: ratio(base.clicks, base.impressions, 100),
|
|
2919
|
+
cpc: ratio(base.spend, base.clicks),
|
|
2920
|
+
cpm: ratio(base.spend, base.impressions, 1e3),
|
|
2921
|
+
cpa: ratio(base.spend, base.conversions),
|
|
2922
|
+
roas: ratio(base.conversion_value, base.spend)
|
|
2923
|
+
}).filter(([, value]) => value !== void 0).map(([key, value]) => [key, round2(value)]));
|
|
2924
|
+
}
|
|
2925
|
+
function aggregateAccountRows(rows3, provider, accountId) {
|
|
2926
|
+
const totals = {};
|
|
2927
|
+
for (const metric of ["spend", "impressions", "clicks", "conversions", "conversion_value"]) {
|
|
2928
|
+
if (rows3.every((row) => row.metrics[metric] !== void 0)) totals[metric] = rows3.reduce((sum, row) => sum + row.metrics[metric], 0);
|
|
2929
|
+
}
|
|
2930
|
+
return { provider, accountId, entity: { level: "account", id: accountId, name: accountId }, metrics: performanceMetrics(totals) };
|
|
537
2931
|
}
|
|
538
2932
|
function validateMicrosoftReadPath(path) {
|
|
539
2933
|
const normalized = path.replace(/^\/+|\/+$/g, "").trim();
|
|
540
2934
|
const action = normalized.split("/").at(-1) ?? "";
|
|
541
2935
|
if (!/^[A-Za-z][A-Za-z0-9]*(?:\/[A-Za-z][A-Za-z0-9]*){1,2}$/.test(normalized) || !/^(?:Query|Search|Get|Submit|Poll)/.test(action)) {
|
|
542
|
-
throw new
|
|
2936
|
+
throw new AdportError17("INVALID_INPUT", `microsoft: unsupported read operation path "${path}"`);
|
|
543
2937
|
}
|
|
544
2938
|
return normalized;
|
|
545
2939
|
}
|
|
546
2940
|
function validateMicrosoftResource(resource) {
|
|
547
2941
|
const normalized = resource.trim();
|
|
548
2942
|
if (!/^[A-Z][A-Za-z0-9]{1,80}$/.test(normalized)) {
|
|
549
|
-
throw new
|
|
2943
|
+
throw new AdportError17("INVALID_INPUT", `microsoft: invalid Campaign Management resource "${resource}"`);
|
|
550
2944
|
}
|
|
551
2945
|
return normalized;
|
|
552
2946
|
}
|
|
553
2947
|
function isRecord(value) {
|
|
554
2948
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
555
2949
|
}
|
|
2950
|
+
function requireTypedMutationTool(resource, body) {
|
|
2951
|
+
const collection = resource.toLowerCase();
|
|
2952
|
+
const hasFieldValue = (value, key, matches3) => Array.isArray(value) ? value.some((child) => hasFieldValue(child, key, matches3)) : isRecord(value) && Object.entries(value).some(([field, child]) => field.toLowerCase() === key && typeof child === "string" && matches3(child.trim().toLowerCase()) || hasFieldValue(child, key, matches3));
|
|
2953
|
+
const audienceSelectors = /* @__PURE__ */ new Set(["audience", "audiencecriterion", "custom", "customaudience", "inmarket", "inmarketaudience", "product", "productaudience", "remarketinglist", "similarremarketinglist", "combinedlist", "customerlist", "impressionbasedremarketinglist", "customsegment", "aiprompt"]);
|
|
2954
|
+
if (["campaigncriterions", "adgroupcriterions"].includes(collection) && (hasFieldValue(body, "criteriontype", (value) => value.split(/[,\s]+/).some((value2) => audienceSelectors.has(value2))) || hasFieldValue(body, "type", (value) => ["audience", "audiencecriterion"].includes(value)))) throw new AdportError17("INVALID_INPUT", "microsoft: audience criteria require typed audience-targeting tools for hierarchy, target-mode and opposite-level checks");
|
|
2955
|
+
const generalSelectors = /* @__PURE__ */ new Set(["targets", "age", "agecriterion", "gender", "gendercriterion", "device", "devicecriterion", "daytime", "daytimecriterion", "location", "locationcriterion", "locationintent", "locationintentcriterion", "radius", "radiuscriterion"]);
|
|
2956
|
+
if (["campaigncriterions", "adgroupcriterions"].includes(collection) && (hasFieldValue(body, "criteriontype", (value) => value.split(/[,\s]+/).some((value2) => generalSelectors.has(value2))) || hasFieldValue(body, "type", (value) => generalSelectors.has(value)))) throw new AdportError17("INVALID_INPUT", "microsoft: general targets require microsoft_update_targeting for scope, inheritance, schedule-clock and preservation checks");
|
|
2957
|
+
const hasKey = (value, name5) => Array.isArray(value) ? value.some((child) => hasKey(child, name5)) : isRecord(value) && Object.entries(value).some(([key, child]) => key.toLowerCase() === name5 || hasKey(child, name5));
|
|
2958
|
+
if (["campaigns", "adgroups"].includes(collection) && hasKey(body, "adscheduleusesearchertimezone")) throw new AdportError17("INVALID_INPUT", "microsoft: schedule clocks require microsoft_update_targeting with native account time-zone and inheritance context");
|
|
2959
|
+
if (["campaigns", "adgroups"].includes(collection) && hasFieldValue(body, "type", (value) => ["target", "targetsetting"].includes(value))) throw new AdportError17("INVALID_INPUT", "microsoft: target-setting changes require microsoft_set_audience_target_mode to preserve other targeting details");
|
|
2960
|
+
if (collection === "audiences") throw new AdportError17("INVALID_INPUT", "microsoft: audience mutations require typed audience tools for Account ownership, replacement-rule semantics and deletion reference checks");
|
|
2961
|
+
if (collection === "experiments") throw new AdportError17("INVALID_INPUT", "microsoft: experiments require typed tools for inherited pause/budget policy, ownership, snapshots and coupled campaign effects; promotion and graduation need separate reviewed workflows");
|
|
2962
|
+
if (collection === "uettags") throw new AdportError17("INVALID_INPUT", "microsoft: use microsoft_create_uet_tag for new uninstalled tags; customer-wide tag edits, deletion and sharing are not exposed through single-account generic tools");
|
|
2963
|
+
if (collection === "conversiongoals") throw new AdportError17("INVALID_INPUT", "microsoft: conversion-goal mutations require typed conversion tools for account scope, native auto-tagging side effects and event-criteria preservation");
|
|
2964
|
+
if (["offlineconversions", "offlineconversionadjustments"].includes(collection)) throw new AdportError17("INVALID_INPUT", "microsoft: offline events require typed upload tools for private previews, goal binding and indexed receipt handling");
|
|
2965
|
+
const referencesSharedBudget = (value) => Array.isArray(value) ? value.some(referencesSharedBudget) : isRecord(value) && Object.entries(value).some(([key, child]) => key.toLowerCase() === "budgetid" && child !== null && child !== void 0 && String(child) !== "0" || referencesSharedBudget(child));
|
|
2966
|
+
if (collection === "budgets" || referencesSharedBudget(body)) throw new AdportError17("INVALID_INPUT", "microsoft: shared-budget changes require the typed microsoft shared-budget tools for membership, snapshot and monetary policy checks");
|
|
2967
|
+
}
|
|
556
2968
|
function validateMicrosoftAccountScope(value, accountId) {
|
|
557
2969
|
if (Array.isArray(value)) return value.forEach((item) => validateMicrosoftAccountScope(item, accountId));
|
|
558
2970
|
if (!isRecord(value)) return;
|
|
559
2971
|
for (const [key, child] of Object.entries(value)) {
|
|
560
|
-
if (key === "
|
|
561
|
-
throw new
|
|
2972
|
+
if (key.toLowerCase() === "accountid" && String(child) !== accountId) {
|
|
2973
|
+
throw new AdportError17("INVALID_INPUT", `microsoft: body AccountId ${String(child)} does not match selected account ${accountId}`);
|
|
562
2974
|
}
|
|
563
|
-
if (key === "
|
|
564
|
-
throw new
|
|
2975
|
+
if (key.toLowerCase() === "accountids" && (!Array.isArray(child) || child.some((id3) => String(id3) !== accountId))) {
|
|
2976
|
+
throw new AdportError17("INVALID_INPUT", `microsoft: body AccountIds must contain only selected account ${accountId}`);
|
|
565
2977
|
}
|
|
566
2978
|
validateMicrosoftAccountScope(child, accountId);
|
|
567
2979
|
}
|
|
@@ -570,8 +2982,9 @@ function coerceMicrosoftCreatedStatuses(value, coercions, path = "body") {
|
|
|
570
2982
|
if (Array.isArray(value)) return value.forEach((item, index) => coerceMicrosoftCreatedStatuses(item, coercions, `${path}[${index}]`));
|
|
571
2983
|
if (!isRecord(value)) return;
|
|
572
2984
|
for (const [key, child] of Object.entries(value)) {
|
|
573
|
-
if (key === "
|
|
574
|
-
value[key]
|
|
2985
|
+
if (key.toLowerCase() === "status" && typeof child === "string" && ["active", "paused"].includes(child.toLowerCase()) && (key !== "Status" || child !== "Paused")) {
|
|
2986
|
+
delete value[key];
|
|
2987
|
+
value.Status = "Paused";
|
|
575
2988
|
coercions.push(`${path}.${key} coerced to Paused by policy (paused_creation)`);
|
|
576
2989
|
} else coerceMicrosoftCreatedStatuses(child, coercions, `${path}.${key}`);
|
|
577
2990
|
}
|
|
@@ -591,9 +3004,9 @@ function collectMicrosoftBudgets(value, path = "body") {
|
|
|
591
3004
|
for (const [key, child] of Object.entries(value)) {
|
|
592
3005
|
const childPath = `${path}.${key}`;
|
|
593
3006
|
if (/budget/i.test(key) && !/type|id/i.test(key)) {
|
|
594
|
-
const
|
|
595
|
-
if (Number.isFinite(
|
|
596
|
-
deltas.push({ target: childPath, toMicros: Math.round(
|
|
3007
|
+
const amount2 = Number(child);
|
|
3008
|
+
if (Number.isFinite(amount2) && amount2 > 0) {
|
|
3009
|
+
deltas.push({ target: childPath, toMicros: Math.round(amount2 * UNITS_TO_MICROS) });
|
|
597
3010
|
}
|
|
598
3011
|
}
|
|
599
3012
|
deltas.push(...collectMicrosoftBudgets(child, childPath));
|
|
@@ -607,8 +3020,8 @@ function extractMicrosoftIds(value) {
|
|
|
607
3020
|
if (!isRecord(item)) return;
|
|
608
3021
|
for (const [key, child] of Object.entries(item)) {
|
|
609
3022
|
if (/Ids?$/.test(key)) {
|
|
610
|
-
if (Array.isArray(child)) child.forEach((
|
|
611
|
-
if (
|
|
3023
|
+
if (Array.isArray(child)) child.forEach((id3) => {
|
|
3024
|
+
if (id3 !== null) ids.push(String(id3));
|
|
612
3025
|
});
|
|
613
3026
|
else if (typeof child === "string" || typeof child === "number") ids.push(String(child));
|
|
614
3027
|
} else visit(child);
|
|
@@ -622,104 +3035,217 @@ function round2(n) {
|
|
|
622
3035
|
}
|
|
623
3036
|
|
|
624
3037
|
// src/tools.ts
|
|
625
|
-
import { defineTool, guardedWriteTool } from "@adport/core";
|
|
626
|
-
import { z } from "zod";
|
|
627
|
-
|
|
3038
|
+
import { DATE_PRESETS, defineTool as defineTool14, guardedWriteTool as guardedWriteTool13 } from "@adport/core";
|
|
3039
|
+
import { z as z18 } from "zod";
|
|
3040
|
+
|
|
3041
|
+
// src/child-tools.ts
|
|
3042
|
+
import { creativesOutput as creativesOutput3, defineTool as defineTool13, guardedWriteTool as guardedWriteTool12 } from "@adport/core";
|
|
3043
|
+
import { z as z17 } from "zod";
|
|
3044
|
+
var id2 = z17.string().regex(/^\d+$/);
|
|
3045
|
+
var parent = { campaign_id: id2, ad_group_id: id2 };
|
|
3046
|
+
var status = z17.enum(["Active", "Paused"]);
|
|
3047
|
+
var microsoftAdTypes = ["ResponsiveSearch", "Responsive", "DynamicSearch", "ExpandedText", "AppInstall", "Product"];
|
|
3048
|
+
var headlines = z17.array(z17.string().min(1).max(30)).min(3).max(15).refine((value) => new Set(value).size === value.length, "Headlines must be unique");
|
|
3049
|
+
var descriptions = z17.array(z17.string().min(1).max(90)).min(2).max(4).refine((value) => new Set(value).size === value.length, "Descriptions must be unique");
|
|
3050
|
+
var urls2 = z17.array(z17.string().url().refine((value) => ["http:", "https:"].includes(new URL(value).protocol))).min(1).max(10);
|
|
3051
|
+
var copy = { headlines, descriptions, final_urls: urls2, path1: z17.string().max(15).optional(), path2: z17.string().max(15).optional() };
|
|
3052
|
+
var rows2 = z17.object({ rows: z17.array(z17.record(z17.string(), z17.unknown())), truncated: z17.boolean() });
|
|
3053
|
+
function microsoftChildTools(provider) {
|
|
3054
|
+
const write = (name5, description2, payload, kind2 = "update") => guardedWriteTool12({ name: name5, namespace: "microsoft", provider: "microsoft", description: description2, payload, kind: kind2 });
|
|
3055
|
+
return [
|
|
3056
|
+
defineTool13({
|
|
3057
|
+
name: "microsoft_ad_groups",
|
|
3058
|
+
namespace: "microsoft",
|
|
3059
|
+
description: "Read ad groups and their bids/statuses after verifying the campaign belongs to the selected account.",
|
|
3060
|
+
input: z17.object({ account_id: id2, campaign_id: id2 }),
|
|
3061
|
+
output: rows2,
|
|
3062
|
+
annotations: { readOnly: true },
|
|
3063
|
+
handler: (input) => provider.children.listGroups(input)
|
|
3064
|
+
}),
|
|
3065
|
+
defineTool13({
|
|
3066
|
+
name: "microsoft_ads",
|
|
3067
|
+
namespace: "microsoft",
|
|
3068
|
+
description: "Read ad configuration and creative copy with visual edit actions. Verifies the campaign/ad-group hierarchy in the selected account.",
|
|
3069
|
+
input: z17.object({ account_id: id2, ...parent, ad_types: z17.array(z17.enum(microsoftAdTypes)).min(1).default(["ResponsiveSearch"]), limit: z17.number().int().positive().max(200).default(50) }),
|
|
3070
|
+
output: creativesOutput3.extend({ ads: z17.array(z17.record(z17.string(), z17.unknown())) }),
|
|
3071
|
+
presentation: "creatives",
|
|
3072
|
+
annotations: { readOnly: true },
|
|
3073
|
+
handler: (input) => provider.children.listAds(input)
|
|
3074
|
+
}),
|
|
3075
|
+
defineTool13({
|
|
3076
|
+
name: "microsoft_keywords",
|
|
3077
|
+
namespace: "microsoft",
|
|
3078
|
+
description: "Read ad-group keywords, including bids, match types, statuses and URLs, within the selected campaign/account.",
|
|
3079
|
+
input: z17.object({ account_id: id2, ...parent }),
|
|
3080
|
+
output: rows2,
|
|
3081
|
+
annotations: { readOnly: true },
|
|
3082
|
+
handler: (input) => provider.children.listKeywords(input)
|
|
3083
|
+
}),
|
|
3084
|
+
write(
|
|
3085
|
+
"microsoft_create_ad_group",
|
|
3086
|
+
"Create a SearchStandard ad group in an account-owned campaign. CPC bid uses whole account-currency units; policy may force Paused.",
|
|
3087
|
+
z17.object({ campaign_id: id2, name: z17.string().min(1).max(256), language: z17.string().min(1).describe("Microsoft language name, e.g. English or German; chosen explicitly for ad-group targeting"), cpc_bid: z17.number().positive().optional(), status: status.default("Paused") }),
|
|
3088
|
+
"create"
|
|
3089
|
+
),
|
|
3090
|
+
write("microsoft_set_ad_group_status", "Activate or pause an account-owned ad group; the parent campaign status remains unchanged.", z17.object({ ...parent, status })),
|
|
3091
|
+
write(
|
|
3092
|
+
"microsoft_update_ad_group",
|
|
3093
|
+
"Rename an ad group or change its CPC bid in whole currency units. Campaign and ad-group status remain unchanged.",
|
|
3094
|
+
z17.object({ ...parent, name: z17.string().min(1).max(256).optional(), cpc_bid: z17.number().positive().optional() }).refine((value) => value.name !== void 0 || value.cpc_bid !== void 0, "Provide name or cpc_bid")
|
|
3095
|
+
),
|
|
3096
|
+
write(
|
|
3097
|
+
"microsoft_create_responsive_search_ad",
|
|
3098
|
+
"Create a responsive search ad using 3\u201315 unique headlines and 2\u20134 unique descriptions in a SearchStandard ad group. Policy may force Paused.",
|
|
3099
|
+
z17.object({ ...parent, ...copy, status: status.default("Paused") }),
|
|
3100
|
+
"create"
|
|
3101
|
+
),
|
|
3102
|
+
write(
|
|
3103
|
+
"microsoft_update_responsive_search_ad",
|
|
3104
|
+
"Edit supplied responsive search ad fields. Omitted fields and serving status are preserved; existing positional pinning is retained.",
|
|
3105
|
+
z17.object({ ...parent, ad_id: id2, headlines: headlines.optional(), descriptions: descriptions.optional(), final_urls: urls2.optional(), path1: copy.path1, path2: copy.path2 }).refine((value) => ["headlines", "descriptions", "final_urls", "path1", "path2"].some((key) => value[key] !== void 0), "Provide a content field")
|
|
3106
|
+
),
|
|
3107
|
+
write(
|
|
3108
|
+
"microsoft_set_ad_status",
|
|
3109
|
+
"Activate or pause an ad after verifying its exact parent hierarchy. Parent delivery settings remain unchanged.",
|
|
3110
|
+
z17.object({ ...parent, ad_id: id2, ad_type: z17.enum(microsoftAdTypes).default("ResponsiveSearch"), status })
|
|
3111
|
+
),
|
|
3112
|
+
write(
|
|
3113
|
+
"microsoft_add_keywords",
|
|
3114
|
+
"Create up to 100 keywords in an account-owned ad group. Bids use whole currency units. Policy may force Paused.",
|
|
3115
|
+
z17.object({ ...parent, keywords: z17.array(z17.object({ text: z17.string().min(1).max(100), match_type: z17.enum(["Broad", "Phrase", "Exact"]), bid: z17.number().positive().optional(), status: status.default("Paused") })).min(1).max(100) }),
|
|
3116
|
+
"create"
|
|
3117
|
+
),
|
|
3118
|
+
write("microsoft_set_keyword_status", "Activate or pause one verified keyword without replacing its text, match type or bid.", z17.object({ ...parent, keyword_id: id2, status })),
|
|
3119
|
+
write("microsoft_set_keyword_bid", "Change one verified keyword bid in whole currency units; keyword and parent statuses remain unchanged.", z17.object({ ...parent, keyword_id: id2, bid: z17.number().positive() })),
|
|
3120
|
+
write(
|
|
3121
|
+
"microsoft_remove_keywords",
|
|
3122
|
+
"Permanently remove verified keyword IDs from an ad group. This cannot be undone; use microsoft_set_keyword_status to pause instead.",
|
|
3123
|
+
z17.object({ ...parent, keyword_ids: z17.array(id2).min(1).max(100).refine((value) => new Set(value).size === value.length, "Keyword IDs must be unique") }),
|
|
3124
|
+
"remove"
|
|
3125
|
+
)
|
|
3126
|
+
];
|
|
3127
|
+
}
|
|
3128
|
+
|
|
3129
|
+
// src/tools.ts
|
|
3130
|
+
var statusSchema = z18.enum(["Active", "Paused"]);
|
|
628
3131
|
function microsoftTools(provider) {
|
|
629
3132
|
return [
|
|
630
|
-
|
|
3133
|
+
...microsoftChildTools(provider),
|
|
3134
|
+
...microsoftImageTools(provider),
|
|
3135
|
+
...microsoftExtensionTools(provider),
|
|
3136
|
+
...microsoftTargetingTools(provider),
|
|
3137
|
+
...microsoftGeneralTargetingTools(provider),
|
|
3138
|
+
...microsoftNegativeKeywordTools(provider),
|
|
3139
|
+
...microsoftBudgetTools(provider),
|
|
3140
|
+
...microsoftPlanningTools(provider),
|
|
3141
|
+
...microsoftConversionTools(provider),
|
|
3142
|
+
...microsoftAudienceTools(provider),
|
|
3143
|
+
...microsoftAudienceTargetingTools(provider),
|
|
3144
|
+
...microsoftOfflineReportTools(provider),
|
|
3145
|
+
...microsoftOfflineConversionTools(provider),
|
|
3146
|
+
...microsoftExperimentTools(provider),
|
|
3147
|
+
...["keyword", "search_term"].map((kind2) => defineTool14({
|
|
3148
|
+
name: `microsoft_${kind2}_report`,
|
|
3149
|
+
namespace: "microsoft",
|
|
3150
|
+
description: `Read the native Microsoft ${kind2.replace("_", " ")} performance report through Submit/Poll/CSV. Native numeric values remain strings; empty or unavailable values are preserved.`,
|
|
3151
|
+
input: z18.object({ account_id: z18.string().regex(/^\d+$/), date_range: z18.union([z18.enum(DATE_PRESETS), z18.object({ start: z18.string().regex(/^\d{4}-\d{2}-\d{2}$/), end: z18.string().regex(/^\d{4}-\d{2}-\d{2}$/) })]).default("last_7_days"), limit: z18.number().int().positive().max(5e3).default(1e3) }),
|
|
3152
|
+
output: z18.object({ rows: z18.array(z18.record(z18.string(), z18.string())), truncated: z18.boolean(), report_type: z18.string() }),
|
|
3153
|
+
annotations: { readOnly: true },
|
|
3154
|
+
handler: (input) => provider.nativeReport({ ...input, kind: kind2 })
|
|
3155
|
+
})),
|
|
3156
|
+
defineTool14({
|
|
631
3157
|
name: "microsoft_api_read",
|
|
632
3158
|
namespace: "microsoft",
|
|
633
3159
|
description: "Call any documented Microsoft Advertising v13 query, search, get, or reporting submit/poll operation with selected-account headers.",
|
|
634
|
-
input:
|
|
635
|
-
account_id:
|
|
636
|
-
service:
|
|
637
|
-
path:
|
|
638
|
-
body:
|
|
3160
|
+
input: z18.object({
|
|
3161
|
+
account_id: z18.string(),
|
|
3162
|
+
service: z18.enum(["campaign", "customer", "reporting", "adinsight"]),
|
|
3163
|
+
path: z18.string().min(3).describe("REST operation path, e.g. AdGroups/QueryByCampaignId or GenerateReport/Submit"),
|
|
3164
|
+
body: z18.record(z18.string(), z18.unknown()).optional()
|
|
639
3165
|
}),
|
|
640
3166
|
annotations: { readOnly: true },
|
|
641
3167
|
async handler(input) {
|
|
642
3168
|
return provider.apiRead(input);
|
|
643
3169
|
}
|
|
644
3170
|
}),
|
|
645
|
-
|
|
3171
|
+
defineTool14({
|
|
646
3172
|
name: "microsoft_campaigns",
|
|
647
3173
|
namespace: "microsoft",
|
|
648
|
-
description: "List Microsoft Advertising
|
|
649
|
-
input:
|
|
3174
|
+
description: "List all eight Microsoft Advertising campaign types (Id, Name, Status, DailyBudget in account currency, BudgetId when shared).",
|
|
3175
|
+
input: z18.object({ account_id: z18.string().describe("Ad account id") }),
|
|
650
3176
|
annotations: { readOnly: true },
|
|
651
3177
|
async handler(input) {
|
|
652
3178
|
const campaigns = await provider.listCampaigns(input.account_id);
|
|
653
3179
|
return { campaigns };
|
|
654
3180
|
}
|
|
655
3181
|
}),
|
|
656
|
-
|
|
3182
|
+
guardedWriteTool13({
|
|
657
3183
|
name: "microsoft_create_campaign",
|
|
658
3184
|
namespace: "microsoft",
|
|
659
3185
|
description: "Create a Microsoft Advertising Search campaign. daily_budget is a float in account currency. The API's own default status is Paused. No server dry-run \u2014 previews are client-side diffs.",
|
|
660
3186
|
provider: "microsoft",
|
|
661
3187
|
kind: "create",
|
|
662
|
-
payload:
|
|
663
|
-
name:
|
|
664
|
-
daily_budget:
|
|
665
|
-
time_zone:
|
|
3188
|
+
payload: z18.object({
|
|
3189
|
+
name: z18.string().min(1).max(128),
|
|
3190
|
+
daily_budget: z18.number().positive(),
|
|
3191
|
+
time_zone: z18.string().optional().describe("Bing Ads time zone name, default PacificTimeUSCanadaTijuana"),
|
|
666
3192
|
status: statusSchema.optional()
|
|
667
3193
|
})
|
|
668
3194
|
}),
|
|
669
|
-
|
|
3195
|
+
guardedWriteTool13({
|
|
670
3196
|
name: "microsoft_set_campaign_status",
|
|
671
3197
|
namespace: "microsoft",
|
|
672
|
-
description: "Activate or pause a Microsoft Advertising campaign.",
|
|
3198
|
+
description: "Activate or pause a Microsoft Advertising base campaign; related active/scheduled experiments inherit its serving status. Direct experiment-campaign status edits are refused.",
|
|
673
3199
|
provider: "microsoft",
|
|
674
3200
|
kind: "update",
|
|
675
|
-
payload:
|
|
3201
|
+
payload: z18.object({ campaign_id: z18.string(), status: statusSchema })
|
|
676
3202
|
}),
|
|
677
|
-
|
|
3203
|
+
guardedWriteTool13({
|
|
678
3204
|
name: "microsoft_set_budget",
|
|
679
3205
|
namespace: "microsoft",
|
|
680
|
-
description: "Change a Microsoft campaign's DailyBudget (float, account currency).
|
|
3206
|
+
description: "Change a Microsoft base campaign's DailyBudget (float, account currency). Related campaign-copy experiments split this total pool. Direct experiment-campaign edits and shared budgets are refused.",
|
|
681
3207
|
provider: "microsoft",
|
|
682
3208
|
kind: "update",
|
|
683
|
-
payload:
|
|
3209
|
+
payload: z18.object({ campaign_id: z18.string(), daily_budget: z18.number().positive() })
|
|
684
3210
|
}),
|
|
685
|
-
|
|
3211
|
+
guardedWriteTool13({
|
|
686
3212
|
name: "microsoft_api_create",
|
|
687
3213
|
namespace: "microsoft",
|
|
688
|
-
description: "Create through
|
|
3214
|
+
description: "Create through Microsoft Campaign Management v13 using its documented API body. Under paused creation, campaigns/ad groups/ads/keywords receive explicit Paused status, including omitted status. Budget fields are policy-checked; shared budgets, conversion goals, UET tags and audiences require typed tools.",
|
|
689
3215
|
provider: "microsoft",
|
|
690
3216
|
kind: "create",
|
|
691
|
-
payload:
|
|
3217
|
+
payload: z18.object({ resource: z18.string().min(2), body: z18.record(z18.string(), z18.unknown()) })
|
|
692
3218
|
}),
|
|
693
|
-
|
|
3219
|
+
guardedWriteTool13({
|
|
694
3220
|
name: "microsoft_api_update",
|
|
695
3221
|
namespace: "microsoft",
|
|
696
3222
|
description: "Update non-budget fields through any Microsoft Advertising Campaign Management v13 collection.",
|
|
697
3223
|
provider: "microsoft",
|
|
698
3224
|
kind: "update",
|
|
699
|
-
payload:
|
|
3225
|
+
payload: z18.object({ resource: z18.string().min(2), body: z18.record(z18.string(), z18.unknown()) })
|
|
700
3226
|
}),
|
|
701
|
-
|
|
3227
|
+
guardedWriteTool13({
|
|
702
3228
|
name: "microsoft_api_delete",
|
|
703
3229
|
namespace: "microsoft",
|
|
704
3230
|
description: "Permanently delete through any Microsoft Advertising Campaign Management v13 collection.",
|
|
705
3231
|
provider: "microsoft",
|
|
706
3232
|
kind: "remove",
|
|
707
3233
|
destructive: true,
|
|
708
|
-
payload:
|
|
3234
|
+
payload: z18.object({ resource: z18.string().min(2), body: z18.record(z18.string(), z18.unknown()) })
|
|
709
3235
|
})
|
|
710
3236
|
];
|
|
711
3237
|
}
|
|
712
3238
|
|
|
713
3239
|
// src/index.ts
|
|
714
3240
|
async function resolveMicrosoftCredentials(store) {
|
|
715
|
-
const
|
|
716
|
-
if (
|
|
3241
|
+
const record2 = await store.get("microsoft");
|
|
3242
|
+
if (record2?.data.developer_token && record2.data.client_id && record2.data.refresh_token) {
|
|
717
3243
|
return {
|
|
718
|
-
developerToken:
|
|
719
|
-
clientId:
|
|
720
|
-
refreshToken:
|
|
721
|
-
clientSecret:
|
|
722
|
-
sandbox:
|
|
3244
|
+
developerToken: record2.data.developer_token,
|
|
3245
|
+
clientId: record2.data.client_id,
|
|
3246
|
+
refreshToken: record2.data.refresh_token,
|
|
3247
|
+
clientSecret: record2.data.client_secret || void 0,
|
|
3248
|
+
sandbox: record2.data.sandbox === "true"
|
|
723
3249
|
};
|
|
724
3250
|
}
|
|
725
3251
|
const env = process.env;
|
|
@@ -738,9 +3264,9 @@ async function createMicrosoftModule(store) {
|
|
|
738
3264
|
const credentials = await resolveMicrosoftCredentials(store);
|
|
739
3265
|
if (!credentials) return void 0;
|
|
740
3266
|
const client = new MicrosoftAdsClient(credentials, async (rotated) => {
|
|
741
|
-
const
|
|
742
|
-
if (
|
|
743
|
-
await store.set({ ...
|
|
3267
|
+
const record2 = await store.get("microsoft");
|
|
3268
|
+
if (record2) {
|
|
3269
|
+
await store.set({ ...record2, data: { ...record2.data, refresh_token: rotated } });
|
|
744
3270
|
}
|
|
745
3271
|
});
|
|
746
3272
|
const provider = new MicrosoftAdsProvider(client);
|